c# - Is it possible to create a method that returns one of two possible types? -
i have 2 info structures: dictionary<string, string>
, multimap<string, string>
. multimap dictionary under hood. took must of code this question. here's class definition:
public class multimap<tkey, tvalue> : dictionary<tkey, hashset<tvalue>> { ... }
both info structures have .add(tkey key, tvalue value)
method.
i have class responsible populating these maps files. have next 2 methods:
public dictionary<string, string> populatedictionary(...) { dictionary<string, string> returndictionary = new dictionary<string, string>(); ... foreach (...) { ... returndictionary.add(key, value); } homecoming returndictionary; } public multimap<string, string> populatemultimap(...) { multimap<string, string> returnmultimap = new multimap<string, string>(); ... foreach (...) { ... returnmultimap.add(key, value); } homecoming returnmultimap; }
as can see, they're same, both around 25 lines long, , difference homecoming type. looking condense 1 method. first effort have method
public dictionary<string, object> populategenericdictionary(...) { ... }
where object
either string
or hashset<string>
. didn't have much luck casting dictionary<string, object>
multimap<string, string>
.
extracting logic out of methods option, it's not great. because of foreach loops, there's going logic within 2 methods. end methods twice small, there's still 2 identical methods, doesn't solve problem.
this ideal method structure:
public dictionary<string, string> populatedictionary(...) { homecoming methodthatdoesallthelogic(...); } public multimap<string, string> populatemultimap(...) { homecoming methodthatdoesallthelogic(...); } public ??? methodthatdoesallthelogic(...) { ... }
i've been fiddling around casting , generics, can't work. ideas?
edit
i have used millimoose's solution. here's code now:
public dictionary<string, string> generatedictionary(...) { dictionary<string, string> returnmap = new dictionary<string, string>(); populatedictionary(returnmap.add, ...); homecoming returnmap; } public multimap<string, string> generatemultimap(...) { multimap<string, string> returnmap = new multimap<string, string>(); populatedictionary(returnmap.add, ...); homecoming returnmap; } private static void populategenericdictionary(action<string, string> addfunc, ...) { ... foreach (...) { addfunc(key, value); } }
much cleaner!
to work around lack of mutual interface, can invent 1 ad-hoc using bunch of delegate type parameters:
void methodthatdoesallthelogic(action<string, string> addfunc) { // ... addfunc(key, value); // ... } public dictionary<...> populatedictionary() { // ... methodthatdoesallthelogic(result.add); }
(adding more parameters necessary.)
c# generics dictionary casting
No comments:
Post a Comment