5

I have been learning C# myself for 2 months. Before, I learned PHP and see that it has an array where the index is a string, like this:

$John["age"] = 21;
$John["location"] = "Vietnam";

It is very useful to remember what we set to an array element. I tried to find if C# supports that array type, but I haven't seen any answers, yet.

Does C# have an array like this? If it does, how can I create it?

2

3 Answers 3

6

C# supports any type of object for an index. A baked-in implementation is System.Collections.Generic.Dictionary<T1,T2>. You can declare one like this:

Dictionary<string, string> myDictionary = new Dictionary<string, string>();
Sign up to request clarification or add additional context in comments.

1 Comment

You don't have to use Add() to add items - assigning them like in the PHP sample adds them as well.
5

Yes, this is an associative array, represented in C# by the generic Dictionary<TKey, TValue> class or the non-generic Hashtable.

Your code would be only possible with a Hashmap as the values are not all of the same type. However, I strongly suggest you re-think that design.

2 Comments

Would the downvoter please be so kind to comment on the reason? Otherwise the downvote is pointless as I can't improve the answer.
Hey Daniel, you could technically achieve it with Dictionary<string, object>, too. Gains you nothing useful, but you don't need a Hashmap for that requirement.
4

Use a System.Collections.Generic.Dictionary<T1,T2> as other said. To complete your knowledge, you should know that you can control yourself the behavior of the []. Exemple :

public class MyClass
{
    public string this[string someArg]
    {
        get { return "You called this with " + someArg; }
    }

}

class Program
{

    void Main()
    {
        MyClass x = new MyClass();
        Console.WriteLine(x["something"]);
    }
}

Will produce "You called this with something".

More on this in the documentation

3 Comments

No it is not. A Dictionary is a class, and not a passive array!
@JvdBerg: Aha. In what way is an array passive? It does boundary checks for example.
@JvdBerg, in .NET an array is a class as well... even though it has some special properties (e.g. non-fixed size in memory, ability for being casted with co- and contravariance), all arrays are used through a normal object reference to a normal class instance, no magic there.

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.