Is it allowed to work or just a mistake?
The code after you edited the question (to call s0.TestNull() instead of null.TestNull() should work, yes.
Extension methods are just syntactic sugar for invoking static methods, as if they were instance methods. So the call:
s0.TestNull()
converted to
ClassContainingExtensionMethod.TestNull(s0)
... and thatβs it. No validation checks are performed automatically.
It really can be really useful - imagine string.IsNullOrEmpty was an extension method - instead:
if (string.IsNullOrEmpty(foo))
you can write more readable:
if (foo.IsNullOrEmpty())
However, this force should not be taken lightly - most extension methods should throw an ArgumentNullException if the first parameter is zero, and those that do not should be very clear. (For such a method, it should be relatively rare not to include Null somewhere in the name.)
source share