Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override Contains()?

The Contains(...) method for string is case-sensitive. I'd like to override it in order to make it case-INsensitive with the following code (which is stolen from here):

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

However, I don't know where the code should be pasted. Should it be placed inside the same namespace of the class program? Does it need a dedicated class?

like image 832
user1154138 Avatar asked Jan 18 '12 13:01

user1154138


1 Answers

If what you are intending is to create an extension method for the string class, then you need to put it inside some class. To use it, simply make sure you have a using statement specifying a reference to the namespace containing the class.

For example:

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

// ... In some other class ...
using SomeNamespace;

// ...
bool contains = "hello".Contains("ll", StringComparison.OrdinalIgnoreCase);
like image 80
Samuel Slade Avatar answered Oct 05 '22 14:10

Samuel Slade