I'm reading about structs and classes in C# and to my understanding structs are value types and classes are reference types. But I'm a little confused about how class objects behave when they are passed as parameters to a method.
Assume I have the following code:
public class Program
{
public static void Main(string[] args)
{
var program = new Program();
var person = new Person
{
Firstname = "Bob",
};
Console.WriteLine(person.Firstname);
program.ChangeName(person);
Console.WriteLine(person.Firstname);
program.Kill(person);
Console.WriteLine(person.Firstname);
Console.Read();
}
public void ChangeName(Person p)
{
p.Firstname = "Alice";
}
public void Kill(Person p)
{
p = null;
}
}
When I pass my instance of the Person class to Program.ChangeName() and change the value of person.Firstname to Alice, the change is reflected on the original person object as instantiated in my Program.Main() which is what I would expect, the p parameter is a reference to person. However, when I attempt to set p to null, there appears to be no change. Why is this?