1

In Visual Studio 2012 i have this simple example here:

enter image description 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?

Byyo
  • 2,163
  • 4
  • 21
  • 35
  • 1
    possible duplicate of [Value of unassigned non-nullable variable (C#)](http://stackoverflow.com/questions/2929257/value-of-unassigned-non-nullable-variable-c) – Kamil Budziewski Aug 31 '15 at 11:42
  • @wudzik - ok let's say this variable has value `0` .. why can't i use it? – Byyo Aug 31 '15 at 11:47
  • http://stackoverflow.com/a/9233156/1714342 – Kamil Budziewski Aug 31 '15 at 11:48
  • why -1? did i anything wrong? – Byyo Aug 31 '15 at 13:58
  • It seems to me like people aren't understanding that this question's about why the debugger **can** tell you "the value", not about why you can't use it. Maybe they think that the quoted text is an error message you're receiving, and skip the rest of the text... I'm not sure at first glance what you could have done to prevent that. Edit: After looking for a sec, the visual studio and debugger tags instead of "variables" would probably be better. And maybe it's possible to put "debugger shows me" in the question body more often. – 31eee384 Aug 31 '15 at 14:23

2 Answers2

1

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.

Mohammad Chamanpara
  • 2,049
  • 1
  • 15
  • 23
1

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;
        }
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88