C# language feature:

  • Dictionary (index) initializers

applies to

  • dictionaries, collections

benefit

  • Allows use of key/index during initialization. i.e. intialization is similar to usage.

how to use

  • Use key/index between [ and ] followed by = followed by initial value. Seperate with , if repeating multiple key/value initializations.

note

  • Index initializer may also be used with other collections such as List. However, traditional collection initialization are easier to express without “boiler plate” consecutive indexed assignments.

example:

        private Dictionary<int, string> webErrors = new Dictionary<int, string>
        {
            [401] = "Not authorized",
            [404] = "Page/Resource not found",
            [500] = "Internal server error"
        };

        // previously initialization would be declared with and object contianing key value objects seperated by comma
        private Dictionary<int, string> uglier_webErrors_initialization= new Dictionary<int, string>
        {
            {401 , "Not authorized" },
            {404 , "Page/Resource not found" },
            {500 , "Internal server error" }
        };