Search code examples
c#.net.net-2.0c#-2.0

Declaration of a hashtable with key, value


I'm in C# 2.0.

I would like to know if it is possible to declare a Hashtable const initiated with key & values. I know that it is possible with arrays:

public  static string[] ColumnsNames = 
{ "string1", "string2", "string3", "string4"
, "string5", "string6", "string7" };

but how can we do that with Hashtables.


Solution

  • It cannot be done in C# 2.0. The language does not support it. The language specification is here and there is no mention of inline dictionary initialisation.

    C# 3.0 does allow dictionary initialisation similar to the array initialisation you described in your question (language spec here). Here is an example:

    var dictionary = new Dictionary<string, string> {
        {"key1", "value1"},
        {"key2", "value2"}
    };