C# Error CS8160 – A readonly field cannot be returned by writable reference

C# Error

CS8160 – A readonly field cannot be returned by writable reference

Reason for the Error & Solution

A readonly field cannot be returned by writable reference

Example

The following sample generates CS8160:

// CS8160.cs (8,20)


class Program
{
    readonly int i = 0;

    ref int M()
    {
        return ref i;
    }
}

To correct this error

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

class Program
{
    readonly int i = 0;

    int M()
    {
        return i;
    }
}

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