C# Error CS1944 – An expression tree may not contain an unsafe pointer operation

C# Error

CS1944 – An expression tree may not contain an unsafe pointer operation

Reason for the Error & Solution

An expression tree may not contain an unsafe pointer operation

Expression trees do not support pointer types because the method is only allowed to produce verifiable code. See comments.

To correct this error

  1. Do not use pointer types when you are trying to create an expression tree.

Example

The following example generates CS1944:

// cs1944.cs  
// Compile with: /unsafe  
using System.Linq.Expressions;  
unsafe class Test  
{  
    public delegate int* D(int i);  
    static void Main()  
    {  
        Expression<D> tree = x => &x; // CS1944  
    }  
}  
  
using System.Linq.Expressions;  
unsafe class Test  
{  
    public delegate int* D(int i);  
    static void Main()  
    {  
        Expression<D> tree = x => &x; // CS1944  
    }  
}  

In some situations it is okay to have pointers in expression trees. For example, consider the following code:

Expression<Func\<int*[], int*[]>) e = (int*[] i)=>i;

This code is a valid expression tree because no type arguments are pointer types. They are arrays of pointers, and arrays are not pointer types. Also, the body of the expression tree does not do anything dangerous with any pointer.

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