I'm trying to create a class using Activator.CreateInstance(assemblyName, typeName)
but I am getting the error
An unhandled exception of type 'System.TypeLoadException' occurred in mscorlib.dll
Additional information: Could not load type 'Question' from assembly 'AssessmentDeepCompare, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
In this example (which generates the error above) I'm trying to instantiate Question
which inherits from IAssessmentObject
and is in the same assembly.
public IAssessmentObject getInstance(string typeName) {
string assemblyName = Assembly.GetAssembly(typeof (IAssessmentObject)).ToString();
return (IAssessmentObject)Activator.CreateInstance(assemblyName, typeName);
}
What is the proper way to instantiate an object when you only have the Type name without the namespace or assembly?
It sounds like you do have the assembly - just not the namespace-qualified type name.
You can fetch all the types in the assembly, and get the type from that:
var type = typeof(IAssessmentObject).Assembly
.GetTypes()
.Single(t => t.Name == "Question");
var instance = (IAssessmentObject) Activator.CreateInstance(type);
See more on this question at Stackoverflow