Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# String StartsWith and EndsWith Usage

Learn how to use C# StartsWith and EndsWith methods for string prefix and suffix checks, including overloads, StringComparison, culture considerations, and practical examples.

~4 min readC#
#String Methods#C# Programming#String Comparison#Text Processing
C# string prefix and suffix comparison with StartsWith and EndsWith methods

The StartsWith and EndsWith methods on the C# String class let you test whether a string begins with a specified prefix or ends with a specified suffix. This article covers their syntax, overloads, comparison behavior, culture considerations, edge cases, and practical examples.

Basic Syntax

The simplest overload takes a single string argument and returns a bool. By default, the comparison is case-sensitive and uses the current culture.

csharp
string filename = "report_final.pdf"; bool startsWithReport = filename.StartsWith("report"); bool endsWithPdf = filename.EndsWith(".pdf"); Console.WriteLine(startsWithReport); // True Console.WriteLine(endsWithPdf); // True

An important edge case is an empty string argument: both methods return true for string.Empty because the empty string is considered a prefix and a suffix of every string. Do not use these methods to reject an empty prefix. If the value argument is null, both methods throw an ArgumentNullException.

csharp
string text = "hello"; Console.WriteLine(text.StartsWith("")); // True Console.WriteLine(text.EndsWith("")); // True

Using the Overloads for Comparison Control

The default overload is often not the best choice. The overloads that accept a StringComparison value give you explicit control over case sensitivity and culture handling.

csharp
string url = "HTTPS://example.com"; bool startsWithHttps = url.StartsWith("https://", StringComparison.OrdinalIgnoreCase); bool endsWithCom = url.EndsWith(".com", StringComparison.OrdinalIgnoreCase); Console.WriteLine(startsWithHttps); // True Console.WriteLine(endsWithCom); // True

For file paths, URLs, identifiers, and most user input checks, StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase is usually the right choice. These comparisons are faster than culture-sensitive comparisons and do not depend on the machine's culture settings.

Culture-Sensitive vs. Ordinal Comparison

The choice of StringComparison affects both correctness and performance. CurrentCulture and InvariantCulture apply culture-specific rules, which can produce different results on different systems. For example, Turkish culture handles the case mapping of i and I differently from the invariant mappings, so a culture-sensitive case-insensitive comparison can be surprising.

StringComparison ValueCase HandlingCultureUse Case
OrdinalCase-sensitiveNoneFast and culture-invariant; ideal for identifiers, paths, and fixed strings
OrdinalIgnoreCaseCase-insensitiveNoneGood for case-insensitive URI or file-extension checks
CurrentCultureCase-sensitiveCurrent cultureRarely useful for prefix/suffix checks; results can vary by machine
CurrentCultureIgnoreCaseCase-insensitiveCurrent cultureUse only when you have a specific culture requirement
InvariantCultureCase-sensitiveInvariant cultureLocale-aware comparisons that need a stable culture
InvariantCultureIgnoreCaseCase-insensitiveInvariant cultureRarely needed for prefix/suffix checks

For most prefix and suffix checks, prefer StringComparison.Ordinal or OrdinalIgnoreCase. This keeps behavior predictable across environments and avoids the overhead of culture-specific rules.

Practical Examples: File Processing and URL Validation

A common use case is checking file extensions. To accept a file regardless of case, use EndsWith with OrdinalIgnoreCase.

csharp
string file = "data.TXT"; if (file.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)) { // Process as a text file }

Another common scenario is allowing only HTTPS URLs. StartsWith checks only the beginning; it does not validate the rest of the URL structure. For full URL validation, use Uri or a regular expression, but for simple prefix checks StartsWith is sufficient.

csharp
bool IsHttpsUrl(string url) { return url.StartsWith("https://", StringComparison.OrdinalIgnoreCase); }

Performance Considerations

For ordinal comparisons, the work is roughly proportional to the length of the prefix or suffix being tested, so short checks are cheap. Culture-sensitive comparisons can be slower because they apply collation and casing rules. If you call these methods many times in a loop, use StringComparison.Ordinal or OrdinalIgnoreCase unless you have a specific culture requirement.

Also avoid manual checks such as Substring followed by == when you only need to test a prefix or suffix. Substring allocates a new string, while StartsWith and EndsWith do not.

Edge Cases and Common Pitfalls

A null value argument causes ArgumentNullException. An empty value returns true for both methods. If the target string is null, calling an instance method on it throws a NullReferenceException, so null-check before calling these methods when the target can be null.

csharp
string? value = null; if (value?.StartsWith("a") == true) { // value is not null and starts with "a" }

Another pitfall is relying on the default culture-sensitive comparison for programmatic identifiers. For example, checking whether a file name starts with a particular ASCII prefix may fail or behave differently under certain culture settings. Specify an ordinal comparison explicitly for these strings.

When to Use StartsWith and EndsWith vs. Other Approaches

Use StartsWith and EndsWith when you need to match a fixed prefix or suffix. If you need to locate a value anywhere in the string, use Contains or IndexOf. If you need wildcard or pattern matching, a regular expression is more flexible but more expensive. For fixed boundary matches, StartsWith and EndsWith are efficient and readable.

Advanced Scenario: Combining StartsWith and EndsWith

You can combine these checks to validate a fixed prefix and suffix without parsing the entire string.

csharp
bool IsValidReportName(string name) { return name.StartsWith("report_", StringComparison.OrdinalIgnoreCase) && name.EndsWith("_2024.csv", StringComparison.OrdinalIgnoreCase); }

This works well when you only need to test the ends of the string. If the middle portion also needs validation, combine these checks with splitting, IndexOf, or a more complete pattern.

Compatibility Notes

StartsWith and EndsWith are available in all current .NET implementations, including .NET Framework, .NET Core, and .NET 5+. The StringComparison overloads have been available since .NET Framework 2.0, so they work in virtually any modern .NET project. Ordinal comparisons behave consistently across platforms.

Because the default overload uses the current culture, the same code can produce different results on machines with different culture settings. In web applications and other deployment environments, specify a StringComparison explicitly so behavior does not depend on the server's culture.

By choosing the right overload and comparison rule, you can use StartsWith and EndsWith to write clear, predictable string checks.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.