C# String IsUpper and IsLower Methods

Lowercase and uppercase words

You want to quickly test if a string instance contains no lowercase letters (is uppercase), or if it contains no uppercase letters (is lowercase). The .NET Framework does not currently provide string type IsLower and IsUpper methods, but you can add this with extension methods in a static class.

Example

In this first part, we demonstrate a program text that contains a static class of extension methods. The IsUpper and IsLower methods are public static parameterful methods written with the extension method syntax. The Program class introduces the Main entry point, where we test the IsUpper and IsLower extension methods on various string literals.

This C# example program tests strings to see if they are uppercase or lowercase.

Program that implements string IsUpper and IsLower [C#]

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
    }
}

Output

True
False
False
False
False
True

IsUpper and IsLower logic. The example shows the logic of the IsUpper and IsLower methods. A string is defined as uppercase if it contains no lowercase letters; it is defined as lowercase if it contains no uppercase letters. This is not the same as a string containing only uppercase or only lowercase letters. You could change the implementation to fit this requirement if necessary.

Extension methods

Programming tip

This article provides an example of the extension method syntax in the C# language. In large projects, using a static class of extension methods is often simpler than trying to remember different static methods in different classes. You can read more details on extension methods on this site.

Extension Method

Summary

The C# programming language

In this short tutorial, we implemented the IsUpper and IsLower extension methods on the string type in the C# language. These methods perform a fast scanning of the source string, rather than requiring another allocation and conversion. The IsUpper and IsLower methods can provide a clearer method call syntax as well as better performance for this test.

String Type
.NET