OT: Generics question

OT: Generics question

Old forum URL: forums.lhotka.net/forums/t/1444.aspx


razorkai posted on Wednesday, October 11, 2006

Given a method such as this

public List<T> GetPickedIds<T>()

Is there any way I can call this method passing in a Type for T derived from elsewhere?  What I mean is instead of typing GetPickedIds<int> I could do something like

Type type = GetType("int");
GetPickedIds<type>;

Any thoughts?

TIA.

Brian Criswell replied on Wednesday, October 11, 2006

As far as I know, you cannot do that.  Reasons include that there is no way to know what type T is for the List<T>.  Use generics when you can tell what type it will be.  In your case, you would need to use an ArrayList.

Tamir replied on Wednesday, October 11, 2006

hi razorkai
i'm pretty sure you can't
generics mechanism need to know at compile time what kind of type it handle.

i think that one of the purposes of generics is to simplify the implementation of
strong Type classes.
if what you're suggesting is true that what would

'GetPickedIds<type>[0]' returns?

 

 

 

xal replied on Wednesday, October 11, 2006

Well, you definitely can, but it's not as straight forward... you're going to have to use reflection.

Andrés

razorkai replied on Wednesday, October 11, 2006

Andrés

Don't dangle the carrot like that! <g>  How could I achieve this?  I have been trying for ages but figured it was not possible.  Any example code would be appreciated.

John.

Tamir replied on Wednesday, October 11, 2006

hi.

i tried it' just 4 fun :) and i think you're mistaken.

when you try this code you get InvalidOperationException: "Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true."

public static void test<T>()
{
      Console.WriteLine(typeof(T).FullName);
}
private static void Main(string[] args)
{
      typeof(Program).GetMethod("test", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);
}

xal replied on Thursday, October 12, 2006

No I'm not.
Create a windows forms vb project and paste this inside the form's code:

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles MyBase.Load
        Dim mi As Reflection.MethodInfo = Me.GetType().GetMethod("DoSomething")
        Dim mi2 As Reflection.MethodInfo = mi.MakeGenericMethod(GetType(Integer))
        mi2.Invoke(Nothing, New Object() {2})
    End Sub

    Public Shared Sub DoSomething(Of T)(ByVal param As T)
        MessageBox.Show(param.ToString())
    End Sub

Andrés

Copyright (c) Marimer LLC