C# offers a rich set of features for working with strings, and formatting literal strings is a crucial part of creating clean, readable, and maintainable code. Literal strings, also known as string literals, are sequences of characters enclosed in double quotes. While they are straightforward, understanding how to format and manipulate them effectively can make your code more robust and expressive.
1. Types of String Literals in C#
C# supports two types of string literals:
Regular String Literals
Enclosed in double quotes, they support escape sequences (e.g., \n, \t).
Console.WriteLine("Hello\nWorld!");
Console.WriteLine("Hello\tWorld!");
//Output
//Hello
//World!
//Hello World!
Verbatim String Literals
Prefixed with @, they ignore escape sequences and support multi-line text.
string verbatim = @"Hello
World";
// Output: Hello
//World
2. Escape Sequences in Regular String Literals
Escape sequences provide a way to include special characters in strings. Some common ones include:
- \n – Newline
- \t – Tab
- \" – Double quote
- \\ – Backslash
string escaped = "C:\\Program Files\\MyApp";
Console.WriteLine(escaped);
// Output: C:\Program Files\MyApp
3. Formatting Verbatim Strings
Verbatim strings make it easy to work with file paths, multi-line text, or any string that includes special characters
string filePath = @"C:\Program Files\MyApp";
string multiLine = @"This is a
multi-line string.";
Note. Verbatim strings can include double quotes by doubling them ("").
string quoteExample = @"She said, ""Hello!""";
4. Interpolated Strings
String interpolation in C# is a powerful feature for embedding expressions within string literals. Prefixed with $, interpolated strings can include placeholders in curly braces {}.
int age = 30;
string name = "John";
string greeting = $"Hello, {name}. You are {age} years old.";
Console.WriteLine(greeting);
// Output: Hello, John. You are 30 years old.
Note. Combining Verbatim and Interpolation: Use $@" to combine both features.
string directory = "Documents";
string filePath = $@"C:\Users\John\{directory}";
5. Composite Formatting with string.Format
An older but still relevant way to format strings is using string.Format.
string formatExample = string.Format("The result is {0:F2}", 123.456);
Console.WriteLine(formatExample);
// Output: The result is 123.46
6. Unicode escape characters
You can also add encoded characters in literal strings using the \u escape sequence, then a four-character code representing some character in Unicode (UTF-16).
// Kon'nichiwa World
Console.WriteLine("\u3053\u3093\u306B\u3061\u306F World!");
Conclusion
Understanding and effectively using string formatting in C# is a key skill for writing clean and maintainable code. From basic escape sequences to advanced interpolated and raw strings, C# provides powerful tools to handle literal strings for any scenario.