0

I don't understand this:- Why is the initial value & order (in case you want to change) of the array also changes when I am passing it through a class method.

Here's my code

Main method

class Program
    {
        static void Main(string[] args)
        {
            int[] val = new int[2];
            val[0] = 12;
            val[1] = 32;

            int[] res;

            HelperClass obj = new HelperClass();
            obj.MyProperty = val;
            Console.WriteLine("{0} {1}",val[0],val[1]);

            obj.ValueChange();
            res = obj.MyProperty;
            Console.WriteLine("{0} {1}", val[0], val[1]);
            Console.WriteLine("{0} {1}", res[0], res[1]);
        }
    }

helper class

public class HelperClass
    {
        private int[] myVar;

        public int[] MyProperty
        {
            get { return myVar; }
            set { myVar = value; }
        }

        public void ValueChange()
        {
            MyProperty[0] = MyProperty[0] + 100;
            MyProperty[1] = MyProperty[1] + 100;
        }
    } 

Expected Output

12 32
12 32
112 132

Getting Output

12 32
112 132
112 132

What do i need to do to make the initial array constant?

Also this does not happen if the values are some other type such as int, double etc..

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Nitish Kumar Pal
  • 2,738
  • 3
  • 18
  • 23
  • 4
    Array is a reference type in C#, whereas int and double are value types. When you pass a reference type instance as parameter, you only pass the reference to the original instance, so if you modify the parameter, you modify where the reference points at, which is the original instance. Value types are copied (new instance) when passed as parameters. – weichch Mar 29 '20 at 06:25
  • 1
    In your case, to get the expected output, you need to, in the setter of your property, create a new instance of array and copy values over to it. – weichch Mar 29 '20 at 06:27
  • 1
    Like this `set { myVar = value.ToArray(); }` – vc 74 Mar 29 '20 at 06:28

0 Answers0