Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting string to enum [duplicate]

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 = /// ///,     }; 
like image 423
user1765862 Avatar asked Dec 20 '12 10:12

user1765862


People also ask

How to convert string into Enum?

Use the 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.

Can we convert string to Enum in Java?

You can create Enum from String by using Enum. valueOf() method. valueOf() is a static method that is added on every Enum class during compile-time and it's implicitly available to all Enum along with values(), name(), and cardinal() methods.

What does Enum ToString return c#?

Returns. The string representation of the value of this instance as specified by format .


1 Answers

Use Enum.Parse().

var content = (ContentEnum)Enum.Parse(typeof(ContentEnum), fileContentMessage); 
like image 183
CodeCaster Avatar answered Oct 13 '22 00:10

CodeCaster