Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate Constant String and Enum [duplicate]

I have a large C# class which is full of nothing but public const string fields. However, in one case I am trying to concatenate a string and a enum value into a const string field, like this:

public const string GET_VALUES = "SELECT * FROM [tbl] WHERE [id] = " + Enum.Val;

However, I get this compiler error:

'Namespace.SqlStatements.GET_VALUES' must be constant

I know I could drop the const clause, but I would like to keep all fields within this class consistent. Is it possible to concatenate a constant string and a enum in C#?

like image 396
Oliver Spryn Avatar asked Jul 25 '14 10:07

Oliver Spryn


People also ask

Do enums have to be sequential?

It is not necessary to assign sequential values to Enum members. They can have any values. In the above example, we declared an enum PrintMedia .

What is the correct use of ENUM in my sql?

An ENUM is a string object with a value chosen from a list of permitted values that are enumerated explicitly in the column specification at table creation time.

Why we use ENUM in python?

Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over.


1 Answers

From MSDN:

A constant expression is an expression that can be fully evaluated at compile time. Therefore, the only possible values for constants of reference types are string and a null reference.

In your case, the enum will have to be converted to a string using ToString, which is not possible at compile time. I'd suggest you change it to readonly as elgonzo mentioned.

like image 193
Chris Avatar answered Oct 05 '22 13:10

Chris