Understanding Read-Only Properties with Object (Refererence Types)

using System;
using System.Text;

namespace TestReadOnly
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass1 myObject1 = new MyClass1();

            // myObject1.MyObject2 = new MyClass2();    // clearly illegal

            // legal, reference is read-only, not object
            myObject1.MyObject2.x = 1;
            Console.WriteLine("myObject1.MyObject2.x: {0}", myObject1.MyObject2.x);

            // also legal, similar to above, anotherObject2 is just a reference to the same object
            MyClass2 anotherObject2 = myObject1.MyObject2;
            anotherObject2.x = 2;     //probably will be allowed
            Console.WriteLine("anotherObject2.x: {0}", anotherObject2.x);

            // also legal, anotherObject2 is now a reference to a completely new objcet
            anotherObject2 = new MyClass2();
            anotherObject2.x = 3;      // no affect on myObject1.Myobj2
            Console.WriteLine("anotherObject2.x: {0}", anotherObject2.x);

            // show that myObject1.MyObject2 was not affected by last attempt
            Console.WriteLine("myObject1.MyObject2.x: {0}", myObject1.MyObject2.x);

            Console.Read();
        }
    }

    class MyClass1
    {
        private MyClass2 _object2 = new MyClass2();
        public MyClass2 MyObject2
        {
            get{ return _object2; }
        }
    }

    class MyClass2
    {
        public int x = 0;
    }
}

Posted

in

, ,

by

Tags: