0

so I created a class with two arrays (vector and vectorNorm) and wanted to include some setter and getter functions.

using System;

public class Vectors {
    double[] vector = new double[2];
    double length;
    double[] vectorNorm = new double[2];

    public double[] Vector {
        private set {
            Console.WriteLine("set called");
            this.vector = value;
        }
        get {
            Console.WriteLine("get called");
            return this.vector;
        }
    }

    public double[] VektorNorm {
        get {
            return vector;
        }
        set {
            vector = value;
        }
    }

    public double Length {
        get {
            return length;
        }
        set {
            length = value;
        }
    }

    public Vectors(double parVector1, double parVector2) {
        Vector[0] = parVector1;
        Vector[1] = parVector2;
    }

    public Vectors() {
        ;
    }

    public void calcLength() {
        Length = (Vector[0]*Vector[0])+(Vector[1]*Vector[1]);
        Console.WriteLine("Length " + Math.Sqrt(length));
        Console.ReadLine();
    }

}

My programm that executes looks like this

using System;

public class VectorsProg {
    public static void Main() {
        var vec1 = new Vectors(3, 4);
        vec1.calcLength();
        vec1.Vector[0] = 10;
        Console.WriteLine(vec1.Vector[0]);
        Console.ReadLine();
    }
}

The output on console looks like this

get called
get called
get called
get called
get called
get called
Length 5

get called
get called
10

So the Console.WriteLine("set called") never gets executed but the value of vec1.vector[0] changes. I also included the "private set" that doesn't even allow other classes to use the set function but the value still changes.

Is my code wrong in some way? Any solutions?

Meta
  • 17
  • 2
  • 2
    Arrays are reference type, your getter returns a reference to the array. – CodeCaster Nov 24 '17 at 13:15
  • 2
    You can't replace the whole array from outside, but once you have this array you can replace every item in it. Return a `ReadOnlyCollection` instead of the array. It has also an indexer. – Tim Schmelter Nov 24 '17 at 13:16
  • https://stackoverflow.com/questions/2158160/prevent-other-classes-from-altering-a-list-in-a-class, https://stackoverflow.com/questions/1219268/how-to-prevent-a-method-caller-from-modifying-a-returned-collection, https://stackoverflow.com/questions/967402/are-arrays-or-lists-passed-by-default-by-reference-in-c – CodeCaster Nov 24 '17 at 13:17
  • So how can I implement the setter and getter functions to my class? Or is that not even possible? – Meta Nov 24 '17 at 13:19
  • Depends on what you actually want to happen. You could let your getter just return a copy of the array, for example. – CodeCaster Nov 24 '17 at 13:22

0 Answers0