Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a dynamically sized matrix in C#

Tags:

c#

I am working on a C# app that will calculate some values. I need to put those values in a x-by-x array of strings. If I knew that "x" was for example, I know that I could just do:

string[,] matrix = new string[3, 3]; 

Unfortunately, I do not know what "x" will be. Is there a way to dynamically grow a matrix in C#? If so, how?

like image 685
user70192 Avatar asked Mar 04 '16 13:03

user70192


2 Answers

you can define the size of the array with variables and then change their values at runtime

int arrayWidth = 3;
int arrayHeight = 3;
string[,] matrix = new string[arrayWidth, arrayHeight]; 

however, as darin pointed out, arrays cannot be resized; so be sure to leave the initialisation right until you size values are confirmed.

like image 77
Souhaieb Besbes Avatar answered Nov 04 '22 09:11

Souhaieb Besbes


No, in C# arrays are of static size. They cannot be re-sized at runtime unless you declare a new array with the new size and then copy the elements from the old array to the new one (which depending on your specific needs might be feasible or not). So basically you could use some of the dynamic list structures in .NET such as IList<T> which allows you to add elements to it dynamically at runtime. Of course there are no miracles, under the covers a List<T> will use a .NET array for backing the data, except that it will re-size it intelligently as you are dynamically adding elements to this structure.

like image 20
Darin Dimitrov Avatar answered Nov 04 '22 10:11

Darin Dimitrov