Search code examples
c#arraysdynamicdimensionscustom-dimensions

Create Array with Dimension selected by User


The User should choose the Dimension (1, 2). After the user chose the Dimension, an Array with the dimension should be created. After this the array will be filled randomly, sorted and printed. I have created Methods for this that take a reference of an one dimensional or two dimensional array.

My only problem is now that both arrays need to have the same name (arr) because the methods later only take arr as a parameter.

I have tried creating a var variable before choosing the array-dim. But with var I need to specify the type of the variable, so I cannot simply use var arr;

Is there any solution to my problem? I really don't know how to solve this problem.

In the End I want something like that:

        var arr;
        switch (arrDim)
        {
            case 1:
                arr = Fill1DArrayRandom();
                break;
            case 2:
                arr = Fill2DArrayRandom();
                break;
        }


        PrintArray(arr);

        switch (chosenAlgo)
        {
            case 1:
                Algorithms.InsertionSort.Sort(ref arr);
                break;
                ...

The Methods that take either an one or two dimensional array.

 static void PrintArray(int[] arr) ...
    
 static void PrintArray(int[,] arr) ...

 static bool IsSorted(ref int[] arr) ...
 
 static bool IsSorted(ref int[,] arr)
 {
      for (int i = 0; i < arr.Length - 1; i++)
           for (int j = 0; j < arr.Length - 1; j++)
                if (arr[i,j] > arr[i-1,j-1])
                     return false;
      return true;
 }

Solution

  • One ugly solution is to create an object, then cast it to int[] array like this:

    var arr = new object();
    
    // switch here
    arr = new int[5] { 1 ,2,3, 4, 5};
    Console.WriteLine((arr as int[])[0]);
    arr = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
    Console.WriteLine((arr as int[,])[0, 0]);
    

    and printing:

        private static void Print(object arr) 
            {
                if (arr.GetType() == typeof(int[,]))
                {
                    int[,] myArr = arr as int[,];
                    Console.WriteLine(myArr[0, 0]);
                    // do stuff here with 2D array
                } 
                else 
                {
                    int[] myArr = arr as int[];
                    Console.WriteLine(myArr[0]);
                    // do stuff here with 1D array
                }
            }