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?
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.)
const
is a keyword of the language. 1s defined, your not allowed to change it down the line. Yes the property also depicts the same story, but it can have much more structure in it.
In const
, Once initialize can not modify. get
can also not modify.
But when you have a scenario where you need different values every time you call Or, your value depends on any other function call, get
will be used.
private static string Mask
{
get
{
var someOtherMethodText = SomeOtherMethodText();
return "some text" + someOtherMethodText;
}
}
get
accessor only can be considered as readonly.readonly
means that the object can not be replaced once initializers and constuctors are done. Aget
property can return different objects every time called.