Search code examples
c#visual-studio

Enforce the use of the "this" and "base" at compile-time in Visual Studio/C#


When extending classes, I find it very descriptive to use the base (MyBase in VB) keyword when accessing methods in the base-class. And the this (Me in VB) keyword when accessing functions in the class extending the base-class. That goes for a "flat" structure with no inheritance as well.

I find it easier to read this:

public class World
{
    public String baseName = "World";
}


public class Hello : World
{
    public String thisName = "Hello";


    public String GetNames()
    {
        return this.thisName + " " + base.baseName;
    }
}

Than this:

...

    public String GetNames()
    {
        return thisName + " " + baseName;
    }

...

Now, my question is: is it possible to enforce the use of this and base at compile-time in Visual Studio/C#, so that the compiler throws an error or a warning if you do not use these keywords in your code?


Solution

  • Have a look at StyleCop.

    http://code.msdn.microsoft.com/sourceanalysis

    There are some rules in there that should do what you want. You can configure it to show any style violations as warnings or errors.