Last active
April 25, 2021 09:36
-
-
Save nikanos/b81c5a1dfde8715eeef82e2168e81663 to your computer and use it in GitHub Desktop.
EnumUtils.ConvertTo
This file contains 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 EnumUtils | |
{ | |
public static T ConvertTo<T, S>(S source) | |
where T : struct | |
where S : struct | |
{ | |
if (!typeof(T).IsEnum) | |
throw new ArgumentException("T must be an enumerated type"); | |
if (!typeof(S).IsEnum) | |
throw new ArgumentException("S must be an enumerated type"); | |
string sourceName = Enum.GetName(typeof(S), source); | |
if (!Enum.IsDefined(typeof(T), sourceName)) | |
throw new ArgumentException($"enum name {sourceName} does not exist in {typeof(T).Name} enum.", nameof(source)); | |
return (T)Enum.Parse(typeof(T), sourceName); | |
} | |
} |
This file contains 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 Color | |
{ | |
black, | |
white | |
} | |
enum NoColor | |
{ | |
} | |
static void Main(string[] args) | |
{ | |
ColorDTO dto = ColorDTO.black; | |
Color c = EnumUtils.ConvertTo<Color, ColorDTO>(dto); | |
Console.WriteLine(c);//Prints black | |
NoColor nc = EnumUtils.ConvertTo<NoColor, ColorDTO>(dto);//Throws | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment