Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AV1570: Update for is-patterns #106

Closed
bkoelman opened this issue Oct 17, 2017 · 1 comment
Closed

AV1570: Update for is-patterns #106

bkoelman opened this issue Oct 17, 2017 · 1 comment

Comments

@bkoelman
Copy link
Contributor

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:

  • is-patterns
    Testing for interface implementation using as nowadays triggers a Resharper refactoring suggestion to replace the expression with an is-pattern. Example:
interface IUser { }

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:

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
Copy link
Owner

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants