1
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

Hadi Haidar
  • 337
  • 2
  • 13
  • 1
    In C#, you work with references to the objects. When you clone your array, you actually clone pointers too, so they eventually point to the same objects. You need to implement `Clone` and actually clone your object, e.g. `PremiumBill x = temporaryList.OrderBy(...).FirstOrDefault(...).Clone()`. – Yeldar Kurmangaliyev Oct 18 '21 at 14:13
  • Does this answer your question? [How do I clone a generic list in C#?](https://stackoverflow.com/questions/222598/how-do-i-clone-a-generic-list-in-c) – derpirscher Oct 18 '21 at 14:32

1 Answers1

2

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.

jegtugado
  • 5,081
  • 1
  • 12
  • 35