I have two constants:
public const string DateFormatNormal = "MMM dd";
public const string TimeFormatNormal = "yyyy H:mm";
after i decided to have another constant base on those two:
public const string DateTimeFormatNormal = String.Format("{0} {1}", DateFormatNormal, TimeFormatNormal);
But i get compile error The expression being assigned to 'Constants.DateTimeFormatNormal' must be constant
After i try do do like that:
public const string DateTimeFormatNormal = DateFormatNormal + " " + TimeFormatNormal;
It is working with + " " +
but i still prefer to use something similar to String.Format("{0} {1}", ....)
any thoughts how i can make it work?
To set a constant in C#, use the const keyword. Once you have initialized the constant, on changing it will lead to an error. const string one= "Amit"; Now you cannot modify the string one because it is set as constant.
const is compile time. When you use const string you end up not using space for this variable during run time. The compiler uses this value in a way not dissimilar to a macro. When you don't use const string it acts like any other variable and occupies additional space during run time.
It marks the string as a verbatim string literal. In C#, a verbatim string is created using a special symbol @. @ is known as a verbatim identifier. If a string contains @ as a prefix followed by double quotes, then compiler identifies that string as a verbatim string and compile that string.
Constants are immutable values which are known at compile time and do not change for the life of the program. Constants are declared with the const modifier. Only the C# built-in types (excluding System. Object) may be declared as const .
Unfortunately not. When using the const keyword, the value needs to be a compile time constant. The reslult of String.Format isn't a compile time constant so it will never work.
You could change from const
to readonly
though and set the value in the constructor. Not exact the same thing...but a similar effect.
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