Jorr.it
Jorr.it

Reputation: 1300

What is the typeArguments parameter of the Expression.Call Method when making a Expression Tree?

Currently I am trying to make an Expression Tree with MethodCallExpressions for When, Select and GroupBy. I started with this manual on MSDN and several posts on StackOverflow. This gives us good examples to get started. To be able to write my own Expression Trees, without examples, I feel the need to understand the Expression.Call method with parameters as follows:

public static MethodCallExpression Call(
    Expression instance,
    string methodName,
    Type[] typeArguments,
    params Expression[] arguments
)

The third parameter is described by Microsoft like this:

An array of Type objects that specify the type parameters of the generic method. This argument should be null when methodName specifies a non-generic method.

This sounds rather general to me and I can't find out how to define which Type(s) I should pass with my Expression.Call method call.

Who can help me with a general explanation of the typeArguments parameter? Thanks in advance.

Upvotes: 0

Views: 801

Answers (2)

Simon Belanger
Simon Belanger

Reputation: 14870

The typeArguments parameter is used to call a generic method without giving the MethodInfo. Consider these functions for example:

public void NonGenericMethod() 
{
}

public void GenericMethod<T>()
{
}

public void GenericMethod2<T1, T2>()
{
}

For NonGenericMethod the typeArguments should be an empty array (use Type.EmptyTypes). GenericMethod<T> has 1 type argument: the typeArguments should be an array with one Type (if you wanted to call GenericMethod<int>, it would be new [] { typeof(int) }). GenericMethod2<T1, T2> has 2 type arguments: the typeArguments array should have two elements (GenericMethod2<int, int> would be new [] { typeof(int), typeof(int) } ). And so on.

Upvotes: 3

Markus
Markus

Reputation: 22436

A generic method is a method that has one or more type parameters. You create a generic method to apply an algorithm over a variety of types. For example:

public T DoSomething<T>(T input)
{
     return T; // do something useful
}

You can call this method like this:

var result = DoSomething<int>(123);

In order to call a generic method, you have to specify the Type parameters. Therefore, you use the typeArguments argument in the Expression.Call method.

Upvotes: 1

Related Questions