I expect the following source code to output

value = 0, Copied value = 0
value = 0, Copied value = 200

But it is actually giving

value = 0, Copied value = 0
value = 200, Copied value = 200

I have re-assigned
CopyMyValWithRef.reference.value = 200;

This assignment must affect CopyMyValWithRef.reference.value only.
This assignment is also affecting MyValWithRef.reference.value

What could be the reason for this.

Source Code:

class Program
    {
        struct MyValueType 
        {
            public int value;
        }

        class MyReferenceType
        {
            public int value;
        }

        struct MyValueWithRefType
        {
            public int value;
            public MyReferenceType reference;
        }


        static void Main()
        {
            MyValueWithRefType MyValWithRef = new MyValueWithRefType();
            MyValWithRef.reference = new MyReferenceType();

            MyValueWithRefType CopyMyValWithRef = MyValWithRef;

            Console.WriteLine("value = {0}, Copied value = {1}", MyValWithRef.reference.value, CopyMyValWithRef.reference.value);

            CopyMyValWithRef.reference.value = 200;

            Console.WriteLine("value = {0}, Copied value = {1}", MyValWithRef.reference.value, CopyMyValWithRef.reference.value);            
        }
    }

Edited 7 Years Ago by vinodxx: n/a

The assignment to a variable of a value type creates a copy of the assigned value, while the assignment to a variable of a reference type create a copy of the reference but not of the referenced object.

This article has been dead for over six months. Start a new discussion instead.