Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.

Metadata

ID: csharp-best-practices/is-instead-of-as

Language: C#

Severity: Notice

Category: Best Practices

Description

The is keyword in C# is used for checking the compatibility of an object with a given type, and the result of the operation is a Boolean: true if the object is of the given type, and false otherwise. The as operator, on the other hand, performs a type conversion and returns the object if the conversion is successful, or null if it isn’t.

Using the as operator to check for type compatibility can lead to less straightforward and potentially confusing code. It can also have performance implications. When you use as, the runtime performs the type check and the conversion, and if you then use the result in a conditional statement, you’re effectively checking the type twice: once with as, and once with the null check.

How to Remediate

To remediate this error, prefer using the is keyword when the aim is to check for type compatibility. This not only makes the code clearer and more straightforward, but it also eliminates the unnecessary type check, leading to potentially better performance. For instance, instead of if (x as string != null), you should use if (x is string).

Non-Compliant Code Examples

// checking type with the "as" keyword
if (x as string != null)
{
}

Compliant Code Examples

// testing type with is
if (foo is string)
{
}
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 Security

PREVIEWING: guacbot/translation-pipeline