I'm working on a matrix/vector class(es) and part of it has operator overloading. One of the odd things is, that instead of returning a new object (in this case vector) it's mutating the vector, AND returning a new one. How do I cleanly return a new instance of my Vector?
here are the constructors:
private List<double> v = new List<double>();
private int dims;
public Vector(double[] a)
{
foreach (double d in a)
{
v.Add(d);
dims++;
}
}
public Vector(int dims)
{
var a = new double[dims];
v = a.ToList();
this.dims = dims;
}
private Vector(List<double> a)
{
v = a;
dims = a.Count;
}
and the operator overloads (just posting addition because all of them have the problem, and have similar construction, so should have identical solutions)
public static Vector operator + (Vector a, Vector b)
{
Vector c = new Vector();
c = a;
for (int dim = 0; dim < c.dims; dim++)
{
c[dim] += b[dim];
}
return c;
}
EDIT: So, I've changed the class to a struct, and it seems like I still have the issue. Maybe it''s because the variable v
is a list, and therefore it's a class, it's still passing in the reference to the list? Maybe I have to use an array instead of a list?