Consider class A with private field _data of any type (eg. int) and property Data to work with that field:
public class A
{
private int _data;
public int Data
{
get => _data;
set => _data = value;
}
// Constructor is redudant, I created that for testing purposes...
public A(int data)
{
_data = data;
}
}
Now consider class B with the same private field _data and property Data that only returns reference to our field:
public class B
{
private int _data;
public ref int Data
{
get => ref _data;
}
// Constructor is redudant, I created that for testing purposes...
public B(int data)
{
_data = data;
}
}
And now the question for which I can't find the answer: Why I'm able to change the value of _data in the instance of class B if there is no set modifier for Data?
B b = new B(50);
// This line doesn't produce any warnings or errors
b.Data = 100;
Console.WriteLine(b.Data == 100); // True
Does that work like pointers in C/C++ and compiler understands that this property is just a pointer, so it automatically assings value to what this pointer point to (without any special operators and/or casting) or I'm missing something?
I couldn't find an answer on this on docs.microsoft.com (searching both for Properties and ref), so any explanation would be appreciated.