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

2
  • 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(). Commented Oct 18, 2021 at 14:13
  • Does this answer your question? How do I clone a generic list in C#? Commented Oct 18, 2021 at 14:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.