from this question, I know that a const string can be the concatenation of const things. Now, an enum is just a set of cont integers, isn’t it ?
So why isn’t it ok to do this :
const string blah = "blah " + MyEnum.Value1;
or this :
const string bloh = "bloh " + (int)MyEnum.Value1;
And how would you include an enum value in a const string ?
Real life example : when building an SQL query, I would like to have "where status <> " + StatusEnum.Discarded.
As a workaround, you can use a field initializer instead of a const, i.e.
As for why: for the enum case, enum formatting is actually pretty complex, especially for the
[Flags]case, so it makes sense to leave this to the runtime. For theintcase, this could still potentially be affected by culture specific issues, so again: needs to be deferred until runtime. What the compiler actually generates is a box operation here, i.e. using thestring.Concat(object,object)overload, identical to:where
string.Concatwill perform the.ToString(). As such, it could be argued that the following is slightly more efficient (avoids a box and a virtual call):which would use
string.Concat(string,string).