Does C # have an array with an index - a string similar to PHP?

I myself studied in C # for 2 months. I used to learn PHP and see that it has an array where the index is a string, for example:

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

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

Does C # have such an array? If so, how can I create it?

+5
source share
3 answers

C # supports any type of object for an index. Baked Implementation System.Collections.Generic.Dictionary<T1,T2>. You can declare the following:

Dictionary<string, string> myDictionary = new Dictionary<string, string>();
+6
source

Yes, this is an associative array, represented in C # by a common class Dictionary<TKey, TValue>or not a common one Hashtable.

Hashmap, . , , .

+5

Use System.Collections.Generic.Dictionary<T1,T2>like others. To complete your knowledge, you must know that you can control behavior []. Example:

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 it something."

Read more about this in the documentation.

+4
source

All Articles