Shekhar Pankaj Shekhar Pankaj - 28 days ago 7
C# Question

C# : Extending Generic class

partial class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
}


My generic repository implements a common set of methods for
TEntity
like

public TEntity Get(int id)
{
return _context.Set<TEntity>()
.Find(id);
}

public TEntity Get(Expression<Func<TEntity, bool>> predicate)
{
return _context.Set<TEntity>()
}


which I can access like

Repository<User>().Get();


Many repositories does the same set of operation, so it is beneficial but now I want to extend
Repository<User>
to support some additional behavior.

partial class Repository<User> : IRepository<User>
{
public user DoMagicFunction()
{
}
}


so that I can use the repository like

Repository<User>().DoMagicFunction();


how can I extend the same generic class for Some
Tentity
to extend new behaviour instead of modifying it.

I could have done the same like creating another
UserRepository
to support new feature, but the accessor would become

UserRepository.DoMagicFunction();


but I want it to be like

Repository<User>().DoMagicFunction();

Answer Source

You can use an extension method:

public static class ExtensionMethods {

    public static User DoMagicFunction(this Repository<User> repository) {
        // some magic
        return null; //or another user
    } 

}

This will thus add the function in a syntactically nice way to Repository<User> objects.

In case you want to support it not only for Users, but for subclasses of Users as well, you can make the function generic:

public static class ExtensionMethods {

    public static TEntity DoMagicFunction<TEntity>(this Repository<TEntity> repository)
        where TEntity : User {
        // some magic
        return null; //or another TEntity
    } 

}