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

Fix S3242: Rule should not suggest base type for virtual methods #1537

Closed
antoinebj opened this issue Jul 9, 2018 · 1 comment
Closed

Fix S3242: Rule should not suggest base type for virtual methods #1537

antoinebj opened this issue Jul 9, 2018 · 1 comment
Assignees
Labels
Type: False Positive Rule IS triggered when it shouldn't be.
Milestone

Comments

@antoinebj
Copy link

antoinebj commented Jul 9, 2018

Description

The signature of virtual methods can be considered like a contract between the base class and its subclasses.
If the implementation of the base class does not use the most concrete type of a parameter, a subclass might.

I'm facing this issue with a specialized collection type.
I have type B inheriting from type A.
My collection type inherits from Collection<B>, and defines a virtual method that is meant to apply to an item of the collection, so of type B. However the base implementation only accesses members from type A, so rule S3242 kicks in and suggests to take A as parameter. But if I do that, I can imagine that a developer implementing a derived class will go through the first 3 or 4 stages of grief.

Repro steps

  1. Have type B inherit from type A

  2. Create a virtual method with a parameter of type B, but whose implementation only uses members of type A

using System;
using System.Collections.ObjectModel;

namespace NS1
{
    public class A
    {
        public string ParentProperty { get; set; }
    }

    public class B : A
    {
        public string ChildProperty { get; set; }
    }

    public class MyCollection : Collection<B>
    {
        protected virtual string Manipulate(B item) // <- S3242 raised here
        {
            return item.ParentProperty;
        }
    }
}

Expected behavior

Rule should not raise a violation.

Actual behavior

Rule raises a violation.

Related information

  • SonarC# Version 7.2
  • Visual Studio Version 15.7
@duncanp-lseg duncanp-lseg added Type: False Positive Rule IS triggered when it shouldn't be. Community labels Jul 9, 2018
@duncanp-lseg
Copy link
Contributor

Thanks for reporting the issue @antoinebj. I agree that it would be better if the rule didn't raise in this case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Type: False Positive Rule IS triggered when it shouldn't be.
Projects
None yet
Development

No branches or pull requests

4 participants