C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Here: The 4 strings we use are all of different Lengths. There are variable strings, constant strings, and literal strings.
Final part: This treats a string literal, contained in quotation marks, as an object in the C# language.
String LiteralC# program that uses Length
using System;
class Program
{
static void Main()
{
// An example string.
string a = "One example";
Console.WriteLine("LENGTH: " + a.Length);
// An empty example string.
string b = "";
Console.WriteLine("LENGTH: " + b.Length);
// A constant string.
const string c = "Three";
Console.WriteLine("LENGTH: " + c.Length);
// A literal string.
Console.WriteLine("LENGTH: " + "Four".Length);
}
}
Output
LENGTH: 11
LENGTH: 0
LENGTH: 5
LENGTH: 4
Also: There are some interesting behaviors with null strings at the class level.
Null StringsC# program that deals with null Length
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);
}
}
}
Output
True
3
4
True
C# program that causes assigned error
class Program
{
static void Main()
{
string value = "test";
value.Length = 10;
}
}
Output
error CS0200: Property or indexer 'string.Length' cannot be assigned to -- it is read only
Tip: It is possible for null characters to be in the middle of C# strings. But this is not a common occurrence in purely managed code.
Quote: 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.
String.Length Property: Microsoft DocsBut: In 2019, this optimization seems to have lost its effectiveness. The JIT compiler inlines Length accesses well.
Opinion: 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.