The following example is bad, because it has code repetition. For example, if we later need to CheckExpirationDate before drinking, we need to add the function call in multiple places. If we need to add charley and stan to the party, the code gets huge quickly.
if (john != designatedDriver)
{
beer.Open();
john.Drink(beer);
}
if (bob != designatedDriver)
{
cider.Open();
bob.Drink(cider);
}
The solution could be to build an array of these objects. That’s really easy if you need to operate one object at a time. For example, if everyone is passing around a single bottle of beer:
beer.Open();
foreach (Dude i in new Dude[] { john, bob })
{
i.Drink(beer);
}
To rewrite the original example, we can use a KeyValuePair. Not particularly pretty, but well worth it for more than two dudes or if the drinking procedure is long enough (wine tasting).
foreach (KeyValuePair<Dude, Booze> i in KeyValuePair<Dude, Booze>[] {
new KeyValuePair<Dude, Booze>(john, beer),
new KeyValuePair<Dude, Booze>(bob, cider) })
{
if (i.Key != designatedDriver)
{
i.Value.Open();
i.Key.Drink(i.Value);
}
}
But what if we need to operate three or more objects at a time? For example, john drinks beer and eats nachos. We can resort to declaring custom types, but that would make the code dependent on other code somewhere far away. We could put each type in its own array and do a good old for loop and access the objects with indexes, but that would mean creating named arrays (Dude[] dudes = new Dude { john, bob };).
What I’m asking is, is there some fancy C# trick that would let me do this very cleanly and compactly? Anonymous types? Something?
You mentioned anonymous types, this should do the trick: