C
C#9mo ago
Mekasu0124

✅ Object reference not set to an instance of an object?

public class UserGenerator
{
private static Random rand = new();

private static List<string> SelectRandomNames(int count)
{
List<string> selectedNames = new();

for (int i = 0; i < count; i++)
{
int index = rand.Next(0, Names.Count);
string name = Names[index];
selectedNames.Add(name);
}

return selectedNames;
}
}
public class UserGenerator
{
private static Random rand = new();

private static List<string> SelectRandomNames(int count)
{
List<string> selectedNames = new();

for (int i = 0; i < count; i++)
{
int index = rand.Next(0, Names.Count);
string name = Names[index];
selectedNames.Add(name);
}

return selectedNames;
}
}
I keep getting a run-time error of Object reference not set to an instance of an object on line int index = rand.Next(0, Names.Count); and I'm not sure why.
5 Replies
Jimmacle
Jimmacle9mo ago
process of elimination of the things on that line, what could possibly be null? i'm confused because this code doesn't compile to begin with
Buddy
Buddy9mo ago
you initialize random rand and it can't be null because you don't modify it anywhere, so you exclude that. then only thing that is left being Names make sure that is not null. $debug
MODiX
MODiX9mo ago
Tutorial: Debug C# code and inspect data - Visual Studio (Windows)
Learn features of the Visual Studio debugger and how to start the debugger, step through code, and inspect data in a C# application.
Buddy
Buddy9mo ago
Learn to use the debugger, it's the absolute most important tool a developer could have.
Mekasu0124
Mekasu0124OP9mo ago
I do use the debugger. I spend x amount of time on error's before I even come here to ask for help. I try and solve them first through my own research, trial, and error.
Want results from more Discord servers?
Add your server