The string Type
A string is a piece of text, like a name tag or a sentence written on a ribbon. Once made, a string cannot be edited in place, so changing it really creates a new string.
In this page:
Syntax
string variableName = "text";
string joined = first + " " + second;
string interpolated = $"Hello, {variableName}!";
The string Type
A string is an immutable sequence of characters, written with double quotes. Strings support concatenation with +, interpolation with $"...", and a rich set of built-in methods.
Because strings are immutable, every "modification" actually creates a new string.
Note:
Prefer string interpolation (
$"Hello {name}") over concatenation for readability.Example: The string Type
using System;
class Program
{
static void Main(string[] args)
{
string first = "Ada";
string last = "Lovelace";
string full = first + " " + last;
string greeting = $"Hello, {full}!";
Console.WriteLine(full);
Console.WriteLine(greeting);
Console.WriteLine(full.Length);
Console.WriteLine(full.ToUpper());
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Comparing strings with the wrong case and expecting equality, since
"a" == "A"is false. - Expecting
s.ToUpper()to changes, when strings are immutable and the method returns a new string. - Building a long string with
+in a loop, which creates many temporary strings; useStringBuilder.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: