Skip to content

Instantly share code, notes, and snippets.

@Tyriar
Created June 25, 2014 18:23
Show Gist options
  • Save Tyriar/b0e5abc7930a480a0827 to your computer and use it in GitHub Desktop.
Save Tyriar/b0e5abc7930a480a0827 to your computer and use it in GitHub Desktop.
Converts a type/enum name to a string as sentence case.
using System;
using System.Text;
public static class TypeNameToString
{
public static string TypeNameToString(this string text)
{
var builder = new StringBuilder();
var typeName = text;
int index = -1;
while (++index < typeName.Length)
{
char nextChar = typeName[index];
if (char.IsUpper(nextChar) && index != 0)
{
if (char.IsLower(typeName[index - 1]))
{
if (typeName.Length > index + 1 &&
char.IsLower(typeName[index + 1]))
{
nextChar = char.ToLower(nextChar);
}
builder.Append(' ');
}
else if (typeName.Length > index + 1 &&
char.IsLower(typeName[index + 1]))
{
builder.Append(' ');
nextChar = char.ToLower(nextChar);
}
}
builder.Append(nextChar);
}
return builder.ToString();
}
public static string ToNiceString<TEnum>(this TEnum val)
where TEnum : struct, IConvertible, IComparable, IFormattable
{
if (!typeof(TEnum).IsEnum)
{
throw new ArgumentException("TEnum must be an enum.");
}
return Enum.GetName(typeof(TEnum), val).TypeNameToString();
}
public static string ToNiceString(this Type type)
{
return type.Name.TypeNameToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment