Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a string to a List

I have a variable usersInput which has a value Console.ReadLine()
I want to add this variable to the array built with List

static void Resize<T>(ref List<T> array, string name)
        {
                     
            array.Add(name);
            Console.WriteLine();
            for (int i = 0; i < array.Count; i++)
            {
                Console.WriteLine(array[i]);
            }
        }


static void Main(string[] args)
        {

             List<string> teachers = new List<string> { "1", "2", "3"};
             Console.WriteLine("Enter a name");
             string userInput = Console.ReadLine();
             Resize(ref teachers, userInput);
                           
        }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why do you need Resize<T> method at all? You could do it easier:

    static void Main(string[] args)
    {

        List<string> teachers = new List<string> { "1", "2", "3" };
        Console.WriteLine("Enter a name");
        string userInput = Console.ReadLine();

        if (string.IsNullOrWhiteSpace(userInput) || !string.IsNullOrEmpty(userInput))
        {
            teachers.Add(userInput);
        }

        // if want to change list to array then use
        // var arr = teachers.ToArray();

        foreach (var teacher in teachers)
        {
            Console.WriteLine(teacher);
        }

    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading