6

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?

3

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

4 Comments

Nope. You can resize array in c# using static method Array.Resize
Of course. And did you read the documentation of this method? In case you haven't lemme quote from it:This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.array must be a one-dimensional array. So let's repeat once again the answer I already provided here. In .NET arrays static size and cannot be re-sized at runtime unless you declare a new array with the new size and copy all the elements from the old to the new one.
So @nicolay.anykienko, could you please explain your downvote on this answer? How does in your opinion my answer provides wrong information (which is usually the case for downvoting).
You are right about behavior of Array.Resize method. Sorry, I'll remove downvote. However, information about Array.Resize would be not excessive in your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.