Hash table declaration with key, value

I'm in C # 2.0.

I would like to know if it is possible to declare a Hashtable const construct with a key and values. I know this is possible with arrays:

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

but how can we do this with Hashtables.

+4
source share
5 answers

This cannot be done in C # 2.0. Language does not support it. The language specification is here , and there is no mention of built-in dictionary initialization.

C # 3.0 allows initializing a dictionary in the same way as initializing an array, which you described in your question (spec language here ). Here is an example:

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

It's easy with C # 3 , collection initializers that can still target .NET 2. Using Dictionary<string, string> instead of Hashtable , though (don't use non-native collections unless you really need 1 ):

 private static readonly Dictionary<string, string> Foo = new Dictionary<string, string> { { "Foo", "Bar" }, { "Key", "Value" }, { "Something", "Else" } }; 

There is nothing like this in C # 2 if you really need to use this. Are you still using Visual Studio 2005? Do not forget that you can still configure .NET 2 to C # 3 and 4 ...

EDIT: If you really want to do this using C # 2 and hashtables, you can write a static method as follows:

 public static Hashtable CreateHashtable(params object[] keysAndValues) { if ((keysAndValues.Length % 2) != 0) { throw new ArgumentException("Must have an even number of keys/values"); } Hashtable ret = new Hashtable(); for (int i = 0; i < keysAndValues.Length; i += 2) { ret[keysAndValues[i]] = keysAndValues[i + 1]; } return ret; } 

Then:

 private static readonly Hashtable Foo = HashtableHelper.CreateHashtable( "key1", "value1", "key2", 10, "key3", 50); 

I would not recommend this though ...


1 The same syntax will work with Hashtable if you use C # 3, but it really is really worth using shared collections, if possible.

+8
source

Believe me, this should work.

 public Hashtable hash = new Hashtable() { { "string1", 1 }, { "string2", 2 } } 
+8
source

You mean

 Dictionary<string, string> DDD = new Dictionary<string, string> { { "A", "B" }, { "X", "Y" }, { "Z", "A" } }; 
+1
source

You must use Dictionary . On average, Hastable about 1/3 slower than the Dictionary (mainly due to its implementation). Then it is deprecated.

0
source

All Articles