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