C# Error CS8162 – Members of readonly field ‘{0}’ cannot be returned by writable reference

C# Error

CS8162 – Members of readonly field ‘{0}’ cannot be returned by writable reference

Reason for the Error & Solution

Members of readonly field cannot be returned by writable reference

Example

The following sample generates CS8162:

// CS8162.cs (12,14)
public class Test
{
    public struct S1
    {
        public char x;
    }

    public readonly S1 i2;

    ref char Test1()
    {
        return ref i2.x;
    }
}

To correct this error

To return the value of a readonly field, refactoring to return by value corrects this error:

public class Test
{
    public struct S1
    {
        public char x;
    }

    public readonly S1 i2;
    char Test1()
    {
        return i2.x;
    }
}

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