Home > front end >  Variable value changing with the change of array in C#
Variable value changing with the change of array in C#

Time:10-19

PremiumBill x = list.OrderBy(j => j.PostingDate).FirstOrDefault(j => j.PostingDate >= input.PostingDate);

Hello I'm trying to save a value from the array in a variable to preserve it while the array is changing but the variable's value is changing with its change. I have tried

PremiumBill[] temporaryList = (PremiumBill[])List.ToArray().Clone();

PremiumBill x = temporaryList.OrderBy(j => j.PostingDate).FirstOrDefault(j => j.PostingDate >= input.PostingDate);

I tried copy to and got the same thing

CodePudding user response:

What you want is a deep-copy of the array. Currently, what you have is a shallow copy where both arrays are pointing to the same references.

Below is an example of a deep copy using ICloneable interface. There are different ways to perform a deep copy and what I usually prefer is simply serializing and deserializing using JSON. This method works for serializeable objects but if ever you encounter an exception, use the ICloneable interface instead. You may refer to this question Deep Copy with Array.

public class Program
{
    public static void Main()
    {
        Foo[] foos = new Foo[] 
        { 
            new Foo() { Bar = 1 } ,
            new Foo() { Bar = 2 } ,
            new Foo() { Bar = 3 } ,
        };
        
        Foo[] tempFoos = foos.Select(r => (Foo)r.Clone()).ToArray();
        
        foos[0].Bar = 5;
        
        Foo foo1 = tempFoos[0];
        
        Console.WriteLine(foo1.Bar); // outputs 1
    }
}

class Foo : ICloneable
{
    public int Bar { get; set; }
    
    public object Clone()
    {
        return new Foo() { Bar = this.Bar };
    }
}

Posted an answer as it makes more sense to do so with an example.

  • Related