C # 7 ref return: what remains in memory: class instance or return property ref?

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

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

The new C # 7 ref return function is used here. After GetData () returns, what is stored in memory? Full copy of MyDataStructure? Or just an integer?

If the instance of MyDataStructure is stored in memory, because someone keeps a reference to the field of this instance, why in this example cannot be stored in memory:

public ref string GetString()
{
    string s = "a";
    return ref s; 
}
+4
source share
2 answers

After GetData () returns, what is stored in memory? Full copy of MyDataStructure? Or just an integer?

MyDataStructure. It exists on the heap, and you have a link to the field inside it.

why cannot be stored in memory in this example

, , , s , . , .

+4

s , .

+2

Source: https://habr.com/ru/post/1693769/


All Articles