views:

437

answers:

2

How can I overload a method that takes a Generic List with different types as a parameter?

For example:

I have a two methods like so:

private static List<allocations> GetAllocationList(List<PAllocation> allocations)
{
    ...
}

private static List<allocations> GetAllocationList(List<NPAllocation> allocations)
{
    ...
}

Is there a way I can combine these 2 methods into one?

+3  A: 

Sure can... using generics!

private static List<allocations> GetAllocationList<T>(List<T> allocations) 
   where T : BasePAllocationClass
{

}

This assumes that your "allocations", "PAllocation" and "NPAllocation" all share some base class called "BasePAllocationClass". Otherwise you can remove the "where" constraint and do the type checking yourself.

womp
I am using your suggestion, but how do I go about doing the type checking?I also need to iterate though the allocations parameter. I tried to use allocations.ForEach(delegate(PAllocation pa){...}); but I get an error that says Incompatible anonymous function signature. Any ideas?
Jon
can you not just do (foreach var in allocations)?
womp
+1  A: 

If your PAllocation and NPAllocation share a common interface or base class, then you can create a method that just accepts a list of those base objects.

However, if they do not, but you still wish to combine the two(or more) methods into one you can use generics to do it. If the method declaration was something like:

private static List<allocations> GetCustomList<T>(List<T> allocations)
{
    ...
}

then you can call it using:

GetCustomList<NPAllocation>(listOfNPAllocations);
GetCustomList<PAllocation>(listOfPAllocations);
rmoore
the <NPAllocation> and <PAllocation> part can be omitted because the type will be inferred automatically
configurator