1

Suppose I have an array of strings like :

myArray["hello", "my", "name", "is", "marco"]

to access to this variable, I have to put an integer as index. So if I wanto to extract the third element I just do :

myArray[2]

Now, I'd like to use label instead of integer. So for example somethings like :

myArray["canada"]="hello";
myArray["america"]="my";
myArray["brazil"]="name";
myArray["gosaldo"]="is";
myArray["italy"]="marco";

How can I do this on C#? Is it possible? Thanks

4 Answers 4

9

That's called an associative array, and C# doesn't support them directly. However, you can achieve exactly the same the effect with a Dictionary<TKey, TValue>. You can add values with the Add method (which will throw an exception if you try to add an already existing key), or with the indexer directly, as below (this will overwrite the existing value if you use the same key twice).

Dictionary<string, string> dict = new Dictionary<string, string>();

dict["canada"] = "hello";
dict["america"] = "my";
dict["brazil"] = "name";
dict["gosaldo"] = "is";
dict["italy"] = "marco";
Sign up to request clarification or add additional context in comments.

Comments

1

C# has a Dictionary class (and interface) to deal with this sort of storage. For example:

Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("canada", "hello");
dict.Add("america", "my");
dict.Add("brazil", "name");
dict.Add("gosaldo", "is");

Here are the docs: http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

Comments

1

With a Dictionary you will be able to set the "key" for each item as a string, and and give them string "values". For example:

Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("canada", "hello");

Comments

0

You're looking for an associative array and I think this question is what you're looking for.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.