0
0
CsharpComparisonBeginner · 3 min read

Contains vs IndexOf in C#: Key Differences and Usage

Contains checks if a substring exists in a string and returns a boolean, while IndexOf returns the position of the substring or -1 if not found. Use Contains for simple existence checks and IndexOf when you need the exact location.
⚖️

Quick Comparison

Here is a quick comparison of Contains and IndexOf methods in C#.

FeatureContainsIndexOf
Return Typebool (true/false)int (position or -1)
PurposeCheck if substring existsFind position of substring
Case SensitivityDepends on overload, default is case-sensitiveDepends on overload, default is case-sensitive
Use CaseSimple existence checkNeed substring index or position
PerformanceSlightly faster for existence checkMore work to find index
Null HandlingThrows ArgumentNullException if argument is nullThrows ArgumentNullException if argument is null
⚖️

Key Differences

The Contains method returns a bool indicating whether the specified substring exists anywhere in the string. It is straightforward and useful when you only need to know if the substring is present or not.

On the other hand, IndexOf returns the zero-based index of the first occurrence of the substring. If the substring is not found, it returns -1. This method is helpful when you need to know the exact position of the substring within the string.

Both methods are case-sensitive by default but have overloads that allow case-insensitive searches using StringComparison. Also, IndexOf can be used to search for characters or substrings, while Contains only works with substrings.

💻

Contains Example

csharp
string text = "Hello, world!";
bool hasHello = text.Contains("Hello");
bool hasBye = text.Contains("Bye");

System.Console.WriteLine(hasHello); // True
System.Console.WriteLine(hasBye);   // False
Output
True False
↔️

IndexOf Equivalent

csharp
string text = "Hello, world!";
int indexHello = text.IndexOf("Hello");
int indexBye = text.IndexOf("Bye");

System.Console.WriteLine(indexHello); // 0
System.Console.WriteLine(indexBye);   // -1
Output
0 -1
🎯

When to Use Which

Choose Contains when you only need to check if a substring exists in a string, as it is simple and clear. Use IndexOf when you need the position of the substring for further processing, like extracting or replacing parts of the string.

If you want to perform case-insensitive checks, both methods support overloads with StringComparison. For performance, Contains is slightly faster when you only need a yes/no answer.

Key Takeaways

Contains returns true/false if substring exists; IndexOf returns position or -1.
Use Contains for simple existence checks and IndexOf to find substring location.
Both methods are case-sensitive by default but support case-insensitive options.
IndexOf can search for characters or substrings; Contains only for substrings.
Choose based on whether you need a boolean or an index for your string operation.