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,
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]);
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With