The compiler does not have the ability to distinguish between the three method calls that you provided, because they all look like Method(key);
One option is to return object , and then expect the consumption code to lead to what it wants:
public object Method(string key) { if(dictionary.ContainsKey(key)) { var temp = dictionary[key]; switch (temp.Type) { case "bool": return Convert.ToBoolean(temp.Value); case "int" return Convert.ToInt(temp.Value); case "string" return temp.Value; } } return "NULL"; } ... int x = (int) Method(key); string word = (string) Method(key); bool isTrue = (bool) Method(key);
You can also use the dynamic keyword to do an implicit action:
public dynamic Method(string key) { if(dictionary.ContainsKey(key)) { var temp = dictionary[key]; switch (temp.Type) { case "bool": return Convert.ToBoolean(temp.Value); case "int" return Convert.ToInt(temp.Value); case "string" return temp.Value; } } return "NULL"; } ... int x = Method(key); string word = Method(key); bool isTrue = Method(key);
However, dynamic is a very powerful concept, and it is easy for him to get out of hand, so you need to be very careful with this.
It seems to me that you expect your call code to know what type of object it expects to receive for each key. It seems like the best approach is to simply provide the user with this information:
public T Method<T>(string key) { if(dictionary.ContainsKey(key)) return (T) Convert.ChangeType(dictionary[key].Value, typeof(T)); return default(T); } ... int x = Method<int>(key); string word = Method<string>(key); bool isTrue = Method<bool>(key);
Thus, there is no need to track the type value in your dictionary objects in the first place.
source share