Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Life after Death: Nullified Reference Looks Still Active

4.80/5 (19 votes)
21 Apr 2014CPOL 22.2K   1  
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):

C#
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:

C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)