I have an object that represents a physical structure (like a utility pole), and it touches a bunch of other objects (the wires on the pole). The other objects have a bunch of characteristics (status, size, voltage, phase, etc.) expressed as enums. I want to write a generic function that counts how many of the wires match any or all of the characteristics.
If enums were first-class objects, I think I'd just write this:
CountWires(EStatus status, ESize size, EVoltage voltage, EPhase phase)
{
int count = 0;
foreach (Wire wire in _connectedWires)
{
if (status != null && wire.Status != status) continue;
if (size != null && wire.Size != size) continue;
...
++count;
}
return count;
}
... and be able to call it to count just new, large wires of any voltage and phase like this:
CountWires(EStatus.New, ESize.Large, null, null);
... but of course that gets me a cannot convert from '<null>' to 'ESize'
error.
We've tackled this in the past by adding an "Any" value to the enums themselves and checking against that, but then if we do something like display all the possible values in a list for the user we have to filter out "Any". So I want to avoid that.
I thought I'd throw this out to the community and see if anyone has any ideas for a way to do this with a clean interface and easy-to-read calling code. I have my own answer I'm toying with that I'll add to the discussion.