Tuesday, June 22, 2010

Useful Things to Know, #425

You can call an extension method on a null class instance.

For example, if you have an extension method IsEmptyOrWhitespace on the class System.String, the following code will work:

string s = null;
Debug.Writeline(s.IsEmptyOrWhitespace());

It makes sense because the string s is actually passed as a parameter to the method IsEmptyOrWhitespace.  Therefore, if you code the method correctly, it'll accommodate a null value and respond in whatever way makes sense.

It's interesting because it's a place where the facade of the extension method actually being an instance method of the class breaks down.  (But I wouldn't code on the assumption that this will always be true!)

3 Comments:

Blogger Steve said...

From what I have seen, 'most' (used loosely) people I have talked to say that passing null into an extension method should always throw a NullRef... but for String functions... it really helps a lot. +1 to you Ann!

6/29/2010 11:46 AM  
Blogger Ann said...

Oh, I would agree: in the majority of cases, throwing an exception when a null object is passed to an extension method makes sense. But it's interesting and worth knowing that the runtime itself doesn't automatically throw one.

6/29/2010 11:52 AM  
Blogger Steve said...

True that... I actually avoided that call... 'null'.ExtensionMethod for a while because of my NPE exception fear.

In reality, it's another one of the syntactic sugar calls that C# has and Java needs, along with 'var' ='''(

7/01/2010 12:32 AM  

Post a Comment

<< Home