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;
    }
}
4
  • xyproblem.info ? Its really not clear what you are trying to do. Commented Jan 4, 2023 at 11:29
  • Does this answer your question? Purpose of Activator.CreateInstance with example? Commented Jan 4, 2023 at 11:30
  • 1
    why are you calling GetName in exception? Commented Jan 4, 2023 at 11:30
  • why do you even want reflection? What's the problem with if(answer == "Dog") return new Dog()? Commented Jan 4, 2023 at 11:37

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

6 Comments

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 OP is not able to understand how to implement and looking for an example. I have tried to provide as many details as possible.
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 you need to pass along with the namespace as well like GetType("YouNamespace.Dog");
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.