C# Error CS8149 – By-reference returns may only be used in methods that return by reference

C# Error

CS8149 – By-reference returns may only be used in methods that return by reference

Reason for the Error & Solution

By-reference returns may only be used in methods that return by reference

Example

The following sample generates CS8149:

// CS8149.cs (9,33)

delegate int E();

class C
{
    static int i;
    static void M()
    {
        var e = new E(() => ref i);
    }
}

To correct this error

Ensuring that methods and delegates declared as a returning by value do not return by reference corrects this error:

delegate int E();

class C
{
    static int i;
    static void M()
    {
        var e = new E(() => i);
    }
}