C# Error CS9043 – Ref returning properties cannot be required.

C# Error

CS9043 – Ref returning properties cannot be required.

Reason for the Error & Solution

Ref returning properties cannot be required.

The required modifier specifies that a member is required to be set during object initialization (i.e., via an object initializer.) For a property to be set within an object initializer, it must have a set accessor (a setter). ref-returning properties cannot have a setter and thus cannot also include the required modifier.

Example

The following sample generates CS9043:

// CS9043.cs (5,29)

class C
{
    private int i;
    public required ref readonly int Number => ref i;
}

To correct this error

To have a required property, refactoring the property to return by value corrects this error:

    public required int Number
    {
        get
        {
            return i;
        }
        set
        {
            i = value;
        }
    }

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