Home > Software engineering >  Add returned user input to list of strings
Add returned user input to list of strings

Time:11-11

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.

CodePudding user response:

if you do Students list = new(); you reintialize your list dont do that.

Like your list students is defined in the class, you could write:

public void AttendenceList()
{
    Console.WriteLine("All students attending class today:\r\n");
    foreach (var item in students)
    {
            Console.WriteLine(item);
    }
}
  • Related