why allow extension methods on null objects?

2019-04-18 15:15发布

what is the point of allowing invocation of extension methods on null objects? this is making me unnecessarily check for a null object in the extension method. AFAIK,i can't understand this? Please explain.

7条回答
【Aperson】
2楼-- · 2019-04-18 15:40

Sometimes, allowing the extension method to be called on a null object simplifies your code by allowing you to move the null check into the method instead at the call site. For example, you may have an extension method that returns a List<T>, but if called on a null object, returns an empty List<T>.

查看更多
虎瘦雄心在
3楼-- · 2019-04-18 15:41

Extension methods are just static methods:

List<int> x = null;
x.Count()

Is equivalent to:

List<int> x = null;
System.Linq.EnumerableExtensions.Count(x); 
//EnumerableExtensions may not be the class, but you get the idea
查看更多
做自己的国王
4楼-- · 2019-04-18 15:44
  1. Extension methods are transformed to static method invocations so the code will still need to check for null arguments as there is no way to avoid the static method to be called normally without the extension method syntactic sugar.
  2. Adding something like a check followed by a NullArgumentException could take execution time and the user may want to assert instead or use something else.
  3. It would make the replacement more complex to explain or do automatically as the simple replacement of the extension method with the corresponding static method call will change the behavior of the code.
  4. There are legitimate case where you want to allow null arguments (for exemple conversions from an object model to another where a null object of one type is converted to a null object of the second type)
查看更多
甜甜的少女心
5楼-- · 2019-04-18 15:49

Another beautiful example that wouldn't be possible otherwise:

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

So you can use

string s = null;
if (s.IsNullOrEmpty()) // no null reference error!
    ...

Instead of

string s = null;
if (string.IsNullOrEmpty(s))
    ....
查看更多
我想做一个坏孩纸
6楼-- · 2019-04-18 15:52

Simply put, why not?

You can sometimes skip the test if the first method you call within the extension would also throw the correct error.

You're essentially asking for the code to be different so that:

  1. Uses which are reasonable on a null object, become disallowed.
  2. Uses which don't need a null check (because it's implicit in something else) get the overhead of the needless check you want to happen automatically.

This seems a lot of an imposition on other uses just to save the one line of:

if(arg == null)throw new ArgumentNullException();
查看更多
爷、活的狠高调
7楼-- · 2019-04-18 15:59

Extension methods are syntactic sugar of the C# language, they get compiled to normal static method calls in ILCode. A static method doesn't know anything about the parameters at compile time.

查看更多
登录 后发表回答