c# - How to return a Enum value from a string? -
I am trying to return a strongly typed value to the string. I'm sure that there is a better way to do this: It looks like a lot of code for just a simple matter:
Public stable device type default device type {get {var deviceTypeString = GetSetting ( "DefaultDeviceType"); If (DeviceTypeString.Equals (DeviceType.IPhone.ToString ())) Back to DeviceType IPhone; If (DeviceTypeString.Equals (DeviceType.Android.ToString ())) Back to DeviceType Android; If (DeviceTypeString.Equals (DeviceType.BlackBerry.ToString ())) DeviceType.BlackBerry; If (DeviceTypeString.Equals (DeviceType.Other.ToString ())) Back to DeviceType other; Returns DeviceType.IPhone; // If no default is provided, then use this default idea} > This takes a parameter (default value calculated). This default also provides a type, so a general estimate can be made and it does not need to explicitly use & lt;> This method is now reduced:
Get the public static device type default device type {get GetTeeting ("DefaultDeviceType"). ToEnum (DeviceType.iphone); }}
A very cool solution that can be reused in the future.
If you are working with (unreliable) user input, then I use an extension method I want to do that which allows a default value. Try it
Public static trashlutt parsnem < TResult & gt; (This string value, trust default value) {try {return (TResult) Enum.Parse (typeof (TRsult), value, true); } Hold (argument expression) {return default default; }}
Comments
Post a Comment