I've got a generic class, which contains a value. This class stores a default value and I want to check, whether the stored value equals to the default one.
At first, I tried simply:
public bool IsDefault
{
get
{
return value == defaultValue;
}
}
But unfortunately (and surprisingly) that does not compile - compiler complains, that it cannot compare T to T. The second approach is:
public bool IsDefault
{
get
{
if (value == null)
return defaultValue == null;
else
return value.Equals(defaultValue);
}
}
It works, but I have a problem with strings, because a null string in my case equals to empty string, but the previous code does not cover that.
I may specialize the class for strings, but I'd avoid that if it is not necessary. Is there a way to compare two T's in a generic way?
Edit: in response to comments
Let's assume, that the class looks like the following:
public class MyClass<T>
{
private T value;
private T defaultValue;
public MyClass(T newDefault)
{
value = newDefault;
defaultValue = newDefault;
}
public T Value
{
get
{
return value;
}
set
{
this.value = value;
}
}
public bool IsDefault
{
get
{
// ?
}
}
}