Alex Rivera | Logout

How to include an enum value in a const string?

Asked 2012-04-13T09:35:44.730
12

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.

Edit
Report

1 Answer

4

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.

answered 2012-04-13T09:38:48.160

Your Answer