Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constants in .NET with String.Format

Tags:

c#

.net-4.0

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?

like image 899
Joper Avatar asked Aug 25 '11 01:08

Joper


People also ask

How do you make a string constant in C#?

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.

Can a const be a string?

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.

What is $@ in C#?

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.

What is constant in C# with example?

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 .


1 Answers

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.

like image 162
Justin Niessner Avatar answered Sep 27 '22 19:09

Justin Niessner