Last active
November 25, 2024 16:02
-
-
Save nikanos/b81c5a1dfde8715eeef82e2168e81663 to your computer and use it in GitHub Desktop.
EnumExtensions.ConvertTo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static class EnumExtensions | |
{ | |
public static TargetEnum ConvertTo<TargetEnum>(this Enum source, bool ignoreCase) | |
where TargetEnum : struct | |
{ | |
if (!typeof(TargetEnum).IsEnum) | |
throw new ArgumentException("T must be an enumerated type"); | |
string sourceName = Enum.GetName(source.GetType(), source); | |
bool parseResult = Enum.TryParse(sourceName, ignoreCase, out TargetEnum result); | |
if (!parseResult) | |
throw new ArgumentException($"enum name {sourceName} does not exist in TargetEnum enum {typeof(TargetEnum)}.", nameof(source)); | |
return result; | |
} | |
public static TargetEnum ConvertTo<TargetEnum>(this Enum source) | |
where TargetEnum : struct | |
{ | |
return ConvertTo<TargetEnum>(source, ignoreCase: false); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
enum ColorDTO { white, black } | |
enum ColorCAPSDTO { WHITE, BLACK } | |
enum Color { black, white } | |
enum NoColor { } | |
static void Main(string[] args) | |
{ | |
Console.WriteLine(ColorDTO.black.ConvertTo<Color>()); //Prints black | |
//Console.WriteLine(ColorCAPSDTO.BLACK.ConvertTo<Color>()); //Throws | |
Console.WriteLine(ColorCAPSDTO.BLACK.ConvertTo<Color>(ignoreCase: true)); //Prints black | |
//Console.WriteLine(ColorDTO.black.ConvertTo<NoColor>()); //Throws | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment