Reputation: 8025
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?
Upvotes: 5
Views: 4743
Reputation: 37700
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
Upvotes: 4
Reputation: 22974
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>();
Upvotes: 6
Reputation: 174389
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.
Upvotes: 5