Skip to main content
added 453 characters in body
Source Link
Marc Gravell
  • 1.1m
  • 273
  • 2.6k
  • 3k

If key is either assembly-qualified, or namespace-qualified within either the core assemblies or the calling assembly, then:

Type type = Type.GetType(key);
return constructorParameter == null ? Activator.CreateInstance(type)
          : Activator.CreateInstance(type, constructorParameter);

I wonder, though, if:

public static object getClassInstance(string key, params object[] args)

is more flexible, allowing:

Type type = Type.GetType(key);
return Activator.CreateInstance(type, args);

with usage such as:

object o = getClassInstance(key); // uses default constructor
object o = getClassInstance(key, null); // passes null to single parameter
object o = getClassInstance(key, 123, "abc"); // etc

If key is either assembly-qualified, or namespace-qualified within either the core assemblies or the calling assembly, then:

Type type = Type.GetType(key);
return constructorParameter == null ? Activator.CreateInstance(type)
          : Activator.CreateInstance(type, constructorParameter);

If key is either assembly-qualified, or namespace-qualified within either the core assemblies or the calling assembly, then:

Type type = Type.GetType(key);
return constructorParameter == null ? Activator.CreateInstance(type)
          : Activator.CreateInstance(type, constructorParameter);

I wonder, though, if:

public static object getClassInstance(string key, params object[] args)

is more flexible, allowing:

Type type = Type.GetType(key);
return Activator.CreateInstance(type, args);

with usage such as:

object o = getClassInstance(key); // uses default constructor
object o = getClassInstance(key, null); // passes null to single parameter
object o = getClassInstance(key, 123, "abc"); // etc
Source Link
Marc Gravell
  • 1.1m
  • 273
  • 2.6k
  • 3k

If key is either assembly-qualified, or namespace-qualified within either the core assemblies or the calling assembly, then:

Type type = Type.GetType(key);
return constructorParameter == null ? Activator.CreateInstance(type)
          : Activator.CreateInstance(type, constructorParameter);