3

how do you execute Get, when all you have is: T expressed as a Type object i.e.

Type type=typeof(int);

and arguments param1 and param2?

    public void DoCall(){
        var type=typeof(int);
        // object o=Get<type> ("p1","p2");   //<-- wont work (expected)
        // *** what should go here? ***
    }

    public IEnumerable<T> Get<T>(string param1,string param2) {
        throw new NotImplementedException();
    }
sgtz
  • 8,849
  • 9
  • 51
  • 91
  • This sort of generic method is for type safety at compile time. If you dont know the type at compile time there is a good chance you're using generics wrong, or should have an additional overload which takes the type as a parameter such as `public IEnumerable Get(Type type, string param1, string param2)`. – Jamiec Sep 22 '11 at 13:35
  • @Jamiec: thanks for the comment Jamiec. I'll keep that in mind. One reason to keep is that I want to use whenever possible. I'd have to abandone usage for this case, or adopt two method signatures (one with , the other with Get(Type typ, ...) – sgtz Sep 22 '11 at 13:42
  • 1
    @sgtz - having 2 methods is the *usual* way to deal with both possibilities. Its how most DA libraries handle this scenario. – Jamiec Sep 22 '11 at 13:44

5 Answers5

4

You need to use reflection:

public IEnumerable GetBoxed(Type type, string param1, string param2)
{
    return (IEnumerable)this
        .GetType()
        .GetMethod("Get")
        .MakeGenericMethod(type)
        .Invoke(this, new[] { param1, param2 });
}
dtb
  • 213,145
  • 36
  • 401
  • 431
2

MakeGenericMethod is the key:

var get = typeof(WhereverYourGetMethodIs).GetMethod("Get");
var genericGet = get.MakeGenericMethod(type);
Community
  • 1
  • 1
Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
0

What's wrong with just using the generic type parameter directly?

public void DoCall(){
    IEnumerable<int> integers = Get<int> ("p1","p2");
    // ...
}
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
0

In the example above the 'T' will be whatever you pass into the Get method and it will also return the same IEnumerable. So if you do the following:

 IEnumerable<int> o = Get<int>("p1", "p2");

o will be IEnumerable

but if you want something else, then you just pass in a different Type, hence Generic types.

0

If possible, you should redefine your Get method to take the type of object as an argument:

public IEnumerable<object> Get(object type, string param1,string param2)
{
}

Then if you really need it, you can rewrite the original generic method as follows:

public IEnumerable<T> Get<T>(string param1,string param2)
{
    var result = Get(typeof(T), param1, param2);
    return result.Cast<T>();
}
Konamiman
  • 49,681
  • 17
  • 108
  • 138