How can you instanitiate a class using a string value? RRS feed

  • Question

  • User-2079069310 posted

    I have a string variable that represents the name of a child class. Example:

    string s = "CustomerA"

    I will need to create a customer using the base class. So, the syntax needed is:

    Customer cust = new ..

    what is the sytax?

    I've had a look at the activator.create instance method but I cant really figure out the syntax

    Customer cust = (Customer)Activator.CreateInstance(Type.GetType("CustomerA"));

    Using the above gives me the following error

    Value cannot be null. Parameter name: type

    Tuesday, July 8, 2014 5:56 AM


  • User-760709272 posted

    Your code is fine, however you need to provide the full type name, not just the class name. 

    string s = "YourNamespace.CustomerA";

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 8, 2014 6:11 AM