Define two methods with same parameter type

Viewed 10185

Today I ran into a scenario where I have to create a method that share the same name, params count and params types with existent one, Something like this:

public static Department GetDepartment(string departmentName)
{
  //LOGIC
}

public static Department GetDepartment(string employeeID)
{
  //LOGIC
}

at first glance I just said why not to name it with a different name and get things done, but I couldn't! I do want to maintain the readability of my code i'm working on, I want it to be overloaded to the first one,
so I said why not to add a fake parameter just to workaround this issue from the compiler Point of view.

 public static Department GetDepartment(string employeeID, object fakePassWtEver)
    {
      //LOGIC
    }

What is the best practice for this case? I see all the ways can let my code run, but none of them satisfied me

5 Answers

A bit late but it is possible, I had the exact same scenario today (constructor overloading, thus can't change name). Here is how I did it, small hack but it lets me have all my LINQ predicates that are related in the same place:

public BusinessStructureFilterSpecification(int responsibilityTypeId, bool dummy1 = true) : base(x => x.ResponsibleGroups.Any(x1 => x1.ResponsibilityTypeId == responsibilityTypeId))
{
    AddIncludes();
}

public BusinessStructureFilterSpecification(int userId, string dummy2 = "") : base(x => x.ResponsibleUsers.Any(x1 => x1.UserId == userId))
{
    AddIncludes();
}

Now the trick is to call them using parameter names like so:

if (responsibiltyTypeId.HasValue && !userId.HasValue)
    spec = new BusinessStructureFilterSpecification(responsibilityTypeId: responsibiltyTypeId.Value);

if (!responsibiltyTypeId.HasValue && userId.HasValue)
    spec = new BusinessStructureFilterSpecification(userId: userId.Value);
Related