C# Error CS8145 – Auto-implemented properties cannot return by reference

C# Error

CS8145 – Auto-implemented properties cannot return by reference

Reason for the Error & Solution

Auto-implemented properties cannot return by reference

Auto-implemented properties are not guaranteed to have a member or variable that can be referenced and thus do not support return by reference.

Example

The following sample generates CS8145:

// CS8145.cs (4,13)

public class C
{
    public ref int Property1 { get; }
}

To correct this error

If the property can be implemented through a backing field, then refactoring to use a backing field and ref-returning the field will correct this error:

public class C
{
    private int property1;

    public ref int Property1 => ref property1;
}

If the property cannot be implemented through a backing field, then removing the ref modifier from the property corrects this error:

public class C
{
    public int Property1 { get; }
}