Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, what happens when you call an extension method on a null object?

Does the method get called with a null value or does it give a null reference exception?

MyObject myObject = null; myObject.MyExtensionMethod(); // <-- is this a null reference exception? 

If this is the case I will never need to check my 'this' parameter for null?

like image 371
tpower Avatar asked May 11 '09 08:05

tpower


People also ask

What does << mean in C?

<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .

What is && operator in C?

The && (logical AND) operator indicates whether both operands are true. If both operands have nonzero values, the result has the value 1 . Otherwise, the result has the value 0 . The type of the result is int . Both operands must have an arithmetic or pointer type.


2 Answers

That will work fine (no exception). Extension methods don't use virtual calls (i.e. it uses the "call" il instruction, not "callvirt") so there is no null check unless you write it yourself in the extension method. This is actually useful in a few cases:

public static bool IsNullOrEmpty(this string value) {     return string.IsNullOrEmpty(value); } public static void ThrowIfNull<T>(this T obj, string parameterName)         where T : class {     if(obj == null) throw new ArgumentNullException(parameterName); } 

etc

Fundamentally, calls to static calls are very literal - i.e.

string s = ... if(s.IsNullOrEmpty()) {...} 

becomes:

string s = ... if(YourExtensionClass.IsNullOrEmpty(s)) {...} 

where there is obviously no null check.

like image 184
Marc Gravell Avatar answered Sep 22 '22 21:09

Marc Gravell


Addition to the correct answer from Marc Gravell.

You could get a warning from the compiler if it is obvious that the this argument is null:

default(string).MyExtension(); 

Works well at runtime, but produces the warning "Expression will always cause a System.NullReferenceException, because the default value of string is null".

like image 25
Stefan Steinegger Avatar answered Sep 18 '22 21:09

Stefan Steinegger