Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a clean Custom Object Initializer for a Matrix class

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?

like image 366
PlTaylor Avatar asked Oct 28 '15 12:10

PlTaylor


People also ask

How to initialise an object in c sharp?

You can use object initializers to initialize type objects in a declarative manner without explicitly invoking a constructor for the type.

How to initialize object data type in c#?

In object initializer, you can initialize the value to the fields or properties of a class at the time of creating an object without calling a constructor. In this syntax, you can create an object and then this syntax initializes the freshly created object with its properties, to the variable in the assignment.

How do you initialize an object?

Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).

What is object initializer syntax?

The object initializers syntax allows you to create an instance, and after that it assigns the newly created object, with its assigned properties, to the variable in the assignment.


1 Answers

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}
};
like image 105
ASh Avatar answered Sep 28 '22 16:09

ASh