Running .NET 2.0, I have a generic method with the following signature:
static listType FillCollection<listType, objType>(IDataReader dr) where listType : ICollection<objType>, new()
it’s purposes is to translate a datareader into a collection of objects both of my choosing. My problem, which isn’t exactly a problem, is that when I call it, the call ends up looking something like this:
List<MyObject> data = FillCollection<List<MyObject>, MyObject>(dr);
I’m curious if there’s a way to cut out the redundancy of having to specify MyObject twice in the call. Ideally, I’d be able to only specify it once, along with the collection type and maintain the strong typed nature of the method. Adding another wrapper method to abstract the ICollection type sorta does the trick:
List<MyObject> data = FillList<MyObject>(dr);
static List<objType> FillList<objType>(dr)
{
return FillCollection<List<objType>, objType>(dr);
}
But I’d rather not have a wrapper method for every collection i want to use.
Maybe I have no choice in the matter, but if so, I don’t have to like it! 😉
Thanks!
Personally, I’m not really sure why you need your method to be able to create multiple different implementations of ICollection. My inclination would be to have a method signature as follows, and just create a List inside the method and return it.
If that’s not acceptable, then I’d go with Joseph’s answer.