Niekon
Niekon
CC#
Created by Niekon on 7/22/2023 in #help
❔ Why can't I reinitialize an object inside a function?
Hi, I created an object in Program.cs file, and passed it as a parameter in a function. If I change the value of a property in the object, it reflects back in Program.cs as well, but if I reinitialize the object, the object reverts to its original values when back in Program.cs. Why is this happening? Program.cs
var person = new Person
{
Name = "ABC",
Age = 10
};

Console.WriteLine($"Program.cs : Name: {person.Name}, Age: {person.Age}");

PersonMethods personMethods = new PersonMethods();
personMethods.Evaluate(person);

Console.WriteLine($"Program.cs : Name: {person.Name}, Age: {person.Age}");
var person = new Person
{
Name = "ABC",
Age = 10
};

Console.WriteLine($"Program.cs : Name: {person.Name}, Age: {person.Age}");

PersonMethods personMethods = new PersonMethods();
personMethods.Evaluate(person);

Console.WriteLine($"Program.cs : Name: {person.Name}, Age: {person.Age}");
PersonMethods.cs
class PersonMethods
{
public void Evaluate(Person person)
{
person = new Person();
person.Name = "XYZ";
person.Age = 0;
Console.WriteLine($"PersonMethods.cs : Name: {person.Name}, Age: {person.Age}");
}
}
class PersonMethods
{
public void Evaluate(Person person)
{
person = new Person();
person.Name = "XYZ";
person.Age = 0;
Console.WriteLine($"PersonMethods.cs : Name: {person.Name}, Age: {person.Age}");
}
}
Output
Program.cs : Name: ABC, Age: 10
PersonMethods.cs : Name: XYZ, Age: 0
Program.cs : Name: ABC, Age: 10
Program.cs : Name: ABC, Age: 10
PersonMethods.cs : Name: XYZ, Age: 0
Program.cs : Name: ABC, Age: 10
15 replies