Declaration of an interface with where

6

I am studying a lot design pattern , as I think they solve a lot and it is very opportune to study them. I got this statement from the Macoratti website and I confess, I could not explain from where . What does that mean?

public interface IRepository<T> where T : class
    
asked by anonymous 11.07.2015 / 22:38

2 answers

7

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

You probably know that this T between the minor and major symbols coming soon after where is a palceholder . That's what we could call a super-variable. It is not a variable in fact, but it is something to identify that there will be something else when it is actually used. I'll illustrate:

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

What where means is that you can only use restricted types, you can not use any type. In your example you can only use types that are classes. You can not type a struct , enum , for example. But you can have classes, other interfaces, or even delegations. It is a way of ensuring that certain conditions of the type are satisfied. For some reason this interface does not do well with other types.

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

public interface IRepository<T> where T : IEnumerable

In this case you can only use types that are enumerable. It can be any type, but it should implement IEnumerable . Of course this is just an example for you to understand, I do not know if it makes sense in this particular case. Following this example you can use:

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

Both List and Dictionary or String implement IEnumerable , then they can be used because they meet the constraint imposed in the above statement.

But I could not use:

new IRepository<Buffer>();

Documentation (translated . Also see the keyword .

    
11.07.2015 / 22:46
6

where T : class is a generic constraint and means that T should be a reference type (a class , interface , or a delegate).

class StringRepository<string>{}
class EnumerableRepository<IEnumerable<string>>{}
class DelegateRepository<Func<string>>{}

The "opposite" constraint is where T : struct , which means T should be a nullable value type - that is, any struct except Nullable<T> .

class IntRepository<int>{}
class DoubleRepository<double>{}

You can find here a complete list of all possible generic restrictions in C #: Constraints on Type Parameters

    
11.07.2015 / 22:45