How do I create a Dictionary that holds different types in C#

Enrico picture Enrico · Nov 5, 2010 · Viewed 62k times · Source

I need some sort of way to store key/value pairs where the value can be of different types.

So I like to do:

 int i = 12;
 string s = "test";
 double x = 24.1;

 Storage.Add("age", i);
 Storage.Add("name", s);
 Storage.Add("bmi", x);

And later retrieve the values with:

 int a = Storage.Get("age");
 string b = Storage.Get("name");
 double c = Storage.Get("bmi");

How should a Storage like this look like? Thanks, Erik

Answer

Jon Skeet picture Jon Skeet · Nov 5, 2010

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