Fill string for listing

I read the contents of the file and take the line in an exact place like this

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

The output will always be either Ok or Err

On the other hand, I have a MyObject that has a 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 such code (to pass the fileContentMessage Content property)

 string fileContentMessage = File.ReadAllText(filename).Substring(411, 3); MyObject myObj = new MyObject () { Content = /// ///, }; 
+49
string enums casting c #
Dec 20
source share
4 answers

Use Enum.Parse() .

 var content = (ContentEnum)Enum.Parse(typeof(ContentEnum), fileContentMessage); 
+126
Dec 20 '12 at 10:40
source share

Look at using something like

Enum.TryParse

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

or

Enum.Parse

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

+17
Dec 20 '12 at 10:41
source share

As an extra, you can take the already provided Enum.Parse answers 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 this:

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

Especially useful if you have many (different) Enums to parse.

+15
Dec 20
source share

.NET 4.0+ has a common Enum.TryParse

 ContentEnum content; Enum.TryParse(fileContentMessage, out content); 
+13
Dec 20 '12 at 11:00
source share



All Articles