Joper
Joper

Reputation: 8219

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?

Upvotes: 14

Views: 14959

Answers (2)

ckittel
ckittel

Reputation: 6646

I find myself in this situation often and I end up converting it to something that looks like:

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

(Hope that's right, I'm a VB.NET dev, same idea)

Public Shared ReadOnly DateTimeFormatNormal As String = String.Format("{0} {1}", DateFormatNormal, TimeFormatNormal)

Public Shared ReadOnly is pretty darn close to Public Const.

Upvotes: 4

Justin Niessner
Justin Niessner

Reputation: 245479

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.

Upvotes: 21

Related Questions