Case insensitive ‘Contains(string)’ in C# ?

To perform a case-insensitive check for a substring in C#, you can use one of the following methods:

1. Using IndexOf with StringComparison.OrdinalIgnoreCase

This is the most efficient and reliable approach for all .NET versions.

public static bool ContainsCaseInsensitive(string source, string substring)
{
    return source.IndexOf(substring, StringComparison.OrdinalIgnoreCase) >= 0;
}

// Usage:
string mainString = "Hello World";
bool exists = ContainsCaseInsensitive(mainString, "hello"); // true

2. Using ToLower() or ToUpper()

Convert both strings to the same case (less efficient due to string allocation):

bool exists = mainString.ToLower().Contains("hello".ToLower()); // true
// Or
bool exists = mainString.ToUpper().Contains("HELLO".ToUpper()); // true

Note: Use ToLowerInvariant()/ToUpperInvariant() to avoid culture-specific behavior:

bool exists = mainString
    .ToLowerInvariant()
    .Contains(substring.ToLowerInvariant());

3. .Contains() with StringComparison (Modern .NET)

In .NET Core 3.0+ or .NET 5+, use the Contains overload with StringComparison:

bool exists = mainString.Contains("hello", StringComparison.OrdinalIgnoreCase); // true

4. Extension Method (Reusable)

Create a reusable extension method for cleaner code:

public static class StringExtensions
{
    public static bool ContainsCaseInsensitive(this string source, string substring)
    {
        return source.Contains(substring, StringComparison.OrdinalIgnoreCase);
    }
}

// Usage:
bool exists = mainString.ContainsCaseInsensitive("hello"); // true

Key Notes

  • Performance: IndexOf with StringComparison.OrdinalIgnoreCase is optimal for older .NET versions.
  • Modern Frameworks: Use the built-in .Contains with StringComparison for simplicity.
  • Culture Sensitivity:
  • Use StringComparison.OrdinalIgnoreCase for case-insensitive checks (culture-agnostic).
  • Use StringComparison.CurrentCultureIgnoreCase for culture-aware checks.

Why Avoid ToLower()/ToUpper()?

  • Creates new strings, which can impact performance for large strings.
  • Culture-specific edge cases (e.g., Turkish i/İ issues).

Summary

MethodBest ForFramework Support
IndexOf + StringComparisonAll .NET versions.NET Framework 2.0+
.Contains + StringComparisonModern .NET (Core 3.0+, .NET 5+).NET Core 3.0+
ToLower()/ToUpper()Simple cases (not recommended)All versions

Choose the method that aligns with your framework version and performance needs!

Leave a Reply

Your email address will not be published. Required fields are marked *