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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...