I've been reading on leveraging generic constraints, I've found that generics can be constrained to struct
, class
, new
, Class
and Interface
. The reasons behind the first three are pretty obvious. But I can't really understand why and when to constraint to a class. i.e
class Foo<T> where T : Bar
class Foo<T> where T : IBar
This allows us to constrain to Bar and it's children, and IBar and implementers respectively. Can't we just program to the class, or the interface ? Because that's basically what polymorphism is for, and Microsoft Engineers are far from dumb to implement a useless feature.
What am I missing ?
Update:
My question has been marked as duplicate for : Why use generic constraints in C#
I don't think it's the case.
I went through this question thoroughly, and didn't really find the answer: It discussed the use of generic constraints in general, while here I'm asking about why do we constrain to a class or an interface, why not just program to it directly ?