Strings hold almost every piece of text in C#—user names, API responses, log messages, and file paths. This guide teaches how to create strings, understand immutability, join text with + and interpolation, compare safely, and use essential String methods.
01
String Basics
Text in C#.
02
Immutability
Strings don’t change.
03
Interpolation
Join with $"..."
04
Common Members
Length, [index], Equals.
05
Search & Format
Contains, Format.
06
Method Index
15 full tutorials.
Fundamentals
Definition and Usage
In C#, a string is an instance of the System.String class (you can write the keyword string as a shorthand alias). It represents a sequence of characters used to store and manipulate text. You assign strings to variables, pass them to methods, and print them with Console.WriteLine().
The String class provides dozens of instance methods for comparing text, searching substrings, copying characters, and formatting output. Several helpers such as String.Compare(), String.Concat(), and String.Format() are static and are called on the class name.
💡
Beginner Tip
For strings, == and Equals() both compare character content. When you need case-insensitive or culture-specific rules, pass a StringComparison value: text.Equals("hello", StringComparison.OrdinalIgnoreCase).
Foundation
📝 Syntax
C# offers several ways to create and work with strings:
C#
string literal = "Hello, C#!"; // double-quoted literal
string built = first + " " + last; // + concatenation
string message = $"Hi, {name}!"; // interpolation
int len = text.Length; // Length property
char ch = text[0]; // indexer (zero-based)
bool same = text.Equals("Hi"); // compare content
Creating Strings
String literals ("...") — the most common form; the runtime may intern identical literals for efficiency.
Interpolation ($"...{var}...") — embed variables and expressions directly inside the string.
Verbatim strings (@"...") — backslashes are literal; ideal for file paths and regex patterns.
Raw string literals ("""...""") — multi-line text without escape sequences (C# 11+).
Calling String Methods
Instance methods use dot notation on a string variable; static methods use String:
Work through these five examples from basic string creation to comparison and search patterns used in real C# programs.
📚 Getting Started
Create your first strings and display them in the console.
Example 1 — Create and Display Strings
Assign text to variables and print them—the foundation of every C# program.
C#
using System;
class StringsIntro
{
static void Main()
{
string language = "C#";
int version = 12;
Console.WriteLine("Language: " + language);
Console.WriteLine($"Version: {version}");
Console.WriteLine("Ready to learn strings!");
}
}
📤 Output:
Language: C#
Version: 12
Ready to learn strings!
How It Works
The + operator joins a string and a number; C# converts the number to text automatically. Interpolation with $"Version: {version}" is shorter and easier to read than manual concatenation.
Example 2 — Literals, Escapes, and Verbatim Strings
See how quotes, backslashes, and file paths are written in ordinary and verbatim strings.
She said, "Hello!"
C:\Users\Dev\project
Line 1
Line 2
How It Works
Use \" for a double quote inside a normal string. Prefix with @ for a verbatim string where backslashes are literal—perfect for Windows paths. Use \n in normal strings for newlines. Character literals use single quotes: 'A'.
📈 Practical Patterns
Concatenation, inspection, comparison, and search.
Example 3 — Concatenation with + and String.Concat()
Build messages by joining strings with the + operator, interpolation, or the static Concat() method.
C#
using System;
class StringConcat
{
static void Main()
{
string first = "Hello";
string last = "C#";
string greeting = first + ", " + last + "!";
Console.WriteLine(greeting);
string status = String.Concat("Status: ", "Active");
Console.WriteLine(status);
Console.WriteLine($"{first}, {last}!");
}
}
📤 Output:
Hello, C#!
Status: Active
Hello, C#!
How It Works
Because strings are immutable, every join creates new string objects. The + operator and interpolation are fine for small joins; use StringBuilder when building long text inside loops.
Example 4 — Length, Indexer, and Equals()
Inspect strings and compare content—three essentials every C# beginner should know.
Length: 5
First char: H
Last char: o
Equals(): True
== : True
ReferenceEquals: False
How It Works
The [index] accessor uses zero-based indexing—the first character is at index 0. == and Equals() both return true because the text matches, but ReferenceEquals is false because copy is a separate object in memory.
Example 5 — Split, Join, Search, and Format
Split comma-separated text, rejoin with a new separator, validate paths, and format output—patterns you will use in almost every C# app.
Tag count: 3
Joined: apple | banana | cherry
Has /c-sharp: True
Is .cs file: True
Checked 3 items. URL match: True
How It Works
Split() breaks a string into a string[] (like PHP explode()). string.Join() merges array elements with glue (like PHP implode()). Contains() and EndsWith() handle validation; String.Format() builds readable messages from placeholders.
Applications
🚀 Common Use Cases
User input — read names, emails, and commands from the console or web forms.
Validation — check file extensions with EndsWith(), search paths with Contains().
Display output — build messages with interpolation, +, or String.Format().
Password checks — compare typed passwords with Equals() and an explicit StringComparison.
Sorting text — order names or labels with Compare() or CompareTo().
CSV and lists — split comma-separated values with Split(), join tags with string.Join().
APIs and files — pass strings to JSON serializers, loggers, and file I/O methods.
🧠 How C# Strings Work
1
You create a string
Write a literal "Hello", use interpolation $"Hi {name}", or read input from the console or an API.
Create
2
C# stores immutable text
The string object holds a fixed character sequence. Any “change” produces a new string.
Immutable
3
Methods read or transform
Call Length, [index], Equals(), Contains(), and dozens more on the object.
Methods
=
💬
Result or output
Print to the console, return from a method, serialize to JSON, or pass to the next step in your app.
Important
📝 Notes
Strings are immutable—assign the return value of methods like ToUpper() and Trim().
For strings, == compares content; use ReferenceEquals() only when you need same-object identity.
Guard against null: calling instance methods on null throws NullReferenceException. Use string.IsNullOrEmpty(text) first.
Length counts UTF-16 code units; emoji and some symbols may use two units.
Prefer StringBuilder over repeated + in loops for better performance.
String methods use dot notation—text.Length, text.Contains("x")—not global functions like in PHP.
Wrap Up
Conclusion
Strings are the backbone of C# text handling. Master literals, immutability, interpolation, and a handful of essential members like Length, the indexer, Equals(), and Contains()—and you are ready to write real programs that read, compare, and display text.
Practice the examples on this page, then explore the full String Methods index for in-depth tutorials on every method in our series.
Use interpolation ($"...") for readable formatted output
Compare with explicit StringComparison when case rules matter
Use Contains() and EndsWith() for simple validation
Assign results from Trim(), ToUpper(), etc.
Use StringBuilder when concatenating in loops
❌ Don’t
Call instance methods on a possibly null string reference
Assume Length equals visible character count for all Unicode
Build long strings with + inside tight loops
Forget that strings never change—methods return new objects
Rely on default culture for security-sensitive comparisons—prefer Ordinal
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about C# strings
Use these points as you write your first C# programs.
5
Core concepts
💬01
String Type
Text is an object.
Basics
🔒02
Immutable
Methods return new text.
Concept
🔗03
Interpolation
Embed values with $.
Syntax
🛠04
Length & [index]
Inspect characters.
Members
📚05
Method Index
15 full tutorials.
Next step
❓ Frequently Asked Questions
A string is an instance of System.String (alias string) that stores a sequence of characters—names, messages, file paths, JSON, and more. You create strings with double-quoted literals like "Hello", string interpolation ($"Hi {name}"), or verbatim strings (@"C:\path"). String is one of the most used types in C# programs.
Strings are immutable. Once created, their character sequence cannot change. Methods like ToUpper(), Concat(), and Format() return new string objects. For frequent edits in loops, use StringBuilder instead of repeated + concatenation.
For strings, == compares character content (value equality), just like Equals(). Both check whether the text matches. Use String.Equals(a, b, StringComparison.OrdinalIgnoreCase) when you need explicit comparison rules such as case-insensitive or culture-aware matching.
Use the + operator: string full = first + " " + last;. You can also call String.Concat(first, last) or use interpolation: $"{first} {last}". For many pieces in a loop, StringBuilder is faster than repeated + concatenation.
Length is a property (not a method) that returns the number of char code units in the string—the same index range used by the [index] accessor. It counts UTF-16 code units; some Unicode characters such as emoji may use two code units.
Learn how to create strings and print them with Console.WriteLine, then practice Length, the [0] indexer, Contains(), and Equals(). When you are comfortable with the basics on this page, open the String Methods index for full guides on every method in our series.
Did you know?
C# string literals like "Hello" may be interned by the runtime. When you write string a = "Hi"; string b = "Hi";, both variables can refer to the same interned object—so ReferenceEquals(a, b) may be true for identical literals, even though the strings are still immutable and compared by value with ==.