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

Andreas Grech picture Andreas Grech · Jun 2, 2011 · Viewed 94.7k times · Source

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?

Answer

João Angelo picture João Angelo · Jun 2, 2011

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.