How to implement a read only property

akonsu picture akonsu · Oct 12, 2010 · Viewed 171.7k times · Source

I need to implement a read only property on my type. Moreover the value of this property is going to be set in the constructor and it is not going to be changed (I am writing a class that exposes custom routed UI commands for WPF but it does not matter).

I see two ways to do it:

  1. class MyClass
    {
        public readonly object MyProperty = new object();
    }
    
  2. class MyClass
    {
        private readonly object my_property = new object();
        public object MyProperty { get { return my_property; } }
    }
    

With all these FxCop errors saying that I should not have public member variables, it seems that the second one is the right way to do it. Correct?

Is there any difference between a get only property and a read only member in this case?

I would appreciate any comments/advice/etc.

Answer

Oded picture Oded · Oct 12, 2010

The second way is the preferred option.

private readonly int MyVal = 5;

public int MyProp { get { return MyVal;}  }

This will ensure that MyVal can only be assigned at initialization (it can also be set in a constructor).

As you had noted - this way you are not exposing an internal member, allowing you to change the internal implementation in the future.