Change the value in the list without changing the variable

Алексей Куликов 21 Reputation points
2021-04-10T11:34:03.84+00:00

Hello. I have a list. I want to change the last element in it. But without changing the object and / or variable. And when you change an item in the list, the variable also changes. How to do it?

    class ClassM
    {
        public int value { get; set; }
    }

        ClassM dimTemp;
        List<ClassM> lstData = new List<ClassM>();


lstData.LastOrDefault().value = dimTemp.value + lstData.LastOrDefault().value;

I need the value in dimTemp not to change. And it changes.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,302 questions
{count} votes

Accepted answer
  1. Ken Tucker 5,846 Reputation points
    2021-04-10T12:09:14.04+00:00

    I dont think you posted all the code. I suspect you added dimTemp to the list. So the last item in the list is dimTemp and updating the item in the list will make it to the variable. Add a clone of dimTemp to the list if you do not want the dimTemp variable to update.

    class ClassM:ICloneable
    {
        public int value { get; set; }
        public object Clone()
        {
            return new ClassM()
            {
                value = this.value
            };
        }
    }
    
    
            ClassM dimTemp;
            List<ClassM> lstData = new List<ClassM>();
            dimTemp = new ClassM();
            dimTemp.value = 1;
            lstData.Add((ClassM)dimTemp.Clone());
            Console.WriteLine(dimTemp.value);
            lstData.LastOrDefault().value = dimTemp.value + lstData.LastOrDefault().value;
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Алексей Куликов 21 Reputation points
    2021-04-10T12:12:21.45+00:00
    ClassM = dimTemp;
    List<ClassM> lstData = new List<ClassM>();
    void Start()
    {
    dimTemp = new ClassM () { value = 1 };
    
    AddMetod();
    AddMetod();
    
    ChangeMetod();
    }
    
    void AddMetod()
    {
    dimTemp = new ClassM (){value = 1};
    lstData .Add(dimTemp);
    }
    void Changemetod()
    {
    
    lstData.LastOrDefault().value = dimTemp.value + lstData.LastOrDefault().value;
    
    }
    

    dimTemp also becomes 2. Although it should remain 1.

    0 comments No comments