c# – Declaring an interface with where

Question:

I'm studying design patterns a lot, because I think they solve a lot of things and it's very opportune to study them. I got this statement from Macoratti's website and I confess, I didn't know how to explain it from where . What does that mean?

public interface IRepository<T> where T : class

Answer:

This is declaring an interface as you already know. You must also understand that it is generic. That is, it can work with different types of objects, as long as a specified type is used when it is implemented.

You probably know that this T between the lesser and greater symbols and that comes right after the where is a placeholder . It's what we might call a super variable. It is not actually a variable, but it is something to identify that there will be something else there when it is actually used. I will exemplify:

When you use IRepository<Cliente> it is the Cliente type that will be used in this interface.

What the where means is that you can only use restricted types, you can't use any type. In your example you can only use types that are classes. You can't have a type that is a struct or enum , for example. But it may have classes, other interfaces or even delegations (these are all classes). It is a way of ensuring that certain conditions of the type are satisfied. For some reason this interface doesn't get along well with other types.

You can further restrict, you can use a specific type. You could use for example:

public interface IRepository<T> where T : IEnumerable

In that case you can only use types that are enumerable. It can be any type, but it must implement IEnumerable . Of course, this is just an example for you to understand, I don't know if it makes sense in this specific case. Following the same example you can use:

new IRepository<List>();
new IRepository<Dicionary>();
new IRepository<String>();

I put it on GitHub for future reference .

Both List and Dictionary or String implement IEnumerable , so they can be used because they satisfy the restriction imposed in the above declaration.

But could not use:

new IRepository<Buffer>();

Documentation ( translated ). See also about keyword .

Scroll to Top