You can´t use the ==
-operator on your Type T
because there is no guarantee that this operator is defined on that type. Imagine T
is of type KeyValuePair
for example. You cannot write the following:
var areEqual = (new KeyValuePair<string, string>("1", "1") == new KeyValuePair<string, string>("2", "2"))
Make some constraint on your generic type such as where T : new()
to allow only classes where the default-value is null
.
EDIT: As a constraint on only classes is quite meaningless because reference-types allways default to null
you can unbox your instance of T
to object
and then call the ==
-operator:
public bool Compare<T>()
{
object var1 = default(T);
object var2 = default(T);
if (var1 == null) return var1 == var2;
return var1.Equals(var2);
}
This allows you to call the method for both value- and reference-types.