C# Error CS1708 – Fixed size buffers can only be accessed through locals or fields

C# Error

CS1708 – Fixed size buffers can only be accessed through locals or fields

Reason for the Error & Solution

Fixed size buffers can only be accessed through locals or fields

A new feature in C# 2.0 is the ability to define an in-line array inside of a struct. Such arrays can only be accessed via local variables or fields, and may not be referenced as intermediate values on the left-hand side of an expression. Also, the arrays cannot be accessed by fields that are static or readonly.

To resolve this error, define an array variable, and assign the in-line array to the variable. Or, remove the static or readonly modifier from the field representing the in-line array.

Example

The following sample generates CS1708.

// CS1708.cs  
// compile with: /unsafe  
using System;  
  
unsafe public struct S  
{  
    public fixed char name[10];  
}  
  
public unsafe class C  
{  
    public S UnsafeMethod()  
    {  
        S myS = new S();  
        return myS;  
    }  
  
    static void Main()  
    {  
        C myC = new C();  
        myC.UnsafeMethod().name[3] = 'a';  // CS1708  
        // Uncomment the following 2 lines to resolve:  
        // S myS = myC.UnsafeMethod();  
        // myS.name[3] = 'a';  
  
        // The field cannot be static.  
        C._s1.name[3] = 'a';  // CS1708  
  
        // The field cannot be readonly.  
        myC._s2.name[3] = 'a';  // CS1708  
    }  
  
    static readonly S _s1;  
    public readonly S _s2;  
}  

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