Search code examples
c#getterreadonly

getter vs readonly


Is there any difference between the following?

class C
{
    // One:
    public static readonly int ValueAsAMember = 42;

    // Two:
    public static int ValueAsAProperty { get { return 42; } }
}

I'm used to writing constants the first way (unless they're private/internal, in which case I use the const keyword), but I recently saw the second form.

Is there any advantage one way over the other in terms of readability, convention, performance, or anything else?


Solution

  • 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.