Is it possible to have something like the following:
class C
{
public Foo Foos[int i]
{
...
}
public Bar Bars[int i]
{
.
There IS a way.. if you define 2 new types to alow the compiler to distinguish the two different signatures...
public struct EmployeeId
{
public int val;
public EmployeeId(int employeeId) { val = employeeId; }
}
public struct HRId
{
public int val;
public HRId(int hrId) { val = hrId; }
}
public class Employee
{
public int EmployeeId;
public int HrId;
// other stuff
}
public class Employees: Collection<Employee>
{
public Employee this[EmployeeId employeeId]
{
get
{
foreach (Employee emp in this)
if (emp.EmployeeId == employeeId.val)
return emp;
return null;
}
}
public Employee this[HRId hrId]
{
get
{
foreach (Employee emp in this)
if (emp.HRId == hrId.val)
return emp;
return null;
}
}
// (or using new C#6+ "expression-body" syntax)
public Employee this[EmployeeId empId] =>
this.FirstorDefault(e=>e.EmployeeId == empId .val;
public Employee this[HRId hrId] =>
this.FirstorDefault(e=>e.EmployeeId == hrId.val;
}
Then to call it you would have to write:
Employee Bob = MyEmployeeCollection[new EmployeeID(34)];
And if you wrote an implicit conversion operator:
public static implicit operator EmployeeID(int x)
{ return new EmployeeID(x); }
then you wouldn't even have to do that to use it, you could just write:
Employee Bob = MyEmployeeCollection[34];
Same thing applies even if the two indexers return different types...