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.
Since Enum
Type implements IConvertible
interface, a better implementation should be something like this:
public T GetEnumFromString<T>(string value) where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
//...
}
This will still permit passing of value types implementing IConvertible
. The chances are rare though.
Best Answer
Create a stylesheet,
Create a numberingformat,
Create a cell format and apply the numbering format id
and when you append the value to the cell have the following center code hereonversion and apply the style index in my case i had three style index hence the 3 one was my percentage style index i.e 2 since the indexes start from 0