In my WPF application I have an Observable Collection of Functions
private ObservableCollection<Function> functions = new ObservableCollection<Function>();
I wrote a command for a button to add new functions to the collection: In this case I am adding a polynomial function.
public ICommand AddPolyFuncCommand
{
get
{
return new Command(obj =>
{
Function newPolyFunc = new PolyFunction(this.Coefficients);
functions.Add(newPolyFunc);
CalculatePoints();
});
}
}
However, if I keep adding more functions, all of the latest functions in the collection are overwritten with the function I want to add. For example I have 3 entries, but the functions are all the same (they should be different).
For example, I create a first function. After that I want to add another different function to the collection.
It lets me create the "newPolyFunc" properly but if I take a look at the FunctionsCollection
at runtime the first value is already overwritten with the function.
public ICommand AddTrigoFuncCommand
{
get
{
return new Command(obj =>
{
this.functions.Add(newTrigoFunc);
CalculatePoints();
});
}
}
By writing
Function newPolyFunc = new PolyFunction(this.Coefficients);
you pass the Reference of theCoefficents
and not a new set of Coefficients. You could use LINQ to create a deep copy of the Coefficients or create an empty set and pass them like this:Important: When you pass a reference you pass a pointer to the instance/object and not a clone/copy. Always be aware if its a reference or value type. For example the
newTrigoFunc
is an instance and is passed as reference. So thethis.functions
has now the same reference saved 2 times and not to different instances/objects. When you want to add a new object/instance i suggest you to create a new one with the Constructor like this