say I have the following code:
public class Pond
{
public List<Frog> Frogs { get; set; }
public List<MudSkipper> MudSkippers { get; set; }
public List<Eel> Eels { get; set; }
}
public class Frog: IAquaticLife
{
}
public class MudSkipper: IAquaticLife
{
}
public class Eel: IAquaticLife
{
}
Now I want to write a generic method that will for a certain pond return the list of these types:
public IEnumerable<T> GetByPond<T>(int pondId) where T : IAquaticLife
{
return Uow.GetByID<Pond>(pondId).Eels;
}
Ok, so what I have there will return all the eels in that pond. What I was wanting to do was to return all the T’s.
so if I called GetByPond<MudSkipper>(1) that would return all the mudskippers.
Anyone know how to do this?
How about something like
or simply (using the approach that @DStanley pointed out before changing his answer)
That requires Uow.GetByID(int id) to return all types of creatures in the particular pond that implement IAquaticLife. The alternative, though, is that you hard-code knowledge of the various implementers of IAquaticLife into your generic method. That is not a good idea.
UPDATE
Currently a Pond has separate collections for Eels, Mudskippers, etc. That becomes fragile if you want to add more things that implement IAquaticLife as your code evolves because you have to change both Pond and the generic method above.
I suggest that instead of separate methods for each type of aquatic life, you instead have a single method that returns everything in the pond that implements IAquaticLife, e.g.
I have updated my code above with this assumption.
Anyone that has a Pond instance and wants to get, say, just the Eels can do this: