• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 343
  • Last Modified:

C#: Need to turn a text value into an enumeration

I have an enumeration and need to convert a string value into that matching enumerated value.

For example:

        public enum RuleTypes
        {
            Wf_Adm = 1,
            Wf_Case = 2,
            Wf_Ref = 3,
        }

If I have a string of "Wf_Case" I need to get a value of RuleTypes.Wf_Case.

I do not want to use a switch statement.

Thanks!
0
newbieweb
Asked:
newbieweb
  • 3
  • 2
  • 2
2 Solutions
 
Julian HansenCommented:
0
 
newbiewebAuthor Commented:
It probably should, but I can not figure it out.  I just need to convert from string to enum.
0
 
tlaytonCommented:
How about something like this?

        public RuleTypes GetEnum(string Value)
        {
            RuleTypes _return;
            Enum.TryParse(Value, out _return);
            return _return;
        }
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
newbiewebAuthor Commented:
Thanks!
0
 
tlaytonCommented:
Then to get your enum from the string you simply call: GetEnum("Wf_Case")
0
 
tlaytonCommented:
Np, good luck :)
0
 
Julian HansenCommented:
RuleTypes rt = (RuleTypes)Enum.Parse(typeof(RuleTypes), typeString);

Open in new window

Sample Code
using System;

enum RuleTypes { Wf_Adm = 1, Wf_Case = 2, Wf_Ref = 3};
namespace csharpee1
{
    class Program
    {
        static void Main(string[] args)
        {
            string typeString = "Wf_Case";
            try
            {
                RuleTypes rt = (RuleTypes)Enum.Parse(typeof(RuleTypes), typeString);
            }
            catch (ArgumentException)
            {
            }

        }
    }
}

Open in new window

0

Featured Post

 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now