Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# getter vs readonly

Tags:

c#

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?

like image 507
jia103 Avatar asked Sep 27 '14 19:09

jia103


1 Answers

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.

like image 171
pescolino Avatar answered Oct 06 '22 01:10

pescolino