Mark Michaelis wrote in his book (C# 4.0 Essentials):
class EntityBase<T> where T : IComparable<T>
{
public virtual void Method<T>(T t)
where T : IComparable<T>
{
// ...
}
}
class Entity<T> : EntityBase<T> where T : IComparable<T>
{
public override void Method<T>(T t)
// Error: Constraints may not be
// repeated on overriding members
where T : IComparable<T>
{
// ...
}
}
However, overriding members need to
conform to the “interface” defined in
the base class method. Additional
constraints could break polymorphism,
so they are not allowed and the type
parameter constraints on the override
method are implied.
Could somebody kindly explain to me what it means to break polymorphism? And in this example how could polymorphism break?
His example is confusing in part because of the (incorrect, IMO) re-use of
Tfor a generic method within a generic type. The twoTare not the same! So; let’s work with a non-generic type:Here I added
ISomethingElse– and clearly the 2nd method could try to use features of this secondT– however, the caller might be:the base implementation does not enforce
ISomethingElse, so the compiler does not complain that it isn’t implemented. So what does the overridden method do? Hence it can’t exist.However! If you do this at the type level instead, it does work, as for the concrete object to exist we know the constraint was enforced:
And a brief reminder – if you have a generic type with
<T>, don’t also use<T>in a generic method; something more specific likeTValueetc…