Search code examples
c#.netgenericstype-constraints

Can one specify on a generic type constraint that it must implement a generic type?


Here is what I would like to do:

public interface IRepository<TSet<TElement>> where TSet<TElement> : IEnumerable<TElement>
{
    TSet<TEntity> GetSet<TEntity>();
}

Is such a construction possible in .NET?

Edit: The question was not clear enough. Here is what I want to do, expanded:

public class DbRepository : IRepository<DbSet<TElement>> {
    DbSet<TEntity> GetSet<TEntity>();
}

public class ObjectRepository : IRepository<ObjectSet<TElement>> {
    ObjectSet<TEntity> GetSet<TEntity>();
}

Meaning, I want the constrained type to: - accept a single generic parameter - implement a given single generic parameter interface.

Is that possible? In fact, I will be happy with only the first thing.

public interface IRepository<TGeneric<TElement>> {
    TGeneric<TArgument> GetThing<TArgument>();
}

Solution

  • You would need to use two generic types to achieve this, such as:

    public interface IRepository<TCollection, TItem> where TCollection : IEnumerable<TItem>
    {
        TCollection GetSet<TItem>();  
    }
    

    (I'm assuming TEntity should have been TElement in the original...)

    That being said, it's most likely better to write something like:

    public interface IRepository<T>
    {
        IEnumerable<T> GetSet<T>();  
    }
    

    This would be a more common means of accomplishing the above.