Sunday, September 7, 2008

NullReferenceException and Extention Methods

Where does this test fail:


   29         [TestMethod]


   30         public void TestMethod1()


   31         {


   32             Foo a = null;


   33             Assert.AreEqual("a", a.DoIt());


   34             Assert.AreEqual("a", a.ToString());


   35         }


Line 33 or 34?  Or can't you tell?

You can't tell, if DoIt is defined as a member function, then it fails on 33.  But if DoIt is an extension method then it fails on line 34.

This makes sense if you remember that extension methods are just syntactic sugar and really it gets compiled into function calls to the static function so you don't actually need to have a reference to the real object.

0 comments: