Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can array indexes be named in C#?

I'm wondering if the index of an array can be given a name in C# instead of the default index value. What I'm basically looking for is the C# equivalent of the following PHP code:

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

Cheers.

like image 393
diggersworld Avatar asked Mar 25 '12 21:03

diggersworld


People also ask

Can you index an array in C?

Arrays in C are indexed starting at 0, as opposed to starting at 1. The first element of the array above is point[0]. The index to the last value in the array is the array size minus one.

What type is the index of an array in C?

Elements of an array are accessed by specifying the index ( offset ) of the desired element within square [ ] brackets after the array name. Array subscripts must be of integer type. ( int, long int, char, etc. ) VERY IMPORTANT: Array indices start at zero in C, and go to one less than the size of the array.

Can an array index be a string?

Actually, it has very much to do with the question (specifically, yes, you CAN use a string as an index, but not in the obvious way that the original querier wants).

What is the other name of an array index?

index—An array element's position number, also called a subscript. An index either must be zero, a positive integer, or an expression that evaluates to zero or a positive integer. If an application uses an expression as an index, the expression is evaluated first to determine the index.


1 Answers

PHP blends the concept of arrays and the concept of dictionaries (aka hash tables, hash maps, associative arrays) into a single array type.

In .NET and most other programming environments, arrays are always indexed numerically. For named indices, use a dictionary instead:

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

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

like image 113
BoltClock Avatar answered Oct 02 '22 14:10

BoltClock