Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add a new dimension to array

I want to add a new dimension to my array aka. to my Matrix class based on user input in the constructor.

Example:

var matrix = new Matrix<int>(3,2,4); // is 3 dimensional array 

Here is my Matrix class:

class Matrix<T>
{
    private T[][] mArray;
    private readonly int mCols;
    private readonly int mRows;       

    public Matrix(params int[] args)
    {
        //here is what I ve tried.
        /*
        mCols = args[0];
        mRows = args[1];

        mArray = new T[mCols][];

        for (int i = 0; i < mCols; i++)
            mArray[i] = new T[mRows];
        */

        // how to create a multidimensional array based on "args" length?

    }
}

Question: how to create a multidimensional array based on "args" length?

like image 934
Zer0 Avatar asked Nov 30 '25 16:11

Zer0


1 Answers

Found it by looking here

Array.CreateInstance(typeof(YOUR_TYPE), params)

example:

var arr = Array.CreateInstance(typeof(int), 3, 2, 4); // creates a 3 dimensional array

like image 104
Zer0 Avatar answered Dec 02 '25 05:12

Zer0