Extension methods are magic - they only look like instance methods, but given the extension method:
public static class StaticClass { public static void MyMethod(this SomeType obj)
then
instance.MyMethod();
compiles:
StaticClass.MyMethod(instance);
And you would not expect to throw a NullReferenceException - and it really is not.
It is two way. On some levels, this is confusing, but can be very useful. It would be good practice to add your own null-ref check at the beginning if you have no reason to allow null. Another useful option:
public static void ThrowIfNull<T>(T value, string name) where T : class { if(value==null) throw new ArgumentNullException(name); } ... void SomeUnrelatedMethod(string arg) { arg.ThrowIfNull("arg"); }
source share