Search code examples
c#.net-4.0

Constants in .NET with String.Format


I have two constants:

public const string DateFormatNormal = "MMM dd";
public const string TimeFormatNormal = "yyyy H:mm";

Later, I decided to have another constant based on those two:

public const string DateTimeFormatNormal = String.Format("{0} {1}", DateFormatNormal, TimeFormatNormal);

But I get a compile error: The expression being assigned to 'Constants.DateTimeFormatNormal' must be constant

After I try doing it 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?


Solution

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