Jon
Jon

Reputation: 2279

Overloading a method that takes a generic list with different types as a parameter

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?

Upvotes: 0

Views: 1956

Answers (2)

rmoore
rmoore

Reputation: 15393

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);

Upvotes: 1

womp
womp

Reputation: 116977

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.

Upvotes: 4

Related Questions