Vikram Babu Nagineni Vikram Babu Nagineni -4 years ago 70
C# Question

How do we get benefits from generics in IRepository<T> CRUD scenario?

How do we get benefits from generics in the following scenario?

public interface IRepository<T> where T : BaseEntity
{
IEnumerable<T> GetAll();
T Get(long id);
void Insert(T entity);
void Update(T entity);
void Delete(T entity);
}


public interface IRepository
{
IEnumerable<BaseEntity> GetAll();
BaseEntity Get(long id);
void Insert(BaseEntity entity);
void Update(BaseEntity entity);
void Delete(BaseEntity entity);
}


What benefit do we get from first piece of code?

Answer Source

Lets first look at the callers side (using option 1):

IRepository<SomeEntity> x = ...

var se = x.Get(19);

//I can now immediately call SomeEntity specific methods on se
//Without any casts, and I know it's a SomeEntity and not some other type

Or the implementers side (using option 2):

class SomeEntityRepository : IRepository {

    ...

    void Insert(BaseEntity entity) {
        //Now I need to check that what I've been passed is
        //really a SomeEntity, since that's what I'm a repository for
        ...
    }
}

In short, better type safety at compile time

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download