There are times when we need to convert the letters of a string to either uppercase or lowercase. Fortunately, C# offers us two methods for this: ToUpper() and ToLower(). As imagined, the first one will convert all letters of a string into capital letters, while the latter will do the opposite, by converting them to small ones.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; namespace HelloWorld { class Program { private static void Main(string[] args) { string text = "All Kind OF LeTTeRs"; Console.WriteLine(text); Console.WriteLine(text.ToLower()); Console.WriteLine(text.ToUpper()); Console.Read(); } } } |
The output of the above program will look like this:
One instance where these methods could be useful would be when taking input from them, such as passwords, and validating them:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; namespace BunaLume { class Program { private static void Main(string[] args) { string pass = "PaSSwoRD"; Console.WriteLine(pass == "password"); Console.WriteLine(pass.ToLower() == "password"); Console.Read(); } } } |
In the first check, we will get a False result. This is because the difference in casing will make the two string to be considered as different. In the second, by converting it to lower case and comparing it to a lowercase string literal, the result will be True.
Tags: lowercase, string operations, string variable type, uppercase