c# - .ToString() does not raise an exception on double? or long? while it will raise an exception on null string -
i have 3 properties follow:-
public nullable<double> speed { get; set; } public nullable<int64> processorcount { get; set; } public string cpuname { get; set; } now inside asp.net mvc5 web application's controller class, if pass null above 3 variables, follow:-
query["prospeed"] = sj.speed.tostring(); query["procores"] = sj.processorcount.tostring(); query["protype"] = sj.cpuname.tostring(); then tostring() raise exception on null string sj.cpuname.tostring();, can adivce why tostring() not raise exception if try convert double? or long? contain null values string, raise null reference exception if string null ?
to simplify it:
int? x = null; string result = x.tostring(); // no exception here null isn't null reference. it's null value of type int?, i.e. value of type nullable<int> hasvalue false.
you're invoking nullable<t>.tostring() method on value. no null references involved, there's no nullreferenceexception. behaviour documented as:
the text representation of value of current
nullable<t>object ifhasvalueproperty true, or empty string ("") ifhasvalueproperty false.
in other words, it's implemented as:
return hasvalue ? value.tostring() : ""; note works if compile-time type nullable type.
if end boxing null value, you'll end null reference:
object y = x; // oh noes, y null reference... string bang = y.tostring(); // throws!
Comments
Post a Comment