Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's easy with C# 3 <a href="http://msdn.microsoft.com/en-us/library/bb384062.aspx" rel="nofollow"><em>collection initializers</em></a>, which can still target .NET 2. Using a <code>Dictionary&lt;string, string&gt;</code> instead of a <code>Hashtable</code> though (don't use the nongeneric collections unless you really have to<sup>1</sup>):</p> <pre><code>private static readonly Dictionary&lt;string, string&gt; Foo = new Dictionary&lt;string, string&gt; { { "Foo", "Bar" }, { "Key", "Value" }, { "Something", "Else" } }; </code></pre> <p>There's nothing similar in C# 2, if you really have to use that. Are you really still using Visual Studio 2005? Don't forget that you can still target .NET 2 with C# 3 and 4...</p> <p>EDIT: If you <em>really</em> want to do it with C# 2 and hashtables, you could write a static method like this:</p> <pre><code>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 &lt; keysAndValues.Length; i += 2) { ret[keysAndValues[i]] = keysAndValues[i + 1]; } return ret; } </code></pre> <p>Then:</p> <pre><code>private static readonly Hashtable Foo = HashtableHelper.CreateHashtable( "key1", "value1", "key2", 10, "key3", 50); </code></pre> <p>I'd really not recommend that though...</p> <hr> <p><sup>1</sup> The same syntax will work with <code>Hashtable</code> if you're using C# 3, but it's really, really worth using the generic collections if you possibly can.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload