Search code examples
c#stringcompiler-errorscontainsignore-case

string.contains - no overload for contains takes 2 arguments


I'm trying to use the ignore case option for Contains, and I get this error:

CS1501  No overload for method 'Contains' takes 2 arguments 

This is the code line:

item.buildMach.Contains("co.net", StringComparison.CurrentCultureIgnoreCase)

Hovering over Contains, intellisense does say it has 2 overloads, and it looks like it knows it has this second arg.
overload with 2 args

I'm trying to do what Mathieu Renda has in his solution for this: contains - ignore case

What do I need to do to fix this error and use the ignore case?

This project has target framework of .net framework 4.7.2.

An example that is reproducible:

"str".Contains("sT", StringComparison.OrdinalIgnoreCase);

Has the error, no overload for method 'Contains' takes 2 arguments.

I'm trying what Mathieu Renda case insensitive contains uses but get this error.


Solution

  • The overload of Contains taking StringComparison was added in .NET Core 2.1 and never ported back to .NET Framework. However it is quite simple to replace it with no lost efficiency:

    item.buildMach.IndexOf("co.net", StringComparison.CurrentCultureIgnoreCase) != -1
    

    You can also turn it into an extension method:

    static class StringExtensions
    {
        public static bool Contains(this string str, string value, StringComparison comparisonType)
        {
            return str.IndexOf(value, comparisonType) != -1;
        }
    }
    

    Also consider using OrdinalIgnoreCase if you don't need language-aware comparisons, since it is much faster.