I have a C# method which creates a new instance of a class from a string, however, I get an error when running the code.
obj = (ClassX)Activator.CreateInstance(Type.GetType("classPrefix_" + className));
ArgumentNullException was unhandled
Value cannot be null
Parameter name: type
Any help on this error would be appreciated.
This is because the
Type.GetType(classHere)
didn't find anything, are you sure that the classname you're after exists? Remember it should be prefixed with a namespace if possible, and won't be found in an external assembly unless it's already loaded in the App domain.It looks like
Type.GetType("classPrefix_" + className)
is returning null.This returns null when it cannot find the type. A couple of possible causes are missing namespace, or the assembly the class is in is not loaded yet.
The Api documentation on the method which may give some more insite. http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx
You may need to use the assembly qualified name as the argument to Type.GetType
MSDN Doc on assembly qualified names
It looks like your
Type.GetType("classPrefix_" + className)
call is returning anull
. This is causing theArgumentNullException
when passed to theCreateInstance
method.Evaluate
"classPrefix_" + className
and check that you do have a type called what it evaluates to.You also should be specifying the AssemblyQualifiedName when using the Type.GetType method (ie. the fully qualified type name including the assembly name and namespace).
Works for me:
Result:
The class you are looking for must not be defined. Are you sure you typed it correctly?
You may just be missing the namespace from the classname