I recently asked this question on the subject, which was closed as a duplicate of this one – as was this one before mine. However, I want to ask a more specific question on a corner case that I feel none of the above questions, or their answers, really covers:
How should an extension method that doesn’t really need an instance react to null references?
An example (where the answer is obvious) would be the .IsNullOrEmpty() (which of course should just return true on a null reference), but I believe there might be other cases where it makes sense to call an extension method on an object that might be null.
Another example could be a variation of the method I outlined in my other question, if we for a minute assume that the foreach loop will not throw on a null collection (I know it does, but imagine it doesn’t just as a thought experiment).
What would be best practice here? Should we check for null and throw ArgumentNullException anyway, or does it depend on the case? If it does depend on the case, on what criteria should we decide what to do?
Personally, I have an issue with extension methods that do not throw on a null instance. I understand that extension methods are syntactic sugar for static methods. However, their use is like that of an instance method. Hence, I believe they should behave as if they were an instance method and throw when the “this” instance is null.
This is a maintainability concern for me. For a newcomer to a code base who does not know whether a method is on the actual type or is an extension method, seeing a method like IsNull() would be disconcerting because it simply doesn’t make any sense.
So, that is my two cents: a complete utter personal opinion.