0

This is the program in question:

namespace TestStuff
{
    public class Test
    {
        public int x;
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test firstClass = new Test();
            firstClass.x = 5;
            Test secondClass = firstClass;
            firstClass.x = 6;
            Console.WriteLine(secondClass.x);

        }
    }
}

The output of this program is 6, I assume this is because Test secondClass = firstClass;, makes secondClass point to firstClass instead of making a copy of firstClass. If i want to make secondClass a copy of firstClass, how would I go about that ?

1 Answers1

-1

I guess it's an OOP (Object-Oriented Programming) misconception. Although Test.x is an int (thus a value type) and, if copied around, you wouldn't get a reference for it, in this case, you're copying the whole Test instance from firstClass to secondClass.

Test secondClass = firstClass; will make both "references" being the same object and by modifying firstClass.x you'll also update secondClass.x. It's not because of .x, but because firstClass and secondClass are both the same instance of object.

If i want to make secondClass a copy of firstClass, how would I go about that?

In order to achieve this, you need to clone the object, instead. https://stackoverflow.com/a/129395/1256062 might be a good source for it.

tvdias
  • 821
  • 2
  • 10
  • 25