I have the following code at least 10 different times in my code. Seems kind of smelly to me.
public void DisplayTransitInfo(TransitInfo transitInfo)
{
if (InvokeRequired)
EndInvoke(BeginInvoke(new MethodInvoker(() => DisplayTransitInfo(transitInfo))));
else
{
var control = (from string key in _visiblePanes.Keys
where key == "transitInfo"
select _visiblePanes[key].Control).ToList();
TransitInfoControl cntl = (TransitInfoControl)control[0];
//TODO: Transit Info
}
}
public void ModifyParties(UltraTreeNode node)
{
if (InvokeRequired)
EndInvoke(BeginInvoke(new MethodInvoker(() => ModifyParties(node))));
else
{
var control = (from string key in _visiblePanes.Keys
where key == "parties"
select _visiblePanes[key].Control).ToList();
PartiesControl cntl = (PartiesControl)control[0];
cntl.ModifyParties(node);
}
}
I feel that it could be possible to use generics in this situation. I have also considered moving:
var control = (from string key in _visiblePanes.Keys
where key == "parties"
select _visiblePanes[key].Control).ToList();
to its own function that would return the instance of the control in the dictionary.
Is this code smelly or do I just need to get my nose worked on?
Thanks as always!
If you are looking to simplify
and
And if _visiblePanes is a dictionary, which implies it can have no duplicate keys, then you don’t need generics, just use this instead:
and
EDIT
(added casts above for equivalence with the original code)
This suggestion, compared with Jim Mischel’s, is not only simpler to type and read, it is also closer to the original code, because it throws an exception if the key is not present in the dictionary. If the original code used Linq in an attempt to cover that possibility, it fails at
PartiesControl cntl = (PartiesControl)control[0];. Assuming that the absence of a key in the dictionary is non-exceptional, then, of course, Jim’sTryGetValuesolution is better.To return to the original question about generics, there is a possible advantage in extracting the get-and-cast logic into a generic method:
can be called thus:
However, the benefit is slight. Jim’s solution plus a cast is not much more verbose: