Hi there,
I am wondering what the difference is in the following 2 classes.
Thanks
Class X
{
int i = 10;
}
Class X
{
int i;
public X()
{
i = 10;
}
}
Class - member initialization
4 Answers
Know the answer? Post it. Somebody with the same question will find it here.

Eamonn22 reputationPosted Jul 28, 2009, 12:57 AM EDT
In the first case, the field i is intiialized and assigned a value immediately when the class X is initialized, and before the constructor is called.
In the second case, the field i is initialized immediately, but gets a value assigend to it in the constructor.
The difference is the timing of assigning the value to the field i.
Allen sabuhi5 reputationPosted Jul 28, 2009, 5:51 PM EDT
Eamonn22 reputationPosted Jul 29, 2009, 1:44 AM EDT
Initializing the field declaration means that you will never be surprised by an uninitialized variable.
If you have multiple overloaded constructors, and require the same initial value no matter which constructor is called, then it is probably easier and safer to initialize in the declaration.
There is really no rule on how to do this, some developers have a preference, and some argue that in C# it is better not to initialize a field until first use (I disagree by the way, I prefer my variables to be properly initialized), so I guess it really is your own personal choice.
Allen sabuhi5 reputationPosted Jul 30, 2009, 7:26 PM EDT