I have an array where the user can fill it up with objects. Objects are different sodas. There is a function in this simulator where the user has the option to find a specific soda. I don't want it to be case-sensitive so im using the method ToLower(). Everything works fine until one of the spots in the array is empty. I get a null reference error.
I've been trying to solve this issue by using a if statement but then the variable is unavailable in other statements.
How can i solve my issue???
Thanks in advance!
do
{
name = Console.ReadLine();
nameL = name.ToLower();
if (name == "h" || name == "H")
break;
for (int i = 0; i < sodas.Length; i++)
{
sodasL = sodas[i].Name.ToLower();
if (name == "h" || name == "H")
{
Run();
break;
}
else if (sodas[i] == null)
Console.WriteLine("Det är tomt på indexet: {0}!", i + 1);//translation: its empty at index..
else if (sodasL != nameL)
Console.WriteLine("Drycken hittades inte på indexet: {0}.", i + 1);//translation: Could not find soda at index...
else if (sodasL == nameL)
{
Console.WriteLine("Drycken {0} finns på indexet: {1}.\n", sodas[i].Name, i + 1);//translation: found soda at index...
Console.WriteLine("Vill du ta bort drycken?");//translation do you want to remove soda?
Console.WriteLine("[J]a");//yes
Console.WriteLine("[N]ej");//no
Console.WriteLine("[G] för nästa {0}.", sodas[i].Name);
string inmatat = Console.ReadLine();
if (inmatat == "j" || inmatat == "J")
{
amount_bottles--;
sodas[i] = null;
Console.WriteLine("Drycken har tagits bort! Sök efter en annan dryck eller [H] för Huvudmenyn");//soda has been removed
break;
}
else if (inmatat == "n" || inmatat == "N")
{
Console.WriteLine("Drycken är kvar! Sök efter en annan dryck eller [H] för Huvudmenyn.");//soda has not been removed
break;
}
}
}
} while (name != "h" || name != "H");
According to your code, you add objects to sodas
. Let's say that your object looks like this class:
public class Container
{
public string Name;
}
When you add a new object without initialisation of the Name
field, like:
sodas[0] = new Container();
The field Name
is null
. So, in this case, when you call sodasL = sodas[i].Name.ToLower()
, it looks like:
string name = sodas[0].Name; // name = null!!!
sodasL = name.ToLower(); // You try to call the method of an object, but the reference is null.
Here is a couple of solutions:
Name
by default (it may be an empty string).public class Container { public string Name = ""; }
Name
before the ToLower
call.string name = sodas[i].Name; if (name != null) { sodasL = name.ToLower(); // ... }