C# Error CS1666 – You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement.

C# Error

CS1666 – You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement.

Reason for the Error & Solution

You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement.

This error occurs if you use the fixed sized buffer in an expression involving a class that is not itself fixed. The runtime is free to move the unfixed class around to optimize memory access, which could lead to errors when using the fixed sized buffer. To avoid this error, use the fixed keyword on the statement.

Example

The following sample generates CS1666.

// CS1666.cs  
// compile with: /unsafe /target:library  
unsafe struct S  
{  
   public fixed int buffer[1];  
}  
  
unsafe class Test  
{  
   S field = new S();  
  
   private bool example1()  
   {  
      return (field.buffer[0] == 0);   // CS1666 error  
   }  
  
   private bool example2()  
   {  
      // OK  
      fixed (S* p = &field)  
      {  
         return (p->buffer[0] == 0);  
      }  
   }  
  
   private bool example3()  
   {  
      S local = new S();  
      return (local.buffer[0] == 0);
   }
}  

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