Home > OS >  Using runtime string input to instantiate a class
Using runtime string input to instantiate a class

Time:01-04

I want to create an instance of a class using the name which the user has provided in the code.

I know about the Activator.CreateInstance method which has been the answer to similar questions but without an example I'm stumped.

class Program
{
    static void Main()
    {
        Program Pet = new Program();         
        string Name = Pet.GetName();
        Pet.GetSpecies(Name);            
    }

    public void GetSpecies(string name)
    {
        Console.WriteLine($"What species is {name}? We currently see: Dog/Cat/Hamster/Gerbil");
        string answer = Console.ReadLine();
        answer = answer.ToLower();

        if (answer == "dog")
        {
            Console.WriteLine("You have selected: Dog");                
            Dog name = new Dog(); //?
        }                  
    }

    public string GetName()
    {
        Console.WriteLine("And what is your pets name?");            
        string name = Console.ReadLine();
        return name;
    }
}

CodePudding user response:

I will provide you simple example to understand.

Type.GetType("Dog") will give you the Type object for the class named "Dog", and then Activator.CreateInstance(type) will create an instance of this class.

Type type = Type.GetType("Dog");
object instance = Activator.CreateInstance(type);

Few review comments for you below.

You don't need to create an instance of the Program class in order to call its methods. You can simply call the methods directly.

You are using the same variable name for the object, so please use the relevant name.

and also please check, I think it's irrelevant to call the same method in exception, please check.

you can also go for a switch statement if you just want to create an object based on the user input.

switch (answer)
{
    case "dog":
        Console.WriteLine("You have selected: Dog");
        Dog dog = new Dog();
        break;

    case "cat":
        Console.WriteLine("You have selected: Cat");
        Cat cat = new Cat();
        break;

Edit:

You can call the Bark method like this.

MethodInfo method = type.GetMethod("Bark");
method.Invoke(instance, null);
  • Related