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.

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).


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.


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;

Need Your Help

Adding a name to a string with PowerShell

file powershell scripting rename

I have a host of files in a folder that are named as a string. I've found some information similar to what I'm trying to do here. I am not replacing existing characters in the string. I would just ...

Paging ListBox with ReactiveUI and Caliburn.Micro

wpf reactiveui caliburn.micro.reactiveui

I'm trying to implement a paging mechanism for a listbox using Caliburn.Micro.ReactiveUI with a call to EF using ".Skip(currentPage).Take(pageSize)". I'm new to ReactiveUI and Reactive in general. ...