Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why allow extension methods on null objects?

what is the point of allowing invocation of extension methods on null objects? this is making me unnecessarily check for a null object in the extension method. AFAIK,i can't understand this? Please explain.

like image 851
Srinivas Reddy Thatiparthy Avatar asked Mar 28 '11 13:03

Srinivas Reddy Thatiparthy


2 Answers

Extension methods are syntactic sugar of the C# language, they get compiled to normal static method calls in ILCode. A static method doesn't know anything about the parameters at compile time.

like image 164
Femaref Avatar answered Oct 12 '22 16:10

Femaref


Simply put, why not?

You can sometimes skip the test if the first method you call within the extension would also throw the correct error.

You're essentially asking for the code to be different so that:

  1. Uses which are reasonable on a null object, become disallowed.
  2. Uses which don't need a null check (because it's implicit in something else) get the overhead of the needless check you want to happen automatically.

This seems a lot of an imposition on other uses just to save the one line of:

if(arg == null)throw new ArgumentNullException();
like image 45
Jon Hanna Avatar answered Oct 12 '22 15:10

Jon Hanna