C# String EndsWith() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Methods

What You’ll Learn

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.

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).

📝 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.

⚡ Quick Reference

GoalCode
Basic suffix checktext.EndsWith("World")
Ignore casetext.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)
Check last characterpath.EndsWith('/')
Negated condition!name.EndsWith(".tmp")
Check prefix insteadtext.StartsWith("Hello")
Suffix check
file.EndsWith(".cs")

Case-sensitive

Ignore case
EndsWith(s, OrdinalIgnoreCase)

Extensions

Single char
url.EndsWith('/')

.NET 5+

Prefix
text.StartsWith("http")

Start of string

Examples Gallery

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}");
    }
}

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
    }
}

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.

C#
using System;

class Program {
    static void Main() {
        string sampleString = "Hello, World";

        bool caseSensitive = sampleString.EndsWith("world");
        bool ignoreCase    = sampleString.EndsWith(
            "world",
            StringComparison.OrdinalIgnoreCase);

        Console.WriteLine($"Case-sensitive:   {caseSensitive}");
        Console.WriteLine($"Ignore case:      {ignoreCase}");
    }
}

How It Works

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

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}");
    }
}

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.

🚀 Common Use Cases

  • File extension checks — filter or validate .json, .csv, .exe files.
  • 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.

📝 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().

⚡ 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.

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.

💡 Best Practices

✅ Do

  • Use EndsWith() for suffix and extension checks
  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about EndsWith()

Use these points whenever you check string suffixes in C#.

5
Core concepts
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.

Keep Building C# String Skills

Master suffix checks with EndsWith(), then continue to Equals() for full string comparison.

Next: Equals() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful