Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a generic call to function based on a Type object? [duplicate]

Tags:

c#

.net-4.0

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();
    }
like image 891
sgtz Avatar asked Jan 19 '26 14:01

sgtz


2 Answers

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 });
}
like image 134
dtb Avatar answered Jan 21 '26 07:01

dtb


MakeGenericMethod is the key:

var get = typeof(WhereverYourGetMethodIs).GetMethod("Get");
var genericGet = get.MakeGenericMethod(type);
like image 31
Anton Gogolev Avatar answered Jan 21 '26 06:01

Anton Gogolev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!