I have the following code which is intended, as an example, to take a fruitName and assign it to the next available unused "name#" string variable (one that does not already have a fruit name assigned to it).
Wanting to avoid using nested IF statements, i am trying to use a Dictionary as follows.
public static void AssignFruitToNextAvailableSlot(string fruitName)
{
string NextEmptyNameSlot = "";
string Name1 = "Apple";
string Name2 = "Orange";
string Name3 = "Tomato";
string Name4 = "";
string Name5 = "";
string Name6 = "";
string Name7 = "";
string Name8 = "";
string Name9 = "";
Dictionary<string, string> nameSlots = new Dictionary<string, string>()
{
{"Slot1", Name1},
{"Slot2", Name2},
{"Slot3", Name3},
{"Slot4", Name4},
{"Slot5", Name5},
{"Slot6", Name6},
{"Slot7", Name7},
{"Slot8", Name8},
{"Slot9", Name9}
};
foreach (KeyValuePair<string, string> nameSlot in nameSlots)
{
NextEmptyNameSlot = nameSlot.Key;
if (nameSlot.Value == "")
{
break;
}
}
Console.WriteLine($"Available name slot at {NextEmptyNameSlot}");
Console.WriteLine($"Content of empty name slot \"{nameSlots[NextEmptyNameSlot]}\"");
nameSlots[NextEmptyNameSlot] = fruitName;
Console.WriteLine($"Empty image slot has been assigned the value {nameSlots[NextEmptyNameSlot]}");
Console.WriteLine($"Empty image slot has been assigned the value {Name4}");
Console.ReadLine();
}
Sample output for AssignFruitToNextAvailableSlot("Strawberry") :
- Available name slot at Slot4
- Content of empty name slot ""
- Empty image slot has been assigned the value Strawberry
- Empty image slot has been assigned the value
As you can see the code works fine to identify the empty name slot, in this case Slot4. However when using the syntax...
nameSlots[NextEmptyNameSlot] = fruitName
... "strawberry" is assigned to nameSlots[NextEmptyNameSlot], but not the variable Name4. I tried using "ref" to assign by reference but that yielded various error messages.
** What is the right syntax to assign the fruitName "Strawberry" to the Name4 string variable using the dictionary? Sorry if this is a very basic question. I am new to C#. **