Here, Person is a class, hence a reference type, it should be changed when I pass it as parameter in another function and assign it there.
Why program.person is null here after call to ChangePerson ?
namespace IndirectlyPropertySet
{
class Program
{
public Person _person;
public Person person
{
get { return _person; }
set
{
if (_person != value)
{
_person = value;
}
}
}
static void Main(string[] args)
{
Program program = new Program();
ChangePerson(program.person);
// Why program.person is null after executing this ?
program.person = new Person() { Name = "b", Age = 2 };
}
static void ChangePerson(Person p)
{
Person pe = new Person() { Name = "a", Age = 1 };
p = pe;
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
}
As an addition to @JonSkeet’s answer, if you rewrote your code to do this instead it would work.
The key point is to pass the reference type by reference i.e. adding the
refkeyword to your parameter.