Home > Software design >  can any one explain the hierarchy tree public interface IGenericRepository<T> where T: class?
can any one explain the hierarchy tree public interface IGenericRepository<T> where T: class?

Time:07-28

we write the code and when we will use generic repo pattern but can anyone explain this convention please? so can anyone explain this code so we can understand how this inheritance works. public interface IGenericRepository < T > where T: class

CodePudding user response:

This is not inheritance; it is a Type Constraint.

It limits your developers to not use classes in your Generic Repository that are not an actual representation of a DB object.

Imagine, that all your mapped entities implement an Id field of type Guid. You can constraint your repositories to only be usable with objects that have that Id:

public interface IEntity
{
    public Guid Id
}

public interface IGenericRepository < T > where T: IEntity

Your Generic Repo will be limited to types which implement that specific interface, and you would be sure that all concrete implementations have Guid Id property.

CodePudding user response:

There is no inheritance happening in public interface IGenericRepository<T> where T : class.

where T: class is a generic constraint requiring T to be a reference type (non-nullable reference type since C#8 within nullable context):

where T : class - The type argument must be a reference type. This constraint applies also to any class, interface, delegate, or array type. In a nullable context in C# 8.0 or later, T must be a non-nullable reference type.

i.e. you can't create for example a IGenericRepository of int (IGenericRepository<int>) cause it will not compile, but you can create repository for example of some custom class - IGenericRepository<MyClass>. Quite often such restriction comes from repos build on top of EF Core (though some would argue that using generic repository pattern with EF is actually antipattern), cause it requires entity types to be constrained to class.

Related:

  • Related