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

C# Error

CS8161 – A static readonly field cannot be returned by writable reference

Reason for the Error & Solution

A static readonly field cannot be returned by writable reference

Example

The following sample generates CS8161:

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

    public static readonly char s1;

    ref char Test2()
    {
        return ref s1;
    }
}

To correct this error

To return the value of a static readonly field, refactor to return by value:

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

    public static readonly char s1;

    char Test2()
    {
        return s1;
    }
}

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