Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to initialize a Hastable in .NET without using Add method?

Tags:

I am currently initializing a Hashtable in the following way:

Hashtable filter = new Hashtable(); filter.Add("building", "A-51"); filter.Add("apartment", "210"); 

I am looking for a nicer way to do this.

I tried something like

Hashtable filter2 = new Hashtable() {     {"building", "A-51"},     {"apartment", "210"} }; 

However the above code does not compile.

like image 209
hectorsq Avatar asked Sep 24 '08 16:09

hectorsq


2 Answers

The exact code you posted:

        Hashtable filter2 = new Hashtable()         {             {"building", "A-51"},             {"apartment", "210"}         }; 

Compiles perfectly in C# 3. Given you reported compilation problems, I'm guessing you are using C# 2? In this case you can at least do this:

        Hashtable filter2 = new Hashtable();         filter2["building"] = "A-51";         filter2["apartment"] = "210"; 
like image 142
Paul Batum Avatar answered Oct 08 '22 05:10

Paul Batum


In C# 3 it should compile fine like this:

Hashtable table = new Hashtable {{1, 1}, {2, 2}}; 
like image 24
mattlant Avatar answered Oct 08 '22 06:10

mattlant