Length
Every C# string
object has a Length
property. Every character (no matter its value) is counted in this property. Length
is cached on strings.
Length
gets the character count in the string instance. The string
cannot be null
. It is possible to avoid exceptions with help from Length
.
The string
class
has a Length
property, which returns the number of characters in its internal buffer. We do not need to iterate through every character of a string
.
string
local variable and assign it to a string
literal. We print the length of that data.string
literal is used. The length of an empty string
is always 0.string
that uses the "const
" modifier also has a length—this is the same as a literal.string
literal, contained in quotation marks, as an object in the C# language.using System; // Part 1: an example string. string a = "One example"; Console.WriteLine("LENGTH: " + a.Length); // Part 2: an empty example string. string b = ""; Console.WriteLine("LENGTH: " + b.Length); // Part 3: a constant string. const string c = "Three"; Console.WriteLine("LENGTH: " + c.Length); // Part 4: a literal string. Console.WriteLine("LENGTH: " + "Four".Length);LENGTH: 11 LENGTH: 0 LENGTH: 5 LENGTH: 4
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.
null
strings at the class
level.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); } } }True 3 4 True
We cannot assign to Length
. We can only read the value of Length
and change the string
reference in other ways. This is an important aspect of the C# string
type.
class Program { static void Main() { string value = "test"; value.Length = 10; } }error CS0200: Property or indexer 'string.Length' cannot be assigned to -- it is read only
In earlier versions of the .NET Framework, hoisting the Length
and using a local helped speedup programs.
Length
accesses well.Length
of a string
in a local if you use it many times, but do not expect a huge performance win.The Length
property finds the number of chars in a string
. It is precomputed, so is fast to repeatedly access. It returns its result in constant time.