0

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;
    }
}
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
Imogen
  • 85
  • 13

1 Answers1

2

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);
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
  • I doubt that will help OP, as it assumes `Type` to be located in mscorlib. Otherwise you'd need an assembly-qualified name, which is probably OPs actual problem. – MakePeaceGreatAgain Jan 04 '23 at 11:36
  • @MakePeaceGreatAgain OP is not able to understand how to implement and looking for an example. I have tried to provide as many details as possible. – Vivek Nuna Jan 04 '23 at 11:46
  • System.ArgumentNullException HResult=0x80004003 Message=Value cannot be null. (Parameter 'type') Source=System.Private.CoreLib StackTrace: at System.Activator.CreateInstance(Type type, Boolean nonPublic, Boolean wrapExceptions) at System.Activator.CreateInstance(Type type) – Imogen Jan 04 '23 at 11:59
  • 1
    @Imogen you need to pass along with the namespace as well like `GetType("YouNamespace.Dog");` – Vivek Nuna Jan 04 '23 at 12:02
  • Type type = Type.GetType("Vets.Dog"); object instance = Activator.CreateInstance(type); I think this works (I get no errors this time). So now how do I use this instance of the class. E.g I want to call the 'Bark' method for the new dog. – Imogen Jan 04 '23 at 12:07
  • @Imogen check the Edit section of my answer – Vivek Nuna Jan 04 '23 at 12:10