Search code examples
c#propertiesprivateprotected

How to use properties to expose a private array as read-only?


What does the following code do?

class MyClass {
    private int[] myPrivates;
    public int[] GetMyPrivates
    {
      get { return myPrivates; }
    }

    protected int[] SetMyPrivates
    {
      set { myPrivates = value; }
    }
}

Is there a better way of protecting the array myPrivates? Is it possible to make it reat-only?


Solution

  • You could replace your getters and setters with a property this way:

    class MyClass {
        public int[] MyValues { get; protected set; }
    
        public MyClass() {
            MyValues = new [] {1, 2, 3, 4, 5};
        }
    
        public void foo {
            foreach (int i in MyValues) {
                Trace.WriteLine(i.ToString());
            }
        }
    }
    
    MyOtherClass {
        MyClass myClass;
    
        // ...
        void bar {
            // You can access the MyClass values in read outside of MyClass, 
            // because of the public property, but not in write because 
            // of the protected setter.
            foreach (int i in myClass.MyValues) {
                Trace.WriteLine(i.ToString());
            }
        }
    }
    

    You can add pretty much any protection level that is less that the one of the property to getters and setters.