creating dynamic classes
-
Hi, I am getting the name of the class from database as string. I want to create object for this class dynamically. how do I do it?
-
Create a Type object from the name. Use the GetConstructor method to get a ConstructorInfo object for the constructor. Use the Invoke method to run the constructor. --- b { font-weight: normal; }
-
I explained exactly how to do it. Need I actually do it for you also? --- b { font-weight: normal; }
-
That wasnt rude. It was simply "Give it a try yourself". Teach a man to fish and all that..... Current blacklist svmilky - Extremely rude | FeRtoll - Rude personal emails | ironstrike1 - Rude & Obnoxious behaviour
-
Hi, I am getting the name of the class from database as string. I want to create object for this class dynamically. how do I do it?
As well as the answer already provided, which will work no problem, you can also look at the
CreateInstance
method on theActivator
class. The documentation can be found on msdn. Current blacklist svmilky - Extremely rude | FeRtoll - Rude personal emails | ironstrike1 - Rude & Obnoxious behaviour -
Hi, I am getting the name of the class from database as string. I want to create object for this class dynamically. how do I do it?
Hi, As well as the class name, you need to know what assembly the class is contained in. There are different ways of doing this, but just lifting a bit of code from work:
Assembly assembly = Assembly.LoadFile(@"c:\myassembly.dll");
object dynamicClass = assembly.CreateInstance(classNameFromDb);Not sure that helps as you end up with an untyped object. The way we do it here is to make the objects we create dynamically implement an interface, so the second line actually looks more like
IDynamicObject dynamicClass = assembly.CreateInstance(classNameFromDb) as IDynamicObject;
This way, we can then call the methods the interface specifies. After all, creating an instance of a class is little use if you have no idea what the object does. This is why defining an interface is useful. And don't forget the gotcha, the trap I always fall in with this, its not just the type name you need, but also the namespace. eg. "MyNamespace.MyClass" which you need to pass to CreateInstance. Regards, Rob Philpott.