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; }
}

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