dennisdoomen / CSharpGuidelines

A set of coding guidelines for C# 9.0, design principles and layout rules for improving the overall quality of your code development.
https://www.csharpcodingguidelines.com
Other
745 stars 272 forks source link

AV1570: Update for is-patterns #106

Closed bkoelman closed 7 years ago

bkoelman commented 7 years ago

Existing rule:

Always check the result of an as operation (AV1570) 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.

New language features to consider:

class RemoteUser : IUser { }

class Example { void Test(IUser user) { var remoteUser = user as RemoteUser; // ~~~~~~ Resharper: Use pattern matching

    if (remoteUser != null)
    {
        // ...
    }
}

}

which is then changed to:
```csharp
if (user is RemoteUser remoteUser)

I think we should remove this rule, because it advocates outdated language usage.

Aside from that, the description is incorrect: "If you use 'as' to obtain a certain interface reference from an object..." should be reversed. An object either implements the interface, which makes the test redundant -or- the compiler issues an error because no conversion exists. The text should be: "If you use 'as' to safely upcast an interface reference to a certain object..."

dennisdoomen commented 7 years ago

Agreed. This is also the only example of the new pattern matching feature that I actually like ;-)