Created
October 10, 2018 13:46
-
-
Save timiles/7e7ae533ca66c6c0dd52dd5d28b90989 to your computer and use it in GitHub Desktop.
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
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