Jonathan Siegel
Jonathan Siegel

Reputation: 13

Build failure when using some String.IndexOf overrides

When I try to use String.IndexOf(string value, StringComparer comparisonType), I get a build failure. This seems like an environment issue, but I tried reinstalling Visual Studio and it still fails. I am using .NET 4.5.2, and Intellisense is giving me the option of String.IndexOf(string value, StringComparer comparisonType)

namespace ConsoleApplication1 {
    class Program {
        static void Main(string[] args) {
            string test = "TEST";
            string test2 = "t";
            test.IndexOf(test2, StringComparer.OrdinalIgnoreCase); // Causes build failure.
        }
    }
}

I get the build errors:

error CS1503: Argument 1: cannot convert from 'string' to 'char'

error CS1503: Argument 2: cannot convert from 'System.StringComparer' to 'int'

It is clearly trying to use the String.IndexOf(char value, int startIndex) function.

I tested this on .NET Fiddle and it works, so right now I feel like I'm missing something obvious...

Thanks.

Upvotes: 0

Views: 206

Answers (2)

sandokanfirst
sandokanfirst

Reputation: 11

StringComparer is an abstract class. Replace it with StringComparison, and cast that to int:

test.IndexOf(test2, (int)StringComparison.OrdinalIgnoreCase);

That way the code should compile.

Upvotes: 0

SA3709
SA3709

Reputation: 322

Looking at the Microsoft documentation, IndexOf uses the StringComparison enum, while you are using the StringComparer object. Try switching to StringComparison.OrdinalIgnoreCase.

Upvotes: 2

Related Questions