63

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"
      }
2
  • Exact duplicate of stackoverflow.com/questions/630803/enum-with-strings Commented Dec 5, 2009 at 8:51
  • string[] Days = { "یکشنبه", "دوشنبه", "سه شنبه", "چهارشنبه", "پنج شنبه", "جمعه", "شنبه", }; int i =(int) obj.GetDayOfWeek(dt); string DayName = Days[i]; Commented Jul 19, 2013 at 21:13

4 Answers 4

124

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; }
}
Sign up to request clarification or add additional context in comments.

11 Comments

+1 Fit perfectly. Add to that implicit operations, and you're golden: public static implicit operator string(Operation op) { return op.Value; } because then you can use it as a strongly typed parameter, or as a string.
But it's not possible to use the above pattern where string constants are required, for example, in switch..case statements
why not just enum.ToString("F") ?
@ghanashyaml I believe that relies on reflection. It's slow in any case.
@Janis As stated in the answer: "if you don't want to use string as the type in method signatures and you prefer a safer, more restrictive type"
|
43

You could do this using DescriptionAttribute, but then you'd have to write code to get the string out of the attribute.

public enum YourEnum
{
    [Description("YourName1")]
    Name1,

    [Description("YourName2")]
    Name2
}

8 Comments

+1 First time coming across Description attribute. Thanks :)
How to get string out of attribute?
+1 the only answer yet that has taken the position that the OP's intent is to have something that has the full range of possibilities of an Enum type.
There's a number of examples if you google "enum descriptionattribute". Here's one: weblogs.asp.net/grantbarrington/archive/2009/01/19/…
This is a good answer to the question +1, but in practice this attribute is terribly vague as to its function and probably not that helpful in practice
|
11

The whole point of enums is to be ordinal constants.
However, you can achieve what you want by using an 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();   

3 Comments

I really wonder if you would ever use a one-off extension method like this in real-world code ? (there's no sarcasm intended in that question). It is interesting to know this could be done.
I have a snippet that creates extension classes with a Contains and Remove method for flag enums. I don't want it to be part of the public API, so it is internal. But I use it fairly frequently and for built-in flags as well, particularly "Contains".
@RobertGiesecke Just wanted to give you Kudos for this solution. The extension method was a perfect and elegant way for me to do this! The other solutions were to avoid enums but this solution allowed me to extend and it worked perfect without having to go overboard in complicating the task as most of the solutions did..
0

Your operation class won't compile as is... you didn't declare the type of name1 and name2...

But that is the approach I'd take... yes.

If you make it a struct then it becomes a value type which may or may not be what you wanted...

2 Comments

i forgot type it here otherwise its fine.i am just concerned about the right approach to keep string constants.
Yes, I'd do something along those lines too probably.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.