4

I want to create string ENUM in c#.

Basically i wan't to set form name in Enum. When i open form in main page that time i want to switch case for form name and open that particular form. I know ENUM allows only integer but i want to set it to string. Any Idea?

Manoj Savalia
  • 1,402
  • 3
  • 13
  • 36
  • 1
    Enums can't be strings, Enums are always integral values. You can use the Enum class to get the name of an enum value as a string but you won't be able to use spaces etc. – IanNorton Feb 03 '12 at 09:19
  • you want to know which page should load according to enumaration ? – adt Feb 03 '12 at 09:23
  • 1
    Duplicate: http://stackoverflow.com/questions/9125891/why-doesnt-c-sharp-support-string-enumerations – Felix K. Feb 03 '12 at 09:23
  • possible duplicate of [Associating enums with strings in C#](http://stackoverflow.com/questions/630803/associating-enums-with-strings-in-c-sharp) – George Duckett Feb 03 '12 at 09:30
  • 1
    Enums in .NET are value types and must be based on a integer value (byte, int, long etc.). – Mithrandir Feb 03 '12 at 09:20

7 Answers7

18

Enum cannot be string but you can attach attribute and than you can read the value of enum as below....................

public enum States
{
    [Description("New Mexico")]
    NewMexico,
    [Description("New York")]
    NewYork,
    [Description("South Carolina")]
    SouthCarolina
}


public static string GetEnumDescription(Enum value)
{
    FieldInfo fi = value.GetType().GetField(value.ToString());

    DescriptionAttribute[] attributes =
        (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute),
        false);

    if (attributes != null &&
        attributes.Length > 0)
        return attributes[0].Description;
    else
        return value.ToString();
}

here is good article if you want to go through it : Associating Strings with enums in C#

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
5

As everyone mentioned, enums can't be strings (or anything else except integers) in C#. I'm guessing you come from Java? It would be nice if .NET had this feature, where enums can be any type.

The way I usually circumvent this is using a static class:

public static class MyValues
{
    public static string ValueA { get { return "A"; } }
    public static string ValueB { get { return "B"; } }
}

With this technique, you can also use any type. You can call it just like you would use enums:

if (value == MyValues.ValueA) 
{
    // do something
}
Peter
  • 13,733
  • 11
  • 75
  • 122
  • the problem with such hacks is that they dont give the true benefit of "strong type"-ness of enums. For instance in your case, I will be able to do `bool b = MyValues.ValueA == "someString"`.. – nawfal Jun 08 '13 at 18:59
  • True, but I rarely find this to be problematic. If MyValues.ValueA really is "someString", I'd want it to return true. Strings are a simple example, but it allows more complex types too. – Peter Jun 10 '13 at 06:56
  • For complex types which are sealed and have private constructors, this pattern is a good substitute. Not so for other types like `string`s. The issue I posted is simple. How about this: `string a = MyValues.ValueA;` and later, `a = "haha";`.. Basically spoils the idea of an enum.. I agree there are no simple workarounds. Attributes are the best still.. – nawfal Jun 10 '13 at 07:03
  • Great workaround, works for every use case that I need. Love it +1 – Unome Jun 17 '15 at 15:23
2

Do this:

private IddFilterCompareToCurrent myEnum = 
(IddFilterCompareToCurrent )Enum.Parse(typeof(IddFilterCompareToCurrent[1]),domainUpDown1.SelectedItem.ToString());

[Enum.parse] returns an Object, so you need to cast it.

Sagar Rawal
  • 1,442
  • 2
  • 12
  • 39
2

Im not sure if I understood you corectly but I think you are looking for this?

   public enum State { State1, State2, State3 };

    public static State CurrentState = State.State1;

    if(CurrentState ==  State.State1)
    {
    //do something
    }
formatc
  • 4,261
  • 7
  • 43
  • 81
2

I don't think that enums are the best solution for your problem. As others have already mentionde, the values of an enum can only be integer values.

You could simply use a Dictionary to store the forms along with their name like:

Dictionary<string, Form> formDict = new Dictionary<string, Form>();

private void addFormToDict(Form form) {
  formDict[form.Name] = form;
}

// ...
addFormToDict(new MyFirstForm());
addFormToDict(new MySecondForm());
// ... add all forms you want to display to the dictionary


if (formDict.ContainsKey(formName))
  formDict[formName].Show();
else
  MessageBox.Show(String.Format("Couldn't find form '{0}'", formName));
MartinStettner
  • 28,719
  • 15
  • 79
  • 106
2

Either make the names of the Enum members exactly what you want and use .ToString(),

Write a function like this ...

string MyEnumString(MyEnum value)
{
    const string MyEnumValue1String = "any string I like 1";
    const string MyEnumValue2String = "any string I like 2";
    ...

    switch (value)
    {
        case MyEnum.Value1:
            return MyEnumValue1String;

        case MyEnum.Value2:
            return MyEnumValue2String;

        ...
    }
}

Or use some dictionary or hash set of values and strings instead.

Jodrell
  • 34,946
  • 5
  • 87
  • 124
1

string enums don't exist in C#. See this related question.

Why don't you use an int (default type for enums) instead of a string?

Community
  • 1
  • 1
ken2k
  • 48,145
  • 10
  • 116
  • 176