0

since i can not have space in enum and i am trying to do something like this but seems like does not like it....

public enum EnumState
{
    NewYork,
    NewMexico
}


public EnumState State
    {
        get
        {
            return EnumState ;
        }
        set
        {
            if (EnumState .ToString() == "NewYork".ToString())
            {
                value = "New York".ToString();
                EnumState = value;
            }
        }
    }
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
Nick Kahn
  • 19,652
  • 91
  • 275
  • 406
  • 2
    `if (EnumState == EnumState.NewYork)` – SLaks Sep 12 '11 at 15:31
  • 3
    Setting the value of `value` in a setter is a bad idea. – Bala R Sep 12 '11 at 15:33
  • Why are you calling `.ToString()` on strings? What do you intend to accomplish by assigning a string value to an enum typed variable? Whatever you are trying to do, there is probably a better way of approaching it. – recursive Sep 12 '11 at 16:01

2 Answers2

3

I have seen this generally handled by putting a [StringValue("New York")] attribute on the enum members. A quick google search returns this blog post, which has a pretty good way of doing it.

Basically make the attribute class:

public class StringValueAttribute : Attribute {

    public string StringValue { get; protected set; }

    public StringValueAttribute(string value) {
        this.StringValue = value;
    }
}

And an extension method to access it:

   public static string GetStringValue(this Enum value) {
        // Get the type
        Type type = value.GetType();

        // Get fieldinfo for this type
        FieldInfo fieldInfo = type.GetField(value.ToString());

        // Get the stringvalue attributes
        StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
            typeof(StringValueAttribute), false) as StringValueAttribute[];

        // Return the first if there was a match, or enum value if no match
        return attribs.Length > 0 ? attribs[0].StringValue : value.ToString();
    }

Then your enum would look like this:

public enum EnumState{
  [StringValue("New York")]
  NewYork,
  [StringValue("New Mexico")]
  NewMexico,
}

and you can just use myState.GetStringValue();

captncraig
  • 22,118
  • 17
  • 108
  • 151
1

You could use this pattern : C# String enums

It will allow you to define a custom string name for every enum you have in your enumeration.

Community
  • 1
  • 1
Drahakar
  • 5,986
  • 6
  • 43
  • 58