diff --git a/Src/Cheatsheet/Cheatsheet.md b/Src/Cheatsheet/Cheatsheet.md index 28208cd..9c38a59 100644 --- a/Src/Cheatsheet/Cheatsheet.md +++ b/Src/Cheatsheet/Cheatsheet.md @@ -91,7 +91,7 @@ NOTE: Requires Markdown Extra. See http://michelf.ca/projects/php-markdown/extra * Don’t allow methods and constructors with more than three parameters (AV1561) * Don’t use `ref` or `out` parameters (AV1562) * Avoid methods that take a `bool` flag (AV1564) -* Always check the result of an `as` operation (AV1570) +* Prefer `is` patterns over `as` operations (AV1570) * Don’t comment-out code (AV1575)
diff --git a/Src/Guidelines/1500_MaintainabilityGuidelines.md b/Src/Guidelines/1500_MaintainabilityGuidelines.md index 068e372..2afe245 100644 --- a/Src/Guidelines/1500_MaintainabilityGuidelines.md +++ b/Src/Guidelines/1500_MaintainabilityGuidelines.md @@ -408,8 +408,21 @@ Often, a method taking such a flag is doing more than one thing and needs to be ### Don't use parameters as temporary variables (AV1568) ![](images/3.png) Never use a parameter as a convenient variable for storing temporary state. Even though the type of your temporary variable may be the same, the name usually does not reflect the purpose of the temporary variable. -### Always check the result of an `as` operation (AV1570) ![](images/1.png) -If you use `as` to obtain a certain interface reference from an object, always ensure that this operation does not return `null`. Failure to do so may cause a `NullReferenceException` at a much later stage if the object did not implement that interface. +### Prefer `is` patterns over `as` operations (AV1570) ![](images/1.png) + +If you use 'as' to safely upcast an interface reference to a certain type, always verify that the operation does not return `null`. Failure to do so may cause a `NullReferenceException` at a later stage if the object did not implement that interface. +Pattern matching syntax prevents this and improves readability. For example, instead of: + + var remoteUser = user as RemoteUser; + if (remoteUser != null) + { + } + +write: + + if (user is RemoteUser remoteUser) + { + } ### Don't comment out code (AV1575) ![](images/1.png) Never check in code that is commented out. Instead, use a work item tracking system to keep track of some work to be done. Nobody knows what to do when they encounter a block of commented-out code. Was it temporarily disabled for testing purposes? Was it copied as an example? Should I delete it?