Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect nullable type

Tags:

c#

nullable

Is it possible to detect a Nullable type (cast into an object) when it is null?

Since Nullable<T> is really a struct I think it should be possible.

double? d = null;
var s = GetValue(d); //I want this to return "0" rather than ""

public string GetValue(object o)
{
    if(o is double? && !((double?)o).HasValue) //Not working with null
       return "0";
    if(o == null)
       return "";
    return o.ToString();
}  
like image 214
Magnus Avatar asked Nov 24 '25 09:11

Magnus


1 Answers

http://msdn.microsoft.com/en-us/library/ms228597(v=vs.80).aspx

Objects based on nullable types are only boxed if the object is non-null. If HasValue is false, then, instead of boxing, the object reference is simply assigned to null.

and

If the object is non-null -- if HasValue is true -- then boxing takes place, but only the underlying type that the nullable object is based upon is boxed.

So you either have a double or a null.

public string GetValue(object o)
{
    if(o == null) // will catch double? set to null
       return "";

    if(o is double) // will catch double? with a value
       return "0";

    return o.ToString();
} 
like image 192
xanatos Avatar answered Nov 26 '25 23:11

xanatos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!