views:

114

answers:

3

If have the following code. Where you see the XXX I would like to put in an array of type long[].

How can I do this and how would I fetch values from the dictionary? Do I just use defaultAmbience["CountryId"][0] to get the first element?

    public static Dictionary<string, object> defaultAmbience = new Dictionary<string, object>()
        {
            { "UserId", "99999" },
            { "CountryId", XXX },
            { "NameDefaultText", "nametext" },
            { "NameCulture", "it-IT" },
            { "NameText", "namelangtext" },
            { "DescriptionDefaultText", "desctext" },
            { "DescriptionCulture", "it-IT" },
            { "DescriptionText", "desclangtext" },
            { "CheckInUsed", "" }
        };
+2  A: 

Fist Off:

If you don't know the type of the value OR the key, then don't use the Generic Dictionary.

.NET Generics are best suited for when you know the types ahead of time. .NET also provides an entire set of collections for use when you want to store a "mixed bag" of objects of different types.

In this case, the equivalent of the Dictionary would be the HashTable.

Check out the System.Collections (rather than System.Collections.Generic) namespace to see the rest of the options you have.

If you know the type of the key, then what you're doing is the right way.

Secondly:

When you retreive the value...you're going to need to cast the object back out to its original type:

long[] countryIds = (long[]) defaultAmbience["CountryId"];

or

// To get the first value
long id = ((long[])defaultAmbience["CountryId"])[0];
Justin Niessner
Using non-generic types is not going to help here really - he still needs to do the cast etc. And he does know that the keys are going to be strings, so he actually get some benefit from using generic versions.
Grzenio
What's wrong with `Dictionary<string, object>`? For me that shows much clearer the intent to store mixed items. Besides, it stops you from trying to use a non-string key (see also http://stackoverflow.com/questions/1433713/which-collection-class-to-use-hashtable-or-dictionary/1433736#1433736)
0xA3
@0xA3 - Nothing. I updated my answer. What he's doing now is fine as long as he knows the type of the key.
Justin Niessner
Thanks for the lengthy help! I know the types, keys, values ahead of time so the dictionary should suit me well. Thanks everyone for the flood of quick answers, really appreciated!! Cheers
Martin
+2  A: 

You'd need to provide the cast where you call it.

((long[])defaultAmbience["countryID"])[0];
Mark H
+1  A: 

In this case C# doesn't really know what type you expect to get, so you have to cast to the correct type after you take it from the dictionary and before you use it. In case of this long array this would be:

((long[])defaultAmbience["CountryId"])[0]
Grzenio