Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

CaseConverter: A Class for Converting to Different Casing Styles

5.00/5 (2 votes)
6 Feb 2024MIT 2.5K   19  
Easily convert identifiers from one casing style to another with this simple to use class
Code generators often need to do case conversion in order to convert friendly names or names from other structured text documents to appropriately cased identifiers in your code. Here's some code for doing exactly that.

Introduction

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.

Using the Code

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.

C#
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();
}

History

  • 6th February, 2024 - Initial submission

License

This article, along with any associated source code and files, is licensed under The MIT License