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 = /// ///, };
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.
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.
Returns. The string representation of the value of this instance as specified by format .
Use Enum.Parse()
.
var content = (ContentEnum)Enum.Parse(typeof(ContentEnum), fileContentMessage);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With