In C#, how can i declare a two dimension array of buttons?
-
2Why do you have two different questions? – Josh Mein Apr 15 '13 at 14:45
-
`Button[,]` is a 2d array of buttons – Marc Gravell Apr 15 '13 at 14:49
-
-1: It's really not cool to remove the question you have answers for, leaving the other one left. – John H Apr 15 '13 at 14:52
-
how can i allocate position of them in form? – Vishnu T S Apr 15 '13 at 14:52
-
@VishnuTS You have to understand, that Stackoverflow is **not** your personal helper. When you ask a question that gets answered, it is expected that others, who might have the same question, will find their answer here without the need to ask. Right now, you basically changed a valid Q&A into a nonsense Q&A of the form `Q: Why does 1 + 1 equals 2? A: Bananas are bent, because [...]`. You deserved your question-ban. – Nolonar Apr 15 '13 at 15:03
3 Answers
Yes - in the first version, the variable is not definitely assigned. In the second, it is definitely assigned, with the default value (0). So:
int a;
Console.WriteLine(a); // Error!
int a = new int();
Console.WriteLine(a); // Prints 0
I don't think I've ever actually deliberately written new int()
, however. You'd usually write:
int a = 0;
as a rather more readable approach. For generic methods you could use either default(T)
or new T()
however, if T
is constrained to be a non-nullable value type.
Arrays are a completely separate question, and should be asked separately.

- 1,421,763
- 867
- 9,128
- 9,194
The latter (int a = new int();
) assigns a value - it is basically the same as int a = 0;
or int a = default(int);
. This means that if it is a local variable the rules of definite assignment are happy. With the first (int a;
) you can't use it until it has been assigned. For example, Console.WriteLine(a);
would fail if you don't explicitly give a
a value.
Note that fields (aka instance-variables and type-level variables) are inherently treated as "assigned" their default value (0
in this case), so in the case of a field it is simply redundant code.

- 1,026,079
- 266
- 2,566
- 2,900
The first one just declares an integer variable without initializing it's value:
int a;
Because it hasn't been initialized, you won't be able to use this it until you've assigned it a value.
The second one declares the integer variable and initializes it to the default value.
int a = new int();
To answer the second question, you can declare a two dimensional array of any type like this:
Button[,] buttons;
To initialize the array to a certain size use
Button[,] buttons = new Button[4, 5];
Although, element item in the array will be initialized to the default value for its type.

- 146,324
- 30
- 291
- 331