Skip to content

Instantly share code, notes, and snippets.

@nikanos
Last active April 25, 2021 09:36
Show Gist options
  • Save nikanos/b81c5a1dfde8715eeef82e2168e81663 to your computer and use it in GitHub Desktop.
Save nikanos/b81c5a1dfde8715eeef82e2168e81663 to your computer and use it in GitHub Desktop.
EnumUtils.ConvertTo
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);
}
}
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