Create an instance of a class from a string

I have a C # method that creates a new instance of a class from a string, however I get an error when I run 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.

+4
source share
7 answers

You may need to use a qualified assembly name as an argument to Type.GetType

 eg AssemblyName.Namespace.ClassName 

MSDN Doc for the assembly names assigned to them

+5
source

Maybe you just do not have enough namespace from the class name

+3
source

Works for me:

 class ClassX {} class classPrefix_x : ClassX {} public class Program { public static void Main() { string className = "x"; ClassX obj = (ClassX)Activator.CreateInstance(Type.GetType("classPrefix_" + className)); Console.WriteLine(obj); } } 

Result:

 classPrefix_x 

The class you are looking for should not be defined. Are you sure you typed it correctly?

+1
source

It looks like your call to Type.GetType("classPrefix_" + className) returns null . This throws an ArgumentNullException when passed to the CreateInstance method.

Evaluate "classPrefix_" + className and make sure you have a type called what it evaluates.

You must also specify AssemblyQualifiedName when using Type.GetType (i.e. the fully qualified name of the type, including the assembly name and namespace).

0
source

You probably don't have the type "classPrefix_" plus everything you have on className. A call to Type.GetType () returns null, and CreateInstance throws an ArgumentNullException.

0
source

This is due to the fact that Type.GetType(classHere) did not find anything, are you sure that the name of the class after which exists? Remember that it must have a namespace prefix, if possible, and will not be found in the external assembly if it is not already loaded into the application domain.

0
source

It looks like Type.GetType("classPrefix_" + className) returns null.

This returns null when it cannot find the type. A couple of possible reasons: the namespace is missing or the assembly in which the class is located is not yet loaded.

Api documentation on a method that can give some more. http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx

0
source

Source: https://habr.com/ru/post/1301879/


All Articles