Alexander Nagirnyak Alexander Nagirnyak - 1 month ago 6
C# Question

How to check if boxed value is empty in .NET

For example,

I have input parameter of type

object
. And I know that this parameter can store one of value type
int, float, double
(boxed value) etc. But I don't know which value type will come to this method. And I want check if boxed value type empty or not.

Like this piece of code:

bool IsEmpty(object boxedProperty)
{
return boxedProperty == default(typeof(boxedProperty))
}


I understand, I can do this:

bool IsEmpty(object boxedProperty)
{
return boxedProperty is int && boxedProperty == default(int)
|| boxedProperty is float ....
}


But it looks like dirty solution. How do this better?

Answer

I guess something like this can give you a result for reference + boxed value types.

public bool IsDefaultValue(object o)
{
    if (o == null)
        return true;

    var type = o.GetType();
    return type.IsValueType && o.Equals(Activator.CreateInstance(type));
}

object i = default(int);
object j = default(float);
object k = default(double);
object s = default(string);

object i2 = (int)2;
object s2 = (string)"asas";


var bi = IsDefaultValue(i); // true
var bj = IsDefaultValue(j); // true
var bk = IsDefaultValue(k); // true
var bs = IsDefaultValue(s); // true

var bi2 = IsDefaultValue(i2); // false
var bs2 = IsDefaultValue(s2); // false

If you are shure you have a value type, then use this method:

public bool IsDefaultBoxedValueType(object o)
{
    return o.Equals(Activator.CreateInstance(o.GetType()));
}