# 8 string tips that prevent hidden bugs in .NET

> Compare strings ordinally, format with InvariantCulture and slice with spans: 8 .NET string tips, each tested and benchmarked on .NET 11.

- Author: Pavle Davitkovic
- Published: 2026-12-02
- Topic: .NET
- Canonical: https://pavle.codes/blog/string-tips-dotnet/

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:

```csharp
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`](https://learn.microsoft.com/en-us/dotnet/api/system.stringcomparison):

```csharp
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:

```csharp
string path = "/api/orders";

bool isApi = path.StartsWith("/API", StringComparison.OrdinalIgnoreCase);

Console.WriteLine(isApi); // True
```

For collections, use [`StringComparer`](https://learn.microsoft.com/en-us/dotnet/api/system.stringcomparer). A dictionary with case-insensitive keys needs nothing else (the custom provider in my [configuration post](https://pavle.codes/blog/configuration-in-dotnet-sources-providers-precedence/#custom-configuration-providers) builds its keys this way):

```csharp
var headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
    ["Content-Type"] = "application/json"
};

Console.WriteLine(headers["content-type"]); // application/json
```

My rule of thumb:

- **`Ordinal` / `OrdinalIgnoreCase`** for identifiers, keys, file paths, URLs, headers and anything a machine reads.
- **`CurrentCulture`** only for text you sort or show to users.

## Slice strings with ReadOnlySpan<char>

Here's a typical way to pull the parts out of an order number:

```csharp
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>`](https://learn.microsoft.com/en-us/dotnet/api/system.readonlyspan-1) is a view over existing memory. Slicing it moves a pointer and a length; nothing gets copied:

```csharp
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>`](https://learn.microsoft.com/en-us/dotnet/api/system.readonlymemory-1) 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:

```csharp
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:

```csharp
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`](https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo.invariantculture):

```csharp
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`](https://learn.microsoft.com/en-us/dotnet/api/system.string.create) with a culture:

```csharp
string fixedLine = string.Create(
    CultureInfo.InvariantCulture,
    $"{sku},{price}");

Console.WriteLine(fixedLine); // ABC-1,1234.5
```

Two more rules:

- **For comparisons, use `Ordinal`, not `InvariantCulture`.** The invariant culture is for formatting and parsing; the first tip covers comparing.
- **[`InvariantGlobalization`](https://learn.microsoft.com/en-us/dotnet/core/runtime-config/globalization)** (`<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 like `de-DE` then throws `CultureNotFoundException`, 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`:

```csharp
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](https://pavle.codes/blog/resource-expansion-aspnet-core/), but it adds up over a large file.

[`MemoryExtensions.Split`](https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.split) works on a span. Instead of strings, it writes `Range` values that point into the original line:

```csharp
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:

```csharp
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:

```csharp
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:

```csharp
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](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated), so there's no hidden boxing.

**Concatenation** is fine for a few pieces in one expression:

```csharp
string firstName = "Alice";
string lastName = "Smith";

string fullName = firstName + " " + lastName;
```

The compiler turns it into a single [`string.Concat`](https://learn.microsoft.com/en-us/dotnet/csharp/how-to/concatenate-multiple-strings) call.

**[`StringBuilder`](https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder)** is for loops, or whenever you don't know the number of pieces upfront:

```csharp
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`](https://learn.microsoft.com/en-us/dotnet/api/system.string.join)** is for a collection with a separator:

```csharp
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`](https://learn.microsoft.com/en-us/dotnet/api/system.text.compositeformat) and reuse it:

```csharp
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:

```csharp
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<T>

A typical check for invalid file name characters:

```csharp
string fileName = "report:2026?.pdf";

bool hasInvalid = fileName.IndexOfAny(['<', '>', ':', '"', '/', '\\', '|', '?', '*']) >= 0;
```

[`SearchValues<T>`](https://learn.microsoft.com/en-us/dotnet/api/system.buffers.searchvalues-1) analyzes the set of values once and picks the fastest search strategy for it, often vectorized. Create it once and reuse it:

```csharp
public static class FileNameRules
{
    private static readonly SearchValues<char> InvalidChars =
        SearchValues.Create("<>:\"/\\|?*");

    public static bool HasInvalidChars(string fileName) =>
        fileName.AsSpan().ContainsAny(InvalidChars);
}
```

```csharp
Console.WriteLine(FileNameRules.HasInvalidChars(fileName));     // True
Console.WriteLine(FileNameRules.HasInvalidChars("report.pdf")); // False
```

It works for whole words too. A simple spam check:

```csharp
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`:

```csharp
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 `SearchValues` in a `static readonly` field. 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:

```csharp
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](https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/large-object-heap) goes to the large object heap, which the garbage collector only cleans up in a full (Gen 2) collection.

.NET 11 added [`StringStream`](https://learn.microsoft.com/en-us/dotnet/api/system.io.stringstream). It reads a string (or `ReadOnlyMemory<char>`) as a stream and encodes it in small chunks as it goes:

```csharp
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:

```csharp
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](https://pavle.codes/blog/net-11/).

## Use regular expressions when you need to match a pattern

Regex often ends up in checks like this:

```csharp
string orderNumber = "ORD-2026-000123";

bool isOrder = Regex.IsMatch(orderNumber, "^ORD-");
```

A plain string method does the same job and is easier to read:

```csharp
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](https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-source-generators) for it: it compiles the pattern into C# at build time, so there's no parsing at runtime:

```csharp
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);
}
```

```csharp
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](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.cachesize). 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:

```csharp
public static partial class Patterns
{
    [GeneratedRegex(@"^(a+)+$", RegexOptions.None, matchTimeoutMilliseconds: 100)]
    public static partial Regex Nested();
}
```

```csharp
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`](https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-options) 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:

````markdown
---
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.
````
