Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Struct members cannot return 'this' or other instance members by reference
The following sample generates CS8170:
Value types (i.e. struct
s), 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();
}
}
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();
}
}
.NET feedback
.NET is an open source project. Select a link to provide feedback: