Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign string values to enums and use that value in a switch

Tags:

c#

.net

enums

Basically a series of titles will be passed into the switch statement and I need to compare them against the string values of the enum. But I have little to no idea how to do this correctly.

Also, I don't know if this is even the best approach so if anyone has any ideas?

For example:

enum {     doctor = "doctor",     mr = "mr",     mrs = "mrs" } 

and then switch through the string values I've assigned them.

like image 937
ediblecode Avatar asked Nov 01 '11 12:11

ediblecode


People also ask

Can you assign string to enum?

IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum. TryParse () method.

Can enums have string values?

Note: you cannot set an enum to string as enums can only have integers. The conversion above simply converts an already existing enum into a string.

Can you assign values to enums?

You can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially.

How do you match a string to an enum?

For comparing String to Enum type you should convert enum to string and then compare them. For that you can use toString() method or name() method. toString()- Returns the name of this enum constant, as contained in the declaration.


2 Answers

I found that the best way for me to do this is by using the System.ComponentModel.DescriptionAttribute attribute on the enum values.

Here is an example:

using System.ComponentModel;  public enum ActionCode {     [Description("E")]     Edit,     [Description("D")]     Delete,     [Description("R")]     Restore } 

Then, to use it, create an extension method on a static class like so:

Edit: I rewrote the method to include a great suggestion from Laurie Dickinson so that the method returns the name of the enum value when there is no Description attribute. I also refactored the method to try to improve functionality. It now works for all Enums without using IConvertible.

public static class Extensions {     public static string GetDescription(this Enum e)     {         var attribute =             e.GetType()                 .GetTypeInfo()                 .GetMember(e.ToString())                 .FirstOrDefault(member => member.MemberType == MemberTypes.Field)                 .GetCustomAttributes(typeof(DescriptionAttribute), false)                 .SingleOrDefault()                 as DescriptionAttribute;          return attribute?.Description ?? e.ToString();     } } 

So, to get the string associated with our enum above, we could use the following code:

using Your.Extension.Method.Namespace;  ...  var action = ActionCode.Edit; var actionDescription = action.GetDescription();  // Value of actionDescription will be "E". 

Here is another sample Enum:

public enum TestEnum {     [Description("This is test 1")]     Test1,     Test2,     [Description("This is test 3")]     Test3  } 

Here is the code to see the description:

var test = TestEnum.Test2; var testDescription = test.GetDescription(); test = TestEnum.Test3; var testDescription2 = test.GetDescription(); 

Results will be:

testDescription: "Test2" testDescription2: "This is test 3" 

I wanted to go ahead and post the generic method as it is much more useful. It prevents you from having to write a custom extension for all of your enums.

like image 126
Michael Earls Avatar answered Sep 22 '22 04:09

Michael Earls


You can't have an enum with an underlying type of string. The underlying type can be any integral type except char.

If you want to translate a string to your enum then you'll probably need to use the Parse or TryParse methods.

string incoming = "doctor";  // throws an exception if the string can't be parsed as a TestEnum TestEnum foo = (TestEnum)Enum.Parse(typeof(TestEnum), incoming, true);  // try to parse the string as a TestEnum without throwing an exception TestEnum bar; if (Enum.TryParse(incoming, true, out bar)) {     // success } else {     // the string isn't an element of TestEnum }  // ...  enum TestEnum {     Doctor, Mr, Mrs } 
like image 35
LukeH Avatar answered Sep 19 '22 04:09

LukeH