xQuix xQuix - 25 days ago 9
C# Question

Can I name each element of an array with string variables (or someting else)?

As said in the title, I would like to give names to each element of an array.

This is my code:

string[] myArray = new string[5];

bool open = true;

while (open == true)
{

Console.WriteLine(
"Choose a number\n" +
"[1] Put in 5 names\n" +
"[2] Show all 5 names\n" +
"[3] Close\n");

Int32.TryParse(Console.ReadLine(), out int menu);

switch (menu)
{
case 1:

Console.WriteLine("\nWrite 5 letters\n");

for (int i = 0; i < myArray.Length; i++)
{
myArray[i] = Console.ReadLine();
}

Console.ReadLine();
break;

case 2:

Console.WriteLine("\nThese are the 5 letters:\n");

for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine(myArray[i]);
}

Console.ReadLine();
break;

case 3:

open = false;
break;

}


What I want to do is so that instead of printing out the array (if I name the elements a,b,c,d,e) like this:

a
b
c
d
e


I want to put a name infront of each element,
something like this:

[slot 1]: a
[slot 2]: b
[slot 3]: c
[slot 4]: d
[slot 5]: e


I also wanna be able to print out the letter by typing something like: Console.WriteLine([slot 1]);

or what ever I have to write.

I would really appreciate some help with this!
Thanks!

Answer Source

You're looking for a Dictionary<String, String>, not an array.

var myDict = Dictionary<String, String>();

myDict["slot 1"] = "a";
myDict["slot 2"] = "b";

var x = myDict["slot 1"];

if (myDict.ContainsKey("slot 3"))
{
    Console.WriteLine(myDict["slot 3"]);
}

etc.