What's the difference between the first and second definitions?
//1 private static string Mask { get { return "some text"; } } //2 private const string Mask = "some text";
Which benefits has the first and the second approach?
The const (read: constant) keyword in C# is used to define a constant variable, i.e., a variable whose value will not change during the lifetime of the program. Hence it is imperative that you assign a value to a constant variable at the time of its declaration.
The first, const, is initialized during compile-time and the latter, readonly, initialized is by the latest run-time. The second difference is that readonly can only be initialized at the class-level. Another important difference is that const variables can be referenced through "ClassName.
Constant and ReadOnly keyword is used to make a field constant which value cannot be modified. The static keyword is used to make members static that can be shared by all the class objects.
constants are absolute constants in which their value cannot be changed or assigned at the run time. constant variables are compile time variables.
As long as they are private they will probably be optimized to more or less the same code. The re is another story if they are public and used from other assemblies.
const
variables will be substitued/inlined in other assemblies using the const
expression. That means that you need to recompile every assembly using the const
expression if you change the expression. On the other hand the property solution will give you a method call overhead each time used.
Basically const
fields value evaluated at compile time and initiailized at declaration only. Also important point that they are stored in the assembly metadata
so there is could be a problem when you distributing assembly across the customers and then give them an updated version, so they need to recompile assemblies which referencing const to pick up an updated value as well.
In few words static
field is something like a global variable which is accessible without instantiating any instance of underlying type, but in your case private
access modifieds makes it unaccessible out of the type where it declared.
EDIT:
Very good Community Wiki post regarding constants: Referencing constants across assemblies (post no longer exists as of June 2013.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With