The following [c#] code will not compile with the error “operator == cannot be applied to operands of type ‘T’ and ‘T'”.
public class Widget<T> where T: IComparable
{
public T value;
public Widget(T input) { value = input; }
public bool Equals<T>(Widget<T> w) where T : System.IComparable
{
return (w.value == value);
}
}
Is there a way to constrain the type T of the w input parameter to be the same type T as the object being compared thus guaranteeing they can be compared against each other and eliminating the compiler error? Using (dynamic) in front of value as below allows it to compile but it seemed like there would be a better way that would catch an issue at compile time:
public bool Equals<T>(Widget<T> w) where T : System.IComparable
{
return (w.value == (dynamic) value);
}
Assuming you’re really interested in value equality here, you can just use
EqualityComparer.Default:Note that currently your
Equalsmethod is generic too, trying to declare another type parameter T. I don’t think you really want to do that.