Search code examples
c#variablestypesconstructorglobal-variables

How to create an array in constructor that will be used later


I am making a Matrix class and want to make the constructor input the Matrix type too. How can I initialize a specific type 2d array?

public class Matrix
    {
        public int[][] matrix;
        //??


        Matrix(int x,int y,string type)
        {
            switch (type)
            {
                case "int":
                    //initialize a int 2d array
                case "double":
                    //initialize a double 2d array
                case "float":
                    //initialize a float 2d array
                default:
                   //initialize a float 2d array
                   break;

           }

       }
   }

Solution

  • Generics with a constraint of new might help, if the type can be declared at design time

    public class Matrix<T> where T : new()
    {
       public T[][] matrix;
       public Matrix(int x, int y)
          => matrix = Enumerable.Range(0,x).Select(elem => new T[y]).ToArray();    
    }
    

    Usage

    var something = new Matrix<int>(4,4);