Home > Back-end >  How do I make a new class whose name is gathered from user input?
How do I make a new class whose name is gathered from user input?

Time:01-05

I want to create a new instance of a class but I want the name of the instance to be the name inputted by the user whilst the program is running. I don't want Employee employee = new Employee();. I want it to be named according to what the user inputs.

Console.WriteLine("Enter Employee name");
       string inputName = Console.ReadLine();
       Employee [ inputName ] = new Employee();

e.g. If 'inputName' was 'Kaylee' then how do I create an instance whilst the program is running of Employee Kaylee = new Employee();

CodePudding user response:

As others were pointing out in the comments, dynamically defining a variable name is not possible!

If you want your Employee class to be associated to a name that was input by a user, you have two options in my opinion:

  1. Give your Employee class a "Name" property

    public class Employee
    {
        public string Name { get; set; }
    }
    

    That way you can do something like this:

    Console.WriteLine("Enter Employee name");
    string inputName = Console.ReadLine();
    EmployeeList.Add(new Employee{ Name = inputName });
    
  2. Use a dictionary

    Dictionary<string, Employee> employees = new Dictionary<string, Employee>();
    Console.WriteLine("Enter Employee name");
    string inputName = Console.ReadLine();
    // Check if employee already exists, since dictionary keys have to be unique
    if(!employees.ContainsKey(inputName))
    {
        employees.Add(inputName, new Employee());
    }
    

Hope this helps!

  • Related