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.
Fundamentals
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.
Foundation
📝 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.
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}");
}
}
📤 Output:
Does the string contain 'fun'? True
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
}
}
📤 Output:
False
True
True
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().
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);
}
}
}
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}");
}
}
}
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.
Applications
🚀 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.
Important
📝 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.
Performance
⚡ 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.
Wrap Up
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.
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 (==)
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about Contains()
Use these points whenever you search inside strings in C#.
5
Core concepts
🔍01
Instance Method
text.Contains("key")
Basics
✅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.