An example. 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.
Part 1 Here we have a string local variable and assign it to a string literal. We print the length of that data.
Part 2 An empty string literal is used. The length of an empty string is always 0.
Part 3 A string that uses the "const" modifier also has a length—this is the same as a literal.
Part 4 This code treats a 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
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.
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
Error, cannot be assigned. 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
Performance, hoisting length. In earlier versions of the .NET Framework, hoisting the Length and using a local helped speedup programs.
But In 2019, this optimization seems to have lost its effectiveness. The JIT compiler inlines Length accesses well.
Detail It is probably worth storing the 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 25, 2023 (simplify).