Updated on 2024-02-06
Easily convert identifiers from one casing style to another with this simple to use class
I wrote this code twice. The first time, I lost it somewhere in the depths of Azure. I write a lot of code generators so being able to convert for example, camelCase to snake_case, or IPAddress to IP_ADDRESS is especially useful.
You can do two things with this code. The first thing is you can split a string into multiple segments ("words") each containing part of your identifier. For example, "IPAddress" would net you "IP" and "Address" and "WiFi" would net you "Wi" and "Fi". You do this using the SplitCase() function which takes a string and returns an array of strings.
The other thing you can do is convert to a different case with Convert(). Convert takes a string and a CaseStyle and returns a string.
using CaseConvert;
var exps = new string[]
{
"foobar",
"foo_baz",
"IPAddress",
"SQL92",
"WiFi",
"ISO8601",
"fuBar",
"C89"
};
for(int i = 0; i < exps.Length; i++)
{
var sa = CaseConverter.SplitCase(exps[i]);
Console.WriteLine("segments: "+string.Join(", ",sa));
Console.WriteLine(CaseConverter.Convert(exps[i], CaseStyle.PascalCase));
Console.WriteLine(CaseConverter.Convert(exps[i], CaseStyle.CamelCase));
Console.WriteLine(CaseConverter.Convert(exps[i], CaseStyle.SnakeCase));
Console.WriteLine(CaseConverter.Convert(exps[i], CaseStyle.DashCase));
Console.WriteLine(CaseConverter.Convert(exps[i], CaseStyle.MacroCase));
Console.WriteLine();
}