How will you make it if you never even try?

April 2, 2009

C# Delights: Extension methods can be called on null references (and that’s extremely useful)

Filed under: C# — Tags: , , , — charlieflowers @ 12:42 am

Did you know that C# extension methods can be called on null references?? Yes, they can. For example, the following method …

public static void PrintToConsole(this string self)
{
   if(self != null)
      Console.WriteLine("The string is: " + self);
   else
      Console.WriteLine("The string is NULL.");
}

… can be called as follows:

string someString = null;

someString.PrintToConsole();

The output would be:
The string is NULL.

Is this just a gimmick? You might think so at first blush, but it is actually remarkably useful. I’ll write another post soon giving some examples of when it is useful. Here’s one hint: imagine a case where you don’t want the overhead of instantiating objects unless you’re in an unusual situation. (OK, here’s another hint … what if you want to write code that applies business logic to non-null values, but seamlessly ignores nulls, so that the code doesn’t have to be all cluttered up with null checks).

Advertisements

1 Comment »

  1. […] Parameter Validation Filed under: Uncategorized — charlieflowers @ 2:56 am In a recent post, I pointed out that extension methods can be called on null references. For example, this works […]

    Pingback by Example where calling Extension Methods on null references is useful: Parameter Validation « Blog of Charlie Flowers in Atlanta — April 2, 2009 @ 2:56 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: