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.
string s = "hello"; Console.WriteLine(s.Length); // 5
Try it
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.
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
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é"(aneplus a combining accent) looks like four letters but hasLength5. The emoji hasLength2, and the family sequence of three emoji joined by zero-width joiners hasLength8, yet appears as one symbol. - Count the right thing. For code points use
EnumerateRunes(); for what a reader sees useStringInfo.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, ors[^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 useCount. A string behaves like an array here, which is why LINQ'sCount()on a string is rarely needed (and is O(n)). - Compile-time constants.
"abc".Lengthis evaluated at runtime, but the JIT folds it for literals.