Coder14
Coder14

Reputation: 1277

C#7 ref return: what stays in memory: the class instance or the ref returned property?

public ref int GetData()
{
    var myDataStructure = new MyDataStructure();
    return ref myDataStructure.Data;
}

public class MyDataStructure
{
    private int _data;
    public ref int Data => ref _data;
}

This uses the new C#7 ref return feature. After GetData() returns, what is kept in memory? The complete MyDataStructure instance? Or only the integer?

If the MyDataStructure instance is kept in memory, because someone is holding a reference to a field of that instance, why can't s be kept in memory in this example:

public ref string GetString()
{
    string s = "a";
    return ref s; 
}

Upvotes: 4

Views: 125

Answers (2)

Jon Hanna
Jon Hanna

Reputation: 113282

After GetData() returns, what is kept in memory? The complete MyDataStructure instance? Or only the integer?

The MyDataStructure is. It exists on the heap and you have a reference to a field within it.

why can't s be kept in memory in this example

Because while the string on the heap it points to exists on the heap, s itself is a local that is not on the heap. As a local, it no longer exists after the method has completed.

Upvotes: 4

Paulo Morgado
Paulo Morgado

Reputation: 14846

Because s is on the stack, winch is lost when the execution of the method finishes.

Upvotes: 2

Related Questions