Create a case insensitive “Contains(string)”

HomeC#

Create a case insensitive “Contains(string)”

Make text be “typed out” effect in C#
How to escape braces in a format string in C#
Building a String Encryption/Decryption Class in C#

C# is a case sensitive language, and there are occasions where handling strings can be difficult, especially when it relates to casing of the string, but there are options out there that, you can define a new extension method.

public static class StringExtensions
{
    public static bool Contains(this string source, string toCheck, StringComparison comp)
    {
        return source?.IndexOf(toCheck, comp) >= 0;
    }
}

The method has available a null propagation “?” for older versions that don’t support it use this

if (source == null) return false;
return source.IndexOf(toCheck, comp) >= 0;

And to use the extension do the following

string title = "STRING";
bool contains = title.Contains("string", StringComparison.OrdinalIgnoreCase);

 

COMMENTS

DISQUS: 0