How does it work (static extension?)

I saw this in Mark Gravell’s answer, and I just don’t understand how this will work

static bool IsNullOrEmpty(this string value) { return string.IsNullOrEmpty(value); } 

Shouldn't you call s.IsNullOrEmpty (), where s is null, and then return a NullReferenceException? How can you remove an object reference to call the function defined here if the object is null?

Or is it some way to bypass monkey static function?

+4
source share
2 answers

Extension methods are magic - they only look like instance methods, but given the extension method:

 public static class StaticClass { public static void MyMethod(this SomeType obj) // note "this" {...} } 

then

 instance.MyMethod(); 

compiles:

 StaticClass.MyMethod(instance); 

And you would not expect to throw a NullReferenceException - and it really is not.

It is two way. On some levels, this is confusing, but can be very useful. It would be good practice to add your own null-ref check at the beginning if you have no reason to allow null. Another useful option:

 public static void ThrowIfNull<T>(T value, string name) where T : class { if(value==null) throw new ArgumentNullException(name); } ... void SomeUnrelatedMethod(string arg) { arg.ThrowIfNull("arg"); } 
+12
source

Extension methods can be called using null values. Call:

 bool x = foo.IsNullOrEmpty(); 

just translated at compile time to

 bool x = ExtensionClass.IsNullOrEmpty(foo); 

No validation is performed implicitly. This is a very simple syntactic sugar, basically.

While this is strange, when you first see it, it is very convenient for tests in the same way. I also have an extension method that I like to check for parameters:

 x.ThrowIfNull(); 

which throws an ArgumentNullException if x is null.

+2
source

All Articles