Use Contains to check if a string contains something

This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

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