Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 :)

like image 641
MattDavey Avatar asked Jan 25 '11 10:01

MattDavey


1 Answers

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.

like image 67
LukeH Avatar answered Oct 12 '22 15:10

LukeH