Gilad Naaman
Gilad Naaman

Reputation: 6550

Using array initializer

I have a class called Matrix : IEnumerable<double>, (classic, mathematical matrix. It is basically a 2D array with some goodies).

The class is immutable, so there is no way to change its values after instance creation.

If want to create a matrix with pre-existing values I have to pass an array to the constructor like this:

double[,] arr = new double[,]
{
    {1,2,3}, {4,5,6}, {7,8,9}
};
Matrix m = new Matrix(arr);

Is there a way to turn it into this: (?)

Matrix m = new Matrix
{
    {1,2,3}, {4,5,6}, {7,8,9}
};

Update:

Found a hack-ish way yo make it work. I'm not sure if this solution is advisable, but it works.

class Matrix : ICloneable, IEnumerable<double>
{
        // Height & Width are initialized in a constructor beforehand.
        /*
         * Usage:
         * var mat = new Matrix(3, 4)
         * {
         *              {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}
         * };
         */
        int rowIndex;
        bool allowArrayInitializer;
        double[,] tempData;
        double[,] data;
        public void Add(params double[] args)
        {
                if(!allowArrayInitializer)
                        throw new InvalidOperationException("Cannot use array initializer");
                if(args.Length != Width || rowIndex >= Height)
                        throw new InvalidOperationException("Invalid array initializer.");
                for(int i = 0; i < Width; i++)
                        tempData[i, rowIndex] = args[i];
                if(++rowIndex == Height)
                        data = tempData;
        }
}

Upvotes: 2

Views: 510

Answers (3)

watfy
watfy

Reputation: 124

instead of deriving from IEnumerable I would use a property:

class Matrix 
{
        public double[,] Arr { get; set; }
}

Matrix m = new Matrix
{
      Arr = new double [,] { {1d,2d,3d}, { 4d,5d, 6d}}
};

Upvotes: 0

Karthik D V
Karthik D V

Reputation: 926

You will not able to do it via initializer but should be able to do it via parameterized constructor. You can see the sample code below :

class Matrix : IEnumerable<double>
{
    double[,] input;
    public Matrix(double[,] inputArray)
    {
        input = inputArray;
    }

    public IEnumerator<double> GetEnumerator()
    {
        return (IEnumerator<double>)input.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return input.GetEnumerator();
    }
}

In the main method :

    static void Main(string[] args)
    {
        var m = new Matrix(new double[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } });
    }

I hope this helps you!

Upvotes: 0

Ry-
Ry-

Reputation: 225203

Not if it’s immutable; that syntactic sugar is implemented using Add().

Upvotes: 5

Related Questions