John Kaster John Kaster - 3 months ago 10
C# Question

Why does the C# compiler say that string does not have a `Contains` method

Why does the C# compiler say that string does not have a

Contains
method?


  • the
    errors
    object is
    List<Error>

  • Error.Message
    is
    string



For this statement

Assert.True(errors.Any(e => e.Message.Contains("hash value",
StringComparison.OrdinalIgnoreCase)));


the compiler says:


'string' does not contain a definition for 'Contains' and the best extension method overload
System.Linq.Queryable.Contains<TSource>(System.Linq.IQueryable<TSource>, TSource, System.Collections.Generic.IEqualityComparer<TSource>)
has some invalid arguments


And for this statement, the compiler is happy:

Assert.True(errors.Any(e => e.Message.IndexOf("hash value",
StringComparison.OrdinalIgnoreCase) >= 0));

Answer

Is the C# compiler getting confused about which Contains to use, or am I?

You are.

The right method is IndexOf(), not Contains(). There is only one string.Contains() overload (if you could call it that), and it doesn't take a StringComparison parameter.

Comments