C# Error CS1951 – An expression tree lambda may not contain a ref, in or out parameter

C# Error

CS1951 – An expression tree lambda may not contain a ref, in or out parameter

Reason for the Error & Solution

An expression tree lambda may not contain an in, out, or ref parameter.

An expression tree just represents expressions as data structures. There is no way to represent specific memory locations as is required when you pass a parameter by reference.

To correct this error

  1. The only option is to remove the modifier in the delegate definition and pass the parameter by value.

Example

The following example generates CS1951:

// cs1951.cs  
using System.Linq;  
public delegate int TestDelegate(ref int i);  
class Test  
{  
    static void Main()  
    {  
        System.Linq.Expressions.Expression<TestDelegate> tree1 = (ref int x) => x; // CS1951  
    }  
}  

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