C# Contains String MethodUse the Contains method on the string type. Examine the implementation of Contains.
This method searches strings. It checks if one substring is contained in another. It also provides a case-sensitive ordinal method for checking string contents.Strings
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.IndexOf
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.Bool
Next: The example program shows that Contains is case-sensitive. It shows how to test the result of Contains.
Test: We call the Test method 2 times. In that method, the output is printed the console.
And: The string "Net" is first tested with Contains. Contains is case-sensitive.
Info: Test() shows how to test Contains for true and false. We can store the result in a bool.True, FalseIf
C# program that uses Contains
static void Main()
Test("Dot Net Perls");
Test("dot net perls");
static void Test(string input)
// See if the string contains 'Net'
bool contains = input.Contains("Net");
// Write the result
Console.Write("Contains 'Net': ");
// See if the string contains 'perls' lowercase
// See if the string contains 'Dot'
Console.WriteLine("Doesn't Contain 'Dot'");
--- Dot Net Perls ---
Contains 'Net': True
--- dot net perls ---
Contains 'Net': False
Doesn't Contain 'Dot'
Contains calls IndexOf. When IndexOf returns -1, the string was not found. When Contains cannot find the string, it returns false. Contains offers no performance advantage.
Tip: In IL Disassembler, we see how Contains is implemented. A screenshot of Contains is provided.IL Disassembler
This refers to a position number. When used with strings, it means that the characters are treated as numbers, not symbols.
And: With StringComparison.Ordinal, all language characters are treated the same—regardless of the system locale.
Performance. Ordinal comparisons on strings are much faster than culture-dependent comparisons. This makes sense because it is easier for the system to compare numbers than symbols.
Summary. 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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.