c# - Return a generic interface dynamically
c#, generics, interface
Solution
That can only work if the two types share a common base type or interface, and only of the interface is covariant (which yours is not):
public IRepository<CommonAncestor> GenerateRepository(bool flag)
{
if (flag) {
return new Repository<MyFirstType>();
} else {
return new Repository<MySecondType>();
}
}
It doesn't make sense to return an `IRepository` of an unspecified type; the generic members wouldn't be usable.
Problem
I'm trying to return one of two repository instances based on a flag. My Repository Interface and implementation look like so: ``` public interface IRepository<T> { T Insert(T entity); void Delete(T entity); IEnumerable<T> SearchFor(Expression<Func<T, bool>> predicate); IEnumerable<T> GetAll(); T SearchForFirst(Expression<Func<T, bool>> predicate); bool Has(Expression<Func<T, bool>> predicate); } class Repository<T> : IRepository<T> where T : class { ... implementation here ...} ``` And the method that is returning the one of two instances of a repository should look something like: ``` public IRepository<T> GenerateRepository(bool flag) { if ( flag ) { return new Repository<MyFirstType>(); } else { return new Repository<MySecondType>(); } } ``` Could anyone point me in the right direction as to how this should actually be written? Thanks