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

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