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.

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.
string filename = "report_final.pdf";
bool startsWithReport = filename.StartsWith("report");
bool endsWithPdf = filename.EndsWith(".pdf");
Console.WriteLine(startsWithReport); // True
Console.WriteLine(endsWithPdf); // TrueAn 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.
string text = "hello";
Console.WriteLine(text.StartsWith("")); // True
Console.WriteLine(text.EndsWith("")); // TrueUsing 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.
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); // TrueFor 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 Value | Case Handling | Culture | Use Case |
|---|---|---|---|
Ordinal | Case-sensitive | None | Fast and culture-invariant; ideal for identifiers, paths, and fixed strings |
OrdinalIgnoreCase | Case-insensitive | None | Good for case-insensitive URI or file-extension checks |
CurrentCulture | Case-sensitive | Current culture | Rarely useful for prefix/suffix checks; results can vary by machine |
CurrentCultureIgnoreCase | Case-insensitive | Current culture | Use only when you have a specific culture requirement |
InvariantCulture | Case-sensitive | Invariant culture | Locale-aware comparisons that need a stable culture |
InvariantCultureIgnoreCase | Case-insensitive | Invariant culture | Rarely 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.
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.
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.
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.
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 toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# Dispose vs Destructor: Key Differences Explained
c# dispose vs destructor: Understand the difference between Dispose and destructors in C#, when each runs, and how to manage unmanaged resources correctly.
C# Variable Declaration: Syntax and Practical Usage
Learn how to declare variables in C# with explicit types, var, and nullable annotations, and understand how defaults, scope, and readability affect your choices.
C# Primary Constructors for Classes: Syntax and Usage
Learn how to use C# primary constructors for classes: syntax, initialization, dependency injection, and limitations with practical examples.
C# IComparer: Custom Sorting with IComparer<T>
Learn how to implement IComparer<T> in C# to define custom sort order for arrays and lists, handle nulls, and avoid common performance pitfalls.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.