Reputation: 25927
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
{
// ?
}
}
}
Upvotes: 3
Views: 167
Reputation: 10201
The constructor of your class should take an IEqualityComparer<T>
as a parameter, and an overload could pass in the EqualityComparer<T>.Default
. Store it and use to test for equality. In the case of strings, pass in an IEqualityComparer<string>
that considers "" == null
.
Like this:
class Example<T>
{
private readonly IEqualityComparer<T> comparer;
private readonly T defaultValue;
private T value;
public Example(T value, T defaultValue, IEqualityComparer<T> comparer)
{
this.value = value;
this.defaultValue = defaultValue;
this.comparer = comparer;
}
public Example(T value, T defaultValue)
: this(value, defaultValue, EqualityComparer<T>.Default)
{
}
public Example(T value)
: this(value, default(T))
{
}
public Example()
: this (default(T))
{
}
public bool IsDefault
{
get
{
if (value == null)
{
return defaultValue == null;
}
else
{
return comparer.Equals(value, defaultValue);
}
}
}
}
Upvotes: 4