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

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