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

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...