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

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