Suppose you have the following Generic class heirarchy:
public abstract class GenericBase<T>
{
T SomeProperty{ get; set; }
}
public class Foo<T>
{
T SomeProperty{ get; set; }
}
public abstract class GenericChild<T> : GenericBase<T>
{
// ...
public bool DoSomething(Foo<T> foo)
{
// This is invalid:
return SomeProperty == foo.SomeProperty;
}
}
The equality check in the DoSomething method won’t compile. It produces the following error:
Operator '==' cannot be applied to operands of type 'T' and 'T'
If it’s releveant, these classes are in separate files. What’s the best workaround to allow this kind of equality comparison? Is there some kind of pattern or something to allow this in C#?
Update:
A few of the answers suggest using a:
where T : SomeClass
Unfortunately, very often T will be a primitive type.
Try this:
C# does not know if == can be applied to T.