I am a C# newbie. I have noticed that when a local integer variable is declared without an initial value that zero is not automatically assigned as the value. Aren't variables initialised with the same default values in C# as VB?
Printable View
I am a C# newbie. I have noticed that when a local integer variable is declared without an initial value that zero is not automatically assigned as the value. Aren't variables initialised with the same default values in C# as VB?
http://msdn2.microsoft.com/en-us/lib...ch(VS.80).aspx
If you write code that tries to access a variable that might not yet have been assigned to, the compiler will throw an error.
You should always assign a default value when declaring a variable, and only declare variables when you have a meaningful value to give them.
This is curious. I was working with a C# 2003 project when I experienced this problem. A locally declared integer was initialised with a value like 126573. I converted the project to C# 2005 and the same variable was initialised to zero.
You should NEVER rely on a default value even if one is provide. If you want a variable to have a value then you should assign that value to it. No variable should EVER appear on the right hand side of an assignment before it has appeared on the left, i.e. NEVER use a variable's value without assigning that value first. Even if this is not enforced by the compiler it's just plain coding practice. If you use the value of a variable without first assigning a value, how does someone looking at the code later know whether you just forgot to assign a value or not?
I suspect you may be seeing a quirk of the IDE.Quote:
Originally Posted by robertx
Uninitialised variables have an undefined value and so, to prevent strange behaviour, you cannot read from them.
Spot on.
The declaration looked like this:
int i=-1,j, k-1;
j was assigned the value 1245396 was I was unable to assign it to another variable.
Eg. The project would not build if I tried to assign j to i as follows:
int i=-1,j, k-1;
i = j;
This behaviour is different in VB where zero is assigned and the variable can be used. Despite this, I have got into the habit of assigning a value to all primitives.