TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# String Length Property

This C# article shows how to use the Length property on the string type.

String length. Every string object has a Length property.

Every character (no matter its value) is counted in this property. Length is cached on strings. It is possible to avoid exceptions with help from Length.

Exception

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

Null

Example. 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.

C# program that uses Length

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

IsNullOrEmpty

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

Null Strings

C# program that deals with null Length

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

IL: callvirt

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


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf