views:

53

answers:

2

Hi there,

I was thinking of implementing a per-object Repository (e.g. a Person repository, a State repository etc.) before deciding on a line of business Repository instead BUT I still have a question regarding the passing in of an ID (identifier) type with a generic.

In a nutshell, a Person may have a GUID identifier, a State/County may have a int identifier, etc. With this in mind, how can I pass along a type that specifies the ID, er, type of the generic being passed in?

Here's my attempt at the interface:

public interface IRepository<T, TID> where T : class where TID : Type
{        
    T Get(TID id);
    IList<T> GetAll();
    void Update(T entity);
    void Insert(T entity);
    void Delete(TID id);
}

You can see that T is the class (Person, State, etc.) and my intent is to have TID be the type that is used for the identifier, i.e. look at T Get(TID id).

This craps out with the compilation error: "The type 'string' cannot be used as type parameter 'TID' in the generic type or method 'DumpWebApp.IRepository'. There is no implicit reference conversion from 'string' to 'System.Type'."

Another way of doing it would be to pass the actual element into the Get and Delete methods, I guess, but that seems a bit clunky.

Thanks for any suggestions - and incidentally, is returning IList acceptable for GetAll()? Why not IQueryable, or T[] ?

Mike K.

+1  A: 

Just drop the where TID : Type constraint. That should do the trick.

LukeH
Ok, that works like a charm, I assume this is variance? Thank you for the pointer :-)
Mike Kingscott
@Mike: Nope, nothing to do with variance. Using `Type` as a generic constraint isn't shorthand for "any type". `System.Type` is its own, distinct class. If you want to allow any type for `TID` then just skip the constraint altogether.
LukeH
Ok, so what does the second argument in the <> actually represent? I'm guessing it's the type of the generic, obviously, but would like to know fer shure...
Mike Kingscott
+1  A: 

IQueryable no. IList yes. Array yes depending. IList is safe.

Your TID constraint is saying that TID will be of type Type.

drop that.

Sky Sanders
lol. guess I should load answers
Sky Sanders
I can't believe it got answered that quickly! :-s You guys are on FIRE :-)
Mike Kingscott