I\'ve looked through many questions that are similar to this, but none of them really touched on what I precisely want to do. What I am trying to do is read from an external sou
The return type of a function must be typed. As with any other variable or operation, any type that inherits from the specified type is a valid return value (which is why object allows anything as a value).
Personally i dont think it is useful to make one method with multiple return types but if you really want to have one method with multiple return types, you could use the dynamic type in .NET 4.0:
private static void Main(string[] args)
{
int x = Method("varName3");
string word = Method("varName2");
bool isTrue = Method("varName1");
}
private static dynamic Method(string key)
{
var dictionary = new Dictionary>()
{
{ "varName1", new KeyValuePair(typeof(bool), false) },
{ "varName2", new KeyValuePair(typeof(string), "str") },
{ "varName3", new KeyValuePair(typeof(int), 5) },
};
if (dictionary.ContainsKey(key))
{
return dictionary[key].Value;
}
return null;
}
Hope it helps