roslyn: CS0108 Incorrectly shown with fix that breaks code

Version Used: Visual Studio 2017

Steps to Reproduce: Put this code into C#:

    public class BaseClass {
        public const int PRIORITY = 100;   
    }

    public class DerivedClass : BaseClass {
        public const int PRIORITY = BaseClass.PRIORITY + 100;
    }

You get the following warning: Warning CS0108 ‘DerivedClass.PRIORITY’ hides inherited member ‘BaseClass.PRIORITY’. Use the new keyword if hiding was intended.

If you right-click on the squiggilies and select Quick Actions and Refactorings > Hide base member, it changes the code to look like this:

    public class DerivedClass : BaseClass {
        public const new int PRIORITY = BaseClass.PRIORITY + 100;
    }

The problem is, that code doesn’t compile and now generates 4 errors instead of one warning.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 28 (28 by maintainers)

Commits related to this issue

Most upvoted comments

📝 I’m reserving this for a first-time contributor (or any infrequent non-Microsoft contributor) for the next few days. If you’re a first time contributor and want to try your hand at working on Roslyn, this is a pretty basic code fix which you’ll find implemented in HideBaseCodeFixProvider.AddNewKeywordAction.cs. The tests for this feature are in HideBaseTests.cs.

Holy cow… it also works in VS! 💃 😄

PR: https://github.com/dotnet/roslyn/pull/18399

Note: my preferred way to do this would be as follows:

Use SyntaxGenerator (which you can get from document.GetLanguageService<SyntaxGenerator>(). Then call generator.WithModifiers(d, generator.GetModifiers(d).WithIsConst(true));

SyntaxGenerator is our ‘smart’ syntax modifier. It is supposed to know how to generate syntactically correct code. If it does not place ‘const’ last, it should be fixed to place const last. But once that is workign properly, then anyone can use SyntaxGenerator properly for this sort of thing.