Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How to test whether an instance is the default value for its type

Tags:

c#

Given an instance of an unknown reference or value type, is there any way to test whether the instance contains the default value for that type? I envisage something like this ...

bool IsDefaultValue(object value)
{
    return value == default(value.GetType());
}

Of course, this doesn't work because GetType returns a runtime type, but I hope that somebody can suggest a similar technique. Thanks.

like image 771
Tim Coulter Avatar asked Oct 11 '09 14:10

Tim Coulter


1 Answers

static bool IsDefaultValue<T>(T input)
{
    return Object.Equals(input, default(T));
}

Note: you can't use == for equality using generic type T.

like image 184
Juliet Avatar answered Sep 22 '22 14:09

Juliet