I'm working on a project that use different methods to get input from the user and I want to add the user input to a list.
My code looks like this:
public string GetValidName()
{
Console.WriteLine("Let's get you registered!");
Console.WriteLine("Enter your full name: ");
string input = Console.ReadLine();
bool validString = false;
while (validString != true)
{
if (String.IsNullOrEmpty(input))
{
Console.WriteLine("Not a valid input.");
validString = false;
}
else
{
validString = true;
}
}
return input;
}
The list exists in the same class and is declared public List<string> students = new();
I have tried return students.Add(input); but that is not possible and gives the error
Cannot implicitly convert type 'void' to 'string'
Edit This method is called through this method and has been edited with changes so it now looks like this;
public void Register()
{
students.Add(GetValidName());
}
To print all items in the list I use this piece of code:
public void AttendenceList()
{
Students list = new();
Console.WriteLine("All students attending class today:\r\n");
foreach (var item in list.students)
{
Console.WriteLine(item);
}
}
When the foreach loop runs, it only prints the Console.WriteLine though, and not any items in the list.
List<string.Add(...)does not return a value, hencevoid. Perhaps you meant to first add to the list, thenreturn input;?string.IsNullOrWhiteSpaceand the user enters only spaces it will return true as well. link