C# Error CS0854 – An expression tree may not contain a call or invocation that uses optional arguments

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);

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...