|
-
May 3rd, 2007, 01:09 AM
#1
Thread Starter
Frenzied Member
[2.0] Initialise Variables
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?
-
May 3rd, 2007, 01:54 AM
#2
Re: [2.0] Initialise Variables
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.
-
May 3rd, 2007, 02:04 AM
#3
Thread Starter
Frenzied Member
Re: [2.0] Initialise Variables
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.
-
May 3rd, 2007, 02:24 AM
#4
Re: [2.0] Initialise Variables
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?
-
May 3rd, 2007, 02:27 AM
#5
Re: [2.0] Initialise Variables
 Originally Posted by robertx
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.
I suspect you may be seeing a quirk of the IDE.
Uninitialised variables have an undefined value and so, to prevent strange behaviour, you cannot read from them.
-
May 3rd, 2007, 02:40 AM
#6
Thread Starter
Frenzied Member
Re: [2.0] Initialise Variables
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|