First of all, this is not the purpose of reflection to create some instance of some type using hard-coded type name. Getting a type from string is rarely used (by serialization, for example) and fairly often abused. But I can understand if you are doing some exercises, for understanding.
None of the type can possibly have the name "class name", so the code will fail in first line. If you used another name, I'm not sure it was a correct full name. Also, this method assumes that the type is in the calling assembly. From your code, this is also unknown.
But let's assume you got the type object
t2
. Then the
Activator.CreateInstance
method you are using assumes that successful instantiation of this type if supposed to be performed using the parameterless constructor of the type, which is also not always the case.
So, this, for example, will work:
namespace TypeNamespace {
class Target {
public override string ToString() {
return "this is the right type";
}
}
class Program {
static void Main(string[] args) {
System.Type type = System.Type.GetType("TypeNamespace.Target");
System.Object @object = System.Activator.CreateInstance(type);
System.Console.WriteLine(@object.ToString());
}
}
}
Not the the namespace and its use in the file name and the fact this is all in one assembly. For other cases, you need to use
System.Assembly
methods.
Anyway, this is all practically useless. This is not the purpose of reflection.
More detailed and general approach for searching of types instantiation is not
Activator
, but the
System.Type
class itself. You find some appropriate constructor in metadata and, if such constructor is found, pass arguments to this method (which can also be done with
Activarot
). You need to confirm is that the right type to activate. It makes sense to never rely on names (strings). One good approach is to check up if the type implements some expected interface. As this is also type, not string, the compiler can check up validity of this code.
This code fragment tells you how you should ask the questions (please see my comment to the question). Note that the code sample is self-contained, written specially for this discussion, does not depend on anything else. Only then it makes sense for a forum post. Please see:
http://www.sscce.org[
^].
—SA