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