C# Error CS8155 – Lambda expressions that return by reference cannot be converted to expression trees

C# Error

CS8155 – Lambda expressions that return by reference cannot be converted to expression trees

Reason for the Error & Solution

Lambda expressions that return by reference cannot be converted to expression trees

Example

The following sample generates CS8155:

// CS8155.cs (11,51)

using System.Linq.Expressions;
class TestClass
{
    int x = 0;

    delegate ref int RefReturnIntDelegate(int y);

    void TestFunction()
    {
        Expression<RefReturnIntDelegate> lambda = (y) => ref x;
    }
}

To correct this error

To be convertible to an expression tree, refactoring to return by value corrects this error:

class TestClass
{
    int x = 0;

    delegate int RefReturnIntDelegate(int y);

    void TestFunction()
    {
        Expression<RefReturnIntDelegate> lambda = (y) => x;
    }
}

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...