0

I have seen examples on how to convert string to class type, but I was unable to apply the same logic to a class that has a constructor, which itself takes a string as a parameter. This is what I have seen on other posts.

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

What I want to do is to apply the same to this case

public class ExampleClass
{
    public ExampleClass(string strParameter)
    {
    }
}

I would normally instantiate ExampleClass as

var exClassInst = new ExampleClass("stringParam");

How can I achieve the same, but first converting "ExampleClass" string to type and then instantiating it. Thank you for your help.

user2217057
  • 237
  • 3
  • 17

3 Answers3

0

You could try finding the constructor and invoking it.

ConstructorInfo ci = type.GetConstructor( BindingFlags.Instance | BindingFlags.Public, null, new Type[0], null );
return (ExampleClass)ci.Invoke( new Object[] { "stringParam" );
csm8118
  • 1,213
  • 9
  • 11
0

You still can use Activator but using CreateInstance overload with the constructor arguments:

Type type = Type.GetType("Namespace.ExampleClass");
object instance = Activator.CreateInstance(type, "string param");
Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53
  • Thanks for your quick reply. Up to creating an instance with the string parameter seems fine, however, when I try to access the class methods via the instance.DoSomething() I receive an error - object does not contain a definition for DoSomething.... When I instantiate the class regular way, I can see the class methods. Not sure what's going on. – user2217057 Apr 22 '16 at 22:49
  • @user2217057: That's because `CreateInstance` return the instance as `object`, you have to cast it to `ExampleClass` to be able to use the proper members of that class. – Arturo Menchaca Apr 25 '16 at 13:55
  • How would you do casting if the class type is decided dynamically in a loop, based on a given string type? I might be missing something, but casting the object type into specific class type would work if the class type is already known. – user2217057 May 10 '16 at 20:29
  • If you don't know the type at compile time, then will need to access the members using reflexion. In your previous comment you say you cant call DoSomething() but if you don't know the type, how you know about this method, if is a base method, you can cast the object to the base type, otherwise you will need reflexion – Arturo Menchaca May 10 '16 at 20:49
0

Activator.CreateInstance has already the following overload:

Creates an instance of the specified type using the constructor that best matches the specified parameters.

public static object CreateInstance(
    Type type,
    params object[] args
)
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206