The instance method EndsWith() checks whether a string’s trailing characters match a given suffix. It returns true or false—ideal for file extensions, URL paths, domain checks, and any logic that depends on how text finishes.
01
Instance Method
text.EndsWith("x")
02
bool Return
true or false.
03
Suffix Only
End of string.
04
Case Sensitive
Default overload.
05
StringComparison
Ignore case option.
06
vs StartsWith
Prefix vs suffix.
Fundamentals
Definition and Usage
In C#, EndsWith() determines whether a string ends with a specified substring (or single character). It is an instance method, so you call it on the text being tested: path.EndsWith(".json").
Unlike Contains(), which searches anywhere in the string, EndsWith() only compares the final characters. That makes it perfect when the suffix position matters—such as verifying a filename ends with .cs or a URL ends with /.
💡
Beginner Tip
The default EndsWith(string) overload is case-sensitive. "file.PDF".EndsWith(".pdf") returns false. For extension checks, use EndsWith(".pdf", StringComparison.OrdinalIgnoreCase).
Foundation
📝 Syntax
Common overloads on System.String:
C#
public bool EndsWith(string value);
public bool EndsWith(string value, StringComparison comparisonType);
public bool EndsWith(char value); // .NET 5+
Parameters
value — the suffix to match at the end of the string. Must not be null for string overloads.
comparisonType — how to compare: e.g. Ordinal, OrdinalIgnoreCase, CurrentCultureIgnoreCase.
Return Value
true if the string ends with the suffix; false otherwise. An empty suffix "" always returns true.
Run with dotnet run. Each example shows a practical way to use EndsWith()—from basic suffix checks to case rules, file filtering, and comparison with StartsWith().
📚 Getting Started
Check whether a string ends with a given suffix.
Example 1 — Basic EndsWith() Usage
Test if "Hello, World" ends with "World".
C#
using System;
class Program {
static void Main() {
string sampleString = "Hello, World";
bool endsWithWorld = sampleString.EndsWith("World");
Console.WriteLine($"Ends with 'World'? {endsWithWorld}");
}
}
📤 Output:
Ends with 'World'? True
How It Works
EndsWith compares the last five characters of sampleString to "World". They match exactly, so the method returns true. It would return false for "orld" alone because the suffix must align with the very end.
Example 2 — Case Sensitivity
See how the default overload treats uppercase and lowercase differently.
C#
using System;
class Program {
static void Main() {
string text = "Hello, World";
Console.WriteLine(text.EndsWith("world")); // false — case mismatch
Console.WriteLine(text.EndsWith("World")); // true — exact match
Console.WriteLine(text.EndsWith("ld")); // true — valid suffix
}
}
📤 Output:
False
True
True
How It Works
"world" fails because W is uppercase in the source. "ld" succeeds because those are the final two characters—the suffix can be shorter than the whole last word.
📈 Practical Patterns
Case-insensitive checks, file filtering, and related methods.
Example 3 — Case-Insensitive Suffix Check
Use StringComparison.OrdinalIgnoreCase for extension-style matching.
The two-argument overload ignores letter casing while still requiring the suffix at the end. This is the recommended approach for file extensions and protocol identifiers on modern .NET.
Example 4 — Filter Files by Extension
Keep only filenames that end with .pdf, regardless of casing.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
string[] files = {
"report.pdf",
"notes.txt",
"photo.PDF",
"draft.docx"
};
List<string> pdfs = new List<string>();
foreach (string file in files) {
if (file.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)) {
pdfs.Add(file);
}
}
Console.WriteLine("PDF files:");
foreach (string name in pdfs) {
Console.WriteLine(" - " + name);
}
}
}
📤 Output:
PDF files:
- report.pdf
- photo.PDF
How It Works
Each filename is tested for a .pdf suffix. photo.PDF matches because casing is ignored. For production file work, also consider Path.GetExtension(file), but EndsWith is clear and beginner-friendly.
Example 5 — EndsWith() vs StartsWith()
Pick the method that matches where you need to test characters.
C#
using System;
class Program {
static void Main() {
string url = "https://codetofun.com/docs/";
bool startsHttps = url.StartsWith("https://");
bool endsSlash = url.EndsWith("/");
bool endsCom = url.EndsWith(".com"); // false — .com is not the suffix
Console.WriteLine($"Starts with https:// : {startsHttps}");
Console.WriteLine($"Ends with / : {endsSlash}");
Console.WriteLine($"Ends with .com : {endsCom}");
}
}
📤 Output:
Starts with https:// : True
Ends with / : True
Ends with .com : False
How It Works
StartsWith checks the beginning; EndsWith checks the end only. The URL ends with /, not .com, because /docs/ follows the domain. Use Contains(".com") if you need the domain anywhere in the string.
URL path validation — ensure paths end with / or a specific segment.
Domain suffix rules — detect .edu, .gov, or regional TLDs at the end.
Input validation — require usernames or codes to end with a digit or pattern.
Guard clauses — skip processing when a required suffix is missing.
🧠 How EndsWith() Works
1
You call on a string
Example: file.EndsWith(".txt") on the source text.
Input
2
Runtime aligns suffix at end
The suffix length is compared against the final characters only.
Align
3
Characters are compared
Using ordinal rules by default, or your chosen StringComparison.
Compare
=
✅
bool returned
true if trailing chars match; false if not. Original string unchanged.
Important
📝 Notes
Default EndsWith(string) is ordinal and case-sensitive.
Passing null as the suffix throws ArgumentNullException.
An empty suffix "" always returns true.
If the suffix is longer than the string, the method returns false.
EndsWith(char) is available in .NET 5+ for single-character suffix checks.
For middle-of-string matches, use Contains() instead of EndsWith().
Performance
⚡ Optimization
EndsWith() is efficient because it only compares the trailing portion of the string—not the entire content. If you test the same suffix repeatedly in a loop, store the boolean result in a local variable. For many file paths, Path.GetExtension() can be an alternative, but EndsWith remains clear and fast for typical suffix checks.
Wrap Up
Conclusion
The C# EndsWith() method is the right tool when you need to know whether text finishes with a specific suffix. It is readable, returns a simple bool, and pairs well with StringComparison for case-insensitive extension checks.
Practice the examples above, choose the correct overload for your comparison rules, then continue to Equals() for full string equality testing.
Pass StringComparison.OrdinalIgnoreCase for file extensions
Validate user input before calling EndsWith()
Use StartsWith() for prefix checks
Consider Path.GetExtension() for file system paths
❌ Don’t
Pass null as the suffix argument
Assume default EndsWith ignores case
Use EndsWith when the match can be anywhere in the string
Confuse suffix match with full string equality
Call ToLower() on both strings when an overload exists
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about EndsWith()
Use these points whenever you check string suffixes in C#.
5
Core concepts
📝01
Instance Method
text.EndsWith("x")
Basics
✅02
bool Return
true or false.
Return
📍03
Suffix Only
End of string.
Scope
🔄04
StringComparison
Ignore case cleanly.
Overload
👈05
vs StartsWith
Prefix vs suffix.
Related
❓ Frequently Asked Questions
EndsWith() checks whether a string ends with a specified suffix. It returns true if the trailing characters match and false if they do not. Call it on the string being tested: filename.EndsWith(".pdf").
text.EndsWith(suffix) for a basic check. Overloads accept StringComparison for case/culture rules, or a char in .NET 5+. Example: url.EndsWith("/", StringComparison.Ordinal);
It returns bool: true when the string ends with the given suffix, false otherwise. It only checks the end—not the middle or start of the string.
The single-argument EndsWith(string) overload uses ordinal, case-sensitive comparison. For case-insensitive suffix checks, use EndsWith(suffix, StringComparison.OrdinalIgnoreCase).
Passing null as the suffix throws ArgumentNullException. The string you call EndsWith() on can be empty, but the suffix argument must not be null. An empty suffix "" always returns true.
Use EndsWith() when you care about the trailing part—file extensions, URL paths ending with a slash, domain suffixes. Use StartsWith() for prefixes like "http://" or country codes at the beginning.
Did you know?
EndsWith() only inspects the tail of a string, so it can stop comparing as soon as the suffix length is checked—unlike Contains(), which may scan the whole string. For long text with a short suffix test, EndsWith is often the clearer and more efficient choice.