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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With