Edit

Share via


Compiler Error CS8170

Struct members cannot return 'this' or other instance members by reference

Example

The following sample generates CS8170:

Value types (i.e. structs), are most commonly allocated on the stack. A value type allocated on the stack becomes invalid leaving the scope in which it was declared. The compiler avoids a reference to a variable that becomes invalid leaving the scope by generating this error.

C#
// CS8170.cs (8,14)

struct Program
{
    public int d;

    public ref int M()
    {
        return ref d;
    }
}

public class Other
{
    public void Method()
    {
        var p = new Program();
        var d = p.M();
    }
}

To correct this error

Changing the method to not ref-return corrects this error:

C#
delegate void D();

struct Program
{
    public event D d;

    public D M()
    {
        return d;
    }
}

If a reference to a member is required, consider extending the scope of the value. For example:

C#
public struct Program
{
    public int d;
}

public static class Extensions
{
    public static ref readonly int RefD(this in Program program)
    {
        return ref program.d;
    }
}

public class Other
{
    public void Method()
    {
        var p = new Program();
        var d = p.RefD();
    }
}