Initialize a static Dictionary inline in the declaration

Have you ever wanted to initialize a Dictionary object with lookup values, but didn’t want to put the code into a static constructor?

Well, here is the easy way to do it. Quite easy actually, just like declaring an Arrays initial values.

I decided I want to create a simple lookup dictionary keyed off of a string with the value being an int. Basically, I have strings that need to be matched to ints, for a custom sort algorithm with discrete inputs.


//discrete mapping dictionary
//initialized with the 4 values below
public static Dictionary<string,int> sortValueLookupDictionary = new Dictionary<string,int>()
 {"Key 1",1},


Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.