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;
}
}
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
EamonnPosted Jul 28, 2009, 4:57 AM
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 sabuhiPosted Jul 30, 2009, 11:26 PM
EamonnPosted Jul 29, 2009, 5:44 AM
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 sabuhiPosted Jul 28, 2009, 9:51 PM