kurnakovv / EnumConverter

EnumConverter is a little open source library for converting enums

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

EnumConverter

NuGet NuGet download Visitors Build/Test MIT License Code Smells Coverage

Description

EnumConverter is a little open source library for converting enums.

How it works

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

Reason

I always forget how to convert enum, so I created this library for convenience

Give a star ⭐

I hope this library is useful for you, if so, please give this repository a star, thank you :)

About

EnumConverter is a little open source library for converting enums

License:MIT License


Languages

Language:C# 100.0%