I am researching a way to make Visual Studio fire a warning if I override a specific method in a base class but forget to call the base method in the overridden one. E.g:
class Foo
{
[SomeAttributeToMarkTheMethodToFireTheWarning]
public virtual void A() { ... }
}
class Bar : Foo
{
public override void A()
{
// base.A(); // warning if base.A() is not called
// ...
}
}
So far I couldn't find a way and probably it is not possible to make the compiler fire such a warning directly. Any ideas for a way to do it, even if it's a 3rd-party tool or using some API from the new Roslyn .NET compiler platform?
UPDATE:
For example, in AndroidStudio (IntelliJ) if you override onCreate()
in any activity but forget to call the base method super.onCreate()
, you get a warning. That's the behavior I need in VS.
If you want to ensure some code is run then you should change your design:
In this way
A()
is always fired before your overridden methodTo have multiple inheritence and to ensure A() is called you would have to make bar abstract as well:
There is no way to do exactly what you want in C#. This isn't a Visual Studio issue. This is how C# works.
Virtual method signatures can be overridden or not, called in the base or not. You have two options virtual or abstract. Your using
virtual
and I've given you anabstract
soltuion. It's up to you to choose which one you want to use.The nearest thing I can think of of what you want would be a
#warning
. See this answer. But this will only produce the warning in the Output window not in intellisense. Basically C# does not support custom compiler warnings.I finally had some time to experiment with Roslyn and looks like I found a solution with an analyzer. This is my solution.
The attribute to mark the method that needs to be overriden in the subclass:
The analyzer:
The CodeFix provider:
And a demo how it works: http://screencast.com/t/4Jgm989TI
Since I am totally new to the .NET Compiler Platform, I would love to have any feedback and suggestions on how to improve my solution. Thank you in advance!