I have a private setter on a class property of a mutable type, that i set through the classes constructor using myMutableVariable
.
However when I change something on myMutableVariableafter
Class.Property = myMutableVariable
, there is a difference between myMutableVariableand
Class.Property
.
Changin, for instance is - setting myVariable to null.
The property remains private
- does not change.
This is true even for lists and its members inside the same private property.
How does that work?
public class Class1
{
public Class1(string name)
{
this._name = name;
}
private string _name = "";
public string Name { get { return _name; } set { _name = value; } }
}
public class Class2
{
public Class2(Class1 c1)
{
this._c1 = c1;
}
private Class1 _c1;
public Class1 C1 { get { return _c1; } }
}
The test:
static void Main(string[] args)
{
Class1 myMutableVariable = new Class1("c1name");
Class2 c2 = new Class2(myMutableVariable);
myMutableVariable = null;
Console.WriteLine(c2.C1.Name);
//c2.C1 remains 'c1name'
}