As a workaround, you can use a field initializer instead of a constant, i.e.
static readonly string blah = "blah " + MyEnum.Value1; static readonly string bloh = "bloh " + (int)MyEnum.Value1;
As for the reason: for the enum case, enum formatting is actually quite complicated, especially for the [Flags]
case, so it makes sense to leave this at run time. For the int
case, this could potentially be affected by culture-related issues, so again it needs to be delayed until execution. What the compiler generates is a box operation here, i.e. using string.Concat(object,object)
overload, identical:
static readonly string blah = string.Concat("blah ", MyEnum.Value1); static readonly string bloh = string.Concat("bloh ", (int)MyEnum.Value1);
where string.Concat
will execute string.Concat
.ToString()
. Thus, it can be argued that the following is somewhat more efficient (avoids the box and virtual call):
static readonly string blah = "blah " + MyEnum.Value1.ToString(); static readonly string bloh = "bloh " + ((int)MyEnum.Value1).ToString();
which would use string.Concat(string,string)
.
source share