Friday, January 18, 2008

Calling Methods on a Null Reference???

Is it really possible to call a method of a reference pointing to null?

Take a look at this piece of code:

static void Main ( )
MySecondType myObject = null;
myObject = myObject.Parse("10");

Is it possible to make it actually run and not generate a 'null reference' exception?

Well, as long as you're using .NET 3.5 - it is! :)

The idea is to declare the Parse method as an extension method operating on objects of type MySecondType:

static class MySecondTypeExtensions
public static MySecondType Parse ( this MySecondType me, string text )
Int32 value = Int32.Parse(text);
return new MySecondType(value);


As you can see - it does not matter if me points to null - since the method operates on the text parameter only!

So - nothing makes it illegal to call it on myObject - even though myObject point to null :)

The broader context is here:
Inferred Typing with Factory Methods as Extension Methods

No comments: