C# Error CS8153 – An expression tree lambda may not contain a call to a method, property, or indexer that returns by reference

C# Error

CS8153 – An expression tree lambda may not contain a call to a method, property, or indexer that returns by reference

Reason for the Error & Solution

An expression tree lambda may not contain a call to a method, property, or indexer that returns by reference

Example

The following sample generates CS8153:

// CS8153.cs (11,46)

using System;
using System.Linq.Expressions;

namespace RefPropCrash
{
    class Program
    {
        static void Main(string[] args)
        {
            TestExpression(() => new Model { Value = 1 });
        }

        static void TestExpression(Expression<Func<Model>> expression)
        {
        }
    }

    class Model
    {
        int value;
        public ref int Value => ref value;
    }
}

To correct this error

To use a method within an expression, ensure it is not by reference. For example:

    class Model
    {
        public int Value { get; set; }
    }

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