Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can extensions methods be called on no-object?

Why does the following piece of code work?

call:

SomeObject sO = null;
bool test = sO.TestNull();

code:

public static bool TestNull(this SomeObject sO)
{
    return sO == null;
}

Is this allowed to work or just a bug?

like image 906
Offler Avatar asked Nov 28 '13 12:11

Offler


2 Answers

Is this allowed to work or just a bug?

The code after you've edited the question (to call s0.TestNull() instead of null.TestNull() is meant to work, yes.

Extension methods are just syntactic sugar for calling static methods as if they're instance methods. So a call of:

s0.TestNull()

is converted into

ClassContainingExtensionMethod.TestNull(s0)

... and that's all. No nullity checks are performed automatically.

This can actually be really useful - imagine if string.IsNullOrEmpty had been an extension method - then instead of writing:

if (string.IsNullOrEmpty(foo))

you could write the more readable:

if (foo.IsNullOrEmpty())

However, this power should not be taken lightly - most extension methods should throw ArgumentNullException if the first parameter has a null value, and those which don't should be very clear about it. (It should be relatively rare for such a method not to include Null somewhere in the name.)

like image 104
Jon Skeet Avatar answered Oct 29 '22 07:10

Jon Skeet


Assuming you meant

bool test = sO.TestNull();

Then the answer is just that static functions do not need an instance of the object. Also, calling an extension function is just syntactic sugar for calling the function with parameters.

edit:

I recommend also reading Jon Skeet's answer.

like image 6
David S. Avatar answered Oct 29 '22 07:10

David S.