Can array indices be called in C #?

I am wondering if it is possible to give the index of the array a name in C # instead of the default index value. I am basically looking for the C # equivalent of the following PHP code:

$array = array( "foo" => "some foo value", "bar" => "some bar value", ); 

Greetings.

+8
arrays c # indexing
source share
4 answers

PHP mixes the concept of arrays and the concept of dictionaries (aka hash tables, hash maps, associative arrays) into one array type .

In .NET and most other software environments, arrays are always indexed numerically. For named indexes, use the dictionary instead:

 var dict = new Dictionary<string, string> { { "foo", "some foo value" }, { "bar", "some bar value" } }; 

Unlike PHP associative arrays, dictionaries in .NET are not sorted. If you need a sorted dictionary (but probably not), .NET provides a sorted dictionary type .

+26
source share

No in the array. However, there is a very useful Dictionary class, which is a collection of KeyValuePair objects. It looks like an array in that it is an iterable collection of objects with keys, but more general in that the key can be of any type.

Example:

 Dictionary<string, int> HeightInInches = new Dictionary<string, int>(); HeightInInches.Add("Joe", 72); HeightInInches.Add("Elaine", 60); HeightInInches.Add("Michael", 59); foreach(KeyValuePair<string, int> person in HeightInInces) { Console.WriteLine(person.Key + " is " + person.Value + " inches tall."); } 

MSDN Documentation for Dictionary<TKey, TValue>

+2
source share

Take a look at Hashtable in C #. This is a data structure that does what you want in C #.

+1
source share

You can use the Dictionary<string, FooValue> type, or a similar type or collection type, or, if you must adhere to the array, define Enum with your labels.

0
source share

All Articles