2

I was wondering what's the reason behind the syntax? I mean it's like this:

int[ , ] arrayName = new int[10,10];

Wouldn't it be simpler if we had something like:

int[10,10] arrayName ;

What caused the software architect to make such a decision?

3
  • I'd like to point out that these two lines of code would not do the same thing. The first would create arrayName on the stack, and the second would create it on the heap. Commented Aug 10, 2015 at 4:55
  • 3
    Arrays are not stored on the stack. Commented Aug 10, 2015 at 4:56
  • I now realize how silly the initial comment was. I assume the "software architect" made this decision precisely because arrays are not stored on the stack. Commented Aug 10, 2015 at 4:58

4 Answers 4

6

It's because you can declare the variable in one scope, and initialize it in another (normally in a constructor).

Something like this:

public class Foo
{
    private int[ , ] Bar;  // Bar will be null until initialized

    public Foo(int a, int b)
    {
        Bar = new int[a, b];
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

With int[10,10] arrayName; you are committing to the array size. What would happen if I did this?

int[10,10] arrayOne;
int[11,11] arrayTwo;

arrayOne = arrayTwo;

An array object is simply a pointer to a block of managed memory. Knowing this, arrayOne = arrayTwo would have to be technically legal.

Therefore, stating that it as an int[10,10] is actually a lie. It may start that way, but it could at any time be reassigned into an array of different dimensions.

1 Comment

@AndreAndersen - Of course it wouldn't, because I'm using the alternative (non-existent) C# syntax that the OP is suggesting.
2

This

int[ , ] arrayName = new int[10,10];

already initializes the variable in memory and instantiate it. Also, you could change the size of the array during runtime, for example

arrayName = new int[20,20]

On the other hand

int[10,10] arrayName ;

Will just declare the variable for the array. arrayNamethen is still null.

3 Comments

Initializes means assigns memory to it? is it filled with a value, say 0 , when initialized?
Yes, just declaring the array will not actually create it. This is done with the new keyword
It will be null until initialized (normally with the new keyword)
1
int[,] arrayName = new int[10,10];

Only the left hand side is declaring the array, the right hand side is initialising it. This is true for most (if not all) of variables in C#. For example

string test; //declaring
test = "test"; //initialising
string test = "test"; //declare and initialise

Comments

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.