C# getter vs readonly

You have three choices:

  • public static readonly int Value = 42;
  • public static int Value { get { return 42; } }
  • public const int Value = 42;

Choose static readonly if the value will not change at runtime but might change in future versions of your code.

Choose a property if the value might change at runtime. Of course it won't change if you use the given code.

Choose const if the value is really a constant that will not even change in future versions (something like Math.PI or int.MinValue). And of course the use of const is limited by the type of the value.

The difference between const and static readonly is that the const value will be replaced on the call site. If you change the value of a const in a future version then all assemblies that rely on your class need to be recompiled using the new value.

The property requires a method call (calling a getter is a method call). So if the value is constant at runtime there is no need for that.


Yes, there is an advantage:

If the value gets changeable at any point in the future (e.g. in a future version of your code), in a way that it is, for example, time-dependent, you can support that in the read-only property without changing the public interface of your class.

If you have to replace a readonly field with a property, you will have to recompile any other assemblies that use your class.


There are two major differences:

The first is that fields cannot be on interfaces, whereas properties can. So if you want to use this in an interface, you have to use the property.

The second, more interesting, is that readonly fields CAN be modified, while the object is being constructed. Take the following code:

public class MyTestClass
{
    public readonly int MyInt = 1;

    public MyTestClass()
    {
        MyInt = 2;
    }
}

If a caller does

new MyTestClass().MyInt

they will get 2. The same goes for static constructors for a static readonly field.

Tags:

C#