Register | Login 
Forum  
SearchForum Home
     
  Discussions  Development Topics  Extension Metho...
 Extension Methods and Nulls
 
 1/7/2008 5:20:01 PM
AlGonzalez
85 posts
nomadicview.blogspot.com/


Extension Methods and Nulls
Just a heads up that even though extension methods will make it appear as if the object being extended has a new method, it is just syntactic sugar that is being converted to a function call that takes the object instance as the first parameter.

One noteable gotcha is if your object is null, the extension method is still called while on a true method you'll get a NullReferenceException.

Here is a simple (and fairly useless) extension method for a string:
    static class StringExtensions
{
public static string BracketSelf(this string instance)
{
return "[" + instance + "]";
}
}

Here is an example calling the method:
    string s = "Text";
Console.WriteLine(s.BracketSelf());
// this should output [Text]

Now for the gotcha:
    string s = null;
Console.WriteLine(s.BracketSelf());
// this should output []
Console.WriteLine(s.ToLower());
// this should throw a NullReferenceException

Note that on a true a method like ToLower you get an exception but on an extension method you do not.

So in order to have the extension method act more like a true method you need to test first parameter for null and throw a NullReferenceException if it is.

Here is the extension method doing just that:
    static class StringExtensions
{
public static string BracketSelf(this string instance)
{
if (instance == null) throw new NullReferenceException();
return "[" + instance + "]";
}
}


Al Gonzalez
P.S. Solutions, Inc.
http://www.linkedin.com/in/algonzalez
 1/7/2008 5:30:45 PM
AlGonzalez
85 posts
nomadicview.blogspot.com/


Re: Extension Methods and Nulls
After reading my own post, I just wanted to clarify that this isn't so much a "gotcha" as behavior difference that you should be aware of when using Extension Methods.
Al Gonzalez
P.S. Solutions, Inc.
http://www.linkedin.com/in/algonzalez
 1/12/2008 12:41:02 PM
AlGonzalez
85 posts
nomadicview.blogspot.com/


Re: Extension Methods and Nulls
On the plus side, this lets you write extension methods like the following:

    public static bool IsNull(this object instance) {
return instance == null;
}

This extension method allows you have any reference value test itself for null like this:
    string s = null;
Console.WriteLine(s.IsNull());
// this should output true
s = "Some Text";
Console.WriteLine(s.IsNull());
// this should output false

Al Gonzalez
P.S. Solutions, Inc.
http://www.linkedin.com/in/algonzalez
  Discussions  Development Topics  Extension Metho...

Copyright (c) 2008 GSP Developers
Walling Info Systems | Terms Of Use | Privacy Statement