Lire en anglais Modifier

Partager via


String.Length Property

Definition

Gets the number of characters in the current String object.

C#
public int Length { get; }

Property Value

The number of characters in the current string.

Examples

The following example demonstrates the Length property.

C#
string str = "abcdefg";
Console.WriteLine("1) The length of '{0}' is {1}", str, str.Length);
Console.WriteLine("2) The length of '{0}' is {1}", "xyz", "xyz".Length);

int length = str.Length;
Console.WriteLine("3) The length of '{0}' is {1}", str, length);

// This example displays the following output:
//    1) The length of 'abcdefg' is 7
//    2) The length of 'xyz' is 3
//    3) The length of 'abcdefg' is 7

Remarks

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. Use the System.Globalization.StringInfo class to work with each Unicode character instead of each Char.

In some languages, such as C and C++, a null character indicates the end of a string. In .NET, a null character can be embedded in a string. When a string includes one or more null characters, they are included in the length of the total string. For example, in the following string, the substrings "abc" and "def" are separated by a null character. The Length property returns 7, which indicates that it includes the six alphabetic characters as well as the null character.

C#
string characters = "abc\u0000def";
Console.WriteLine(characters.Length); // Displays 7

Applies to

See also