I need need to create dictionary whose key is string and values is either (delegate function OR string).
Because, I want to implement call back mechanism, wherein sometimes I need function for more processing which returns string and sometimes just need to fixed string.
Is there any way to do that in C#?
Thank you
I think the easiest way is to create a Dictionary<string, Func<string>>
. This can obviously hold the call back case. For the non-call back case you can create a trivial lambda to return the hard coded value.
private Dictionary<string, Func<string>> m_map;
public void AddValue(string key, string value) {
m_map[key] = () => value;
}
public void AddValue(string key, Func<string> value) {
m_map[key] = value;
}
In the case where you need to have a fixed string you can instead create a function which returns a fixed string. Then in both cases you only need to deal with functions which return strings.
A Dictionary<string, object>
would do the trick, you'll just need to cast the result to string
or Func<string>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With