martial
martial

Reputation: 3883

Can I define an overloaded '+' that add a double and an array in C#

I want to define a '+' so that I can add a double and a double array:

double[] x = {1.2, 1.4, 1.8};
double[] y = new double[3];
y = x + 0.3;

The result y should equals to {1.5, 1.7, 2.1}. That is, each element of x is added 0.3. I tried, but got compile error. Does that mean there is no way to accomplish this task? '+' can only be applied to two operands with the same type?

Upvotes: 0

Views: 95

Answers (2)

Personally, I quite like the solution suggested by @Habib. For the sake of variety, I am going to outline an alternative solution.

If you find yourself working quite a lot with vectors and matrices (i.e. one and two dimensional arrays), then you might find many of the extension methods in the Accord.Math library useful. You can install it with NuGet like so:

Install-Package Accord.Math

Then add a using declaration to your class to bring the extension methods into play

using Accord.Math;

Now you can add a scalar to every element in a vector (array) like so:

double[] x = {1.2, 1.4, 1.8};
double[] y = x.Add(0.3);
Console.WriteLine(y.ToString(DefaultMatrixFormatProvider.CurrentCulture));

which outputs

1.5 
1.7 
2.1

Upvotes: 0

Habib
Habib

Reputation: 223282

You can do:

double[] x = { 1.2, 1.4, 1.8 };
double[] y = x.Select(r => r + 0.3).ToArray();

Which would add 0.3 to each element in x, but if you want to overload + operator then look at operator overloading

Upvotes: 4

Related Questions