Export (0) Print
Expand All
Expand Minimize
1 out of 2 rated this helpful - Rate this topic

Compiler Error CS1657 

Error Message

Cannot pass 'variable' as a ref or out argument because it a 'readonly variable type'

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
    }
}
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.