Home
C#
String IsUpper, IsLower
Updated Jun 6, 2021
Dot Net Perls
IsUpper, IsLower. Some C# strings contain only lowercase letters. These strings do not need to be lowercased. By testing first, we can avoid excess work.
C# method notes. We must implement our own custom IsLower and IsUpper methods. We add them with extension methods in a static class.
static
Example. This program contains a static class of extension methods. The IsUpper and IsLower methods are public static methods written with the extension method syntax.
Detail Here we test the IsUpper and IsLower extension methods on various string literals.
String Literal
Info A string is defined as uppercase if it contains no lowercase letters. It is lowercase if it contains no uppercase letters.
Note This is not the same as a string containing only uppercase or only lowercase letters.
Tip You could change the implementation of these methods to fit this requirement if necessary.
using System; static class Extensions { public static bool IsUpper(this string value) { // Consider string to be uppercase if it has no lowercase letters. for (int i = 0; i < value.Length; i++) { if (char.IsLower(value[i])) { return false; } } return true; } public static bool IsLower(this string value) { // Consider string to be lowercase if it has no uppercase letters. for (int i = 0; i < value.Length; i++) { if (char.IsUpper(value[i])) { return false; } } return true; } } class Program { static void Main() { Console.WriteLine("test".IsLower()); // True Console.WriteLine("test".IsUpper()); Console.WriteLine("Test".IsLower()); Console.WriteLine("Test".IsUpper()); Console.WriteLine("TEST3".IsLower()); Console.WriteLine("TEST3".IsUpper()); // True } }
True False False False False True
Syntax. We used extension method syntax. In large projects, using a static class of extension methods is often simpler than trying to remember different static methods in different classes.
Extension
We implemented IsUpper and IsLower for strings. These methods perform a fast scanning of the source string, rather than requiring another allocation and conversion.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 6, 2021 (rewrite).
Home
Changes
© 2007-2025 Sam Allen