5

I have a custom Matrix class that I would like to implement a custom object initializer similar to what a double[,] can use but can not seem to figure out how to implement it.

Ideally I would like to have it look like this

var m1 = new Matrix
        {
            { 1.0, 3.0, 5.0 },
            { 7.0, 1.0, 5.0 }
        };

as of now I have a regular constructor with a signature of

public Matrix(double[,] inputArray){...}

that accepts a call like this

var m1 = new Matrix(new double[,]
        {
            { 1.0, 3.0, 5.0 },
            { 7.0, 1.0, 5.0 }
        });

and an object intializer that accepts the following using by inheriting the IEnumerable<double[]> interface and implementing an public void Add(double[] doubleVector) method

var m2 = new Matrix
        {
            new [] { 1.0, 3.0, 5.0 },                
            new [] { 7.0, 1.0, 5.0 }
        };

when I try using the object intializer I would like to I get a compiler error of not having an overload for Add that takes X number of arguments where X is the number of columns I am trying to create (i.e. in my provided examples 3).

How can I set up my class to take in an argument like I provided?

ASh
  • 34,632
  • 9
  • 60
  • 82
PlTaylor
  • 7,345
  • 11
  • 52
  • 94

1 Answers1

5

define Add method with params keyword and ignore ending element in array, which is longer than matrix width

public void Add(params double[] doubleVector)
{
   // code
}

if array is shorter, default elements are left (0)

// sample
var M = new Matrix()
{
    { 1.2, 1.0 },
    { 1.2, 1.0, 3.2, 3.4}
};
ASh
  • 34,632
  • 9
  • 60
  • 82