Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store function OR string as value in dictionary (C#)

Tags:

c#

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

like image 381
Invincible Avatar asked Dec 02 '10 20:12

Invincible


3 Answers

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;
}
like image 155
JaredPar Avatar answered Sep 28 '22 01:09

JaredPar


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.

like image 29
Mark Byers Avatar answered Sep 28 '22 01:09

Mark Byers


A Dictionary<string, object> would do the trick, you'll just need to cast the result to string or Func<string>.

like image 29
dahlbyk Avatar answered Sep 28 '22 02:09

dahlbyk