CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Feb 2007
    Posts
    1

    Question 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.

  2. #2
    Join Date
    Apr 2005
    Posts
    576

    Re: Creating a managed object by name

    Yes, it can be done using System.Reflection.

  3. #3
    Join Date
    Apr 2004
    Location
    England, Europe
    Posts
    2,492

    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.
    My hobby projects:
    www.rclsoftware.org.uk

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured