C # Generics: What is a common bounding interface?

The MSDN - C # Programming Guide Restrictions on type parameters , it says:

where T: interface_name

The type argument must be either implement the specified interface. multiple interface restrictions may be specified. A containment interface can also be shared.

Can someone explain what it means to have a common interface? And explain how this could be a limitation and what does it provide?

A simple example and a simple explanation are much appreciated.

Thanks a lot in advance :)

+4
source share
4 answers

An example of a common interface is IEnumerable<T> . It is a collection that you can list. The type of elements in the collection is not related to the interface, so it allows you to specify this using a common parameter.

You can, for example, create a class as follows:

 class Foo<T, E> where T : IEnumerable<E> { } 

Thus, the general parameter T can only be a collection of type E. The hiding interface is also common. You can also do this:

 class Foo<T> where T : IEnumerable<string> { } 

In this case, you do not allow any type of collection, but only a collection of strings. You can go crazy like this:

 class Foo<T> where T : IEnumerable<T> { } 

Where T should be some collection that contains T. collections

+2
source

You can use the general interface as a limitation. For instance:

 class MyClass<T> where T:IEnumerable<string> 

you can even replace the general parameter of the type that you define with your restriction:

 class MyClass<T> where T:IEnumerable<T> 
+7
source

The proposal only states that the bounding interface can be not only a class or interface, but also a common one.

For example, such a restriction is valid:

 public class Controller<TModel,TRepository> where TRepository: Repository<TModel>{...} 
+2
source

One use is when you want a function or class to work as a whole, but want to limit which types can be used with it (so you don't have to do a few overloads, for example).

Completely arbitrary code example:

 interface IAnimal { } interface IShape { } class Tiger : IAnimal { } class Wolf : IAnimal { } class Circle : IShape { } class Rectangle : IShape { } public void MakeSound<T>(T animal) where T : IAnimal { } public void Draw<T>(T shape) where T : IShape { } 

Actually, this is not the way you would structure this type of functionality. :) You can also use other restrictions:

 public void someFunction<T>(T input) where T : IShape, new() // constraint to IShape, allow construction of new T with parameterless constructor 

In general, they are useful for general functions limited to certain types.

+2
source

All Articles