W metodzie można zmienić jakieś pole w taki sposób: p.personAge = 99;. Dlaczego w linijce z kodem: p = new Person("Joe", 99); nie tworzy się ten nowy obiekt w tej referencji ? Obiekt przesłaliśmy przez wartość ale jest to obiekt, więc do referencji p powinien zostać wpisany i zapamiętany ten nowy obiekt.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Person
{
public string personName;
public int personAge;
public Person(string name, int age)
{
personName = name;
personAge = age;
}
public Person() { }
public void Display()
{
Console.WriteLine("Name: {0}, Age: {1}", personName, personAge);
}
}
class Program
{
static void SendAPersonByValue(Person p)
{
p.personAge = 99;
p = new Person("Joe", 99);
}
static void Main(string[] args)
{
Person fred = new Person("Fred", 12);
Console.WriteLine("Before by value call, Person is:");
fred.Display();
SendAPersonByValue(fred);
Console.WriteLine("\nAfter by value call, Person is:");
fred.Display();
Console.ReadLine();
}
}
}