C# String Contains() Method

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

What You’ll Learn

The instance method Contains() answers a simple question: does this string include a given piece of text? It returns true or false—perfect for validation, filtering, and conditional logic. You call it on the string being searched, not as a static method.

01

Instance Method

text.Contains("key")

02

bool Return

true or false.

03

Case Sensitive

Default overload.

04

StringComparison

Ignore case option.

05

vs IndexOf()

When to use each.

06

Null Safety

Search value not null.

Definition and Usage

In C#, Contains() checks whether a substring appears anywhere within a string. It is an instance method, so you invoke it on the text you want to search: sentence.Contains("world").

The method returns a bool—no index, no new string. That makes it ideal for straightforward conditions like “does this email contain an @ symbol?” or “does this log line mention ERROR?” When you need the position of a match, use IndexOf() instead.

💡
Beginner Tip

The default Contains(string) overload is case-sensitive and uses ordinal comparison. Searching for "Fun" inside "C# is fun!" returns false. For case-insensitive checks, pass StringComparison.OrdinalIgnoreCase to the two-argument overload.

📝 Syntax

Common overloads on System.String:

C#
public bool Contains(string value);
public bool Contains(string value, StringComparison comparisonType);
public bool Contains(char value);  // .NET 5+

Parameters

  • value — the substring (or character) to search for. Must not be null for string overloads.
  • comparisonType — how to compare: e.g. Ordinal, OrdinalIgnoreCase, CurrentCultureIgnoreCase.

Return Value

true if the substring is found anywhere in the string; false otherwise. Searching for an empty string "" always returns true.

⚡ Quick Reference

GoalCode
Basic substring checktext.Contains("fun")
Ignore casetext.Contains("fun", StringComparison.OrdinalIgnoreCase)
Check for a characteremail.Contains('@')
Negated condition!text.Contains("spam")
Need match positiontext.IndexOf("key") >= 0
Simple check
msg.Contains("error")

Case-sensitive

Ignore case
Contains(s, OrdinalIgnoreCase)

Recommended

Single char
path.Contains('\\')

.NET 5+

Find index
text.IndexOf("key")

Position needed

Examples Gallery

Run with dotnet run. Each example shows a practical way to use Contains()—from basic checks to case rules, filtering, and comparison with IndexOf().

📚 Getting Started

Check whether a substring exists in a sentence.

Example 1 — Basic Contains() Usage

Search for the word "fun" inside a greeting string and print the result.

C#
using System;

class Program {
    static void Main() {
        string mainString   = "C# programming is fun!";
        string searchString = "fun";

        bool found = mainString.Contains(searchString);

        Console.WriteLine($"Does the string contain '{searchString}'? {found}");
    }
}

How It Works

Contains scans mainString for an exact, case-sensitive match of "fun". Because "fun" appears inside "fun!", the method returns true. The original string is unchanged.

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.Contains("world"));  // false — case mismatch
        Console.WriteLine(text.Contains("World"));  // true  — exact match
        Console.WriteLine(text.Contains("o W"));    // true  — middle substring
    }
}

How It Works

"world" fails because W is uppercase in the source text. Contains() looks for a contiguous sequence of characters—it can match in the middle of a string, not only at the start or end.

📈 Practical Patterns

Case-insensitive search, filtering, and alternatives.

Example 3 — Case-Insensitive Search

Use the StringComparison overload instead of manually calling ToLower().

C#
using System;

class Program {
    static void Main() {
        string email = "User@Example.COM";

        bool hasAt = email.Contains(
            "@",
            StringComparison.OrdinalIgnoreCase);

        bool hasDomain = email.Contains(
            "example.com",
            StringComparison.OrdinalIgnoreCase);

        Console.WriteLine($"Has @ symbol: {hasAt}");
        Console.WriteLine($"Has example.com: {hasDomain}");
    }
}

How It Works

StringComparison.OrdinalIgnoreCase compares characters without regard to letter casing and without culture-specific sorting rules. It is the preferred approach for identifiers, file extensions, and protocol-style text.

Example 4 — Filter Items with Contains()

Keep only filenames that include a specific keyword—a common real-world pattern.

C#
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        string[] files = {
            "report-2024.pdf",
            "notes.txt",
            "report-draft.pdf",
            "photo.jpg"
        };

        List<string> reports = new List<string>();

        foreach (string file in files) {
            if (file.Contains("report", StringComparison.OrdinalIgnoreCase)) {
                reports.Add(file);
            }
        }

        Console.WriteLine("Report files:");
        foreach (string name in reports) {
            Console.WriteLine("  - " + name);
        }
    }
}

How It Works

Each filename is tested with Contains. Only strings that include "report" (any casing) are added to the list. With LINQ you could write the same logic as files.Where(f => f.Contains("report", StringComparison.OrdinalIgnoreCase)).

Example 5 — Contains() vs IndexOf()

Both can answer “is it there?”—but IndexOf() also tells you where.

C#
using System;

