Can anyone help me to clarify this doubt why j is not initialized in if block?


namespace consoleapplication3 { class program { static void main(string[] args) { int = 10; int j; // int j=10; got output 20 in console app if j declaring here , initializing - if (a == 10) //- in if block not getting output 20 why? { j = 20; } console.writeline(j);

/*here not getting output instead of error coming use of unassigned local variable 'j' */

console.readline(); } } }


while clear inspection j assigned value of 20 in if block, bit irrelevant error, couple of reasons.

the short answer c# language rules require j unconditionally assigned value before use it.  clearly in case j assigned value conditionally (the fact condition true not relevant language rules

another reason code flow analysis required determine j=20 line hit.  however code flow analysis done after code has been parsed , after cil has been generated, , long after uninitialized variable error has been generated.

finally, users find confusing changing line 

int = 10;

to

int = 9; 

would result in compile error 6 lines later.




Visual Studio Languages  ,  .NET Framework  >  Visual C#



Comments

Popular posts from this blog

Azure DocumentDB Owner resource does not exist

BizTalk Server 2013 Azure VM Log Shipping and HA for hosts

How to Share webservice object to all user