C# Dictionary Initializer limit?

Took forever to track, but our Unity Mac Builds crash due to a long static Dictionary Initializer (Windows runs Fine)… This sounds like a proper compiler bug? Or can anyone explain why I shouldn’t be allowed a long initializer (18k entries) example follows:

Code:

public static Dictionary<string, int> ColorList2 = new Dictionary<string, int>() {
{"red",0xFF0344},
{"green",0x7aFF3a},
{"blue",0x1919FF},
//// (18,000 more lines like these in code file)
};

Thanks much.

First of all make sure you don’t have any duplicate keys in your field initializer data. This would throw an exception. Also having 18000 entries in a field initializer is never a good idea. Field initializers in general can be really tricky. I would highly recommend to move the initialization to the static constructor. The initialization of field initializers is some blurry black magic. The compiler has to figure out an order that makes sense. Also as you can read in the second article I’ve linked if your class does not have a static constructor the class would be marked with “beforefieldinit” which makes the exact behaviour very unpredictable. The actual compiler implementation might be different on Mac (I don’t use a mac). Maybe the compiler has trouble to arrange the field initializers correctly or it has some internal memory limit for the field initializer data (64k?).

Note that collection initializers are syntactic sugar provided by the C# compiler. It follows a pattern matching approach just like the foreach implementation. The compiler might have trouble handling that many entries. If you want to know more about pattern matching, read Eric Lippert’s “Following The Pattern” blog post.

So if moving the initialization to a static constructor doesn’t solve your issue, you may need to convert your collection initialization to explicit Add calls. With a few well designed local search and replace magic this shouldn’t be that difficult as long as the formatting of your 18000 entries is consistent. Do you use an untyped Dictionary or do you actually use a generic Dictionary<string, int> and you just accidentally stripped the generic parameter due to not formatting the code correctly?

To add code to your post, just select all code and press the “101 / 010” button from the tool bar. This should simply indent every line by 4 spaces and ensures an empty line before and after the code block. Single line code can be enclosed in backticks `

For more information on the markdown syntax, see this page. Though note that UA’s markdown renderer has some issues and limitations.

Confirmed Fix involved converting to 18k individual:

ColorList.Add("red",0xFF0344); 

in a startup method and my macOs crash went away.
So Mac compiler must be a “weaker” implementation in this area.

Thanks @Bunny83