How to convert CamelCase to snake_case in C #?

Posted on

Question :

I would like to know how to convert a string with CamelCase to snake_case into C #.

For example:

 EuAmoCsharp => eu_amo_csharp
 SnakeCase   => snake_case


Answer :

It would look something like this:

string stringSnake = string.Concat(
                         stringCamel.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString().ToLower() : x.ToString().ToLower())

I made you a Fiddle .


string is an enumeration of char in C #. Then I can use:


One of the ways to use Select is by specifying two variables in the predicate, x being the current character of the iteration and i the index of that iteration.

The conditional is simpler to understand:

i > 0 && char.IsUpper(x) ? "_" + x.ToString().ToLower() : x.ToString().ToLower()

I check if i is greater than zero and if the current character is uppercase, this is because I do not want to write _ before the first character.

If the character is uppercase, I type _ and the character in lower case. If not, just write the character.

I need to keep ToLower() in both results because of the first character.


Just curious, you can do with regex too, but it’s a bit slower.

string stringSnake = Regex.Replace(input, "(?<=.)([A-Z])", "_$0", RegexOptions.Compiled);


Leave a Reply

Your email address will not be published. Required fields are marked *