C #: How to use an enumeration to store string constants?

Possible duplicate:
Enumeration with strings

it is possible to have string constants in a type enumeration

enum{name1="hmmm" name2="bdidwe"} 

if this is not the best way to do this?

I tried so that it does not work for the string, so right now I'm grouping all the related constnats in one class, for example

  class operation { public const string name1="hmmm"; public const string name2="bdidwe" } 
+44
string enums constants
Dec 05 '09 at 8:18
source share
4 answers

Enum constants can only be of ordinal types ( int by default), so you cannot have string constants in enumerations.

When I want something like "string-based renaming," I create a class to hold constants, just like you, except that I make it a static class to prevent both undesired creation and undesired subclass.

But if you don't want to use a string as a type in method signatures, and you prefer a safer, more restrictive type (like Operation ), you can use a safe enumeration 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; } } 
+88
Dec 05 '09 at 8:50
source share

You can do this using DescriptionAttribute , but then you have to write code to get the string from the attribute.

 public enum YourEnum { [Description("YourName1")] Name1, [Description("YourName2")] Name2 } 
+35
Dec 05 '09 at 8:42
source share

The whole point of enumerations is ordinal constants.
However, you can achieve what you want using the extension method:

  enum Operation { name1, name2 } static class OperationTextExtender { public static String AsText(this Operation operation) { switch(operation) { case Operation.name1: return "hmmm"; case Operation.name2: return "bdidwe"; ... } } } ... var test1 = Operation.name1; var test2 = test1.AsText(); 
+4
Dec 05 '09 at 8:30
source share

Your operation class will not compile as is ... you have not declared the type name1 and name2 ...

But this is the approach I would take ... yes.

If you create a structure, it will become a value type, which may or may not be what you wanted ...

0
Dec 05 '09 at 8:20
source share



All Articles