Search code examples
c#mathnet-numerics

Is there a way to automatically cast double argument to Vector?


I am currently using the Math.NET Numerics library in a .NET project, and I find myself often writing code like the following:

public double Foo(Vector<double> x)
{
    ...
}

...

public double Foo(double x)
{
    return Foo(Vector<double>.Build.Dense(1, x));
}

The Vector class is from the Math.NET library, and the idea here is that a one-element vector is really just a scalar, so it is both convenient and intuitive to be able to call Foo with a double argument when the input happens to be 1-dimensional. The call Vector<double>.Build.Dense(1, x) implements the type conversion from double to Vector<double>.

Is there any way to automate this conversion? That is, some way to have double implicitly cast as Vector<double> when calling a function taking a Vector<double> argument?


Solution

  • What you want is to define an implicit cast operator as an extension, i.e., for two classes which are not under your control.

    Unfortunately, at the time of writing (Sept 2023), this is currently not supported by C#. This feature has been requested multiple times and is being discussed at the C# language repository: