Compiler Error CS1657

Cannot pass 'parameter' as a ref or out argument because 'reason''

This error occurs when a variable is passed as a ref or out argument in a context in which that variable is readonly. Readonly contexts include foreach iteration variables, using 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

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

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