Constants in .NET with String.Format

I have two constants:

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

after I decided to have another permanent base for these two:

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

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

After I try to do this:

public const string DateTimeFormatNormal = DateFormatNormal + " " + TimeFormatNormal;

It works with + " " +, but I still prefer to use something similar to String.Format("{0} {1}", ....)any thoughts, how can I make it work?

+5
source share
2 answers

Unfortunately no. When using the const keyword, the value must be a compile-time constant. The result of String.Format is not a compile time constant, so it will never work.

const readonly . ... .

+12

, :

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

(, , VB.NET, )

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

Public Shared ReadOnly Public Const.

+3

All Articles