Possible Duplicate:
Enum with strings
Is it possible to have string constants in enum like the following?
enum{name1="hmmm" name2="bdidwe"}
If it is not, what is the best way to do so?
I tried it, but it's not working for string so right now I am grouping all related constants in one class like
class operation { public const string name1="hmmm"; public const string name2="bdidwe" }
You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: “permanent”, “temp”, “apprentice”), or flags (“execute now”, “defer execution”).
If we do not explicitly assign values to enum names, the compiler by default assigns values starting from 0. For example, in the following C program, sunday gets value 0, monday gets 1, and so on.
In C programming, an enumeration type (also called enum) is a data type that consists of integral constants. To define enums, the enum keyword is used. enum flag {const1, const2, ..., constN}; By default, const1 is 0, const2 is 1 and so on.
Enumeration "values" aren't stored at all, as they are compile-time named constants. The compiler simply exchanges the use of an enumeration symbol, with the value of it. Also, the type of an enumeration value is of type int , so the exact size can differ.
Enum constants can only be of ordinal types (int
by default), so you can't have string constants in enums.
When I want something like a "string-based enum" I create a class to hold the constants like you did, except I make it a static class to prevent both unwanted instantiation and unwanted subclassing.
But if you don't want to use string as the type in method signatures and you prefer a safer, more restrictive type (like Operation
), you can use the safe enum pattern:
public sealed class Operation { public static readonly Operation Name1 = new Operation("Name1"); public static readonly Operation Name2 = new Operation("Name2"); private Operation(string value) { Value = value; } public string Value { get; private set; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With