Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixing the 'Use of unassigned local variable' with a null assignment. Why?

With a piece of code like this, the compiler complains on c.MyProperty:

MyClass c;  try { throw new Exception(); } catch (Exception) { }  c.MyProperty = 2; // "Use of unassigned local variable 'c'". 

Yet it doesn't complain if you assign a null to c in initialization:

MyClass c = null;  try { throw new Exception(); } catch (Exception) { }  c.MyProperty = 2; // no complains this time. 

So, why does this work? If c wasn't assigned a null and the compiler hypothetically allowed it, wouldn't the same exception be thrown at c.MyProperty, Object reference not set to an instance of an object?

like image 727
Andreas Grech Avatar asked Jun 02 '11 10:06

Andreas Grech


People also ask

What is the error use of an unassigned local variable in c#?

The CS0165 error is caused when a variable created within a method is not assigned with a value using the new keyword. The error CS0165 is resolved by assigning the local variable with a new instance of it's type or as a reference to a variable of the same type.

What is unassigned variable?

In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used.


1 Answers

When you assign null to the variable you're telling the compiler to back off because you know better than him so he should not complain about this.

This is probably due to the fact that assigning null is considered to imply an explicit action by the developer.

like image 105
João Angelo Avatar answered Oct 13 '22 14:10

João Angelo