Is it possible to call extension methods without an object?

Why does the following code snippet work?

call:

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

code:

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

Is it allowed to work or just a mistake?

+6
source share
4 answers

Assuming you meant

 bool test = sO.TestNull(); 

Then the answer lies only in the fact that static functions do not require an instance of the object. In addition, calling an extension function is just syntactic sugar for calling a function with parameters.

edit:

I also recommend reading John Skeet's answer .

+6
source

Is it allowed to work or just a mistake?

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

Extension methods are just syntactic sugar for invoking static methods, as if they were instance methods. So the call:

 s0.TestNull() 

converted to

 ClassContainingExtensionMethod.TestNull(s0) 

... and that’s it. No validation checks are performed automatically.

It really can be really useful - imagine string.IsNullOrEmpty was an extension method - instead:

 if (string.IsNullOrEmpty(foo)) 

you can write more readable:

 if (foo.IsNullOrEmpty()) 

However, this force should not be taken lightly - most extension methods should throw an ArgumentNullException if the first parameter is zero, and those that do not should be very clear. (For such a method, it should be relatively rare not to include Null somewhere in the name.)

+13
source

The code should be bool test = sO.TestNull(); . And yes, that should work.

You extend the object with a function, it doesn't matter if the object is null or contains a value. This is essentially the same as writing SomeStaticClass.TestNull(sO);

+4
source

As John and others have already noted, this is standard behavior. It may be useful for

  • Extension methods that trigger events and check for invalidation before doing so
  • Extension methods that Maybes chains provide, where each part of the chain can be null.

I thought for a long time that it is normal to send messages to null links , but time has shown that it is quite pragmatic and useful, especially considering the fact that null links simply do not exist in other languages.

+2
source

Source: https://habr.com/ru/post/958986/


All Articles