question

09294413 avatar image
0 Votes"
09294413 asked 09294413 edited

Change the value in the list without changing the variable

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.

dotnet-csharp
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.


Currently dimTemp is unassigned or null, the list is empty, and the statement does not work. Show an example that works.


0 Votes 0 ·
vb2ae avatar image
0 Votes"
vb2ae answered

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;
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

09294413 avatar image
0 Votes"
09294413 answered 09294413 edited
 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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.