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

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