This only checks the end. For a match anywhere, use Contains.
Library declarations
C#
public bool EndsWith(string value);
public bool EndsWith(string value, StringComparison comparisonType);
Parameters
Parameter
Description
value
Required. The suffix to look for. Do not pass null.
comparisonType
Optional. Rules for case and culture, such as OrdinalIgnoreCase.
Return Value
Return Value
Description
true
The string ends with the suffix.
false
The string does not end with the suffix.
C# Examples
Example 1 — Basic EndsWith() Check
Ask whether a greeting ends with "World", then print the boolean result.
C#
using System;
class Program {
static void Main() {
string text = "Hello, World";
bool ends = text.EndsWith("World");
Console.WriteLine($"Ends with \"World\"? {ends}");
if (ends) {
Console.WriteLine("Suffix matched.");
}
}
}
Output
Ends with "World"? True
Suffix matched.
How It Works
Call on the string.text.EndsWith("World") checks only the trailing characters.
Compare the suffix. Default rules are ordinal and case-sensitive.
Get a bool.ends is true because the string ends with "World".
Use in an if. Clear yes/no logic for suffix validation.
Example 2 — Case-Sensitive vs Ignore Case
File extensions often vary in casing. Default EndsWith misses .PDF when you search for .pdf.
C#
using System;
class Program {
static void Main() {
string file = "report.PDF";
bool sensitive = file.EndsWith(".pdf");
bool ignore = file.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase);
Console.WriteLine($"Case-sensitive: {sensitive}");
Console.WriteLine($"Ignore case: {ignore}");
}
}
Output
Case-sensitive: False
Ignore case: True
How It Works
Default is case-sensitive.".PDF" ≠ ".pdf" → false.
Pass StringComparison.OrdinalIgnoreCase folds case without culture-specific letter rules.
Extension matches. Ignore-case returns true.
Best practice. Prefer ordinal ignore-case for paths and file types—fast and stable across machines.
Example 3 — Filter Files by Extension
Keep only list entries that end with .cs—a common pattern for simple file filters.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var files = new List<string> {
"Program.cs",
"readme.md",
"Helpers.CS",
"data.json"
};
foreach (string file in files) {
if (file.EndsWith(".cs", StringComparison.OrdinalIgnoreCase)) {
Console.WriteLine(file);
}
}
}
}
Output
Program.cs
Helpers.CS
How It Works
Loop the list. Each file is a candidate name.
Test the suffix. Ignore-case so .CS matches .cs.
Print matches only. Markdown and JSON names are skipped.
Need a prefix? Switch to StartsWith for schemes like "http".
Frequently Asked Questions
EndsWith() checks whether a string ends with a given suffix and returns true or false.
value is required. comparisonType is optional for case and culture rules.
true when the suffix matches the end, false otherwise.
Yes by default. Pass StringComparison.OrdinalIgnoreCase to ignore case.
EndsWith() only checks the end. Contains() looks anywhere in the string.