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?

5
  • 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. Commented Feb 3, 2012 at 9:19
  • 1
    Enums in .NET are value types and must be based on a integer value (byte, int, long etc.). Commented Feb 3, 2012 at 9:20
  • you want to know which page should load according to enumaration ? Commented Feb 3, 2012 at 9:23
  • 1
    Duplicate: stackoverflow.com/questions/9125891/… Commented Feb 3, 2012 at 9:23
  • possible duplicate of Associating enums with strings in C# Commented Feb 3, 2012 at 9:30

7 Answers 7

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#

Sign up to request clarification or add additional context in comments.

Comments

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
}

4 Comments

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"..
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.
For complex types which are sealed and have private constructors, this pattern is a good substitute. Not so for other types like strings. 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..
Great workaround, works for every use case that I need. Love it +1
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.

Comments

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
    }

Comments

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));

Comments

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.

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.