1

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;

           }

       }
   }
Clement
  • 128
  • 11

3 Answers3

4

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);
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
0

Standard approach would be to use generics instead of string name of the type like Matrix<T>.

If you want to specify type as string at run-time you have to either add multiple fields to store each type of an array or use dynamic or object as the type of array (since you can't assign float[][] to field of type int[][]).

For non-performance sensitive code I'd go with dynamic as it will give you code that looks reasonable (you loose intellisense and compile time safety) and validates all operations at run-time anyway.

public class Matrix
{
    dynamic matrix;

    Matrix(int x,int y,string type)
    {
        switch (type)
        {
            case "int":
                matrix = 
                   Enumerable.Repeat(0, x).Select(_ => new int[y]).ToArray();
                break;
            case "double":
                //initialize a double 2d array
                matrix = 
                   Enumerable.Repeat(0, x).Select(_ => new double[y]).ToArray();
                break;
            case "float":
            default:
                //initialize a float 2d array
                matrix = 
                   Enumerable.Repeat(0, x).Select(_ => new float[y]).ToArray();
                break;
         }
     }
 }

For array initialization see Multidimensional Array question.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
0

Look into generics

public class Matrix<T> 
{    
    public T[,] matrix;

    public Matrix<T>(int x, int y)
    {
        matrix = new T[x, y];
    }
}

You can probably find an existing, well-tested Matrix class somewhere on the internet.

Christo
  • 292
  • 1
  • 7
  • Same answer as Michael's, except you are showing some other array type than OP asked for - sample code shows Jagged Array (which they probably by mistake call 2d array) – Alexei Levenkov Feb 09 '19 at 02:33