On MSDN – C# Programming guide Constraints on Type Parameters, it says:
where T : interface_name
The type
argument must be or implement the
specified interface. Multiple
interface constraints can be
specified. The constraining interface
can also be generic.
Could somebody kindly explain, what it means to have a generic interface? And explain how that can be a constraint and what it provides?
A simple example and a simple explanation is highly appreciated.
Many thanks in advance : )
An example of a generic interface is
IEnumerable<T>. It represents some collection you can enumerate. The type of the items in the collection is not relevant to the interface, so it allows you to specify that with a generic parameter.You can for example create a class like this:
This way, the generic parameter T can only be a collection of type E. The constraining interface is generic as well. You can also do this:
In which case you’re not allowing any type of collection, only collections of strings. You can go pretty crazy with this, like this:
Where T has to be some collection that contains collections of T.