Hello,
Is using static string better than const string in C#
static string _mystr;
vs
const string Mystr;
Hello,
Is using static string better than const string in C#
static string _mystr;
vs
const string Mystr;
When you use a const
string, the compiler embeds the string's value at compile-time.
Therefore, if you use a const
value in a different assembly, then update the original assembly and change the value, the other assembly won't see the change until you re-compile it.
A static readonly
string is a normal field that gets looked up at runtime. Therefore, if the field's value is changed in a different assembly, the changes will be seen as soon as the assembly is loaded, without recompiling.
This also means that a static readonly
string can use non-constant members, such as Environment.UserName
or DateTime.Now.ToString()
. A const
string can only be initialized using other constants or literals.
Also, a static readonly
string can be set in a static constructor; a const
string can only be initialized inline.
Note that a static string
can be modified; you should use static readonly
instead.
OQ asked about static string
vs const
. Both have different use cases (although both are treated as static).
Use const only for truly constant values (e.g. speed of light - but even this varies depending on medium). The reason for this strict guideline is that the const value is substituted into the uses of the const in assemblies that reference it, meaning you can have versioning issues should the const change in its place of definition (i.e. it shouldn't have been a constant after all). Note this even affects private const
fields because you might have base and subclass in different assemblies and private fields are inherited.
Static fields are tied to the type they are declared within. They are used for representing values that need to be the same for all instances of a given type. These fields can be written to as many times as you like (unless specified readonly).
If you meant static readonly
vs const
, then I'd recommend static readonly
for almost all cases because it is more future proof.