Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most concise way to initialize a C# hashtable [duplicate]

Tags:

c#

hashtable

Does C# allow hashtables to be populated in one-line expressions? I am thinking of something equivalent to the below Python:

mydict = {"a": 23, "b": 45, "c": 67, "d": 89} 

In other words, is there an alternative to setting each key-value pair in a separate expression?

like image 551
RexE Avatar asked May 08 '09 18:05

RexE


1 Answers

C# 3 has a language extension called collection initializers which allow you to initialize the values of a collection in one statement.

Here is an example using a Dictionary<,>:

using System; using System.Collections.Generic;  class Program {     static void Main()     {         var dict = new Dictionary<string, int>         {             {"a", 23}, {"b", 45}, {"c", 67}, {"d", 89}         };     } } 

This language extension is supported by the C# 3 compiler and any type that implements IEnumerable and has a public Add method.

If you are interested I would suggest you read this question I asked here on StackOverflow as to why the C# team implemented this language extension in such a curious manner (once you read the excellent answers to the question you will see that it makes a lot of sense).

like image 71
Andrew Hare Avatar answered Sep 20 '22 03:09

Andrew Hare