Search code examples
c#asp.netobjectconsoleuserinfo

How to create more than one object from user input in c# console app?


in class File:

 class Employee {
   //PROPS
   public string Name {get; set;}
   public int Id {get; set;}
   //CONST.
   public Employee (string name, int id){
      Name = name;
      Id = id;
   }

in method class ( or in Main() ):

public void NewEmployee(string name, int id){

   Console.Write("ENTER NEW NAME: ");
   string new_employee = Console.ReadLine();
   Console.Write("ENTER ID: ");
   int employee_id = Console.ReadLine();

   Employee e = new Employee(new_employee, employee_id);
}

now it creates only one object I called it "e". but how to create more than one object one after the other by user?


Solution

  • I'd probably do something along the lines of:

       List<Employee> employees = new List<Employee>();
    
       while (true) {
           Console.Write("ENTER NEW NAME: ");
           string new_employee = Console.ReadLine();
           if (new_employee == "")
               break;
           Console.Write("ENTER ID: ");
           int employee_id = Console.ReadLine();
           Employee e = new Employee(new_employee, employee_id);
           employees.Add(e);
        }
       
    

    This will add new employees to a list until it gets an empty line for the name.