-
February 2nd, 2007, 09:26 AM
#1
Creating a managed object by name
I am moving from a C++/MFC environment to C# and the .NET framework. MFC allows C++ classes to be instantiated by name (a string value) at runtime by including runtime class macros in the C++ class definitions. I am looking for the C# .NET equivalent to this mechanism. Specifically, I need to be able to create an instance of a managed class at runtime given a string with the class name as its value. Any ideas? Thanks.
-
February 3rd, 2007, 09:26 AM
#2
Re: Creating a managed object by name
Yes, it can be done using System.Reflection.
-
February 3rd, 2007, 09:37 AM
#3
Re: Creating a managed object by name
You need to get hold of an object of type System.Reflection.Assembly representing the assembly (i.e. the EXE or DLL) in which the class is defined.
You can then call Assembly.CreateInstance(fullClassNameWithNamespace);
For example you can create an instance of a class like this.
Code:
System.Object MakeMyObject(System.String fullClassNameWithNamespace)
{
// Get the assembly in which the current method is defined:
System.Reflection.Assembly thisAssembly = System.Reflection.Assembly.GetExecutingAssembly();
// Create an instance of a class which is defined in this assembly.
return thisAssembly.CreateInstance(fullClassNameWithNamespace);
}
Last edited by Zaccheus; February 3rd, 2007 at 09:48 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|