Strings
Declaration and Initialization
string is an alias for System.String and is an immutable reference type. Once created, the content of a string cannot be changed.
Example
string name = "Hello";
string empty = "";
string nullStr = null;
string fromChar = new string('A', 5);
Console.WriteLine(name);
Console.WriteLine(fromChar);
Hello
AAAAA
String Immutability
Once a string object is created, its character sequence cannot be modified. All "modification" operations return a new string, leaving the original unchanged.
Example
string a = "Hello";
string b = a;
a = a + " World";
Console.WriteLine(a);
Console.WriteLine(b);
Hello World
Hello
Tip: b still points to the original "Hello", while a + " World" produces an entirely new string object.
String Concatenation
Use the + operator, String.Concat(), or String.Join() to combine multiple strings.
Example
string s1 = "Hello" + " " + "World";
string s2 = String.Concat("A", "B", "C");
string s3 = String.Join(", ", new string[] { "apple", "banana", "cherry" });
Console.WriteLine(s1);
Console.WriteLine(s2);
Console.WriteLine(s3);
Hello World
ABC
apple, banana, cherry
String Interpolation
Use $"" interpolation syntax or String.Format() to embed variables within a string.
Example
string name = "Alice";
int age = 25;
string s1 = $"My name is {name}, age {age}.";
string s2 = String.Format("My name is {0}, age {1}.", name, age);
string s3 = $"2 + 3 = {2 + 3}";
Console.WriteLine(s1);
Console.WriteLine(s2);
Console.WriteLine(s3);
My name is Alice, age 25.
My name is Alice, age 25.
2 + 3 = 5
Tip: You can write any C# expression inside interpolation braces {}, and add format specifiers such as {value:F2}.
String Comparison
The == operator performs value equality comparison on strings (not reference comparison). Equals(), Compare(), and CompareOrdinal() offer more fine-grained control.
Example
string a = "hello";
string b = "hello";
string c = "HELLO";
Console.WriteLine(a == b);
Console.WriteLine(a.Equals(b));
Console.WriteLine(String.Compare(a, c, StringComparison.OrdinalIgnoreCase) == 0);
Console.WriteLine(String.CompareOrdinal(a, c) > 0);
True
True
True
True
Warning: String == compares values, not references, which differs from the behavior of most other reference types.
Common Methods: Length / Substring / Replace / Split
These are the most frequently used methods for everyday string operations.
Example
string s = "Hello, World!";
Console.WriteLine(s.Length);
Console.WriteLine(s.Substring(7));
Console.WriteLine(s.Substring(0, 5));
Console.WriteLine(s.Replace("World", "C#"));
string parts = "a,b,c";
foreach (string p in parts.Split(','))
{
Console.WriteLine(p);
}
13
World!
Hello
Hello, C#!
a
b
c
Common Methods: Trim / Contains / Index
Trim() removes leading and trailing whitespace, Contains() checks for a substring, and IndexOf() / LastIndexOf() find positions.
Example
string s = " Hello World ";
Console.WriteLine($"[{s.Trim()}]");
Console.WriteLine(s.Contains("World"));
Console.WriteLine(s.IndexOf("World"));
Console.WriteLine(s.LastIndexOf("o"));
[Hello World]
True
8
7
Common Methods: Case / StartsWith / EndsWith / Pad / Remove / Insert
More practical string processing methods.
Example
string s = "Hello";
Console.WriteLine(s.ToUpper());
Console.WriteLine(s.ToLower());
Console.WriteLine(s.StartsWith("Hel"));
Console.WriteLine(s.EndsWith("llo"));
Console.WriteLine("5".PadLeft(3, '0'));
Console.WriteLine("5".PadRight(3, '0'));
string r = "Hello World".Remove(5);
Console.WriteLine(r);
string ins = "H World".Insert(1, "ello");
Console.WriteLine(ins);
HELLO
hello
True
True
005
500
Hello
Hello World
Verbatim Strings and Raw Strings
Verbatim strings @"" do not process escape sequences, making them ideal for file paths. C# 11 introduced raw string literals """ for multi-line content that requires no escaping.
Example
string path = @"C:\Users\Doc\file.txt";
string json = """
{
"name": "Alice",
"age": 25
}
""";
Console.WriteLine(path);
Console.WriteLine(json.Trim());
C:\Users\Doc\file.txt
{
"name": "Alice",
"age": 25
}
Tip: In verbatim strings, a double quote is written as "". Raw string literals start and end with at least three quotation marks.
StringBuilder Overview
When concatenating strings repeatedly in a loop, string creates a new object each time, which hurts performance. StringBuilder operates on an internal buffer and produces the final string only once.
Example
using System.Text;
var sb = new StringBuilder();
for (int i = 0; i < 5; i++)
{
sb.Append(i);
sb.Append(" ");
}
Console.WriteLine(sb.ToString().Trim());
0 1 2 3 4
Tip: Prefer StringBuilder when concatenating many strings in a loop to significantly reduce memory allocations.
Character Encoding
C# strings use UTF-16 encoding. A char occupies 2 bytes (one UTF-16 code unit).
Example
char ch = 'A';
Console.WriteLine(ch);
Console.WriteLine((int)ch);
Console.WriteLine(sizeof(char));
A
65
2
❓ FAQ
== compare references or values?== operator for strings has been overloaded to perform content equality comparison.string is immutable, each concatenation creates a new object. StringBuilder modifies a buffer and only generates the final string at the end.@"" and a regular string?\n, \t); backslashes are preserved literally, making them ideal for file paths and regular expressions.ArgumentOutOfRangeException. You should check the length before calling it.📖 Summary
stringis an immutable reference type and an alias forSystem.String- Concatenation:
+,String.Concat(),String.Join() - Interpolation:
$""andString.Format() - Comparison:
==compares values;Equals()andCompare()provide more options - Common methods:
Length,Substring,Replace,Split,Trim,Contains,IndexOf,ToUpper,ToLower,StartsWith,EndsWith,PadLeft,PadRight,Remove,Insert - Verbatim strings
@""disable escaping; raw string literals"""support multi-line content StringBuilderis ideal for repeated concatenation in loops, improving performance- Strings use UTF-16 encoding, and
charoccupies 2 bytes
📝 Exercises
- Declare a string variable and use interpolation to output
"My name is XXX, and I am XX years old." - Write a program that takes a comma-separated string
"a,b,c,d", splits it withSplit, and prints each element on a separate line - Trim the string
" Hello World ", then replace"World"with"C#"and output the result - Use
StringBuilderto concatenate the numbers 1 through 100, one per line, and output the final string - Define a Windows file path
C:\Program Files\MyApp\config.jsonusing a verbatim string and output it



