Casting string to enum

C#StringCastingEnums

C# Problem Overview


I'm reading file content and take string at exact location like this

 string fileContentMessage = File.ReadAllText(filename).Substring(411, 3);

Output will always be either Ok or Err

On the other side I have MyObject which have ContentEnum like this

public class MyObject

    {
      public enum ContentEnum { Ok = 1, Err = 2 };        
      public ContentEnum Content { get; set; }
    }

Now, on the client side I want to use code like this (to cast my string fileContentMessage to Content property)

string fileContentMessage = File.ReadAllText(filename).Substring(411, 3);

    MyObject myObj = new MyObject ()
    {
       Content = /// ///,
    };

C# Solutions


Solution 1 - C#

Use Enum.Parse().

var content = (ContentEnum)Enum.Parse(typeof(ContentEnum), fileContentMessage);

Solution 2 - C#

As an extra, you can take the Enum.Parse answers already provided and put them in an easy-to-use static method in a helper class.

public static T ParseEnum<T>(string value)
{
    return (T)Enum.Parse(typeof(T), value, ignoreCase: true);
}

And use it like so:

{
   Content = ParseEnum<ContentEnum>(fileContentMessage);
};

Especially helpful if you have lots of (different) Enums to parse.

Solution 3 - C#

.NET 4.0+ has a generic Enum.TryParse

ContentEnum content;
Enum.TryParse(fileContentMessage, out content);

Solution 4 - C#

Have a look at using something like

Enum.TryParse

> Converts the string representation of the name or numeric value of one > or more enumerated constants to an equivalent enumerated object. A > parameter specifies whether the operation is case-sensitive. The > return value indicates whether the conversion succeeded.

or

Enum.Parse

> Converts the string representation of the name or numeric value of one > or more enumerated constants to an equivalent enumerated object.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1765862View Question on Stackoverflow
Solution 1 - C#CodeCasterView Answer on Stackoverflow
Solution 2 - C#pleinolijfView Answer on Stackoverflow
Solution 3 - C#Chris FulstowView Answer on Stackoverflow
Solution 4 - C#Adriaan StanderView Answer on Stackoverflow