Is it necessary to throw a NullReferenceException from an extension method? [duplicate]

回眸只為那壹抹淺笑 提交于 2019-11-28 04:18:44

问题


This question already has an answer here:

  • ArgumentNullException or NullReferenceException from extension method? 5 answers

If I define an extension method such as this:

static public String ToTitleCase(this string instance, CultureInfo culture)
{
    if (instance == null)
        throw new NullReferenceException();

    if (culture == null)
        throw new ArgumentNullException("culture");

    return culture.TextInfo.ToTitleCase(instance);
}

Is it necessary for me to check the string instance for null and throw an null reference exception myself? Or does the CLR treat extension methods like instance methods in this case and handle the checking/throwing for me?

I know extension methods are just syntactic sugar for static methods, perhaps the C# compiler adds in the check at compile time? Please clarify :)


回答1:


No. You should never throw a NullReferenceException manually. It should only ever be thrown by the framework itself.

In this context, you should be throwing ArgumentNullException for both instance and culture:

static public String ToTitleCase(this string instance, CultureInfo culture)
{
    if (instance == null)
        throw new ArgumentNullException("instance");

    if (culture == null)
        throw new ArgumentNullException("culture");

   return culture.TextInfo.ToTitleCase(instance);
}

From the NullReferenceException documentation:

Note that applications throw the ArgumentNullException exception rather than the NullReferenceException exception discussed here.




回答2:


It most certainly is not. However, "fail fast" and, what some people forget ... "fail helpfully". However, I believe the reasons for not throwing an ArgumentNullException (debate vs. NullReferenceException left to other posts) are limited and usually related to over-cleverness :-) One hypothetical use-case may be IsNullOrEmpty. As long as it actually serves a purpose and makes code cleaner: go for it.

There is no check from the CLR. As far as the runtime is concerned it just passed a (possibly null) argument to a static method. The rest is sugar -- and none of that sugar involves adding extra null checks :-)

Happy coding.



来源:https://stackoverflow.com/questions/4792275/is-it-necessary-to-throw-a-nullreferenceexception-from-an-extension-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!