C# Error CS1651 – Fields of static readonly field ‘{0}’ cannot be used as a ref or out value (except in a static constructor)

C# Error

CS1651 – Fields of static readonly field ‘{0}’ cannot be used as a ref or out value (except in a static constructor)

Reason for the Error & Solution

Fields of static readonly field ‘identifier’ cannot be passed ref or out (except in a static constructor)

This error occurs if you pass a variable to a function that is a member of a static readonly field as a ref argument. Since ref parameters may be modified by the function, this is not allowed. To resolve this error, remove the readonly keyword on the field, or do not pass the members of the readonly field to the function. For example, you might try creating a temporary variable which can be modified and passing the temporary as a ref argument, as shown in the following example.

The following sample generates CS1651:

// CS1651.cs  
public struct Inner  
  {  
    public int i;  
  }  
  
class Outer  
{
  public static readonly Inner inner = new Inner();  
}  
  
class D  
{  
   static void f(ref int iref)  
   {  
   }  
  
   static void Main()  
   {  
      f(ref Outer.inner.i);  // CS1651  
      // Try this instead:  
      // int tmp = Outer.inner.i;  
      // f(ref tmp);  
   }  
}  

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