Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null target of extension method

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.

like image 868
Aaron Anodide Avatar asked Dec 29 '22 06:12

Aaron Anodide


1 Answers

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.

like image 83
Anthony Pegram Avatar answered Jan 12 '23 14:01

Anthony Pegram