Text in C# is handled by the string type. It's everywhere โ names, messages, file paths, you name it. Let's look at the basics.
Declaring Strings
A string is a sequence of characters wrapped in double quotes. Strings are reference types, but they behave a lot like you'd expect.
using System;
class Program {
static void Main() {
string name = "Alice";
Console.WriteLine(name);
}
}
Try it Yourself โ
Concatenation
Combine strings with the + operator. Simple and straightforward.
using System;
class Program {
static void Main() {
string first = "Hello";
string second = "World";
string result = first + " " + second;
Console.WriteLine(result);
}
}
Try it Yourself โ
String Interpolation
With interpolation, you embed expressions directly into a string using $"..." and {}. Much cleaner than mashing things together with +.
using System;
class Program {
static void Main() {
string name = "Bob";
int age = 28;
Console.WriteLine($"My name is {name} and I'm {age} years old.");
}
}
Try it Yourself โ
Verbatim Strings
Prefix a string with @ to get a verbatim string. Escape sequences like \n are ignored, and backslashes become literal. Perfect for file paths.
using System;
class Program {
static void Main() {
string path = @"C:\Users\Alice\Documents";
Console.WriteLine(path);
string multi = @"First line
Second line
Third line";
Console.WriteLine(multi);
}
}
Try it Yourself โ
String Equality
Compare strings with ==. In C#, == compares the actual content, not memory references โ unlike some other languages.
using System;
class Program {
static void Main() {
string a = "hello";
string b = "hello";
Console.WriteLine(a == b);
}
}
Try it Yourself โ