C# Error CS8170 – Struct members cannot return ‘this’ or other instance members by reference

C# Error

CS8170 – Struct members cannot return ‘this’ or other instance members by reference

Reason for the Error & Solution

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.

// 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:

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:

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

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...