Strings in C# are used to store and work with text. A string can contain letters, numbers, symbols, spaces, or even an empty value. In C#, the string type is one of the most commonly used types because almost every application needs to handle names, messages, file paths, user input, JSON, logs, labels, commands, and other text data.
C# strings are powerful because they come with many built-in methods for searching, replacing, splitting, joining, comparing, trimming, and formatting text. At the same time, strings have an important behavior that every learner must understand: they are immutable. That means once a string object is created, its content cannot be changed directly.
What Is a String in C#?
A string is a sequence of characters. In C#, string values are written inside double quotes.
string name = "Alex";
string message = "Welcome to C# programming";
The keyword string is an alias for System.String. Both refer to the same type, but string is the common style used in regular C# code.
A string stores text, but it is still a full object with properties and methods.
Creating Strings in C#
The simplest way to create a string is by assigning a string literal.
string city = "Mumbai";
You can also create strings using constructors, character arrays, formatting, interpolation, joining, or results returned from methods. In most beginner programs, string literals and interpolation are enough.
String Length
The Length property gives the number of characters in a string.
string language = "CSharp";
Console.WriteLine(language.Length);
The output is 6 because the string contains six characters.
Accessing Characters in a String
You can access individual characters in a string using index positions. Indexing starts from 0.
string text = "Code";
Console.WriteLine(text[0]); // C
Console.WriteLine(text[1]); // o
If you try to access an index outside the valid range, the program throws an exception. Always make sure the index is valid before accessing a character.
Strings Are Immutable
String immutability means that the content of an existing string object cannot be changed directly. Operations that look like modifications usually create a new string.
string word = "Hello";
word = word + " World";
The variable word now refers to a new string. The original string object was not edited in place. This behavior matters when many string changes are performed repeatedly.
String Concatenation
Concatenation means joining strings together. The + operator can be used for this.
string firstName = "Aman";
string lastName = "Verma";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName);
For simple cases, concatenation is fine. For more readable formatting, string interpolation is often preferred.
Common String Methods in C#
| Method | Purpose |
|---|---|
ToUpper() | Converts text to uppercase. |
ToLower() | Converts text to lowercase. |
Trim() | Removes leading and trailing whitespace. |
Contains() | Checks whether a substring exists. |
StartsWith() | Checks whether text starts with a value. |
EndsWith() | Checks whether text ends with a value. |
Replace() | Returns a new string with replacements. |
Substring() | Extracts part of a string. |
Split() | Splits a string into parts. |
string input = " Hello C# ";
Console.WriteLine(input.Trim());
Console.WriteLine(input.ToUpper());
Console.WriteLine(input.Contains("C#"));
These methods return results. Because strings are immutable, methods like Trim() and Replace() do not modify the original string directly.
Comparing Strings
Strings can be compared using ==, Equals(), or comparison methods depending on the requirement.
string a = "CSharp";
string b = "CSharp";
Console.WriteLine(a == b);
This prints true because the text values are equal. For case-insensitive comparison, use an overload with StringComparison.
string x = "hello";
string y = "HELLO";
bool same = string.Equals(x, y, StringComparison.OrdinalIgnoreCase);
Using explicit comparison options is better than relying on unclear default behavior in important application logic.
Null and Empty Strings
A string variable can be null, empty, or contain whitespace. These are different cases.
| Value | Meaning |
|---|---|
null | No string object is assigned. |
"" | An empty string with zero characters. |
" " | A string containing spaces. |
string? name = null;
string empty = "";
string spaces = " ";
C# provides helper methods for checking these cases.
string.IsNullOrEmpty(name);
string.IsNullOrWhiteSpace(spaces);
Verbatim Strings
A verbatim string starts with @. It is useful for file paths and multi-line strings because backslashes are treated more naturally.
string path = @"C:\Users\Admin\Documents";
Without @, backslashes may need escaping. Verbatim strings make path-heavy code easier to read.
String Interpolation
String interpolation allows variables and expressions to be inserted directly into a string using $ and braces.
string name = "Riya";
int age = 22;
Console.WriteLine($"{name} is {age} years old");
This is often cleaner than joining many strings with the + operator.
Using StringBuilder
When you need to build or modify text repeatedly, StringBuilder can be more efficient than repeated string concatenation.
using System.Text;
StringBuilder builder = new StringBuilder();
builder.Append("Hello");
builder.Append(" ");
builder.Append("C#");
string result = builder.ToString();
StringBuilder is useful when working with loops, generated reports, logs, large text blocks, or repeated append operations.
Escape Sequences in Strings
Escape sequences are special character combinations used inside strings. They start with a backslash and represent characters that are hard to type directly.
| Escape Sequence | Meaning |
|---|---|
\n | New line |
\t | Tab space |
\" | Double quote inside string |
\\ | Backslash |
string text = "Line one\nLine two";
Console.WriteLine(text);
Raw String Literals
Modern C# supports raw string literals, which are useful for writing text that contains quotes, JSON, paths, or multi-line content without heavy escaping.
string json = """
{
"name": "Alex",
"language": "C#"
}
""";
Raw string literals are especially helpful when writing sample JSON, SQL, markup, or template-like text inside C# code.
Splitting and Joining Strings
Split() breaks one string into multiple parts. string.Join() combines multiple values into one string.
string csv = "red,green,blue";
string[] colors = csv.Split(',');
string joined = string.Join(" | ", colors);
Console.WriteLine(joined);
These methods are common when working with user input, CSV-like text, tags, command arguments, and simple file data.
Culture and String Comparison
String comparison can depend on culture, language rules, or ordinal binary comparison. For identifiers, keys, commands, and internal values, StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase is often preferred because it is predictable. For user-facing text, culture-aware comparison may be more appropriate.
bool sameCommand = string.Equals(
input,
"start",
StringComparison.OrdinalIgnoreCase);
Choosing the comparison rule explicitly makes the program easier to reason about and avoids subtle bugs.
Formatting Strings
C# supports several ways to format strings. String interpolation is usually the cleanest for everyday code, but string.Format() and formatting specifiers are also useful when you need control over numbers, dates, alignment, or display style.
decimal price = 1250.5m;
Console.WriteLine($"Price: {price:C}");
Format specifiers help convert values into readable text without manually building every part of the output.
Strings in Loops
Because strings are immutable, repeatedly adding text inside a large loop can create many temporary strings. For small loops this is fine, but for heavy text generation, StringBuilder is usually a better choice.
StringBuilder report = new StringBuilder();
for (int i = 1; i <= 5; i++)
{
report.AppendLine($"Item {i}");
}
This pattern is common in report generation, log building, file export, and dynamic message creation.
Cleaning User Input
User input often contains extra spaces, inconsistent casing, or empty values. String methods help clean and validate this data before using it in business logic.
string? input = " Admin ";
string cleaned = input.Trim().ToLower();
Console.WriteLine(cleaned);
In real applications, always consider null checks and validation before trusting user-provided text.
String Equality and Case Sensitivity
By default, many string comparisons are case-sensitive. That means "admin" and "Admin" are different values. For login names, commands, tags, and search-like features, you may need case-insensitive comparison.
string role = "Admin";
bool isAdmin = role.Equals("admin", StringComparison.OrdinalIgnoreCase);
Unicode and Strings
C# strings are based on Unicode text, so they can represent characters from many languages and symbol sets. This matters for applications that handle international names, multilingual content, emojis, or user-generated text. Text processing is often more complicated than simple English examples suggest, so avoid assuming every visible character behaves like one basic ASCII letter.
Basic String Validation Pattern
A common pattern is to reject missing or whitespace-only input before using it.
if (string.IsNullOrWhiteSpace(userName))
{
Console.WriteLine("Username is required");
}
This is safer than only checking for an empty string because it also handles null and values that contain only spaces.
Substring Safety
Substring() is useful, but it requires valid start positions and lengths. If the requested range is outside the string, C# throws an exception. Before extracting text from user input, file data, or external values, check the string length or use safer parsing logic.
Common Mistakes with Strings in C#
- Forgetting that strings are immutable.
- Using repeated concatenation inside large loops.
- Confusing
null, empty string, and whitespace. - Using case-sensitive comparisons when case-insensitive comparison is needed.
- Accessing a string index without checking length.
- Forgetting to assign the result of string methods like
Trim()orReplace().
Is string a value type or reference type in C#?
string is a reference type, but it is immutable and has special language support, so it feels simpler than many other reference types.
Can a string be changed in C#?
An existing string object cannot be changed directly. Operations that appear to modify a string return a new string.
When should I use StringBuilder?
Use StringBuilder when you need to build text through many repeated modifications, especially inside loops or large text-generation logic.
Best Practices for Strings in C#
- Use string interpolation for readable formatted output.
- Use
StringComparisonwhen comparison rules matter. - Use
IsNullOrEmpty()orIsNullOrWhiteSpace()for validation. - Remember that string methods return new strings.
- Use
StringBuilderfor repeated string modification. - Use meaningful variable names for text values.
Strings in C# are easy to start with but important to understand deeply. Their immutability, built-in methods, comparison behavior, null handling, and formatting features appear constantly in real-world C# applications.