C# Error CS1657 – Cannot use ‘{0}’ as a ref or out value because it is a ‘{1}’

C# Error

CS1657 – Cannot use ‘{0}’ as a ref or out value because it is a ‘{1}’

Reason for the Error & Solution

Cannot pass ‘parameter’ as a ref or out argument because ‘reason”

This error occurs when a variable is passed as a or argument in a context in which that variable is readonly. Readonly contexts include iteration variables, variables, and fixed variables. To resolve this error, do not call functions that take the foreach, using or fixed variable as a ref or out parameter in using blocks, foreach statements, and fixed statements.

Example 1

The following sample generates CS1657:

// CS1657.cs  
using System;  
class C : IDisposable  
{  
    public int i;  
    public void Dispose() {}  
}  
  
class CMain  
{  
    static void f(ref C c)  
    {  
    }  
    static void Main()  
    {  
        using (C c = new C())  
        {  
            f(ref c);  // CS1657  
        }  
    }  
}  

Example 2

The following code illustrates the same problem in a fixed statement:

// CS1657b.cs  
// compile with: /unsafe  
unsafe class C  
{  
    static void F(ref int* p)  
    {  
    }  
  
    static void Main()  
    {  
        int[] a = new int[5];  
        fixed(int* p = a) F(ref p); // CS1657  
    }  
}  

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