C # class instance from string

I have an abstract class, and I want to initialize it for a class that extends it.

I have the name of the child classes as a string.

Besides...

String childClassString; MyAbstractClass myObject; if (childClassString = "myExtenedObjectA") myObject = new ExtenedObjectA(); if (childClassString = "myExtenedObjectB") myObject = new ExtenedObjectB(); 

How can i do this? Basically, how can I get rid of if statements here?

+51
polymorphism reflection c #
Feb 11 2018-10-11T00
source share
3 answers

Take a look at Activator.CreateInstance ().

 myObject = (MyAbstractClass)Activator.CreateInstance("AssemblyName", "TypeName"); 

or

 var type = Type.GetType("MyFullyQualifiedTypeName"); var myObject = (MyAbstractClass)Activator.CreateInstance(type); 
+98
Feb 11 '10 at 20:47
source share

I believe this should work:

 myObject = (MyAbstractClass)Activator.CreateInstance(null, childClassString); 

null in the first parameter, the current execution assembly is used by default. For more information: MSDN

edit: forgot to translate to MyAbstractClass

+19
Feb 11 '10 at 20:53
source share

It was difficult for me to fulfill some of the answers here because I was trying to instantiate an object from another assembly (but in the same solution). Therefore, I thought I would publish what I found to work.

First, the Activator.CreateInstance method has several overloads. If you simply call Activator.CreateInstance(Type.GetType("MyObj")) , this assumes that the object is defined in the current assembly, and it returns MyObj .

If you answer as indicated in the answers here: Activator.CreateInstance(string AssemblyName, string FullyQualifiedObjectName) , it returns an ObjectHandle , and you need to call Unwrap() on it to get your object. This overload is useful when trying to call a method defined in another assembly (BTW, you can use this overload in the current assembly, just leave the AssemblyName parameter null).

Now I found that the suggestion typeof(ParentNamespace.ChildNamespace.MyObject).AssemblyQualifiedName for AssemblyName suggested above really gave me errors, and I could not get this to work. I would get a System.IO.FileLoadException (could not load the file or assembly ...).

What I got works as follows:

 var container = Activator.CreateInstance(@"AssemblyName",@"ParentNamespace.ChildNamespace.MyObject"); MyObject obj = (MyObject)container.Unwrap(); obj.DoStuff(); 
+2
Apr 02 '17 at 22:58 on
source share



All Articles