C# String Length

Length property

Every string object has a length. Every character—no matter what it is—is counted in the Length property. Length is cached on the string type. It is possible to avoid exceptions while accessing Length.

Exception

Note:Length returns the character count in the string instance.
The string cannot be null.

Null

Example

Note

First, string is a reference type that has a Length property, which returns the number of characters in its internal buffer. You cannot iterate through every character of a string, checking for '\0'.

Here:The four strings we use are all of different Lengths. There are variable strings, constant strings, and literal strings.

Program that uses Length: C#

using System;

class Program
{
    static void Main()
    {
	// An example string
	string a = "One example";
	Console.WriteLine(a.Length);

	// An empty example string
	string b = "";
	Console.WriteLine(b.Length);

	// A constant string
	const string c = "Three";
	Console.WriteLine(c.Length);

	// A literal string
	Console.WriteLine("Four".Length);
    }
}

Output

11
0
5
4

The final part above shows how to treat a string literal, contained in quotation marks, as an object in the C# language. This is a powerful feature and can help make your code clearer by avoiding magic constants.

String Literal

Null

Null keyword

We must first test for null strings before calling the Length property. This is because you cannot access members on null reference types. The IsNullOrEmpty method is ideal for this.

string.IsNullOrEmpty

Also:There are some interesting behaviors with null strings at the class level.

Null Strings
Program that deals with null Length: C#

using System;

class Program
{
    static void Main()
    {
	F(null);
	F("cat");
	F("book");
	F("");
    }

    static void F(string a)
    {
	if (string.IsNullOrEmpty(a))
	{
	    // String is null or empty
	    Console.WriteLine(true);
	}
	else
	{
	    // Print length of string
	    Console.WriteLine(a.Length);
	}
    }
}

Output

True
3
4
True

Research

Note

Microsoft's article on this subject has some interesting details on string Length. It tells you that the Length is not derived from the number of chars, but not symbolic Unicode chars.

It is possible for null characters to be in the middle of C# strings. But this is not a common occurrence in purely managed code. And this is not something that most code must handle.

The Length property returns the number of Char objects in this instance, not the number of Unicode characters. The reason is that a Unicode character might be represented by more than one Char.

String.Length Property: MSDN

Cache

Cache

We next explore the idea of caching string Length integers. If you are using a string thousands of times and accessing the Length property each time, this may be incurring some overhead.

Then:When accessing string Length, the callvirt MSIL instruction will be generated. Next the value will be retrieved.

callvirt InstructionIL

Benchmark. I experimented with storing, or hoisting, the string Length outside of a tight loop. My result was that avoiding recalculating Length can have a performance benefit. Please see the benchmark result chart below.

Input data in benchmark: C#

// Example string
string one = "one" + 1.ToString();

// Cached length
int cl = one.Length;

Code benchmarked in loops, 1000000000 iterations: C#

// A
int len = one.Length;
if (one[len - 1] == 'x')
{
}

// B
if (one[cl - 1] == 'x')
{
}

Results

Access Length repeatedly: 1305 ms
Hoist Length out of loop:  646 ms [faster]

Summary

Property

The string type in C# provides the Length property, which is useful for finding the number of chars in a string. We saw an example of the Length property being used on four different strings, as well as with null and empty strings.

Finally:We found that hoisting the string Length out of a tight loop can improve performance.

Property

C#: String