C# Error CS8152 – ‘{0}’ does not implement interface member ‘{1}’. ‘{2}’ cannot implement ‘{1}’ because it does not have matching return by reference.

C# Error

CS8152 – ‘{0}’ does not implement interface member ‘{1}’. ‘{2}’ cannot implement ‘{1}’ because it does not have matching return by reference.

Reason for the Error & Solution

Type does not implement interface member. cannot implement because it does not have matching return by reference.

Example

The following sample generates CS8152:

To implement an interface with a method that returns by reference, the implementation of the method must also return by reference and not by value.

// CS8152.cs (6,21)

public interface ITest
{
    ref readonly int M();
}
public class Test : ITest
{
    public int M() => 0;
} 

To correct this error

Ensure interface methods that return by reference do not return by value. For example:

public class Test : ITest
{
    int m;
    public ref readonly int M() => ref m;
}