How to include an enumeration value in a const string?

from this question , I know that const string can be a concatenation of const things. Now an enumeration is just a lot of integers, isn't it? So why is it not all right:

 const string blah = "blah " + MyEnum.Value1; 

or that:

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

And how would you include the enum value in the const string?

Real life example: when creating an SQL query, I would like to have "where status <> " + StatusEnum.Discarded .

+6
source share
3 answers

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

+6
source

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

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

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

+4
source

You cannot do this because MyEnum.Value1 and (int)MyEnum.Value1 are not string constants. There will be an implicit conversion at the time of the assignment.

Use static readonly string instead:

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

Source: https://habr.com/ru/post/913119/


All Articles