public class Program {
public static void Main(string[] args) {
Person person = new Person();
person.name = "from main function";
Program pro = new Program();
Console.WriteLine(person.name);
pro.change(person);
Console.WriteLine(person.name);
}
public void change(Person per) {
per.name = "From public void Change function";
}
public class Person {
public string name {get; set;}
}
}
}
why is the person object overwritten by the change function?
because I have different objects for the person’s class
2
Answers
Here you pass a reference type
Person
by value. In this case, thechange()
method receives a copy of the reference to the class instance. Since thechange()
method has the address of the instance, it can change the members of theper
object.In C#, when you pass an object to a method, you are not making a copy of the object. Instead, you are telling the method where to find the original object in the computer’s memory. This is like giving the method a map with the object’s location.
Now, because both the original object and the object inside the method are pointing to the same memory location (like two different arrows pointing to the same spot), any changes made to the object inside the method will also affect the original object. It’s like if you make changes to something on the map, it will affect the real thing in that location.
So, be careful when you pass objects to methods. If you modify the object inside the method, those changes will show up in the original object because both are pointing to the same place in the computer’s memory. If you want to keep the original object unchanged, you need to create a new copy of the object inside the method and work with that copy instead.