Life after Death: Nullified Reference Looks Still Active






4.80/5 (19 votes)
After reference to instance of a class was set to null, it seemed it was still active
One morning, still drinking my usual strong black coffee I was debugging some code that seemed fairly routine. But behavior of a code fragment looking simple appeared somewhat abnormal. Soon I realized that I was dealing with something like this (after removing all irrelevant code):
var c = new C();
//...........................
c = null;
//...........................
c.Foo(); // no exception, execution goes on!
After reference to instance of a class was set to null, it seemed it was still active! And I was pretty sure that there were no tricks with regeneration on finalization.
Well, may be coffee was not strong enough. Or perhaps something wrong with my new glasses... I had repeated debugging - with the same result.
It took me some time to realize what's going on. Extension methods were added to C# for quite a time already, but not very wide spread. This is simplified code allowing the above behavior:
class C
{
//...................
}
static class CExtension
{
public static void Foo(this C c)
{
if (c == null)
return;
//...................
}
}
Such a simple explanation! I found it funny and happy to share it with you.