Do I need to throw a NullReferenceException from an extension method?

If I define an extension method, for example:

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);
}

Do I need to check the string instance for null and throw a null reference exception on my own? Or does the CLR handle extension methods, such as instance methods in this case, and handle check / throw for me?

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

+3
source share
2 answers

No. You should never throw NullReferenceExceptionby hand. It should be ever thrown by the card itself.

ArgumentNullException instance 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);
}

NullReferenceException :

, ArgumentNullException NullReferenceException .

+23

, , . " " , ... " ". , , ArgumentNullException ( NullReferenceException, ) :-) IsNullOrEmpty. : .

CLR . , (, ) . - - : -)

.

+1

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


All Articles