C# getter vs readonly

前端 未结 9 2168
遥遥无期
遥遥无期 2020-12-29 19:23

Is there any difference between the following?

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

    // Two:
    public static int V         


        
相关标签:
9条回答
  • 2020-12-29 20:09

    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.

    0 讨论(0)
  • 2020-12-29 20:15

    A Property is just syntactic sugar around a field, a property without a setter is simply declared a readonly field so the compiler will allow you to set it at runtime in the constructor, because to the compiler you are referencing a readonly field. There is a larger discussion around what to use a field or property, which is not within the scope of the question. And yes its this syntactic sugar that you have to do the recompiling referenced by @SOreadytohelp. Just to be clear a property is a field with a get and set method created for it, C# will allow you to reference it like a field rather than doing an annoying call to the getter or setter everytime.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题