C# string
last modified November 6, 2026
In this article we show how to work with strings in C#.
A string is a sequence of characters. In C#, a string is a
sequence of UTF-16 code units of the System.String type; the
string keyword is its alias. A string written directly in source
code is a string literal.
Strings are immutable: methods such as Replace or
ToUpper return a new string and leave the original unchanged.
For building strings piece by piece, .NET has the mutable
System.Text.StringBuilder class.
Creating strings
There are several ways to create a string.
using System.Text;
string lang = "C#";
string db = new(['M', 'y', 'S', 'Q', 'L']);
string stars = new('*', 5);
string empty = string.Empty;
Console.WriteLine(lang);
Console.WriteLine(db);
Console.WriteLine(stars);
Console.WriteLine($"empty: '{empty}', length {empty.Length}");
var sb = new StringBuilder();
sb.Append("Fields");
sb.Append(" of ");
sb.Append("glory");
string title = sb.ToString();
Console.WriteLine(title);
The most common way is a string literal.
string db = new(['M', 'y', 'S', 'Q', 'L']);
string stars = new('*', 5);
A string can be created from an array of characters or from a character repeated a number of times.
string title = sb.ToString();
A StringBuilder collects parts of a string; its
ToString method creates the final string.
$ dotnet run C# MySQL ***** empty: '', length 0 Fields of glory
Escape sequences
Regular string literals are enclosed in double quotes and can contain escape sequences, which start with a backslash.
Console.WriteLine("deep\tforest");
Console.WriteLine("deep\nforest");
Console.WriteLine("C:\\Users\\Admin\\Documents");
Console.WriteLine("He said, \"Which one is your favourite?\"");
Console.WriteLine("caf\u00E9 \u03C0 \U0001F600");
\t is a tab and \n a new line. A backslash and a
double quote must be escaped as \\ and \".
Console.WriteLine("caf\u00E9 \u03C0 \U0001F600");
\u followed by four hexadecimal digits inserts a Unicode
character; \U with eight digits inserts characters outside the
Basic Multilingual Plane, such as emojis.
$ dotnet run deep forest deep forest C:\Users\Admin\Documents He said, "Which one is your favourite?" café π 😀
Verbatim strings
Verbatim strings start with @. They do not interpret escape
sequences and can span multiple lines.
Console.WriteLine(@"deep \t forest"); Console.WriteLine(@"C:\Users\Admin\Documents"); var text = @"Lao Tzu has said: ""If you do not change direction, you may end up where you are heading."""; Console.WriteLine(text);
The \t is printed as two characters, and paths do not need
doubled backslashes.
""If you do not change direction, you may end up
Inside a verbatim string, a double quote is written as two double quotes.
$ dotnet run deep \t forest C:\Users\Admin\Documents Lao Tzu has said: "If you do not change direction, you may end up where you are heading."
Raw string literals
Since C# 11, raw string literals start and end with at least three double quotes. They need no escaping at all, which makes them ideal for JSON, XML, SQL, or regular expressions.
string json = """
{
"name": "John Doe",
"path": "C:\Users\john",
"tags": ["admin", "dev"]
}
""";
Console.WriteLine(json);
string quote = """He said, "Which one is your favourite?" and smiled.""";
Console.WriteLine(quote);
string name = "Jane";
int age = 34;
string msg = $$"""
{ "name": "{{name}}", "age": {{age}} }
""";
Console.WriteLine(msg);
In a multi-line raw string, the indentation of the closing
""" is removed from every line. Backslashes and quotes are
taken literally.
string msg = $$"""
{ "name": "{{name}}", "age": {{age}} }
""";
An interpolated raw string can start with several $
characters. With $$, interpolation holes use double braces,
so single braces are literal text.
$ dotnet run
{
"name": "John Doe",
"path": "C:\Users\john",
"tags": ["admin", "dev"]
}
He said, "Which one is your favourite?" and smiled.
{ "name": "Jane", "age": 34 }
String interpolation
An interpolated string starts with $ and contains expressions
in braces. The expressions are evaluated and their values inserted into the
string.
string name = "Peter";
int age = 23;
var date = new DateTime(2026, 11, 6, 14, 30, 0);
Console.WriteLine($"{name} is {age} years old");
Console.WriteLine($"In ten years, {name} will be {age + 10}");
Console.WriteLine($"Today is {date.DayOfWeek}, it's {date:HH:mm} now");
Console.WriteLine($"{name.ToUpper()} has {name.Length} letters");
double price = 1234.5;
Console.WriteLine($"Price: {price:F2} | {price,12:N2} | {price,-12:F1}|");
bool vip = true;
Console.WriteLine($"Status: {(vip ? "VIP" : "regular")}");
Any expression can be placed inside the braces, including method calls and arithmetic.
Console.WriteLine($"Price: {price:F2} | {price,12:N2} | {price,-12:F1}|");
A format string follows a colon, and an alignment follows a comma. A positive alignment right-aligns the value; a negative one left-aligns it.
Console.WriteLine($"Status: {(vip ? "VIP" : "regular")}");
A conditional expression must be enclosed in parentheses, because the colon would otherwise start a format string.
$ dotnet run Peter is 23 years old In ten years, Peter will be 33 Today is Friday, it's 14:30 now PETER has 5 letters Price: 1234.50 | 1,234.50 | 1234.5 | Status: VIP
Strings are immutable objects
Strings are objects of the String class, which derives from
Object.
using System.Text;
string lang = "Java";
Console.WriteLine(lang.GetType().Name);
Console.WriteLine(lang.GetType().BaseType!.Name);
Console.WriteLine($"The string has {lang.Length} characters");
string name = "Jane";
string name2 = name.Replace('J', 'K').Replace('n', 't');
Console.WriteLine($"{name} -> {name2}");
var sb = new StringBuilder("Jane");
sb.Replace('J', 'K', 0, 1);
sb.Replace('n', 't', 2, 1);
Console.WriteLine(sb);
GetType and BaseType show the class and its parent.
The Length property returns the number of UTF-16 code units.
string name2 = name.Replace('J', 'K').Replace('n', 't');
Replace returns a new string; name still holds
"Jane".
sb.Replace('J', 'K', 0, 1);
sb.Replace('n', 't', 2, 1);
The StringBuilder is modified in place. This overload replaces
characters only in the given part of the builder.
$ dotnet run String Object The string has 4 characters Jane -> Kate Kate
Concatenation
Strings can be joined with the + operator, the
Concat and Join methods, interpolation, or a
StringBuilder.
using System.Text;
string s1 = "Return";
string s2 = "of";
string s3 = "the king.";
Console.WriteLine(s1 + " " + s2 + " " + s3);
Console.WriteLine(string.Concat(s1, " ", s2, " ", s3));
Console.WriteLine(string.Join(" ", s1, s2, s3));
Console.WriteLine($"{s1} {s2} {s3}");
var sb = new StringBuilder();
for (int i = 1; i <= 5; i++)
{
sb.Append(i).Append(i < 5 ? ", " : ".");
}
Console.WriteLine(sb);
string msg = "Hello";
msg += " there";
Console.WriteLine(msg);
The first four lines create the same string in four ways.
for (int i = 1; i <= 5; i++)
{
sb.Append(i).Append(i < 5 ? ", " : ".");
}
In loops, a StringBuilder is preferred; each + on
strings creates a new string object. Append returns the
builder, so calls can be chained.
msg += " there";
The += operator creates a new string and assigns it to the
variable.
$ dotnet run Return of the king. Return of the king. Return of the king. Return of the king. 1, 2, 3, 4, 5. Hello there
String elements
A string can be indexed like an array and sliced with ranges.
string s = "ZetCode";
Console.WriteLine($"First: {s[0]}, last: {s[^1]}");
Console.WriteLine($"Range [0..3]: {s[0..3]}");
Console.WriteLine($"Range [3..]: {s[3..]}");
foreach (char c in s)
{
Console.Write($"{c} ");
}
Console.WriteLine();
char[] chars = s.ToCharArray();
Array.Reverse(chars);
Console.WriteLine(new string(chars));
int upper = s.Count(char.IsUpper);
Console.WriteLine($"Uppercase letters: {upper}");
s[^1] is the last character. A range such as
s[0..3] returns a new string with the characters at indexes 0,
1, and 2.
char[] chars = s.ToCharArray(); Array.Reverse(chars);
To reverse a string, we copy it to a character array, reverse the array, and create a new string.
int upper = s.Count(char.IsUpper);
A string implements IEnumerable<char>, so LINQ methods
work on it.
$ dotnet run First: Z, last: e Range [0..3]: Zet Range [3..]: Code Z e t C o d e edoCteZ Uppercase letters: 2
StringBuilder
StringBuilder has methods to append, insert, remove, and
replace characters.
using System.Text;
var sb = new StringBuilder("Misty mountains");
Console.WriteLine(sb);
sb.Remove(sb.Length - 1, 1);
Console.WriteLine(sb);
sb.Append('s');
Console.WriteLine(sb);
sb.Insert(0, "The ");
Console.WriteLine(sb);
sb.Replace('M', 'm', 4, 1);
Console.WriteLine(sb);
sb[0] = 't';
Console.WriteLine($"{sb} ({sb.Length} characters)");
sb.Clear();
sb.AppendLine("first line");
sb.AppendFormat("{0} + {1} = {2}", 2, 3, 2 + 3);
Console.WriteLine(sb);
Remove deletes the last character, and Append
adds it back.
sb.Insert(0, "The ");
Insert places text at the given index.
sb[0] = 't';
Unlike a string, a builder allows assignment to its indexer.
sb.Clear();
sb.AppendLine("first line");
sb.AppendFormat("{0} + {1} = {2}", 2, 3, 2 + 3);
Clear empties the builder. AppendLine adds a new
line, and AppendFormat uses composite formatting.
$ dotnet run Misty mountains Misty mountain Misty mountains The Misty mountains The misty mountains the misty mountains (19 characters) first line 2 + 3 = 5
Comparing strings
The == operator compares the content of two strings, with case
sensitivity. Other comparisons take a StringComparison value.
string a = "ZetCode";
string b = "zetcode";
Console.WriteLine(a == b);
Console.WriteLine(a.Equals(b, StringComparison.OrdinalIgnoreCase));
Console.WriteLine(string.Compare(a, b, StringComparison.Ordinal));
Console.WriteLine(string.Compare(a, b, StringComparison.OrdinalIgnoreCase));
Console.WriteLine(string.Compare("apple", "banana", StringComparison.Ordinal) < 0);
string[] words = ["banana", "Apple", "cherry", "apple"];
Array.Sort(words, StringComparer.Ordinal);
Console.WriteLine(string.Join(", ", words));
Array.Sort(words, StringComparer.InvariantCulture);
Console.WriteLine(string.Join(", ", words));
Equals with OrdinalIgnoreCase ignores the case.
Console.WriteLine(string.Compare(a, b, StringComparison.Ordinal));
Compare returns a negative number if the first string sorts
before the second, zero if they are equal, and a positive number otherwise.
Ordinal comparison uses the numeric values of the characters; 'Z' (90)
minus 'z' (122) gives -32.
Array.Sort(words, StringComparer.Ordinal);
An ordinal sort puts all uppercase letters before lowercase ones. A culture-aware sort orders words alphabetically, as people expect. Use ordinal comparisons for identifiers, keys, and file names, and culture-aware ones for text shown to users.
$ dotnet run False True -32 0 True Apple, apple, banana, cherry apple, Apple, banana, cherry
Searching
Contains, IndexOf, LastIndexOf,
StartsWith, and EndsWith search inside strings.
string text = "An old falcon flew over the old castle";
Console.WriteLine(text.Contains("falcon"));
Console.WriteLine(text.Contains("FALCON"));
Console.WriteLine(text.Contains("FALCON", StringComparison.OrdinalIgnoreCase));
Console.WriteLine(text.IndexOf("old"));
Console.WriteLine(text.LastIndexOf("old"));
Console.WriteLine(text.IndexOf("old", 5));
Console.WriteLine(text.IndexOf("eagle"));
Console.WriteLine(text.StartsWith("An"));
Console.WriteLine(text.EndsWith("castle"));
string[] words = ["club", "sky", "blue", "cup", "coin", "new", "cent", "falcon"];
var res = words.Where(w => w.StartsWith('c') || w.EndsWith('y'));
Console.WriteLine(string.Join(" ", res));
int count = 0;
int idx = 0;
while ((idx = text.IndexOf('o', idx)) != -1)
{
count++;
idx++;
}
Console.WriteLine($"'o' occurs {count} times");
Contains is case-sensitive unless a
StringComparison is given.
Console.WriteLine(text.IndexOf("old", 5));
Console.WriteLine(text.IndexOf("eagle"));
IndexOf returns the index of the first occurrence, optionally
starting at a given index. It returns -1 if the text is not found.
while ((idx = text.IndexOf('o', idx)) != -1)
Calling IndexOf in a loop, each time from the position after
the last match, finds all occurrences.
$ dotnet run True False True 3 28 28 -1 True True club sky cup coin cent 'o' occurs 4 times
Substrings
Substring and ranges extract a part of a string.
string word = "bookcase";
Console.WriteLine(word.Substring(0, 4));
Console.WriteLine(word.Substring(4, 4));
Console.WriteLine(word.Substring(4));
Console.WriteLine(word[..4]);
Console.WriteLine(word[4..]);
Console.WriteLine(word[^4..]);
string email = "john.doe@example.com";
int at = email.IndexOf('@');
Console.WriteLine($"User: {email[..at]}, domain: {email[(at + 1)..]}");
try
{
Console.WriteLine(word.Substring(6, 4));
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine(e.GetType().Name);
}
Substring(4, 4) takes four characters from index 4;
Substring(4) takes the rest of the string. The range
expressions [..4], [4..], and [^4..]
do the same with shorter syntax.
Console.WriteLine($"User: {email[..at]}, domain: {email[(at + 1)..]}");
Combined with IndexOf, ranges split a string at a separator.
Console.WriteLine(word.Substring(6, 4));
If the requested part goes beyond the end of the string,
ArgumentOutOfRangeException is thrown.
$ dotnet run book case case book case case User: john.doe, domain: example.com ArgumentOutOfRangeException
Split and Join
Split divides a string into an array of parts;
Join combines parts with a separator.
string[] items = ["C#", "Visual Basic", "Java", "Perl"];
string langs = string.Join(",", items);
Console.WriteLine(langs);
string[] parts = langs.Split(',');
Console.WriteLine($"{parts.Length} parts: {string.Join(" | ", parts)}");
string data = " sky, ,blue , cup,,";
string[] raw = data.Split(',');
Console.WriteLine($"{raw.Length} parts: [{string.Join("][", raw)}]");
string[] clean = data.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Console.WriteLine($"{clean.Length} parts: [{string.Join("][", clean)}]");
string text = "one two three\tfour\nfive";
string[] words = text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(string.Join(",", words));
string[] pair = "key=value=more".Split('=', 2);
Console.WriteLine($"{pair[0]} -> {pair[1]}");
Split keeps empty parts and white space by default.
string[] clean = data.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
TrimEntries trims each part, and
RemoveEmptyEntries drops the parts that are empty afterwards.
string[] words = text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
With null separators, the string is split at any white-space
character.
string[] pair = "key=value=more".Split('=', 2);
The count argument limits the number of parts; the last part contains the rest of the string.
$ dotnet run C#,Visual Basic,Java,Perl 4 parts: C# | Visual Basic | Java | Perl 6 parts: [ sky][ ][blue ][ cup][][] 3 parts: [sky][blue][cup] one,two,three,four,five key -> value=more
Replace, Remove, and Insert
These methods return a modified copy of a string.
string text = "The quick brown fox jumps over the lazy dog.";
Console.WriteLine(text.Replace("fox", "cat"));
Console.WriteLine(text.Replace("the", "a"));
Console.WriteLine(text.Replace("the", "a", StringComparison.OrdinalIgnoreCase));
Console.WriteLine(text.Replace(" ", ""));
Console.WriteLine(text.Remove(16, 4));
Console.WriteLine(text.Remove(19));
Console.WriteLine(text.Insert(10, "and red "));
Console.WriteLine(text);
Replace replaces all occurrences. It is case-sensitive unless a
StringComparison is given; the third call also replaces "The".
Console.WriteLine(text.Remove(16, 4)); Console.WriteLine(text.Remove(19));
Remove(16, 4) deletes four characters from index 16, the word
"fox" with the following space. Remove(19) deletes everything
from index 19.
Console.WriteLine(text);
The last line shows that the original string is unchanged.
$ dotnet run The quick brown cat jumps over the lazy dog. The quick brown fox jumps over a lazy dog. a quick brown fox jumps over a lazy dog. Thequickbrownfoxjumpsoverthelazydog. The quick brown jumps over the lazy dog. The quick brown fox The quick and red brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.
Trimming
Trim, TrimStart, and TrimEnd remove
white space, or given characters, from the ends of a string.
string input = " hello there ";
Console.WriteLine($"Trim: '{input.Trim()}'");
Console.WriteLine($"TrimStart: '{input.TrimStart()}'");
Console.WriteLine($"TrimEnd: '{input.TrimEnd()}'");
string text = "Did you go there? We did, but we had a \"great\" service there.";
char[] punct = ['.', ',', '?', '"'];
var words = text.Split(' ').Select(w => w.Trim(punct));
Console.WriteLine(string.Join(" ", words));
Console.WriteLine("0042.5000".TrimStart('0').TrimEnd('0'));
Without arguments, the methods remove white-space characters.
var words = text.Split(' ').Select(w => w.Trim(punct));
With a character array, Trim removes punctuation and quotes
from both ends of each word.
$ dotnet run Trim: 'hello there' TrimStart: 'hello there ' TrimEnd: ' hello there' Did you go there We did but we had a great service there 42.5
Padding
PadLeft and PadRight extend a string to a given
width with spaces or another character.
Console.WriteLine("42".PadLeft(5, '0'));
Console.WriteLine("42".PadRight(8, '-') + "|");
Console.WriteLine("falcon".PadLeft(3));
(string Name, int Qty, decimal Price)[] items =
[
("apples", 12, 0.5m),
("bananas", 6, 0.25m),
("watermelon", 1, 3.99m),
];
foreach (var (name, qty, price) in items)
{
Console.WriteLine(name.PadRight(12, '.') + qty.ToString().PadLeft(4) + price.ToString("F2").PadLeft(8));
}
A string that is already longer than the width is returned unchanged.
Console.WriteLine(name.PadRight(12, '.') + qty.ToString().PadLeft(4) + price.ToString("F2").PadLeft(8));
Padding aligns the columns of a simple text table.
$ dotnet run 00042 42------| falcon apples...... 12 0.50 bananas..... 6 0.25 watermelon.. 1 3.99
Case conversion
ToUpper and ToLower change the case of letters
using the current culture.
using System.Globalization;
string word = "Cherry";
Console.WriteLine(word.ToUpper());
Console.WriteLine(word.ToLower());
string sk = "\u010Cere\u0161\u0148a";
Console.WriteLine($"{sk} -> {sk.ToUpper()}");
var tr = new CultureInfo("tr-TR");
Console.WriteLine($"title -> {"title".ToUpper(tr)} (Turkish)");
Console.WriteLine($"title -> {"title".ToUpperInvariant()} (invariant)");
TextInfo ti = CultureInfo.InvariantCulture.TextInfo;
Console.WriteLine(ti.ToTitleCase("an old falcon"));
The methods work with letters outside the ASCII range, such as the Slovak word for cherry.
Console.WriteLine($"title -> {"title".ToUpper(tr)} (Turkish)");
Case rules depend on the culture. In Turkish, the uppercase form of
i is İ with a dot. For culture-independent results, such
as identifiers, use ToUpperInvariant.
Console.WriteLine(ti.ToTitleCase("an old falcon"));
TextInfo.ToTitleCase capitalizes the first letter of each word.
$ dotnet run CHERRY cherry Čerešňa -> ČEREŠŇA title -> TİTLE (Turkish) title -> TITLE (invariant) An Old Falcon
Unicode characters
Length counts UTF-16 code units, not the characters a user
sees. A Rune is one Unicode scalar value, and a text element
(grapheme cluster) is what is displayed as one character.
using System.Globalization;
string animals = "\U0001F404\U0001F999\U0001F418";
Console.WriteLine(animals);
Console.WriteLine($"Length: {animals.Length}");
Console.WriteLine($"Runes: {animals.EnumerateRunes().Count()}");
foreach (var rune in animals.EnumerateRunes())
{
Console.WriteLine($"{rune} U+{rune.Value:X}");
}
string word = "cafe\u0301";
Console.WriteLine($"{word}: Length {word.Length}, " +
$"runes {word.EnumerateRunes().Count()}, " +
$"text elements {new StringInfo(word).LengthInTextElements}");
string family = "\U0001F468\u200D\U0001F469\u200D\U0001F467";
Console.WriteLine($"{family}: Length {family.Length}, " +
$"runes {family.EnumerateRunes().Count()}, " +
$"text elements {new StringInfo(family).LengthInTextElements}");
Console.WriteLine($"Normalized: {word.Normalize().Length}, equals caf\u00E9: {word.Normalize() == "caf\u00E9"}");
Each animal emoji lies outside the Basic Multilingual Plane and takes two
UTF-16 code units, so three emojis have a length of 6.
EnumerateRunes returns the three code points.
string word = "cafe\u0301";
Here the letter é is written as e followed by a combining accent.
The string has five code units and five runes, but four text elements, which
StringInfo counts.
string family = "\U0001F468\u200D\U0001F469\u200D\U0001F467";
The family emoji consists of three emojis joined by zero-width joiners; it is eight code units and five runes, but one text element.
Console.WriteLine($"Normalized: {word.Normalize().Length}, equals caf\u00E9: {word.Normalize() == "caf\u00E9"}");
Normalize converts the string to Unicode normalization form C,
which combines e and the accent into a single character. Normalize
strings from different sources before comparing them.
$ dotnet run 🐄🦙🐘 Length: 6 Runes: 3 🐄 U+1F404 🦙 U+1F999 🐘 U+1F418 café: Length 5, runes 5, text elements 4 👨👩👧: Length 8, runes 5, text elements 1 Normalized: 4, equals café: True
Palindrome
A palindrome is a word that reads the same backward as forward, such as radar.
Console.WriteLine(IsPalindrome("radar"));
Console.WriteLine(IsPalindrome("kayak"));
Console.WriteLine(IsPalindrome("forest"));
static bool IsPalindrome(string original)
{
char[] data = original.ToCharArray();
int i = 0;
int j = data.Length - 1;
while (j > i)
{
if (data[i] != data[j])
{
return false;
}
i++;
j--;
}
return true;
}
The method compares characters from both ends towards the middle.
while (j > i)
{
if (data[i] != data[j])
{
return false;
}
If any pair differs, the word is not a palindrome.
$ dotnet run True True False
Composite formatting
string.Format, Console.WriteLine, and
StringBuilder.AppendFormat support composite formatting. A
format string contains indexed format items:
{index[,alignment][:formatString]}
int oranges = 2;
int apples = 4;
int bananas = 3;
string str1 = "There are {0} oranges, {1} apples and {2} bananas";
string str2 = "There are {1} oranges, {2} bananas and {0} apples";
Console.WriteLine(str1, oranges, apples, bananas);
Console.WriteLine(str2, apples, oranges, bananas);
string msg = string.Format("{0} + {0} = {1}", 5, 5 + 5);
Console.WriteLine(msg);
Console.WriteLine("{0,-8}|{1,8}|", "left", "right");
Console.WriteLine("{0:D5} {1,8:X}", 502, 546);
The index refers to an argument after the format string, starting at 0.
string str2 = "There are {1} oranges, {2} bananas and {0} apples";
The items do not have to appear in index order, and an item can be used
more than once, as in {0} + {0}.
Console.WriteLine("{0:D5} {1,8:X}", 502, 546);
D5 pads an integer with zeros to five digits;
{1,8:X} formats 546 in hexadecimal, right-aligned in eight
characters.
$ dotnet run There are 2 oranges, 4 apples and 3 bananas There are 2 oranges, 3 bananas and 4 apples 5 + 5 = 10 left | right| 00502 222
Formatting numbers
Standard and custom format strings control how numbers are displayed.
using System.Globalization;
CultureInfo.CurrentCulture = new CultureInfo("en-US");
double n = 1234.5678;
Console.WriteLine($"Fixed-point: {n:F2}");
Console.WriteLine($"Number: {n:N2}");
Console.WriteLine($"Scientific: {n:E3}");
Console.WriteLine($"Currency: {n:C2}");
Console.WriteLine($"Percent: {0.256:P1}");
Console.WriteLine($"Hexadecimal: {255:X} {255:x4}");
Console.WriteLine($"Custom: {n:0000.0} {n:#,##0.##}");
Console.WriteLine($"German: {n.ToString("N2", new CultureInfo("de-DE"))}");
We set the en-US culture so that the output does not depend on the system
settings. We state the number of decimals explicitly; the default for
N and P differs between platforms.
Console.WriteLine($"Custom: {n:0000.0} {n:#,##0.##}");
In custom formats, 0 is a digit that is always shown and
# a digit shown only when significant.
Console.WriteLine($"German: {n.ToString("N2", new CultureInfo("de-DE"))}");
German uses a dot as the group separator and a comma for decimals.
$ dotnet run Fixed-point: 1234.57 Number: 1,234.57 Scientific: 1.235E+003 Currency: $1,234.57 Percent: 25.6% Hexadecimal: FF 00ff Custom: 1234.6 1,234.57 German: 1.234,57
Formatting dates
Dates also have standard and custom format strings.
using System.Globalization;
CultureInfo.CurrentCulture = new CultureInfo("en-US");
var date = new DateTime(2026, 11, 6, 17, 13, 30);
Console.WriteLine($"Short date: {date:d}");
Console.WriteLine($"Long date: {date:D}");
Console.WriteLine($"Short time: {date:t}");
Console.WriteLine($"Long time: {date:T}");
Console.WriteLine($"Month: {date:M}");
Console.WriteLine($"Year: {date:Y}");
Console.WriteLine($"ISO 8601: {date:yyyy-MM-ddTHH:mm:ss}");
Console.WriteLine($"Custom: {date:ddd, d MMM yyyy}");
d, D, t, T,
M, and Y are standard formats whose layout depends
on the culture.
Console.WriteLine($"Custom: {date:ddd, d MMM yyyy}");
Custom formats combine specifiers such as ddd for the
abbreviated day name and MMM for the abbreviated month name.
$ dotnet run Short date: 11/6/2026 Long date: Friday, November 6, 2026 Short time: 5:13 PM Long time: 5:13:30 PM Month: November 6 Year: November 2026 ISO 8601: 2026-11-06T17:13:30 Custom: Fri, 6 Nov 2026
String identity and interning
The runtime keeps one instance of each string literal in an intern pool. Strings created at run time are separate objects.
string a = "falcon"; string b = "falcon"; string c = new string(['f', 'a', 'l', 'c', 'o', 'n']); Console.WriteLine(a == c); Console.WriteLine(ReferenceEquals(a, b)); Console.WriteLine(ReferenceEquals(a, c)); string d = string.Intern(c); Console.WriteLine(ReferenceEquals(a, d)); object o1 = a; object o2 = c; Console.WriteLine(o1 == o2); Console.WriteLine(o1.Equals(o2));
a and b refer to the same interned object, while
c has the same content in a different object.
string d = string.Intern(c);
string.Intern returns the pooled instance with the same
content.
Console.WriteLine(o1 == o2); Console.WriteLine(o1.Equals(o2));
When strings are typed as object, == compares
references and returns false. Equals is virtual
and still compares the content.
$ dotnet run True True False True False True
Source
In this article we have worked with strings in C#.
Author
List all C# tutorials.