Skip to content
Tutorials Center
My learning

Topics

C# Reference · Strings and Text

C# String.Length property

Reference for String.Length in C#: it counts UTF-16 code units, not visible characters. Emoji, accents, surrogate pairs, runes and text elements explained.

String.Length returns the number of UTF-16 code units (char values) in a string. Reading it is O(1): the length is stored with the string. For ordinary English text, one char is one letter, so Length matches what you expect.

For other text it can differ from what a person counts. Characters outside the Basic Multilingual Plane, including most emoji, use two chars (a surrogate pair), and some visible symbols are built from several code points. Know which of those you want to count.

C#
string s = "hello";
Console.WriteLine(s.Length);   // 5

Try it

C# Length of different texts

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Using Length safely

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public int Length { get; }
Name Description
Length Number of char (UTF-16) units. No parameters; read-only.

Returns: an int from 0 upward. An empty string has Length == 0.

Errors: throws NullReferenceException when the string is null. Use s?.Length or string.IsNullOrEmpty(s) if null is possible.

Usage notes

  • Not the number of visible characters. In the first example, "café" (an e plus a combining accent) looks like four letters but has Length 5. The emoji has Length 2, and the family sequence of three emoji joined by zero-width joiners has Length 8, yet appears as one symbol.
  • Count the right thing. For code points use EnumerateRunes(); for what a reader sees use StringInfo.LengthInTextElements. See Rune and Text elements.
  • Bytes are different again. The size when saved as UTF-8 comes from Encoding.UTF8.GetByteCount(s). A database column limit or a network protocol usually counts bytes or characters in its own way.
  • Last index. The final character is at Length - 1, or s[^1]. An empty string has no valid index, so check before reading.
  • Validation. Length limits on user input should state what they count. Counting text elements is fairer to users; counting UTF-16 units is simpler and cheap.
  • Arrays use Length, lists use Count. A string behaves like an array here, which is why LINQ's Count() on a string is rarely needed (and is O(n)).
  • Compile-time constants. "abc".Length is evaluated at runtime, but the JIT folds it for literals.