77

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 = /// ///,
    };
NoWar
  • 36,338
  • 80
  • 323
  • 498
user1765862
  • 13,635
  • 28
  • 115
  • 220

4 Answers4

176

Use Enum.Parse().

var content = (ContentEnum)Enum.Parse(typeof(ContentEnum), fileContentMessage);
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • 4
    `Enum.Parse` returns an `object` which needs to be casted. I felt free to edit :) – Matthias Meid Dec 20 '12 at 10:42
  • Perfect, a one-line solution. Thanks! This saves me from writing another method to handle it. – John Suit Nov 11 '14 at 15:20
  • 1
    I tried with Parity Enum and when I give the string value of 123 it returns it without issue, even though Parity enum does not include 123 value of enum – John Demetriou Aug 07 '17 at 08:31
  • @JohnDemetriou that's documented: _"If value is the string representation of an integer that does not represent an underlying value of the enumType enumeration, the method returns an enumeration member whose underlying value is value converted to an integral type. If this behavior is undesirable, call the IsDefined method to ensure that a particular string representation of an integer is actually a member of enumType"_. – CodeCaster Aug 07 '17 at 08:52
  • @CodeCaster thx – John Demetriou Aug 07 '17 at 11:45
27

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.

pleinolijf
  • 891
  • 12
  • 29
22

.NET 4.0+ has a generic Enum.TryParse

ContentEnum content;
Enum.TryParse(fileContentMessage, out content);
Chris Fulstow
  • 41,170
  • 10
  • 86
  • 110
18

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.

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284