0

I have an extension method called ParseItemsToIntegers which is an extension method of an array of strings, and I'm using it like any extension would be used.

var ids = ChkBoxSelected.ParseItemsToIntegers();

The behavior I've observed is that, if ChkBoxSelected is null, it will call the extension method without a problem, but then in side the extension method it throws a null reference exception on the null string array.

How was it able to resolve the extension method on the null?

Why did it not throw a null reference exception on ChkBoxSelected when I called the extension method?

tdbeckett
  • 618
  • 8
  • 19
  • Try { ... if (return == null) { return -1 } } Catch { return -1 } – Dieter B Oct 16 '15 at 20:44
  • No I get that Dieter B. I curious as to why it doesn't throw the null reference at the top level. How does it get into the extension method on a null object? – tdbeckett Oct 16 '15 at 20:45
  • Because it searches for the extension method on the type, not the object itself. – Ron Beyer Oct 16 '15 at 20:45
  • 2
    Extension methods are really just static method calls. Whatever object you 'call them on' is just passed as the first argument. – Pieter Witvoet Oct 16 '15 at 20:46

3 Answers3

6

It doesn't throw a NRE because extension methods aren't instance methods, regardless of how much they appear to be instance methods. As is made clear when you're defining the method, it's actually a static method. A NRE isn't thrown when you pass a null value as the first argument to a static method, it just passes in a null value and that static method can do whatever it wants with it.

Servy
  • 202,030
  • 26
  • 332
  • 449
3

Calling the extension method ChkBoxSelected.ParseItemsToIntegers() is equivalent to calling it using regular static method syntax ParseItemsToIntegers(ChkBoxSelected). The type of ChkBoxSelected is known at compile time, so the compiler can resolve the method.

The NullReferenceException is thrown inside the method it tries to use the ChkBoxSelected.

When calling an instance method, the NullReferenceException is thrown immediately because the CLR checks the actual type of the object to choose correct polymorphic call (even non-virtual methods are called like that).

Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
2

Extension methods are just syntactic sugar for a more explicit static method call.

So your code which might appear to be (it's not)

null.ParseItemsToIntegers();

is really being called like

StaticClass.ParseItemsToIntegers(null);

The null reference is just a parameter, which is perfectly fine accepting null as a value (since it's a legal value for a reference type). Somewhere inside your actual method, it's presumably expecting a non-null array, and that throws an NPE then.

ryanyuyu
  • 6,366
  • 10
  • 48
  • 53