.ToString() does not raise an exception on double? or long? while it will raise an exception on null string

I have three properties as follow:-

public Nullable<double> SPEED { get; set; }
public Nullable<Int64> PROCESSORCOUNT { get; set; }
public string CPUNAME { get; set; }

now inside my asp.net mvc5 web application's controller class, if i pass null for the above three variables, as follow:-

query["proSpeed"] = sj.SPEED.ToString();
query["proCores"] = sj.PROCESSORCOUNT.ToString();
query["proType"] = sj.CPUNAME.ToString();

then the toString() will only raise an exception on the null string mainly sj.CPUNAME.ToString();, so can anyone adivce why ToString() will not raise an exception if i try to convert double? or long? that contain null values to string, but it will raise a null reference exception only if the string is null ?

Jon Skeet
people
quotationmark

To simplify it:

int? x = null;
string result = x.ToString(); // No exception

Here null isn't a null reference. It's just a null value of the type int?, i.e. a value of type Nullable<int> where HasValue is false.

You're just invoking the Nullable<T>.ToString() method on that value. No null references are involved, so there's no NullReferenceException. The behaviour is documented as:

The text representation of the value of the current Nullable<T> object if the HasValue property is true, or an empty string ("") if the HasValue property is false.

In other words, it's effectively implemented as:

return HasValue ? Value.ToString() : "";

Note that this only works if the compile-time type is the nullable type.

If you end up boxing a null value, you'll end up with a null reference:

object y = x;               // Oh noes, now y is a null reference...
string bang = y.ToString(); // so this throws!

people

See more on this question at Stackoverflow