Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an array constant specifying desired indexes

What I just want is to initialize a string[] array constant by specifying not only the values, but the indexes they will be attached to.

For example, on:

private static readonly string[] Pets = new string[] {"Bulldog", "GreyHound"};

I would like to state that BullDog corresponds to index 29 and GreyHound to 5 (Like php :) )

Any suggestion?

Cheers,

like image 838
Ramon Araujo Avatar asked Aug 23 '10 20:08

Ramon Araujo


2 Answers

If you have some flexibility in terms of your data structure, it would be more efficient to use a Dictionary<int, string> instead of an array for this behavior.

Example (if you are using C# 3 or above):

var pets = new Dictionary<int, string> {
    { 29, "Bulldog" },
    { 5, "Greyhound" }
};
Console.WriteLine(pets[5]);

Same example for legacy applications:

Dictionary<int, string> pets = new Dictionary<int, string>();
pets[29] = "Bulldog";
pets[5] = "Greyhound";
Console.WriteLine(pets[5]);
like image 158
Ben Hoffstein Avatar answered Sep 28 '22 04:09

Ben Hoffstein


It sounds like you don't want an array, but a Dictionary<int, string> instead, which could be initialized like this:

private static readonly Dictionary<int, string> pets = 
    new Dictionary<int, string> {
    { 29, "Bulldog" },
    { 5, "Greyhound" }
};

(Note that this collection initializer syntax was only added in C# 3. If you're using an older version you'll have to call Add or the indexer explicitly multiple times.)

You can access a dictionary via its indexer which looks like array access:

string x = pets[29];
pets[10] = "Goldfish";
like image 22
Jon Skeet Avatar answered Sep 28 '22 06:09

Jon Skeet