Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use enum in C# for storing string constants? [duplicate]

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"       } 
like image 562
Maddy.Shik Avatar asked Dec 05 '09 08:12

Maddy.Shik


People also ask

How do you use enums?

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

How do we declare enum variable in C?

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.

What is enum keyword in C?

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.

How is enum stored in C?

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.


1 Answers

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; } } 
like image 113
R. Martinho Fernandes Avatar answered Oct 16 '22 18:10

R. Martinho Fernandes