Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a dictionary with anonymous objects

I'm trying to do the following.

private static Dictionary<int, object> MAPS = new Dictionary<int, object>
{
  {1, new {1, 2, 3}}
};

It doesn't work as I'd expect based on MSDN, so I'm pretty certain that the issue is that I'm using anonymous objects. Supposed that I don't want to create a new type for my thingies and still want to keep all the mappings in the same dictionary, what should I do?

I've seen this answer but it's a bit dated now so I'm hoping there's something new for that in the framework.

like image 336
Konrad Viltersten Avatar asked Sep 05 '25 17:09

Konrad Viltersten


1 Answers

Try this if you want an array of ints as the value.

private static Dictionary<int, object> MAPS = new Dictionary<int, object>
{
  {1, new[] {1, 2, 3}}
};

Or this if you want an anonymous class

private static Dictionary<int, object> MAPS = new Dictionary<int, object>
{
  {1, new { a = 1, b = 2, c = 3}}
};

Or better yet don't use object. Use int[] or List<int> for a collection of int or declare a class or struct if you need specific values. Maybe even use Tuple<int,int,int> if you just need 3 ints for each value. But, in general you should try to avoid the need to cast to and from object.

like image 151
juharr Avatar answered Sep 07 '25 10:09

juharr