1

During the declaration of local variables, they are stored on the stack and memory is also allocated the same time. In case of int, it takes its default value 0.

And MSDN states "uninitialized variables in C# is not allowed" and so it takes its default value. 0 as in case of an int.

But if I write a code like int a; int b=a; I will get an error like "use of unassigned local variable a". In this case why is it not taking the default value 0?

D Stanley
  • 149,601
  • 11
  • 178
  • 240
Vishnu Y
  • 2,211
  • 4
  • 25
  • 38
  • "use of unassigned local variable a" is probably a warning unless you have set it to show as an error. – ckv Jul 07 '14 at 12:44
  • @ckv no it is an [error](http://msdn.microsoft.com/en-us/library/4y7h161d.aspx) – Selman Genç Jul 07 '14 at 12:46
  • why do you use int b = a if you want b to be default? – Yaugen Vlasau Jul 07 '14 at 12:46
  • 2
    Please show *exactly* which bit of MSDN you're referring to. I think you're talking about fields, not local variables. Local variables do *not* get default values. – Jon Skeet Jul 07 '14 at 12:48
  • 1
    Variables must always be initialized, hence the error. Properties, however, do not need to be. An uninitialized integer property will not complain when accessed, and will simply return the default 0 as you expect. – JW Lim Jul 07 '14 at 12:48
  • Have a look at this [similar question](http://stackoverflow.com/questions/9233000/why-compile-error-use-of-unassigned-local-variable) – Adrian Fâciu Jul 07 '14 at 12:49
  • @YaugenVlasau I simply wrote the code to explain the scenario more clearly. If int a has default value 0 and if MSDN tells like "uninitialized variables in C# is not allowed", why we are getting an error for the statement int b=a;? Why its not taking the default value 0? – Vishnu Y Jul 07 '14 at 12:49
  • If you people write a method and inside that write int a; When debugging you can see its value as 0. Then why a manual initialization is needed to use that variable? – Vishnu Y Jul 07 '14 at 12:53
  • 2
    @VishnuY : Because that's how the compiler is written. In purest technical terms, it might not be necessary, but the compiler won't let you. Why? Because that's how it is. It prevents a whole bunch of bugs that might otherwise slip through the net. – spender Jul 07 '14 at 13:01
  • you are right the compiler gives you that error. so you have no options rather then assign a. for example: int a = default(int); – Yaugen Vlasau Jul 07 '14 at 13:24

0 Answers0