What is the difference between Expression.Variable() and Expression.Parameter()?

.net c# expression expression-trees

Question

Both seem to return the same type, and have the same signature.

So what is the difference between them, and when should we use each?

1
11
8/29/2015 8:20:44 AM

Accepted Answer

Expression.Variable is used to declare a local variable within a block. Expression.Parameter is used to declare a parameter for an incoming value.

Now currently C# doesn't allow statement-bodied lambda expressions, but if it did, imagine:

// Not currently valid, admittedly...
Expression<Func<int, int>> foo = x =>
{
    int y = DateTime.Now.Hour;
    return x + y;
};

If this were valid, the C# compiler would generate code using Expression.Parameter for x, and Expression.Variable for y.

At least, that's my understanding. It's a real shame that the documentation for the two methods is basically the same :(

10
8/29/2015 8:24:33 AM

Popular Answer

Effectively, there is no difference, apart from the fact that Variable() does not allow ref types. To see that, you can look at the reference source:

public static ParameterExpression Parameter(Type type, string name) {
    ContractUtils.RequiresNotNull(type, "type");

    if (type == typeof(void)) {
        throw Error.ArgumentCannotBeOfTypeVoid();
    }

    bool byref = type.IsByRef;
    if (byref) {
        type = type.GetElementType();
    }

    return ParameterExpression.Make(type, name, byref);
}

public static ParameterExpression Variable(Type type, string name) {
    ContractUtils.RequiresNotNull(type, "type");
    if (type == typeof(void)) throw Error.ArgumentCannotBeOfTypeVoid();
    if (type.IsByRef) throw Error.TypeMustNotBeByRef();
    return ParameterExpression.Make(type, name, false);
}

As you can see, both methods call ParameterExpression.Make(), so the returned object will behave the same.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow