Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include an enum value in a const string?

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.

like image 884
Zonko Avatar asked Apr 13 '12 09:04

Zonko


3 Answers

As a workaround, you can use a field initializer instead of a const, i.e.

static readonly string blah = "blah " + MyEnum.Value1;

static readonly string bloh = "bloh " + (int)MyEnum.Value1;

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 the int case, 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 the string.Concat(object,object) overload, identical to:

static readonly string blah = string.Concat("blah ", MyEnum.Value1);
static readonly string bloh = string.Concat("bloh ", (int)MyEnum.Value1);

where string.Concat will perform the .ToString(). As such, it could be argued that the following is slightly more efficient (avoids a box and a 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).

like image 54
Marc Gravell Avatar answered Oct 27 '22 08:10

Marc Gravell


You need to use readonly or static readonly instead of const.

static readonly string blah = "blah " + MyEnum.Value1;

The reason MyEnum.Value1 is not treated as const is that a method call is required to convert the value to a string, and the result of a method call is not treated as a constant value even if the method arguments are constant.

like image 31
Albin Sunnanbo Avatar answered Oct 27 '22 06:10

Albin Sunnanbo


You can't do this, because MyEnum.Value1 and (int)MyEnum.Value1 are not constant string values. There will be an implicit conversion at the time of the assignment.

Use a static readonly string instead:

static readonly string blah = "blah " + MyEnum.Value1;
like image 30
Daniel Hilgarth Avatar answered Oct 27 '22 07:10

Daniel Hilgarth