If I had to choose two things that cause hidden bugs in my code, they would be strings and date & time. And yet, even today, I see people struggle with both.
Today I’ll tackle strings and share 8 tips I’ve collected over the years. At the end, I have a small free gift for you.
So, let’s get started.
Compare strings with StringComparison and StringComparer
A case-insensitive check I still see in code reviews:
CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
string command = "file";
Console.WriteLine(command.ToUpper()); // FİLE
Console.WriteLine(command.ToUpper() == "FILE"); // False
ToUpper() uses the current culture. In Turkish, the uppercase of i is İ (dotted capital I), so "file" becomes "FİLE" and the check fails.
Tell the comparison what you want with StringComparison:
bool isFileCommand = string.Equals(
command,
"FILE",
StringComparison.OrdinalIgnoreCase);
Console.WriteLine(isFileCommand); // True
Ordinal compares the characters’ numeric values, so the result doesn’t depend on culture. It also skips the extra string that ToUpper() allocates.
Most string methods that compare have an overload that takes it:
string path = "/api/orders";
bool isApi = path.StartsWith("/API", StringComparison.OrdinalIgnoreCase);
Console.WriteLine(isApi); // True
For collections, use StringComparer. A dictionary with case-insensitive keys needs nothing else (the custom provider in my configuration post builds its keys this way):
var headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["Content-Type"] = "application/json"
};
Console.WriteLine(headers["content-type"]); // application/json
My rule of thumb:
Ordinal/OrdinalIgnoreCasefor identifiers, keys, file paths, URLs, headers and anything a machine reads.CurrentCultureonly for text you sort or show to users.
Slice strings with ReadOnlySpan
Here’s a typical way to pull the parts out of an order number:
string orderNumber = "ORD-2026-000123";
string prefix = orderNumber.Substring(0, 3);
int year = int.Parse(orderNumber.Substring(4, 4));
int sequence = int.Parse(orderNumber.Substring(9));
That’s three new strings to read three values you already have in memory.
ReadOnlySpan<char> is a view over existing memory. Slicing it moves a pointer and a length; nothing gets copied:
ReadOnlySpan<char> order = orderNumber.AsSpan();
ReadOnlySpan<char> orderPrefix = order[..3];
int orderYear = int.Parse(order[4..8]);
int orderSequence = int.Parse(order[9..]);
bool isOrder = orderPrefix.Equals("ORD", StringComparison.Ordinal);
I measured both versions with BenchmarkDotNet: the Substring version allocates 104 bytes per call, the span version 0.
| Method | Mean | Allocated |
|---|---|---|
Substring | 36.48 ns | 104 B |
ReadOnlySpan<char> | 18.23 ns | 0 B |
.NET 11.0.0, Intel Core i7-8700, BenchmarkDotNet 0.16.0-preview.2. The preview is the first BenchmarkDotNet version that recognizes .NET 11; the latest stable release (0.15.8) stops with a NotImplementedException before running.
Spans have limits, and the compiler enforces them:
- You can’t store a span in a class field (error CS8345).
- You can’t keep one alive across an
await(error CS4007).
When you need either, use ReadOnlyMemory<char> and call .Span where you read it.
Format and parse with InvariantCulture
ToString() and Parse() use the current culture, so the same code behaves differently on a machine with different regional settings. On a German one:
CultureInfo.CurrentCulture = new CultureInfo("de-DE");
decimal price = 1234.5m;
Console.WriteLine(price.ToString()); // 1234,5
Console.WriteLine(decimal.Parse("1234.5")); // 12345
German groups thousands with ., so "1234.5" parses as 12345 without an error.
String interpolation formats with the current culture too:
string sku = "ABC-1";
string csvLine = $"{sku},{price}";
Console.WriteLine(csvLine); // ABC-1,1234,5
That CSV line now has three columns instead of two.
For anything a machine reads (files, APIs, logs, configuration, database values), pass CultureInfo.InvariantCulture:
Console.WriteLine(price.ToString(CultureInfo.InvariantCulture)); // 1234.5
decimal parsed = decimal.Parse("1234.5", CultureInfo.InvariantCulture);
Console.WriteLine(parsed == 1234.5m); // True
Console.WriteLine(parsed); // 1234,5 (formatted with de-DE again)
For interpolated strings, use string.Create with a culture:
string fixedLine = string.Create(
CultureInfo.InvariantCulture,
$"{sku},{price}");
Console.WriteLine(fixedLine); // ABC-1,1234.5
Two more rules:
- For comparisons, use
Ordinal, notInvariantCulture. The invariant culture is for formatting and parsing; the first tip covers comparing. InvariantGlobalization(<InvariantGlobalization>true</InvariantGlobalization>in the project file) makes the whole app use the invariant culture. It fits APIs and background services with no user-facing text. Creating a named culture likede-DEthen throwsCultureNotFoundException, so don’t turn it on for apps that show formatted dates or numbers to users.
Split and parse without allocating
Reading a CSV line with string.Split:
string line = "ABC-1,3,1234.5";
string[] parts = line.Split(',');
string sku = parts[0];
int quantity = int.Parse(parts[1]);
decimal price = decimal.Parse(parts[2], CultureInfo.InvariantCulture);
It allocates an array plus a string per field. That’s fine for a value parsed once per request, like the expand parameter in my resource expansion post, but it adds up over a large file.
MemoryExtensions.Split works on a span. Instead of strings, it writes Range values that point into the original line:
ReadOnlySpan<char> fields = line.AsSpan();
Span<Range> ranges = stackalloc Range[3];
int count = fields.Split(ranges, ',');
ReadOnlySpan<char> skuSpan = fields[ranges[0]];
int quantityValue = int.Parse(fields[ranges[1]]);
decimal priceValue = decimal.Parse(fields[ranges[2]], CultureInfo.InvariantCulture);
If the line has more fields than ranges, the last range holds the rest of the line.
When you don’t know how many values there are, enumerate them:
ReadOnlySpan<char> numbers = "3,5,8,13";
int total = 0;
foreach (Range range in numbers.Split(','))
{
total += int.Parse(numbers[range]);
}
Console.WriteLine(total); // 29
For input you don’t control, use TryParse, which has span overloads too:
ReadOnlySpan<char> input = "3,x,8";
int sum = 0;
foreach (Range range in input.Split(','))
{
if (int.TryParse(input[range], out int value))
{
sum += value;
}
}
Console.WriteLine(sum); // 11
Both versions of the CSV line parse:
| Method | Mean | Allocated |
|---|---|---|
string.Split | 116.6 ns | 144 B |
Span Split | 101.1 ns | 0 B |
.NET 11.0.0, Intel Core i7-8700, BenchmarkDotNet 0.16.0-preview.2
Most of the time goes to decimal.Parse; the win is zero allocations per line.
Choose the right way to build strings
C# gives you six ways to build a string.
Interpolation is the readable default for a few values:
string customer = "Alice";
int orderId = 1042;
string message = $"Order {orderId} for {customer} is ready.";
Since C# 10 the compiler builds it with an interpolated string handler, so there’s no hidden boxing.
Concatenation is fine for a few pieces in one expression:
string firstName = "Alice";
string lastName = "Smith";
string fullName = firstName + " " + lastName;
The compiler turns it into a single string.Concat call.
StringBuilder is for loops, or whenever you don’t know the number of pieces upfront:
string[] lines = ["ABC-1,3", "ABC-2,1", "ABC-3,7"];
var csv = new StringBuilder(capacity: 256);
foreach (string line in lines)
{
csv.Append(line).Append('\n');
}
Pass a capacity when you can estimate the size; it saves the internal buffer from resizing.
string.Join is for a collection with a separator:
int[] productIds = [12, 7, 42];
string idList = string.Join(", ", productIds); // 12, 7, 42
string.Format is for templates that aren’t known at compile time, such as localized text from a resource file. Parse the template once with CompositeFormat and reuse it:
string template = "{0} items in your cart"; // e.g. loaded from a resource file
CompositeFormat cartMessage = CompositeFormat.Parse(template);
Console.WriteLine(string.Format(null, cartMessage, 3)); // 3 items in your cart
string.Create is for when you know the final length and want to write the characters into the buffer yourself, with no intermediate strings:
string cardNumber = "4111111111111111";
string masked = string.Create(cardNumber.Length, cardNumber, (span, card) =>
{
span.Fill('*');
card.AsSpan(^4).CopyTo(span[^4..]);
});
Console.WriteLine(masked); // ************1111
The one to avoid is += in a loop. Every iteration copies the whole string built so far. Building a list of IDs:
| Method | Items | Mean | Allocated |
|---|---|---|---|
+= in a loop | 10 | 110.05 ns | 480 B |
StringBuilder | 10 | 92.95 ns | 272 B |
string.Join | 10 | 102.48 ns | 160 B |
+= in a loop | 1,000 | 262,899 ns | 3,844,312 B |
StringBuilder | 1,000 | 5,813 ns | 16,680 B |
string.Join | 1,000 | 8,966 ns | 15,648 B |
.NET 11.0.0, Intel Core i7-8700, BenchmarkDotNet 0.16.0-preview.2
Search for many values with SearchValues
A typical check for invalid file name characters:
string fileName = "report:2026?.pdf";
bool hasInvalid = fileName.IndexOfAny(['<', '>', ':', '"', '/', '\\', '|', '?', '*']) >= 0;
SearchValues<T> analyzes the set of values once and picks the fastest search strategy for it, often vectorized. Create it once and reuse it:
public static class FileNameRules
{
private static readonly SearchValues<char> InvalidChars =
SearchValues.Create("<>:\"/\\|?*");
public static bool HasInvalidChars(string fileName) =>
fileName.AsSpan().ContainsAny(InvalidChars);
}
Console.WriteLine(FileNameRules.HasInvalidChars(fileName)); // True
Console.WriteLine(FileNameRules.HasInvalidChars("report.pdf")); // False
It works for whole words too. A simple spam check:
string[] bannedWords = ["free money", "click here", "winner"];
string comment = "Congratulations, you are a WINNER! Click here to claim.";
bool isSpam = bannedWords.Any(word => comment.Contains(word, StringComparison.OrdinalIgnoreCase));
That scans the comment once per word. SearchValues<string> finds any of them in a single pass and takes a StringComparison:
public static class SpamFilter
{
public static readonly SearchValues<string> BannedWords = SearchValues.Create(
["free money", "click here", "winner"],
StringComparison.OrdinalIgnoreCase);
public static bool IsSpam(string comment) =>
comment.AsSpan().ContainsAny(BannedWords);
}
Checking a 1 KB comment with no banned words (the worst case, since every word gets searched for) against five banned phrases:
| Method | Mean | Allocated |
|---|---|---|
Any + Contains | 439.0 ns | 0 B |
SearchValues<string> | 114.9 ns | 0 B |
.NET 11.0.0, Intel Core i7-8700, BenchmarkDotNet 0.16.0-preview.2
Always store
SearchValuesin astatic readonlyfield. Creating it does the expensive analysis, so creating it per call throws away the benefit.
Stream strings with StringStream
When an API needs a Stream and you have a string, the usual move is to encode the whole thing into a byte array first. Compressing a large JSON payload:
await using var file = File.Create("report.json.gz");
await using var gzip = new GZipStream(file, CompressionLevel.Optimal);
byte[] bytes = Encoding.UTF8.GetBytes(json);
await gzip.WriteAsync(bytes);
For a 1 MB string, that’s a 1 MB array. Anything of 85,000 bytes or more goes to the large object heap, which the garbage collector only cleans up in a full (Gen 2) collection.
.NET 11 added StringStream. It reads a string (or ReadOnlyMemory<char>) as a stream and encodes it in small chunks as it goes:
await using var file = File.Create("report.json.gz");
await using var gzip = new GZipStream(file, CompressionLevel.Optimal);
using var content = new StringStream(json, Encoding.UTF8);
await content.CopyToAsync(gzip);
Compressing a 1 MB JSON string:
| Method | Mean | Allocated |
|---|---|---|
Encoding.UTF8.GetBytes | 458.8 µs | 1,000,443 B |
StringStream | 294.2 µs | 520 B |
.NET 11.0.0, Intel Core i7-8700, BenchmarkDotNet 0.16.0-preview.2
It’s read-only and forward-only:
using var stream = new StringStream("hello", Encoding.UTF8);
Console.WriteLine(stream.CanSeek); // False
Console.WriteLine(stream.CanWrite); // False
Length throws NotSupportedException too, so APIs that need to seek or know the size upfront won’t accept it. For those, you still need the byte array.
It’s one of four new in-memory stream types in .NET 11. The rest of the release is in my C# 15 and .NET 11 post.
Use regular expressions when you need to match a pattern
Regex often ends up in checks like this:
string orderNumber = "ORD-2026-000123";
bool isOrder = Regex.IsMatch(orderNumber, "^ORD-");
A plain string method does the same job and is easier to read:
bool isOrderPrefix = orderNumber.StartsWith("ORD-", StringComparison.Ordinal);
Use regex when you match a real pattern, like the full order number format. Use the source generator for it: it compiles the pattern into C# at build time, so there’s no parsing at runtime:
public static partial class OrderNumber
{
[GeneratedRegex(@"^ORD-\d{4}-\d{6}$")]
private static partial Regex Pattern { get; }
public static bool IsValid(string value) => Pattern.IsMatch(value);
}
Console.WriteLine(OrderNumber.IsValid("ORD-2026-000123")); // True
Console.WriteLine(OrderNumber.IsValid("ORD-26-123")); // False
Validating the order number three ways:
| Method | Mean | Allocated |
|---|---|---|
new Regex(pattern) per call | 1,056.14 ns | 2,552 B |
Regex.IsMatch(input, pattern) | 92.32 ns | 0 B |
[GeneratedRegex] | 25.92 ns | 0 B |
.NET 11.0.0, Intel Core i7-8700, BenchmarkDotNet 0.16.0-preview.2
The static Regex.IsMatch is fast because .NET caches recently used patterns. Creating a new Regex on every call skips that cache and parses the pattern each time.
For input you don’t control, set a timeout. Some patterns backtrack exponentially on certain inputs:
public static partial class Patterns
{
[GeneratedRegex(@"^(a+)+$", RegexOptions.None, matchTimeoutMilliseconds: 100)]
public static partial Regex Nested();
}
string input = new string('a', 30) + "!";
try
{
Console.WriteLine(Patterns.Nested().IsMatch(input));
}
catch (RegexMatchTimeoutException)
{
Console.WriteLine("Timed out"); // Timed out
}
If you can’t control the pattern either, RegexOptions.NonBacktracking guarantees matching time that grows linearly with input length.
Final words
As promised, here’s your gift: all 8 tips as one skill for Claude Code and Codex. Save it as SKILL.md in .claude/skills/dotnet-string-tips/ (Claude Code) or .agents/skills/dotnet-string-tips/ (Codex) in your repository:
---
name: dotnet-string-tips
description: Apply .NET string best practices when writing or reviewing C# that compares, slices, formats, parses, splits, builds, searches, streams or pattern-matches strings.
---
# .NET string tips
Apply these rules to new code and flag violations in reviews. Prefer readability
outside hot paths; apply the allocation rules in code that runs often
(parsers, request handling, loops over large inputs).
## Compare with StringComparison and StringComparer
- Never compare with `ToUpper()`/`ToLower()` + `==`. Use
`string.Equals(a, b, StringComparison.OrdinalIgnoreCase)`.
- Pass a `StringComparison` to `Equals`, `StartsWith`, `EndsWith`, `IndexOf`, `Contains`.
- Use `Ordinal`/`OrdinalIgnoreCase` for identifiers, keys, paths, URLs, headers.
Use `CurrentCulture` only for text sorted or shown to users.
- Give dictionaries and sets a comparer:
`new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase)`.
- Enable analyzers CA1309 and CA1310.
## Slice with ReadOnlySpan<char>
- In hot paths, replace `Substring` with `AsSpan()` and range slicing (`span[4..8]`).
- Parse and compare spans directly: `int.Parse(span)`, `span.Equals("X", StringComparison.Ordinal)`.
- Spans can't be class fields or live across `await`; use `ReadOnlyMemory<char>` there.
## Format and parse with InvariantCulture
- Pass `CultureInfo.InvariantCulture` to `ToString`, `Parse` and `TryParse` for
machine-read data: files, APIs, logs, configuration, database values.
- Build machine-read interpolated strings with
`string.Create(CultureInfo.InvariantCulture, $"...")`.
- Use `Ordinal`, not `InvariantCulture`, for comparisons.
- Consider `<InvariantGlobalization>true</InvariantGlobalization>` for services with
no user-facing text; named cultures then throw `CultureNotFoundException`.
- Enable analyzer CA1305.
## Split and parse without allocating
- In hot paths, replace `string.Split` with `span.Split(ranges, ',')` into a
`stackalloc Range[n]`, or `foreach (Range r in span.Split(','))` when the count is unknown.
- Use `TryParse` with span overloads for input you don't control.
## Choose the right way to build strings
- Interpolation for a few values; `+` for a few pieces in one expression.
- `StringBuilder` (with a capacity when known) for loops or an unknown number of pieces.
- `string.Join` for collections with a separator.
- `string.Format` with a cached `CompositeFormat` for templates loaded at runtime.
- `string.Create(length, state, (span, state) => ...)` when the final length is known.
- Never use `+=` on a string inside a loop.
## Search with SearchValues<T>
- For repeated `IndexOfAny`/`ContainsAny` over a fixed set of chars or words, use
`SearchValues.Create(...)`; for words pass a `StringComparison`.
- Store `SearchValues` in a `static readonly` field; never create it per call.
## Stream strings with StringStream (.NET 11+)
- When an API needs a `Stream`, wrap the string with
`new StringStream(text, Encoding.UTF8)` instead of `new MemoryStream(Encoding.UTF8.GetBytes(text))`.
- It's read-only and forward-only: `CanSeek` is false and `Length` throws. Keep the
byte array for APIs that seek or need the length.
## Use regular expressions only for patterns
- Use `StartsWith`, `EndsWith`, `Contains` or `IndexOf` for fixed text, not regex.
- Use `[GeneratedRegex]` for patterns; never `new Regex(pattern)` per call.
- For untrusted input, set `matchTimeoutMilliseconds` or use `RegexOptions.NonBacktracking`.
- Enable analyzer SYSLIB1045.