❔ 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
PersonMethods.cs
Output
8 Replies
its because how passing the parameters happens, this is always by value
var person = new Person()
:
new Person()
creates a new object somewhere in the memory and returns a reference to that object
which u then store in the variable person
public void Evaluate(Person person)
is a method that has its own person
variable
when u call personMethods.Evaluate(person)
the following happens:
the reference stored in person
of the main method (ur Program.cs), is copied to the variable person
of Evaluate
inside there u only store a new reference of the person
inEvaluate
the person
of ur main method/Program.cs has not been affected by that
if u would have the following:
(note that i left the person = new Person();
) out
its a bit different:But objects are passed by reference, right? And didn't I change the reference I passed it to?
u passed a copy of the reference to the person object to the
Evaluate
method
u basically have 2 different person
variables that have a reference stored:
one in main method/Program.cs
and one in Evaluate
passed by reference means that not the object itself is passed, but a reference to it, the object here is the Person
object
BUT, its not the local person
variable of the Program.csOh! That makes sense
so by doing
person = new Person();
in Evaluate
, where person
is its own variable, u only overwrite that local one
with that code u would still work on the same Person
object, because the Evaluate
's person
variable still stores the same reference to an object as the one in Program.csOkk, I think I understand
basically everything is passed by value, its just that for reference types not the whole object is copied/passed, but a reference to it
oh, i totally forget to mention it, there is a way to manipulate the contents of the
person
variable of the main/Program.cs from within the Evaluate
method: ref
s
these are a bit special, they are basically a pointer to the actual variable (with a ref Person person
u basically have a reference to the variable that holds a reference to the Person
object)
in this case the Program.cs' person
will be overwritten by Evaluate
's person = new Person();
but note that this has some more details to think (performance impact due to one more indirection - reference of reference of object, can not be used in async contexts, to name two)Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.