Char.ToLower
, ToUpper
ToLower
converts only uppercase letters. It changes uppercase letters to lowercase letters. It leaves all other characters unchanged.
ToLower
and ToUpper
are ideal for character conversions. These methods are included in .NET, and act on all characters in a reliable way.
Consider the uppercase letter "A." This has the ASCII value 65. When lowercased, it equals "a" which is ASCII 97.
A (65) a (97)
Here we see char.ToLower
. This converts uppercase characters to lowercase characters, while not changing characters that are already lowercase or digits.
char.ToLower
show how this static
method is used. And the comments show the values returned.char.ToUpper
show how this method is used. The result from each call is shown.Console.WriteLine
.using System; char c1 = 'a'; // Lowercase a char c2 = 'b'; // Lowercase b char c3 = 'C'; // Uppercase C char c4 = '3'; // Digit 3 // Part 1: use char.ToLower. char lower1 = char.ToLower(c1); // a char lower2 = char.ToLower(c2); // b char lower3 = char.ToLower(c3); // c [changed] char lower4 = char.ToLower(c4); // 3 // Part 2: use char.ToUpper. char upper1 = char.ToUpper(c1); // A [changed] char upper2 = char.ToUpper(c2); // B [changed] char upper3 = char.ToUpper(c3); // C char upper4 = char.ToUpper(c4); // 3 // Part 3: write results. Console.WriteLine(c1 + "," + c2 + "," + c3 + "," + c4); Console.WriteLine(lower1 + "," + lower2 + "," + lower3 + "," + lower4); Console.WriteLine(upper1 + "," + upper2 + "," + upper3 + "," + upper4);a,b,C,3 a,b,c,3 A,B,C,3
IsLower
, IsUpper
Sometimes we need to first test if a character is lowercase or uppercase. The char.IsLower
and IsUpper
methods in C# help here.
using System; string test = "AxZ"; // Call IsLower and IsUpper in loop. foreach (char value in test) { if (char.IsLower(value)) { Console.WriteLine("LOWER"); } else if (char.IsUpper(value)) { Console.WriteLine("UPPER"); } }UPPER LOWER UPPER
InvariantCulture
These 2 methods use the CultureInfo.InvariantCulture
parameter internally. The letters are lowercased and uppercased the same in all globalization settings.
Finally, the char.ToLower
and char.ToUpper
methods have worse performance than a custom method that tests ASCII values. It can be worthwhile to use a custom method.
Programs that handle characters can benefit from char.ToLower
and char.ToUpper
. These are simple but useful methods, ready to call with no extra code.