Home > Software engineering >  Is it possible to fill an ArrayList with Console.ReadLine?
Is it possible to fill an ArrayList with Console.ReadLine?

Time:10-05

I'm trying to fill my ArrayList with Console.ReadLine. Unfortunately, I always get an error. Is there another possibility?

class Program
    {
        static void Main(string[] args)
        {
            ArrayList names = new ArrayList();
            names.Add() = Console.ReadLine();
            names.Add() = Console.ReadLine();
            names.Add() = Console.ReadLine();
        }
    }

CodePudding user response:

Your syntax is entirely wrong. You're trying to assign a value to a method invocation (names.Add()), which is not possible. What you want to do is pass the contents of Console.ReadLine() into the method invocation as a parameter:

class Program
    {
        static void Main(string[] args)
        {
            ArrayList names = new ArrayList();
            names.Add(Console.ReadLine());
            names.Add(Console.ReadLine());
            names.Add(Console.ReadLine());
        }
    }

Now, this code is also not very good as you could enter invalid input or not enter anything at all. Ideally your code would be performing some kind of validation to ensure you're only adding values you really want to add into the array.

CodePudding user response:

You can't assign a value to a methode, instead you have to give the value to the methode inside the parenthes like this. names.Add(Console.ReadLine());

CodePudding user response:

try this

   ArrayList names = new ArrayList();
    Console.WriteLine ("type ? to exit")
    var name=string.Empty;
    do
    {
         name =Console.ReadLine();
         if(name!="?")  names.Add(name );
        
    } while(name!="?")
  • Related