Use Contains to check if a string contains something

このページは日本語には対応しておりません。随時翻訳に取り組んでいます。翻訳に関してご質問やご意見ございましたら、お気軽にご連絡ください。

Metadata

ID: csharp-best-practices/indexof-contains

Language: C#

Severity: Info

Category: Best Practices

Description

To check is a string contains a sub-string, use Contains() and do not use proxy functions such as IndexOf.

Non-Compliant Code Examples

class MyClass {
    public static void processString(string s)
    {
        if(strings.IndexOf(s) == -1) {
            // do something
        }

        if(strings.IndexOf(s) < 0) {
            // do something else
        }

        if(strings.IndexOf(s) >= 0) {
            // or do this
        }
    }
}

Compliant Code Examples

class MyClass {
    public static void processString(string s)
    {
        if(!strings.Contains(s)) {
            // do something
        }
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis