Skip to content

Instantly share code, notes, and snippets.

@timiles
Created October 10, 2018 13:46
Show Gist options
  • Save timiles/7e7ae533ca66c6c0dd52dd5d28b90989 to your computer and use it in GitHub Desktop.
Save timiles/7e7ae533ca66c6c0dd52dd5d28b90989 to your computer and use it in GitHub Desktop.
using System;
using System.Text.RegularExpressions;
public static class EnumSnakeCaseExtensions
{
public static string ToSnakeCase(this Enum value)
{
return Regex.Replace(value.ToString(), @"(\p{Ll})(\p{Lu})", "$1_$2").ToLower();
}
public static T FromSnakeCase<T>(this string value) where T : struct
{
if (!typeof(T).IsEnum)
{
throw new NotSupportedException("T must be an Enum type");
}
var pascalCase = Regex.Replace(value, @"(-|_)\w{1}|^\w",
match => match.Value.Replace("-", string.Empty).Replace("_", string.Empty).ToUpper());
return (T)Enum.Parse(typeof(T), pascalCase);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment