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

    Is there a way to instantiate by name?

    I'd like to avoid switch/case statements and/or keeping track of some sort of indexing array/collection.

    I need to be able to do something like:

    Code:
     
            public Iclasstype makeObject(string makeme)
            {
                Iclasstype myobjectvar = new ("classprefix" + makeme)
               // OR
                Iclasstype myobjectvar = new System.SomeByNameFunction("classprefix" + makeme)
    
            }

  2. #2
    Join Date
    May 2003
    Location
    Germany
    Posts
    936

    Re: Is there a way to instantiate by name?

    Have a look at the System.Reflection namespace.
    Useful or not? Rate my posting. Thanks.

  3. #3
    Join Date
    Mar 2004
    Location
    33°11'18.10"N 96°45'20.28"W
    Posts
    1,808

    Re: Is there a way to instantiate by name?

    Code:
    Type theType = Type.GetType(typename);
    
    IClassType ict = (IClassType)Activator.CreateInstance(theType);
    if the assembly containing that type has not been loaded into the app domain, it wont be able to find it using Type.GetType(...), instead you'll need to load the assembly containing that class, then use the assembly object to GetType & pass in a fully qualified type string.

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