tags:

views:

30

answers:

2

Say I have this interface:

public interface IRepository<T> where T : Entity
{
  T Get(string query);
  void Save(T entity);
}

And I have a couple of concrete classes like (where User and Project, of course, inherit from Entity):

public class UserRepository : IRepository<User> { ... }
public class ProjectRepository : IProjectRepository<Project> { ... }

What is the best way to keep a reference to all those in a single collection? You obviously can't have something like:

var repos = new IRepository<Entity>[]
{
  new UserRepository(),
  new ProjectRepository()
}

So must I have a non-generic interface from which the generic interface inherits?

public interface IRepository
{
  Entity Get(string query);
  void Save(Entity entity);
}

public interface IRepository<T> : IRepository { ... }

Thanks for any help, ideas, suggestions.

+1  A: 

So must I have a non-generic interface from which the generic interface inherits?

Yes. You could put fewer methods on that non-generic interface, if you can get away with it: it depends how much type casting you wanted to do. (You could put them in an object[], for instance.)

Tim Robinson
+2  A: 

Your IRepository<T> interface doesn't really lend itself to co- or contra-variance, since T appears in both input and output positions. The best you can really do here is provide a non-generic interface as you point out.

You could, of course, store references to any type using object - but I'm guessing that you're looking for something more typesafe than that.

LBushkin
Yeah, I was handling it all in an object collection and yes, did want a more type-safe way.
xanadont
Also, glad I asked, I will have to read up on the implications of ISomeInterface<out/in T>: http://blog.t-l-k.com/dot-net/2009/c-sharp-4-covariance-and-contravariance Thanks for the hint.
xanadont