Search code examples
c#expression-trees

Are factory methods Expression.Parameter() and Expression.Variable() interchangeable?


Based on the documentation here and here, the two factory methods look interchangeable. Are they?


Solution

  • Expression.Parameter() supports ByRef types (i.e. a ref parameter), while Expression.Variable() will throw an exception if given one.

    They are otherwise identical, but that's an implementation detail and you shouldn't rely on it:

    public static ParameterExpression Parameter(Type type, string name)
    {
        bool isByRef = type.IsByRef;
        if (isByRef)
        {
            type = type.GetElementType();
        }
        return ParameterExpression.Make(type, name, isByRef);
    }
    
    public static ParameterExpression Variable(Type type, string name)
    {
        if (type.IsByRef)
        {
            throw Error.TypeMustNotBeByRef();
        }
        return ParameterExpression.Make(type, name, false);
    }