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?
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.
In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With