How do I create a Dictionary that holds different types in C#
Well, you could use Dictionary<string, dynamic>
in C# 4 / .NET 4 - but other than that, you can't do it with exactly the code shown because there's no type which is implicitly convertible to int
, string
and double
. (You could write your own one, but you'd have to list each type separately.)
You could use Dictionary<string, object>
but then you'd need to cast the results:
int a = (int) Storage.Get("age");
string b = (string) Storage.Get("name");
double c = (double) Storage.Get("bmi");
Alternatively, you could make the Get
method generic:
int a = Storage.Get<int>("age");
// etc
You could declare a Dictionary containing just the type object
and then cast your results; .e.g.
Dictionary<string, object> storage = new Dictionary<string,object>();
storage.Add("age", 12);
storage.Add("name", "test");
storage.Add("bmi", 24.1);
int a = (int)storage["age"];
string b = (string)storage["name"];
double c = (double)storage["bmi"];
However, this isn't that elegant. If you know you are always going to be storing age, name, bmi I would create an object to encapsulate those and store that instead. E.g.
public class PersonInfo
{
public int Age { get; set; }
public string Name { get; set; }
public double Bmi { get; set; }
}
And then use that insead of the Dictionary... e.g.
PersonInfo person1 = new PersonInfo { Name = "test", Age = 32, Bmi = 25.01 };
int age = person1.Age;
etc.
Why not use:
Dictionary<string, object>
You can create an extension method to cast them when you get them:
public static class DictionaryExcetions
{
public static T Get<T>(this Dictionary<string, object> instance, string name)
{
return (T)instance[name];
}
}
var age = dictionary.Get<int>("age");