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.
Example. 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.
Here In this program we call Contains 3 times. The string "abcdef" is tested with Contains.
Tip To test for strings in a case-insensitive way, try passing OrdinalIgnoreCase to the Contains() method.
Note Internally contains calls IndexOf. Thus Contains offers no performance advantage over IndexOf.
Note 2 With 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 extension. This program tests the Contains extension method, which is a separate Contains from the string method. The extension method can be used on many types.
Info In this example, the first Contains call specifies the type parameter int in the angle brackets.
And This tells the C# compiler to select the extension method version of 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.
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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 27, 2023 (rewrite).