Contains
This C# method searches strings. It checks if one substring is contained in another. It also provides a case-sensitive ordinal method for checking string
contents.
Contains
returns true or false, not an index. It is the same as calling IndexOf
and testing for -1 on your own. But Contains
can be clearer to read.
Contains
is an instance method—you can call it on a specific string
in your program. It has a bool
result, which is true if the parameter is found, and false if it is not found.
Contains
3 times. The string
"abcdef" is tested with Contains
.OrdinalIgnoreCase
to the Contains()
method.IndexOf
. Thus Contains
offers no performance advantage over IndexOf
.StringComparison.Ordinal
, all language characters are treated the same—regardless of the system locale.using System; string value = "abcdef"; if (value.Contains("abc")) { Console.WriteLine("CONTAINS abc"); } if (!value.Contains("xyz")) { Console.WriteLine("DOES NOT CONTAIN xyz"); } if (value.Contains("ABC", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("CONTAINS ABC ignore case"); }CONTAINS abc DOES NOT CONTAIN xyz CONTAINS ABC ignore case
Contains
extensionThis program tests the Contains
extension method, which is a separate Contains
from the string
method. The extension method can be used on many types.
Contains
call specifies the type parameter int
in the angle brackets.Contains
, not the List
type's version.using System; using System.Collections.Generic; using System.Linq; var list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Use extension method. bool a = list.Contains<int>(7); // Use instance method. bool b = list.Contains(7); Console.WriteLine(a); Console.WriteLine(b);True True
List
Contains
There is also a Contains
method on the C# List
type. This method can be useful for searching for a value within a List
.
The simplest method to perform a task is often the best one. Contains
is a simplified version of IndexOf
. It allows you to easily check whether a string
is contained in another.