dynamic generic creation using Type.GetType(string)?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • jon

    dynamic generic creation using Type.GetType(string)?

    I'm trying to write a block of code that can create an instance of a
    generic object, with the Type coming in as a dynamic string. It isn't
    working yet. Any advice how I can dynamically create the appropriate
    object to pass into the generic's constructing <T,U>?


    -------------------------------
    // fully qualified types as string
    string type1Str = "ns1.ns2.contro l1, software.lib1";
    string type2Str = "ns1.ns2.contro l2, software.lib1";

    // create type objects
    Type type1Type = Type.GetType(ty pe1Str);
    Type type2Type = Type.GetType(ty pe2Str);

    // try to create generic object passing in dynamic types
    // this next line doesn't compile because of "type1Type" not being
    appropriate here
    GenericObj<type 1Type, type2Typegeneri cObj = new
    GenericObj<type 1Type, type2Type>();

    public class GenericObj<T,U{
    ......
    }
  • Marc Gravell

    #2
    Re: dynamic generic creation using Type.GetType(st ring)?

    Something like:

    Type final = typeof(GenericO bj<,>).MakeGene ricType(type1Ty pe,
    type2Type);
    object obj = Activator.Creat eInstance(final );

    Marc

    Comment

    • Jon Skeet [C# MVP]

      #3
      Re: dynamic generic creation using Type.GetType(st ring)?

      jon <jon.sajdak@gma il.comwrote:
      I'm trying to write a block of code that can create an instance of a
      generic object, with the Type coming in as a dynamic string. It isn't
      working yet. Any advice how I can dynamically create the appropriate
      object to pass into the generic's constructing <T,U>?
      You have to use reflection:

      Type open = typeof(GenericO bj<,>);
      Type constructed = open.MakeGeneri c(new Type[]{type1Type, type2Type});
      object instance = Activator.Creat eInstance(const ructed);
      ....

      --
      Jon Skeet - <skeet@pobox.co m>
      Web site: http://www.pobox.com/~skeet
      Blog: http://www.msmvps.com/jon.skeet
      C# in Depth: http://csharpindepth.com

      Comment

      Working...