Search code examples
c#collection-initializer

C# Collection initialization syntax for use with custom matrix class?


I'm creating a custom matrix class that only has a single 2D array to hold everything (I know that a 1D array is faster and better, but that's not the point of this implementation) the thing is, I'd like to have a constructor, and be able to do something like

Matrix a = new Matrix(2,2){{1,2},{3,4}};

and have it all work out. I've run into the "'Matrix' does not contain a definition for 'Add' and no extension method 'Add' etc." but after looking around, I've yet to be able to find robust enough info on how to define the Add() method in order to make it work. Here's the code I have so far

public class Matrix : IEnumerable
    {
        /* What we know abuot matricies
         * - matricies are defined by rows, cols
         * - addition is element-wise
         */

        public IEnumerator GetEnumerator()
        {
            yield return m;
        }

        private void Add(double a)
        {
            // what exactly should go here anyway?
        }

        private double[,] m;

        public double this[int rows, int cols]
        {
            get => m[rows, cols];
            set => m[rows, cols] = value;
        }       

        public Matrix(int rows, int cols)
        {
            m = new double[rows, cols];
        }
    ...
    }

so, how would I go about doing the Add() method anyway?


Solution

  • Try this code. Your Add method must be public. Also, to make the code safe, you must add verifiers to check if the sizes of the m matrix and the provided data match.

    private int currentRow = 0;
    public void Add(params double[] a)
    {
        for (int c = 0; c < a.Length; c++)
        {
            m[currentRow, c] = a[c];
        }
        currentRow++;
    }
    

    If you don't provide all the rows, the remaining rows will have the elements with their defaults values. Also, note that this method can be called in the future, and it would throw an exception when the m matrix has all the rows filled.