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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…