Hi to all expert.... How to dynamically instantiate a class based on a string being the class name???:nonod: thanks for reply....
Create the object in a switch case statement when the right string is passed the right object is created.
you can instantiate a class dynamically based on string by using the Assembly class (System.Reflection.Assembly) here is a simple sample code Code: private void LoadClass() { Assembly a = Assembly.GetExecutingAssembly() ; //create the class base on string //note : include the namespace and class name (namespace=WindowsFormsApplication1, class name=DynamicLoad) Object o = a.CreateInstance("WindowsFormsApplication1.DynamicLoad"); //check to see if the class is instantiated or not if (o != null) { Console.WriteLine("Class Loaded"); } else { Console.WriteLine("Failed"); } } Hope this help
Hi excavator.... thanks for that piece of code...Honestly, I am very new on this.....but I will just study on this code... Thanks again....
Hi excavator.... thanks for that piece of code... Honestly, I am very new on this.....but I will just study on it... I will just post follow up question if any..... Thanks again....
Well, although excavator's approuch will work, it isnt very 'clean'. Why would you want to create a class, based on a string? Where do's that string come from, user input or your own? If its from the user, you really dont want this. They could just execute any code in your application. If you declared that string yourself, consider changing it to an enum, or better yet think of something else. You could for instance use Inheritance, where you have one base class and several depend on it. Thats most likely the way to go.
Not sure I agree it's not 'clean' - or that you don't want classes instantiated from user input. An example where I want to do this is when I'm reading a set of commands from a text file - then creating "command" classes based on the text read from each line (which are then queued & processed). Using the "switch" approach would lead to a huge multi-choice clause which is not elegant. The CreateInstance approach removes the Switch. If I'm thinking along your lines, an enum would require a switch, wouldn't it?