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.
source share