HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
objectyouextensionhappensmethodwhencallwhatnull

Problem

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?

Solution

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(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.

Code Snippets

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);
}
string s = ...
if(s.IsNullOrEmpty()) {...}
string s = ...
if(YourExtensionClass.IsNullOrEmpty(s)) {...}

Context

Stack Overflow Q#847209, score: 480

Revisions (0)

No revisions yet.