1

We can init a HashTable object using the below syntax.

var listTinhThanh = new System.Collections.Hashtable()
{ 
    { "key", someObject }
};

I want to use the code in such a manner of:

var listTinhThanh = new System.Collections.Hashtable()
{ 
    { Key:"key", Value:someObject }
};

But that DOESN'T work. Do you have any work-around?

Nam G VU
  • 33,193
  • 69
  • 233
  • 372
  • 1
    1) Why HashTable and not Dictionary? 2) Why do you prefer the second syntax? – CodesInChaos Jan 24 '11 at 11:06
  • Just one note: Why don't you use Dictionary<> instead of Hashtable? – Al Kepp Jan 24 '11 at 11:06
  • `{ { "blah", 1 } }` is really just sugar for `.Add("blah", 1)`. And about HashTable, are you running .NET 1.0? – Skurmedel Jan 24 '11 at 11:10
  • @CodeInChaos, Al Keep: I don't know indeed. I just google it and someone recommend me to use Hashtable when need a `named index collection`. Not sure the differences between the two (Hashtable vs Dictionary) – Nam G VU Jan 24 '11 at 11:24
  • @ChodeInChaos: I prefer the second syntax since it is more reader-friendly to me. – Nam G VU Jan 24 '11 at 11:26
  • The difference is that Dictionary is generic, and allows you to restrict the key and value to certain types. So you get more type safety. `HashTable` is similar to a `Dictionary` – CodesInChaos Jan 24 '11 at 11:39

1 Answers1

5

No, there isn't a workaround. Such syntax cannot possibly exist in C# because of the :. Also the first seems shorter to me, I wonder why you need the second.

This being said I would recommend you using a strongly typed Dictionary<TKey, TValue> instead of a Hashtable. The closest you could get is this:

var listTinhThanh = new[]
{ 
    new { Key = "key1", Value = someObject1 },
    new { Key = "key2", Value = someObject2 },
    new { Key = "key3", Value = someObject3 },
}.ToDictionary(x => x.Key, x => x.Value);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • When tried this, I got the error `The name 'Value' does not exist in the current context`, `The name 'Key' does not exist in the current context`. – Nam G VU Jan 24 '11 at 11:37
  • @Nam Gi VU, this is LINQ. You need to reference the `System.Core` assembly and include the `System.Linq` namespace. – Darin Dimitrov Jan 24 '11 at 12:08