So I've been trying to play around little bit with a NuGet package called
But why are the values not applied to the variable "clonedPerson" afterwards?
CodePudding user response:
As your code is currently written, you are assigning a complete new object to your destination
parameter. But this does not change the object you passed into that parameter. To overcome this issue there are several possibilites (in order of my personal preference)
You can just define
PerformDeepCloning
to return aPerson
public static Person PerformDeepCloning(Person source) { //call a method from the package Person destination = source.DeepClone(); //this works fine Console.WriteLine("DEEP CLONED NAME = " destination.Name); return destination; }
and call it like this
Person otherPerson = PerformDeepCloning(person);
This would seem the most natural way for me to do it, instead of populating
out
orref
parameters of a method returningvoid
, why not just return the result viareturn
keyword?Use the
out
keyword which was specifically designed for such situations (ie creating a new object inside the called method and pass it to the caller ifreturn
isn't possible for whatever resons)public static void PerformDeepCloning(Person source, out Person destination) { //call a method from the package destination = source.DeepClone(); //this works fine Console.WriteLine("DEEP CLONED NAME = " destination.Name); }
and then call it like this
//you must not assign a value here, when using the out keyword Person otherPerson; PerformDeepCloning(person, out otherPerson);
or starting with C#7 you can also use an inline declaration
//no need to delare Person otherPerson; prior to the call PerformDeepCloning(person, out Person otherPerson);
Use the
ref
keyword which is capable of updating the reference which was passed in.public static void PerformDeepCloning(Person source, ref Person destination) { //call a method from the package destination = source.DeepClone(); //this works fine Console.WriteLine("DEEP CLONED NAME = " destination.Name); }
and then call it like this
Person otherPerson = new Person(); PerformDeepCloning(person, ref otherPerson);
But as you are creating a new instance of a
Person
anyways, you don't need to create a new object before the call (because this will be thrown away immediately) but initialize theotherPerson
withnull
. But then you of course have to sure, you don't accessotherPerson
's properties, before you created an instance.Person otherPerson = null; PerformDeepCloning(person, ref otherPerson);