Reputation: 2243
In Visual Studio 2012 i have this simple example here:
and when i debug the code and move my cursor over i
to get it's current value, i expect something like
Use of unassigned local variable
but there is a 0
which was not set - why is there a 0
?
Upvotes: 1
Views: 155
Reputation: 29036
When you declare any local/block variable, they didn’t get the default values. They must assigned some value before accessing it other wise compiler will throw an error. If the variable has a global scope then default value can be assigned and accessed. if the variable is of reference type then the default value will be null
. this link contains default values for the primitive datatype:
The compiler will not permit this(since it is local/block variable):
public static void samplemethod()
{
int a;
int b = a;
}
where as the following code works fine since the variable have global scope:
public int i;
public void samplemethod()
{
int a;
int b = i;
}
Upvotes: 1
Reputation: 2179
That's because int is a Value Type not a Reference Type.
MSDN :
Variables that are based on value types directly contain values. Assigning one value type variable to another copies the contained value. This differs from the assignment of reference type variables, which copies a reference to the object but not the object itself.
Have a look at Value Types and Reference Types.
I hope it turns out to be helpful.
Upvotes: 1