class Program {
    static void Main() {
        string url = "https://codetofun.com/c-sharp";

        bool viaContains = url.Contains("/c-sharp");
        int  viaIndexOf  = url.IndexOf("/c-sharp");

        Console.WriteLine($"Contains: {viaContains}");
        Console.WriteLine($"IndexOf:  {viaIndexOf} (position)");

        if (viaIndexOf >= 0) {
            string section = url.Substring(viaIndexOf + 1);
            Console.WriteLine($"Section path: {section}");
        }
    }
}

How It Works

Contains returns a simple true/false. IndexOf returns the zero-based start index, or -1 when not found. Choose Contains for readability in conditions; choose IndexOf when you need to slice or replace text around the match.

🚀 Common Use Cases

  • Input validation — check that a password contains digits or special characters.
  • Search and filter — find list items, filenames, or log lines matching a keyword.
  • Feature flags in text — detect tags like [DEBUG] or ERROR: in messages.
  • URL and path checks — verify a path segment or domain fragment is present.
  • Guard clauses — skip processing when required text is missing: if (!data.Contains("id=")) return;

🧠 How Contains() Works

1

You call on a string

Example: text.Contains("key") on the source text.

Input
2

Runtime scans for a match

Characters are compared in order using the chosen comparison rules (ordinal by default).

Search
3

Match found or exhausted

The scan stops at the first successful match or after checking all positions.

Evaluate
=

bool returned

true if the substring appears anywhere; false if not. No new string is created.

📝 Notes

  • Default Contains(string) is ordinal and case-sensitive.
  • Passing null as the search value throws ArgumentNullException.
  • Searching for "" (empty string) always returns true.
  • Prefer StringComparison.OrdinalIgnoreCase over ToLower() for case-insensitive checks—avoid extra string allocations.
  • Contains(char) is available in .NET 5 and later for single-character checks.
  • For “starts with” or “ends with” checks, use StartsWith() or EndsWith() instead—they express intent more clearly.

⚡ Optimization

Contains() is optimized for typical substring searches and is fine for most application code. If you call it repeatedly on the same large string with the same search term inside a hot loop, store the boolean result in a local variable instead of recomputing. For very large text or many patterns, consider Regex.IsMatch or specialized search libraries—but for simple keyword checks, Contains() remains the clearest choice.

Conclusion

The C# Contains() method is the go-to tool when you need a quick yes-or-no answer about whether text includes a substring. It is readable, efficient for everyday use, and pairs well with StringComparison when casing matters.

Practice the examples above, pick the right overload for your comparison rules, then continue to Copy() to learn how to duplicate string content explicitly.

💡 Best Practices

✅ Do

  • Use Contains() for clear yes/no conditions
  • Pass StringComparison.OrdinalIgnoreCase for case-insensitive IDs
  • Validate user input with IsNullOrEmpty before searching
  • Use StartsWith/EndsWith when position matters
  • Switch to IndexOf when you need the match location

❌ Don’t

  • Pass null as the search string
  • Assume default Contains ignores case
  • Call ToLower() on both strings when an overload exists
  • Use Contains when you only care about prefix/suffix
  • Confuse Contains with exact equality (==)

Key Takeaways

Knowledge Unlocked

Five things to remember about Contains()

Use these points whenever you search inside strings in C#.

5
Core concepts
02

bool Return

true or false.

Return
📝 03

Case Sensitive

Default overload.

Default
🔄 04

StringComparison

Ignore case cleanly.

Overload
📍 05

vs IndexOf()

Position when needed.

Alternative

❓ Frequently Asked Questions

Contains() is an instance method that checks whether a substring (or single char) appears inside a string. It returns true if found and false if not. Call it on the string you search in: text.Contains("fun"). The original string is never modified.
text.Contains(value) where value is the substring to find. Overloads accept StringComparison for case/culture rules, or a char in .NET 5+. Example: message.Contains("error", StringComparison.OrdinalIgnoreCase);
It returns bool: true when the substring exists anywhere in the string, false when it does not. It does not return the position—use IndexOf() if you need where the match starts.
The single-argument Contains(string) overload uses ordinal, case-sensitive comparison. For case-insensitive checks, use Contains(value, StringComparison.OrdinalIgnoreCase) or Contains(value, StringComparison.CurrentCultureIgnoreCase).
Passing null as the search value throws ArgumentNullException. The string you call Contains() on can be empty (""), but the search argument must not be null. Use string.IsNullOrEmpty() on user input before searching.
Use Contains() when you only need yes/no—it's clearer in if statements. Use IndexOf() when you need the starting index, want to search from a position, or plan to extract a substring around the match.
Did you know?

Before the Contains(string, StringComparison) overload was added, developers often wrote text.ToLower().Contains(search.ToLower()) for case-insensitive checks. That creates two extra strings in memory. The modern overload avoids those allocations and makes your intent explicit in one readable call.

Keep Building C# String Skills

Master substring search with Contains(), then continue to Copy() for explicit string duplication.

Next: Copy() →

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