1

I'm trying to understand how to work with matrix in C#.

I used to code in Java:

  • int[][]arr=new int[2][5]; or
  • int [][]arr={{2,3,4,5},{9,3}};

When I try to create an array in C# I only success to make this way:

int[,]={{1,2,3,4},{5,6,7,8}};

This line works for me but it requires same length in every column. I also try to use GetLength() when I worked with for loops and I could get only the number of columns and the size of the second column.

  1. Is there any way to create a matrix with any size I want like the java examples?
  2. How can I get the size of the rows/columns?
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 2
    A `int[,]` isn't equivalent to `int[][]`. –  Aug 31 '17 at 17:30
  • 1
    Seems like this has been answered before https://stackoverflow.com/questions/20521313/declaring-a-2d-array-without-knowing-its-size-in-c-sharp – Bebigu Aug 31 '17 at 17:30
  • Here's the Microsoft documentation: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays – Egbert Aug 31 '17 at 17:34

1 Answers1

2
  1. Is there any way to create a matrix with any size I want like the java examples

The term for such matrices is jagged array. Unlike int[,], this is an array of arrays; you can create it like this:

int [][] arr= { new[] {2,3,4,5}, new[] {9,3} };
  1. How can I get the size of the rows/columns?

Now that this is an array of arrays, you can access Length of each item in arr the same way that you do in Java:

for (var r = 0 ; r != arr.Length ; r++) {
    Console.WriteLine("Row {0} has {1} columns.", r, arr[r].Length);
    for (var c = 0 ; c != arr[r].Length ; c++) {
        ...
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523