Monday, 15 February 2010

c# - Passing a copy of a class is altering the original copy -


I have some code that downloads the data to a class for storage and then creates a copy of that class Passed in a method that changes the data, in any way, my original class is also being changed and I am not sure what I am doing.

  calculation calc = new calculations (symbol, market); Calc.stockData = loadData (symbol, market); (Int j = calc.stockData.Count - 8; j & gt; = 0; j--) {Hypris = 0; / / 0 Latest // As you go higher in the index, this (int k = j + 1; k & lt; j + 8; k ++) {kIndex = k; JIndex = j; Decimal highwaycatcracker high = calculation CalculateReturnPercentageStatic (calc.stockData.ElementAtOrDefault (k). Close, calc.stockData.ElementAtOrDefault (j).); If (hybrid content hi hyperis) {hypermarkets = high content content hi; HighIndex = k; }} Test Test = New Test (); Test.returnPct = High Value; Test.date = calc.stockData.ElementAtOrDefault (highIndex) .det; Test.symbolClass = Symbols List. Alimentateof default (i); Calculation copy = calc; Test.ratingClass = DisplayGeneration (test.symbolClass, copy, test.date); // Sending a copy in the method to change the content. Add (test); // Here is a breakpoint and the original class (calc) has been changed}  

Let's move through your code so that you can understand what is happening here. (The words that you are asking to do are written in the comments.)

  // 1. Make a new example of the object 'calculation' on the heap / 2. Assign that example and assign it to variable 'calc' calculation calculator = new calculation (symbol, market); // 3. Create a variable called 'Copy', which indicates 'calculation' type objects. 4. Assign the value of 'Calc' (which is in the context of a lot of things); copy 'copy' = calc;  

Simply pointing to the same object in your code in the calc and copy memory. This is the reason that the change in copy is affecting calc what you need to do is clone your object so that you have a new object that is equal but memory Is different in


No comments:

Post a Comment