Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value check using generic types [duplicate]

Tags:

c#

generics

I want to be able to check whether a value is the default for its value type. Ideally, I'd like to say:

DoSomething<TValue>(TValue value) {
    if (value == default(TValue)) {
        ...
    }
}

However, the compiler complains that it can't do a == comparison on TValue and TValue. This is the best workaround that I've come up with so far:

DoSomething<TValue>(TValue value) {
    if (value == null || value.Equals(default(TValue))) {
        ...
    }
}

Is there a more elegant/correct way to go about this?

like image 904
StriplingWarrior Avatar asked Feb 02 '10 20:02

StriplingWarrior


1 Answers

public bool EqualsDefaultValue<T>(T value)
{
    return EqualityComparer<T>.Default.Equals(value, default(T));
}
like image 135
Bryan Watts Avatar answered Sep 21 '22 12:09

Bryan Watts