c# - Is it necessary to throw a NullReferenceException from an extension method? -
this question has answer here:
if define extension method such 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 necessary me check string instance null , throw null reference exception myself? or clr treat extension methods instance methods in case , handle checking/throwing me?
i know extension methods syntactic sugar static methods, perhaps c# compiler adds in check @ compile time? please clarify :)
no. should never throw nullreferenceexception
manually. should ever thrown framework itself.
in context, should throwing argumentnullexception
both 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); }
from nullreferenceexception
documentation:
note applications throw
argumentnullexception
exception rathernullreferenceexception
exception discussed here.
Comments
Post a Comment