Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const field or get property

Tags:

c#

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?

like image 948
Alexandre Avatar asked Aug 11 '11 09:08

Alexandre


People also ask

What does const do in C#?

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.

What is the difference between const and readonly?

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.

What is the difference between const readonly and static keyword?

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.

Can we change the value of constant variable in C#?

constants are absolute constants in which their value cannot be changed or assigned at the run time. constant variables are compile time variables.


2 Answers

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.

like image 73
Albin Sunnanbo Avatar answered Sep 24 '22 10:09

Albin Sunnanbo


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

like image 26
sll Avatar answered Sep 26 '22 10:09

sll