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#.
| Feature | Contains | IndexOf |
|---|---|---|
| Return Type | bool (true/false) | int (position or -1) |
| Purpose | Check if substring exists | Find position of substring |
| Case Sensitivity | Depends on overload, default is case-sensitive | Depends on overload, default is case-sensitive |
| Use Case | Simple existence check | Need substring index or position |
| Performance | Slightly faster for existence check | More work to find index |
| Null Handling | Throws ArgumentNullException if argument is null | Throws 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
string text = "Hello, world!"; bool hasHello = text.Contains("Hello"); bool hasBye = text.Contains("Bye"); System.Console.WriteLine(hasHello); // True System.Console.WriteLine(hasBye); // False
IndexOf Equivalent
string text = "Hello, world!"; int indexHello = text.IndexOf("Hello"); int indexBye = text.IndexOf("Bye"); System.Console.WriteLine(indexHello); // 0 System.Console.WriteLine(indexBye); // -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.Contains for simple existence checks and IndexOf to find substring location.IndexOf can search for characters or substrings; Contains only for substrings.