C# Error
CS0854 – An expression tree may not contain a call or invocation that uses optional arguments
Reason for the Error & Solution
An expression tree may not contain a call or invocation that uses optional arguments
Example
The following sample generates CS0854:
// CS0854.cs (10,48)
using System;
using System.Linq.Expressions;
public class Test
{
public static int ModAdd2(int x = 3, int y = 4, params int[] b) { return 0; }
static void Main()
{
Expression<Func<int>> testExpr = () => ModAdd2();
Console.WriteLine(testExpr);
}
}
The creation of an expression tree occurs at compile time, but that expression is evaluated and executed at run-time. The evaluation of optional method parameter values occurs at compile time, not during the execution of an expression. Although default parameters are currently required to be compile-time constants, a method declaration (and any default parameter value) may change after creating the expression (and before execution). Since the actual value used cannot be assured during the creation of the expression, it is considered a compile-time error.
To correct this error
Make the created expression determinate and explicitly declare what value to use when the expression is evaluated and executed:
Expression<Func<int>> testExpr = () => ModAdd2(3, 4);