I am wondering why when we have p = new Person("TOM", 999); by calling fred.PrintInfo();
It doesn’t change the p to TOM and 999 but by using p.age = 99; we can change the fred’s age well the both constructor and properties are public then what is here that I am missing? I don’t want to do anything with this code I just want the reason.
using System;
class Person
{
public string fullName;
public int age;
public Person(string n, int a)
{
fullName = n;
age = a;
}
public void PrintInfo()
{
Console.WriteLine("{0} is {1} years old", fullName, age);
}
}
class MainClass
{
public static void SendAPersonByValue(Person p)
{
p.age = 99;
p = new Person("TOM", 999);
}
public static void Main()
{
Person fred = new Person("Fred", 12);
fred.PrintInfo();
SendAPersonByValue(fred);
fred.PrintInfo();
}
}
fredpoints to some particular location in memory:Upon calling SendAPersonByValue,
ppoints to that same location:p.age = 99;now changes the value in memory:whereas
new Person("TOM", 999);creates a new Person in memory, andp = ...makesppoint to it:And this is exactly why
fredstill containsFred, 99.Now, if you were to pass
fredas arefparameter,pwould become an alias forfred:After
p.age = 99:After
p = new Person("TOM", 999);: