HomeCSharpC# Error CS1649 – Members of readonly field ‘{0}’ cannot be used as a ref or out value (except in a constructor)

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

C# Error

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

Reason for the Error & Solution

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

This error occurs if you pass a variable to a function that is a member of a readonly field as a ref or out argument. Since ref and out 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.

Example

The following sample generates CS1649:

// CS1649.cs  
public struct Inner  
    {  
        public int i;  
    }  
  
class Outer  
{  
    public readonly Inner inner = new Inner();  
}  
  
class D  
{  
    static void f(ref int iref)  
    {  
    }  
  
    static void Main()  
    {  
        Outer outer = new Outer();
        f(ref outer.inner.i);  // CS1649  
        // Try this code 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

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