-1

I have this part of code:

MeasDataSet dset = new MeasDataSet();
MeasDataPoint point = new MeasDataPoint();
//...
MeasDataSet dset2 = new MeasDataSet(dset._path);
dset2.SaveResults();

point = dset2.GetDataPointAt(dset2.Size - 1);
point.Current = 7566;
dset2.SaveResults();

Where MeasDataPoint and Set are just some classes containing measurement data (point a single point and set a collection of points with additional methods)

When calling SaveResults() it should save the data inside the DataSet to a file, but using the code above doesn't save the old point but instead the altered one (point.Current = 7566;). So basically point now changes my values inside my data set instead of being a copy what i expected it to be.

GetDataPointAt (method of DatasSet):

public MeasDataPoint GetDataPointAt(int numberOfPoint)
    {
        return _dataPoints.ElementAt(numberOfPoint);
    }

Anyone an idea why it behaves this way?

Darki
  • 43
  • 1
  • 6
  • 3
    All `class` in C# are reference types - so if you `return` an object, you are returning a reference to the object, not a copy. Creating copies has to be done explicitly. – UnholySheep Jul 06 '17 at 13:29
  • https://stackoverflow.com/questions/23041297/why-are-objects-automatically-passed-by-reference – Vladimir Arustamian Jul 06 '17 at 13:33
  • Thanks, and here again I notice that I'm very new to c#. So I guess I should write a copy constructor and use this to copy? or is there a better/faster way to crate a copy – Darki Jul 06 '17 at 13:33
  • @Darki: Unless you need this copy behavior for many classes in your project, a copy constructor is the easiest one-off solution for this problem. – Flater Jul 06 '17 at 13:44

1 Answers1

0

Is dset._path the entire collection of MeasDataPoint objects? If so, it appears the constructor new MeasDataSet(dset._path) is simply internally storing a reference to your original dset collection of points which means it is manipulating your original collection. See Passing Parameters (C# Programming Guide).

You could extend or modify the MeasDataSet constructor to iterate over the MeasDataPoint objects to create new ones by deep copying when assigning to dset2. Here is a rough idea:

public MeasDataSet(List<MeasDataPoint> path) {
   var copiedPath = new List<MeasDataPoint>();
   foreach(var point in path) {
      copiedPath.Add(new MeasDataPoint() {
         Prop1 = point.Prop1,
         Prop2 = point.Prop2
      });
   }
   // do something with your newly created deep copy of copiedPath...
}
Adam
  • 4,590
  • 10
  • 51
  • 84
  • Thanks, yeah it's a bit confusing, but _path is actually the file-path of this specific test. it's just visible for debugging (usually private). It allows to load an old set of data using the constructor. So there should be no connection between the 2 sets, expect the files which will get copied to a different place in case of changes. – Darki Jul 06 '17 at 13:50