Convert a String to an Enum in C#

Convert a string to an enum in C#

In .NET Core and .NET Framework ≥4.0 there is a generic parse method:

Enum.TryParse("Active", out StatusEnum myStatus);

This also includes C#7's new inline out variables, so this does the try-parse, conversion to the explicit enum type and initialises+populates the myStatus variable.

If you have access to C#7 and the latest .NET this is the best way.

Original Answer

In .NET it's rather ugly (until 4 or above):

StatusEnum MyStatus = (StatusEnum) Enum.Parse(typeof(StatusEnum), "Active", true);

I tend to simplify this with:

public static T ParseEnum<T>(string value)
{
return (T) Enum.Parse(typeof(T), value, true);
}

Then I can do:

StatusEnum MyStatus = EnumUtil.ParseEnum<StatusEnum>("Active");

One option suggested in the comments is to add an extension, which is simple enough:

public static T ToEnum<T>(this string value)
{
return (T) Enum.Parse(typeof(T), value, true);
}

StatusEnum MyStatus = "Active".ToEnum<StatusEnum>();

Finally, you may want to have a default enum to use if the string cannot be parsed:

public static T ToEnum<T>(this string value, T defaultValue) 
{
if (string.IsNullOrEmpty(value))
{
return defaultValue;
}

T result;
return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;
}

Which makes this the call:

StatusEnum MyStatus = "Active".ToEnum(StatusEnum.None);

However, I would be careful adding an extension method like this to string as (without namespace control) it will appear on all instances of string whether they hold an enum or not (so 1234.ToString().ToEnum(StatusEnum.None) would be valid but nonsensical) . It's often be best to avoid cluttering Microsoft's core classes with extra methods that only apply in very specific contexts unless your entire development team has a very good understanding of what those extensions do.

Convert string into Enum

Rohit,

The value of preferenceKey could not easily be converted to an enum as you would expect. The strings could be parsed using Enum.Parse() method however the enum names must be different than what you have in the database. The problems are

  1. Your string starts with a number
  2. Your string contains the - characters

Now that being said you could design a different approach to your naming convetion of an enum as an example (I dont like this example personally but might work).

First define a new attribute called EnumName this attribute will be used to decorate your enums with the name that you expect from the database. Such as

[AttributeUsage(AttributeTargets.Field, AllowMultiple = true)]
public sealed class EnumNameAttribute : Attribute
{
readonly string name;

public EnumNameAttribute(string name)
{
this.name = name;
}

public string Name { get { return this.name; } }
}

The next step will be to define your enums (what I dont like is the names)

public enum Preferences
{
[EnumName("6E-SF-TYPE")]
SIX_E_SF_TYPE = 0,
[EnumName("6E-SF-VALUE")]
SIX_E_SF_VALUE = 1
}

Simple enough, we have our enum with each item decorated with the EnumName attribute. The next step will be to create a method to parse the enum based on the string from the database.

public static class EnumNameParser
{
public static Preferences ParseString(string enumString)
{
var members = typeof(Preferences).GetMembers()
.Where(x => x.GetCustomAttributes(typeof(EnumNameAttribute), false).Length > 0)
.Select(x =>
new
{
Member = x,
Attribute = x.GetCustomAttributes(typeof(EnumNameAttribute), false)[0] as EnumNameAttribute
});

foreach(var item in members)
{
if (item.Attribute.Name.Equals(enumString))
return (Preferences)Enum.Parse(typeof(Preferences), item.Member.Name);
}

throw new Exception("Enum member " + enumString + " was not found.");
}
}

This method simply takes an input stream, evaluates all the EnumNameAttributes and returns the first match (or exception if not found).

Then this can be called such as.

string enumString = "6E-SF-TYPE";
var e = EnumNameParser.ParseString(enumString);

Now if you want to take the enum and get the name for the database you can extend your helper method with

public static string GetEnumName(this Preferences preferences)
{
var memInfo = typeof(Preferences).GetMember(preferences.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(EnumNameAttribute), false);
if (attrs != null && attrs.Length > 0)
return ((EnumNameAttribute)attrs[0]).Name;
}
throw new Exception("No enum name attribute defined");

}

Casting string to enum

Use Enum.Parse().

var content = (ContentEnum)Enum.Parse(typeof(ContentEnum), fileContentMessage);

String to enum conversion in C#

I suggest building a Dictionary<string, Operation> to map friendly names to enum constants and use normal naming conventions in the elements themselves.

enum Operation{ Equals, NotEquals, LessThan, GreaterThan };

var dict = new Dictionary<string, Operation> {
{ "Equals", Operation.Equals },
{ "Not Equals", Operation.NotEquals },
{ "Less Than", Operation.LessThan },
{ "Greater Than", Operation.GreaterThan }
};

var op = dict[str];

Alternatively, if you want to stick to your current method, you can do (which I recommend against doing):

var op = (Operation)Enum.Parse(typeof(Operation), str.Replace(' ', '_'));

Convert.ChangeType How to convert from String to Enum

Use Enum.Parse method for this.

public static T Convert<T>(String value)
{
if (typeof(T).IsEnum)
return (T)Enum.Parse(typeof(T), value);

return (T)Convert.ChangeType(value, typeof(T));
}

Convert string to enum in a function

Without knowing the signature of the function, this is quite difficult to answer, but I think you are looking for Enum.TryParse: Declare the enums eCurrentState and eStable_state_ENDDR, then use

Enum.TryParse(currentState, out eCurrentState);

Enum.TryParse(stable_state_ENDDR, out eStable_state_ENDDR);

path = StatePath.statePath(eCurrentState, eStable_state_ENDDR);

If the TryParse fails, it returns false.

That being said, a general rule of thumb is to avoid scenarios like these and pass enums as int or bit flags, this is because internally thats how enums are stored, and require no conversion function to slow you down. Basically, SomeEnum == someIntValue would work directly without any conversion. So assuming you are getting your data from some server/db, simply request the data as a numeric value equal to the index of the enum that it is declared in. Conversely, store the data in the same way.

e.g. with any enum, with no attributes declared

enum SomeEnum
{
abc, // 0
def, // 1
g // 2
}

abc == 0, def == 1, g == 2, would return true.

How can I cast a String to an Enum

Seems like you are getting the output as string from the specified method. and you want it to be converted to enum, Here better option for you is TryParse, which can be used like the following:

NOA noa;
bool conversionResult = Enum.TryParse(App.DB.GetSetting("NumberOfAnswers"), out noa);

By executing this line you will get a boolean value in conversionResult, if its true means the conversion is completed successfully if it is false which means conversion failed, this time you will get the default value of the NOA in noa, Let the return value from App.DB.GetSetting("NumberOfAnswers") be "10" then the value of noa will be Ten and conversionResult will be true

Convert string to enum, but when enum type is only known at runtime

You could try that:

var castTo = fieldInfo.PropertyType.GetType(); 
var parsedEnum = Convert.ChangeType(Enum.Parse(castTo, valueFromSql), castTo);

More information about changing type can be found here: https://msdn.microsoft.com/en-us/library/system.convert.changetype(v=vs.110).aspx

There should be also a workaround for situation where database contains value that doesn't exists in your enum. Application will crash, as it will be not possible to do casting then.

How do I convert a string to an enum value to an integer?

var result = (int)System.Enum.Parse(typeof(Car), carName)

http://msdn.microsoft.com/en-us/library/essfb559.aspx

This replaces your GetCarType function. You no longer have to iterate over the enum names.



Related Topics



Leave a reply



Submit