EnumConverter is a little open source library for converting enums.
Enums
public enum AnotherEnum { First, Second, Third }
public enum InputEnum { First, Second, Third }
public enum InputEnumLowerCase { first, second, third }
public enum InputEnumUpperCase { FIRST, SECOND, THIRD }
Convert enum with ignore case
InputEnum first = InputEnum.First;
InputEnumLowerCase second = InputEnumLowerCase.second;
InputEnumUpperCase third = InputEnumUpperCase.THIRD;
AnotherEnum anotherEnumFirst = first.ToAnother<AnotherEnum>();
AnotherEnum anotherEnumSecond = second.ToAnother<AnotherEnum>();
AnotherEnum anotherEnumThird = third.ToAnother<AnotherEnum>();
// Output:
// anotherEnumFirst - First
// anotherEnumSecond - Second
// anotherEnumThird - Third
Convert enum without ignore case
InputEnum first = InputEnum.First;
InputEnumLowerCase second = InputEnumLowerCase.second;
InputEnumUpperCase third = InputEnumUpperCase.THIRD;
AnotherEnum anotherEnumFirst = first.ToAnother<AnotherEnum>(false);
AnotherEnum anotherEnumSecond = second.ToAnother<AnotherEnum>(false);
AnotherEnum anotherEnumThird = third.ToAnother<AnotherEnum>(false);
// Output:
// anotherEnumFirst - First
// anotherEnumSecond - Throws ArgumentException
// anotherEnumThird - Throws ArgumentException
Convert string -> enum
string validFirstValue = "First";
string validSecondWithIgnoreCase = "second";
string invalidValue = "InvalidValue";
MyEnum validFirstEnum = validFirstValue.ToEnum<MyEnum>();
MyEnum validSecondEnum = validSecondWithIgnoreCase.ToEnum<MyEnum>();
MyEnum invalidSecondEnum = validSecondWithIgnoreCase.ToEnum<MyEnum>(false);
MyEnum invalidEnum = invalidValue.ToEnum<MyEnum>();
// Output:
// validFirstEnum - MyEnum.First
// validSecondEnum - MyEnum.Second
// invalidSecondEnum - Throws ArgumentException
// invalidEnum - Throws ArgumentException
Full docs here
I always forget how to convert enum, so I created this library for convenience
I hope this library is useful for you, if so, please give this repository a star, thank you :)