views:

56

answers:

3
public static IFoo Bar<T>(this IFoo target, ...)
{
   // I'm curious about how useful this check is.
   if (target == null) throw new ArgumentNullException("target");

   ...
}

(1) The code above seems strange to me because I feel like in any case the calling code would be the one to check that. Is there some subtlety to extension methods in this area that applies?

(2) Is there a legitimate pattern that leverages the fact that the target can be null? I ask this as a consequence of wondering why calling an extension method on a null reference wouldn't generate the runtime exception the same way as if you called an instance method on a null reference.

+3  A: 

Consider that null can be an argument to a method. Consider also that the extension method foo.Bar<int>(); is really just syntactic sugar for IFooExtensions.Bar<int>(foo); and you will see that, yes, the argument can indeed be null so if you're doing something with the argument, it may certainly be appropriate to test it for null (or simply let a NullReferenceException be thrown, take your pick).

Note: You would not get an exception merely by calling it with a null referenced object, because remember that the method does not actually belong to the object. You only get the exception if (a) you purposefully throw one yourself or (b) the method body actually causes it by trying to work with the instance that is null.

Anthony Pegram
+1  A: 

Since extension methods really are only syntactic sugar for calling a static method with the object as the first parameter, I don't see why null for this parameter value shouldn't be allowed.

BrokenGlass
true but aren't classes syntactic sugar for defining a set of static methods that take a struct containing the instance members?
Gabriel
you could consider it as part of the contract of those methods though that they do have access to the data members defined by that struct, the same cannot necessarily be said about extension methods.
BrokenGlass
A: 

(2) Is there a legitimate pattern that leverages the fact that the target can be null? I ask this as a consequence of wondering why calling an extension method on a null reference wouldn't generate the runtime exception the same way as if you called an instance method on a null reference.

Well, here's one use of it.

public static class UtilityExtensions
{
    public static void ThrowIfNull( this object obj, string argName )
    {
        if ( obj == null )
        {
            throw new ArgumentNullException( argName );
        }
    }
}

Now you can write null checks easily and on one line (helpful if your coding convention forces you to use braces with all if statements).

public void Foo(string bar)
{
    bar.ThrowIfNull("bar");
    // ...
}

Whether or not you consider that a "legitimate" pattern is up to you, but I'd be very sad if the runtime was changed to make extension method invocations on null references throw exceptions.

Greg Najda