0

I have the following domain object:

public class Bank : IEntity
{
}

And the following IRepository:

public interface IRepository<TEntity> where TEntity : IEntity
{
}

Is the where TEntity : IEntity needed? What does this mean, that TEntity is of type IEntity? Is there any naming conventions when I use something like TEntity? What does the T stand for?

John Farrell
  • 24,673
  • 10
  • 77
  • 110
Brendan Vogt
  • 25,678
  • 37
  • 146
  • 234

4 Answers4

2

Your IRepository is a generic class and the TEntity is the generic type parameter. It's like a placeholder for the actual type.

TEntity: IEntity means that you will require that the actual type being used implements IEntity and in your actual repository implementation you can refer to methods and properties exposed by the interface IEntity.

Whether or not it is needed depends on the intended usage of the repository. Usually type restrictions are used to enforce certain properties of the types being used on which the implementation of the generic relies on.

Juri
  • 32,424
  • 20
  • 102
  • 136
ChrisWue
  • 18,612
  • 4
  • 58
  • 83
2

You can read about generic constraints and their use in Why use generic constraints?, and you might want to check out the MSDN docs for more official coverage.

As to the 'T', that's strictly a convention that harks back to C++ when such things were called 'templates'. (It is a convention that you should follow, however.)

Community
  • 1
  • 1
ladenedge
  • 13,197
  • 11
  • 60
  • 117
1

where TEntity : IEntity means that the TEntity type has to implement IEntity interface. Saying in other words in your generic interface IRepository you can use types that implements IEntity interface.

Rafal Spacjer
  • 4,838
  • 2
  • 26
  • 34
1

It depends on your design time needs.

You can replace generic TEntity uses with IEntity. But, then you will be restricted to members of IEntity only.

You will have to cast IEntity members to get access to its child type members.

decyclone
  • 30,394
  • 6
  • 63
  • 80