Edit

Share via


Compiler Error CS0459

Cannot take the address of a read-only local variable

There are three common scenarios in the C# language that generate read-only local variables: foreach, using, and fixed. In each of these cases, you are not allowed to write to the read-only local variable, or to take its address. This error is generated when the compiler realizes you are trying to take the address of a read-only local variable.

Example

The following example generates CS0459 when an attempt is made to take the address of a read-only local variable in a foreach loop and in a fixed statement block:

// CS0459.cs
// compile with: /unsafe

class Program
{
    public unsafe void M1()
    {
        int[] ints = new int[] { 1, 2, 3 };
        foreach (int i in ints)
        {
            int *j = &i;  // CS0459
        }

        fixed (int *i = &_i)
        {
            int **j = &i;  // CS0459
        }
    }

    private int _i = 0;
}

Note

Roslyn compiler was updated and this compiler error was removed starting with Visual Studio 2017 version 15.5, so the previous code would compile successfully with this version and later.