#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2004
    Posts
    18
    Rep Power
    0

    C# Hashtable initialization


    Hello all,
    I would like to be able to initialize a hashtable the same way I would an array of strings for example:
    string array
    string[] str = {"hello", "world"};

    I would like to be able to do something like this with the hashtable:
    Hashtable ht = new HashTable("hello"=>"world", "bill"=>"laimbeer");

    Does anybody know of a way that I can do this?

    I realize I can get close by:
    Hashtable ht = new Hashtable();
    string[] values = {"value1", "value2"};
    string[] keys = {"key1", "key2"};
    ht.Values=values;
    ht.Keys=keys;

    Thanks for your help...
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2009
    Posts
    1
    Rep Power
    0
    A handy way to do this:
    c# Code:
    public class myHashtable : Hashtable
    {
    	public myHashtable()
    	{
    		this.Add("hello", "world");
    		this.Add("bill", "laimbeer");
    		this.Add("bill", "lumbergh");
    	}
    }
     
    public class UtilityBlob
    {
    	public static myHashtable ht = new myHashtable();
     
    	...
    }
  4. #3
  5. ASP.Net MVP
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Aug 2003
    Location
    WI
    Posts
    4,378
    Rep Power
    1510
    Sigh. Not only is this post 4 1/2 years old, but the new reply completely ignores the newer collection initializer syntax.
    Primary Forum: .Net Development
    Holy cow, I'm now an ASP.Net MVP!

    [Moving to ASP.Net] | [.Net Dos and Don't for VB6 Programmers]

    http://twitter.com/jcoehoorn
  6. #4
  7. Arcane Scribbler
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Jun 2005
    Location
    Indianapolis, IN
    Posts
    1,907
    Rep Power
    584
    Originally Posted by f'lar
    Sigh. Not only is this post 4 1/2 years old, but the new reply completely ignores the newer collection initializer syntax.
    Which is this:
    [code=C#]Hashtable ht = new Hashtable()
    {
    {"key1", "value1"},
    {"key2", "value2"}
    };[/code]Or you could go with var ht = new Hashtable() {...}.

    If figure if one guy can find this thread from a search, somebody else will, too. Might as well put an example if one is going to mention the initializer syntax.

    Comments on this post

    • f'lar agrees
    Joel B Fant
    "An element of conflict in any discussion is a very good thing. Shows everybody's taking part, nobody left out. I like that."

    .NET Must-Haves
    Tools: Reflector
    References: Threading in .NET

IMN logo majestic logo threadwatch logo seochat tools logo