Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Dynamic Types in Generics?

Dynamic Types in Generics?

Scheduled Pinned Locked Moved C#
csharptutorialquestion
13 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N NandoMan

    Hello people, Is it posible to declare the type of a generic at runtime? I mean, you normaly would have to do something like this: GenericMethod<Type>(); And I want to do something like this: GenericMethod<(expression that evaluates to a type)>(); I have tried a few things but nothing seems to work. MSDN's C# Programming Guide states that: "client code must declare and instantiate a constructed type by specifying a type argument inside the angle brackets. The type argument for this particular class can be any type recognized by the compiler." Thanks!

    P Offline
    P Offline
    Pete OHanlon
    wrote on last edited by
    #2

    You could always use a Func here. For instance:

    GenericMethod<Func<T, TResult>>();

    "WPF has many lovers. It's a veritable porn star!" - Josh Smith

    As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

    My blog | My articles | MoXAML PowerToys | Onyx

    N 1 Reply Last reply
    0
    • P Pete OHanlon

      You could always use a Func here. For instance:

      GenericMethod<Func<T, TResult>>();

      "WPF has many lovers. It's a veritable porn star!" - Josh Smith

      As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

      My blog | My articles | MoXAML PowerToys | Onyx

      N Offline
      N Offline
      NandoMan
      wrote on last edited by
      #3

      Thanks Pete, And what exactly would this Func be or do? Thanks again!

      P 1 Reply Last reply
      0
      • N NandoMan

        Thanks Pete, And what exactly would this Func be or do? Thanks again!

        P Offline
        P Offline
        Pete OHanlon
        wrote on last edited by
        #4

        This[^] article should help. This type of functionality is the mojo behind Linq.

        "WPF has many lovers. It's a veritable porn star!" - Josh Smith

        As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

        My blog | My articles | MoXAML PowerToys | Onyx

        D N 2 Replies Last reply
        0
        • P Pete OHanlon

          This[^] article should help. This type of functionality is the mojo behind Linq.

          "WPF has many lovers. It's a veritable porn star!" - Josh Smith

          As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

          My blog | My articles | MoXAML PowerToys | Onyx

          D Offline
          D Offline
          DaveyM69
          wrote on last edited by
          #5

          Good link Pete, very concise. :-D

          Dave
          BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
          Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
          Why are you using VB6? Do you hate yourself? (Christian Graus)

          1 Reply Last reply
          0
          • N NandoMan

            Hello people, Is it posible to declare the type of a generic at runtime? I mean, you normaly would have to do something like this: GenericMethod<Type>(); And I want to do something like this: GenericMethod<(expression that evaluates to a type)>(); I have tried a few things but nothing seems to work. MSDN's C# Programming Guide states that: "client code must declare and instantiate a constructed type by specifying a type argument inside the angle brackets. The type argument for this particular class can be any type recognized by the compiler." Thanks!

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #6

            What kind of expression that evaluates to a type would you have there? Something with reflection? You could probably use reflection to invoke the method with an expression of the type Type, but I'm not actually sure. Reflection can do a lot though, so why not.. edit: If all else fails, there is still the possibility to compile and run a piece of code that has been generated at runtime. But I wouldn't use that except in emergencies. It's not exactly fast, or a clean design.

            0 1 Reply Last reply
            0
            • L Lost User

              What kind of expression that evaluates to a type would you have there? Something with reflection? You could probably use reflection to invoke the method with an expression of the type Type, but I'm not actually sure. Reflection can do a lot though, so why not.. edit: If all else fails, there is still the possibility to compile and run a piece of code that has been generated at runtime. But I wouldn't use that except in emergencies. It's not exactly fast, or a clean design.

              0 Offline
              0 Offline
              0x3c0
              wrote on last edited by
              #7

              A method which may prove useful is Type.MakeGenericType[^]. I don't fully understand it, but it seems to be a step in the right direction - getting the type of a generic type (without the type specifiers), then calling MakeGenericType on the result to get a dynamically set Type

              Between the idea And the reality Between the motion And the act Falls the Shadow

              N 1 Reply Last reply
              0
              • P Pete OHanlon

                This[^] article should help. This type of functionality is the mojo behind Linq.

                "WPF has many lovers. It's a veritable porn star!" - Josh Smith

                As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

                My blog | My articles | MoXAML PowerToys | Onyx

                N Offline
                N Offline
                NandoMan
                wrote on last edited by
                #8

                Thanks Pete, I read your link and it seems this particular feature it's not for C# 2.0, which is preciselly the version i'm working :(

                1 Reply Last reply
                0
                • N NandoMan

                  Hello people, Is it posible to declare the type of a generic at runtime? I mean, you normaly would have to do something like this: GenericMethod<Type>(); And I want to do something like this: GenericMethod<(expression that evaluates to a type)>(); I have tried a few things but nothing seems to work. MSDN's C# Programming Guide states that: "client code must declare and instantiate a constructed type by specifying a type argument inside the angle brackets. The type argument for this particular class can be any type recognized by the compiler." Thanks!

                  E Offline
                  E Offline
                  Eslam Afifi
                  wrote on last edited by
                  #9

                  This code creates a generic type and instatiate an object of that type in runtime using MakeGenericType as Computafreak mentioned. I was going to post it last night but I forgot and fell asleep. But now I know you want it in .net 2.0 I have to remove var and new[]

                  static void Main(string[] args)
                  {
                  Type t = typeof(List<> );
                  Type gt = t.MakeGenericType(GetTypes());
                  object gtObj = Activator.CreateInstance(gt);
                  }

                  private static Type[] GetTypes()
                  {
                  return new Type[] { typeof(int) };
                  }

                  But gtObj is returned as an object (but it is a List). The problem is that you will probably have to use reflection.

                  Eslam Afifi

                  N 1 Reply Last reply
                  0
                  • E Eslam Afifi

                    This code creates a generic type and instatiate an object of that type in runtime using MakeGenericType as Computafreak mentioned. I was going to post it last night but I forgot and fell asleep. But now I know you want it in .net 2.0 I have to remove var and new[]

                    static void Main(string[] args)
                    {
                    Type t = typeof(List<> );
                    Type gt = t.MakeGenericType(GetTypes());
                    object gtObj = Activator.CreateInstance(gt);
                    }

                    private static Type[] GetTypes()
                    {
                    return new Type[] { typeof(int) };
                    }

                    But gtObj is returned as an object (but it is a List). The problem is that you will probably have to use reflection.

                    Eslam Afifi

                    N Offline
                    N Offline
                    NandoMan
                    wrote on last edited by
                    #10

                    Thanks a lot!

                    E 1 Reply Last reply
                    0
                    • 0 0x3c0

                      A method which may prove useful is Type.MakeGenericType[^]. I don't fully understand it, but it seems to be a step in the right direction - getting the type of a generic type (without the type specifiers), then calling MakeGenericType on the result to get a dynamically set Type

                      Between the idea And the reality Between the motion And the act Falls the Shadow

                      N Offline
                      N Offline
                      NandoMan
                      wrote on last edited by
                      #11

                      Man thanks a lot, it did worked: Type cons = typeof(List<>).MakeGenericType(Tipo); object _list = cons.Assembly.CreateInstance(cons.FullName); +1 for you!

                      1 Reply Last reply
                      0
                      • N NandoMan

                        Thanks a lot!

                        E Offline
                        E Offline
                        Eslam Afifi
                        wrote on last edited by
                        #12

                        You're welcome. I read your other post[^] and you don't have to use the FullName of the Type, you can just pass the Type directly which is faster IMHO.

                        Eslam Afifi

                        N 1 Reply Last reply
                        0
                        • E Eslam Afifi

                          You're welcome. I read your other post[^] and you don't have to use the FullName of the Type, you can just pass the Type directly which is faster IMHO.

                          Eslam Afifi

                          N Offline
                          N Offline
                          NandoMan
                          wrote on last edited by
                          #13

                          Yes indeed! I have corrected my code to use the Activator. Thanks again!

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups