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?

1 Answer 1

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}
};
Sign up to request clarification or add additional context in comments.

5 Comments

Learned something today. Thanks for the help!
wouldn't the class would need to implement IEnumerable to be able to use this?
but matrix should have equal length and width
@M.kazemAkhgary You can't assure that in C# besides with run-time checks anyway
@DerekVanCuyk I stated in the original question that I had already inherited IEnumerable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.