Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>();
}
like image 336
Jean Hominal Avatar asked Mar 16 '11 15:03

Jean Hominal


1 Answers

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.

like image 81
Reed Copsey Avatar answered Oct 18 '22 03:10

Reed Copsey