Welcome to MSDN Blogs Sign in | Join | Help

Property Headers

By default StyleCop comes with two rules which govern the summary documentation for properties, depending upon the types of accessors contained with the property. For example:

/// <summary>
/// Gets or sets the name of the customer.
/// </summary>
public string Name
{
    get;
    set;
}

In this example, StyleCop will require that the summary text starts with “Gets or sets” since the property has visible get and set accessors. In some cases, the set accessor has more limited access than the get accessor. For example:

/// <summary>
/// Gets the name of the customer.
/// </summary>
public string Name
{
    get;
    private set;
}

In this case, StyleCop requires the summary documentation to omit the “or sets” wording since public consumers of the property can only see the get accessor.

Unfortunately, it can sometimes be non-obvious whether the set accessor within a property is actually less accessible than the get accessor. For example, consider the case where a public property is contained within an internal class, and the set accessor has the internal keyword. In effect, both the get and set accessors have the same access level, because the entire class is internal. In this case, the summary documentation should refer to both the get and set accessors, since they have the same access level and can both be viewed by the same set of callers.

This can be a little confusing. In StyleCop 4.3.2, this behavior of this rule has changed slightly to avoid some confusion about when the “or sets” wording should be included. StyleCop now applies a series of rules to determine when the set accessor should be referenced in the property’s summary documentation. In general, these rules require the set accessor to be referenced whenever it is visible to the same set of callers as the get accessor, or whenever it is visible to external classes or inheriting classes.

The specific rules for determining whether to include the set accessor in the property’s summary documentation are:

1. The set accessor has the same access level as the get accessor. For example:

/// <summary>
/// Gets or sets the name of the customer.
/// </summary>
protected string Name
{
    get;
    set;
}

2. The property is only internally accessible within the assembly, and the set accessor also has the internal keyword. For example:

internal class Class1
{
    /// <summary>
    /// Gets or sets the name of the customer.
    /// </summary>
    protected string Name
    {
        get;
        internal set;
    }
}

internal class Class2
{
    public class Class3
    {
        /// <summary>
        /// Gets or sets the name of the customer.
        /// </summary>
        public string Name
        {
            get;
            internal set;
        }
    }
}

3. The property is private or is contained beneath a private class, and the set accessor has any access modifier other than private. In the example below, the access modifier declared on the set accessor has no meaning, since the set accessor is contained within a private class and thus cannot be seen by other classes outside of Class1. This effectively gives the set accessor the same access level as the get accessor.

public class Class1
{
    private class Class2
    {
        public class Class3
        {
            /// <summary>
            /// Gets or sets the name of the customer.
            /// </summary>
            public string Name
            {
                get;
                internal set;
            }
        }
    }
}

4. Whenever the set accessor has protected or protected internal access, it should be referenced in the documentation. A protected or protected internal set accessor can always be seen by an inheriting class, thus it should be included within the documentation. In the example below, the property is internal because it is contained within an internal class. However, the set accessor is protected, meaning that it can be seen by an inheriting class. The constructor of Class3 sets the value of the Name property. Thus, the property header should still refer to the set accessor.

internal class Class1
{
    public class Class2
    {
        /// <summary>
        /// Gets or sets the name of the customer.
        /// </summary>
        public string Name
        {
            get;
            protected set;
        }
    }

    private class Class3 : Class2
    {
        public Class3(string name)
        {
            this.Name = name;
        }
    }
}

Posted by jasonall | (Comments Off)

Rule Suppressions

Starting with StyleCop 4.3.2, it is possible to suppress the reporting of rule violations by adding suppression attributes within the source code. The syntax for these suppressions is similar to that for Visual Studio Code Analysis, or FxCop. For more information about Code Analysis suppressions, see the following article: In Source Suppressions Overview.

StyleCop rule suppressions are registered in code using the SuppressMessage attribute. The SuppressMessage attribute is a conditional attribute, which is included in the IL metadata of your managed code assembly only if the CODE_ANALYSIS compilation symbol is defined at compile time.

We recommend that you use in-source suppressions on debug or check-in builds, in order to eliminate the possibility of mistakenly shipping the in-source suppression metadata and compromising execution or performance because of the metadata bloat. Since StyleCop analyzes the source code directly, there is no need for these attributes to be compiled into the assembly.

The SuppressMessage attribute has the following format:

[SuppressMessage("Rule Category", "Rule Id", "Justification")]

Where:

  • Rule Category - The StyleCop rule namespace in which the rule is defined. For example, Microsoft.StyleCop.CSharp.DocumentationRules
  • Rule Id - The identifier for the rule, using the format shortname:longname. For example, SA1600:ElementsMustBeDocumented
  • Justification - The text that is used to document the reason for suppressing the message.

The SuppressMessage attribute also takes the following optional parameters. These parameters are completely ignored by StyleCop and do not need to be filled in for StyleCop suppressions.

  • Message Id
  • Scope
  • Target

SuppressMessage Usage

StyleCop violations are suppressed at the level to which an instance of the SuppressMessage attribute is applied. The purpose of this is to tightly couple the suppression information to the code where the violation occurs.

For example, a StyleCop SuppressMessage attribute placed on a class will suppress the rule for all contents of the class. The same attribute placed on a method will only suppress the rule within the method.

Global Suppressions

StyleCop does not support the notion of global suppressions or file-level suppressions. Suppressions must be placed on a code element.

Examples:

The following code suppresses the ElementsMustBeDocumented rule for the given class and all its contents:

[SuppressMessage("Microsoft.StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
public class MyUndocumentedClass
{
    public void MyUndocumentedMethod
    {
    }
}

Posted by jasonall | (Comments Off)

StyleCop update 4.3.2.1 is released

I am pleased to announce that we’re released another build of StyleCop which includes multiple bugfixes as well as one significant new feature, the ability to insert in-code rule suppressions using the same attribute syntax as FxCop Code Analysis. For more information about rule suppressions, see this blog post: http://blogs.msdn.com/sourceanalysis/archive/2009/08/10/rule-suppressions.aspx

This release also fixes an issue accidently introduced into the last update which caused a bit of annoyance. It’s once again possible to “stack” your using statements such as:

using (Graphics g = this.CreateGraphics())
using (Form f = new Form())
using (Class c = new Class())
{
    // Do stuff
}

Bugfixes:

  • 89: Incorrect requirement to use string.Empty within const variable and field declarations
  • 125, 217: Support for foreign characters
  • 138, 139: Sorting issues with using directives
  • 161: StyleCop incorrectly calculates accessibility of property set accessors and requires incorrect summary text.
  • 171, 175, 192: Parsing error with complex generic types
  • 173: Parsing error with fixed size array fields
  • 184: StyleCop hangs indefinitely analyzing file
  • 189: Incorrect requirement to use built-in type aliases within using directives
  • 190: Allow using directives to be “stacked”. Only require curly brackets for the last stacked using directive.
  • 218: Spacing issue
  • Fix for threading issue

Please upgrade to the new version at your earliest convenience:

Install link: https://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=sourceanalysis&ReleaseId=1425

Discussions: http://code.msdn.microsoft.com/sourceanalysis/Thread/List.aspx

Bugs: http://code.msdn.microsoft.com/sourceanalysis/WorkItem/List.aspx

Posted by jasonall | (Comments Off)

StyleCop update 4.3.1.3 is released

We have just released an update to StyleCop 4.3 which contains a number of bugfixes as well as a small number of new features. In particular:

  • Ability to use <include> tags within Xml header documentation to pull docs from external files.
  • Get accessor in property required to appear before set accessor
  • .generated.cs files ignored by default

Bugfixes:

  • 18: Partial methods not handled correctly
  • 31: Documentation rules should understand <include> element
  • 56: Require get accessor before set accessor
  • 63: When documenting a generic class, only allows <see cref="MyClass"/> and not <see cref="MyClass`1"/>.
  • 70: Analysis of files in websites crashes Visual studio 2005 and 2008
  • 74: SA1623 and SA1624 warnings appears in wrong situations
  • 82: 'using' statement does not require curly brackets
  • 88: Class without explicit access modifier marked as "public" instead of "internal"
  • 90: False warning: SA1119: The line contains unnecessary parenthesis
  • 93: Ignore .generated.cs files
  • 94: Style Cop Crashes With A Blank Definition File
  • 95: SA1101 isn't raised in method calls when the return value of the method is used.
  • 98: VS crashed for webservices.
  • 121: False syntax error with a nullable generic type reference.
  • 124: LINQ operator "let" cause SA0101 when used with "condition ? true : false" syntax
  • 151: False syntax error with a defaulted array.

Please upgrade to the new version, especially if you are hit by the crash in web projects.

Install link: https://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=sourceanalysis&ReleaseId=1425

Discussions: http://code.msdn.microsoft.com/sourceanalysis/Thread/List.aspx

Bugs: http://code.msdn.microsoft.com/sourceanalysis/WorkItem/List.aspx

Posted by jasonall | 2 Comments

Introducing StyleCop on Legacy Projects

A number of people have asked for tips on rolling out StyleCop on a large, pre-existing codebase. This can prove challenging, since the tool will typically generate thousands of violations the first time it is run on existing code. For a large solution, this can make adoption of the tool a bit daunting.

On the other hand, it is relatively easy to comply with StyleCop when writing new code, especially for developers who are already familiar with the tool.

In this article I’ll describe a technique for doing a slow, staged rollout of StyleCop over your existing codebase. This technique has been used successfully by multiple teams within Microsoft, allowing them to adopt the tool in a controlled manner without generating a lot of noise up front. The general idea is to enable the tool for all of your solutions, but disable the tool from analyzing all pre-existing C# files. This provides the following advantages:

  • One day one, StyleCop will not generate any violations against your code, and will have zero measurable impact on your team.
  • Each time a new C# file is added to any project in your solutions, StyleCop will begin analyzing the code in that file. This will ensure that code in new files will be compliant from the start.
  • Over time, pre-existing files can be slowly cleaned up and introduced to StyleCop one by one.

This technique will allow your developers to slowly get used to the tool over time, without having to be confronted with thousands of StyleCop violations on day one.  

The following steps explain how to introduce StyleCop over time, as described above. At this time, this technique is only possible when running StyleCop through MSBuild integration, meaning that StyleCop runs automatically whenever a build is performed.

1. The first step is to enable StyleCop MSBuild integration for each of your existing projects, as described here.

2. After StyleCop MSBuild integration has been set up, perform a build and verify that you can see StyleCop violations in the build output.

3. The next step is to exclude all pre-existing C# files from StyleCop. To do this, each csproj file must be edited to add an ExcludeFromStyleCop property for each C# file. Within the csproj files, edit each Compile tag as shown in the example below:

<Compile Include="File.cs"/>

Change this to:

<Compile Include="File.cs">
  <ExcludeFromStyleCop>true</ExcludeFromStyleCop>
</Compile>

To make this easy, we have provided a sample tool which can do this for you. To use the tool, download the source code here, and build it in VS. This will produce an EXE called ExcludeStyleCop.exe.

Disclaimers: Keep in mind that this tool is provided as sample source code only, and will edit your project files! It is recommended that you make a copy of your source code before proceeding. This tool is only provided as a sample, and should be used at your own risk!

Running the tool with no command-line arguments will cause the tool to recursively find each C# project under the current directory, and add an exclusion tag for every C# file in every project. It is also possible to pass the path to a single csproj file on the command line, in which case the tool will only add exclusion tags for the files in that project.

4. Finally, perform a clean build and verify that there are no StyleCop violations in the build output. All C# files should be excluded now!

Whenever a new C# file is introduced to any of these projects, StyleCop will automatically begin to enforce the style of the code in that file each time the project is compiled. As more and more new files are introduced over time, developers will gain familiarity with the StyleCop rules.

As time allows, developers can clean up pre-existing files by removing the ExcludeFromStyleCop tag for a file, compiling, and cleaning up the StyleCop violations in that file.

Posted by jasonall | 1 Comments

StyleCop 4.3 SDK

The SDK documentation for StyleCop 4.3 is now available for download, here: https://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=sourceanalysis&ReleaseId=1425

This documentation explains how to create and install custom StyleCop rules, how to integrate custom settings into the StyleCop settings dialog, and how to create a wrapper for hosting StyleCop in a custom build environment.

Posted by jasonall | 4 Comments

StyleCop 4.3 Is Released

The awaited StyleCop 4.3 update is now available. This update includes:

  • Various bugfixes, including fixes for VS integration issues
  • Rules documentation is included and integrated into VS "Show Error Help"
  • New rules (more detail below)
  • Branding change from Source Analysis to StyleCop

As promised, we will also be releasing SDK documentation for StyleCop explaining how to author custom rules and how to integrate the tool into custom build environments. The SDK documentation is currently under final review and we hope to release it very soon.

The new rules shipping with StyleCop 4.3 include:

·         Enforce sort order for using directives. This aligns with the Organize Usings functionality in VS 2008

·         Require standard summary text for constructors and destructors

·         Require parenthesis in arithmetic and comparison expressions for added clarity

·         Require String.Empty rather than “”

·         Require explanation message text in debug asserts

·         Require justification text in Code Analysis suppressions

·         Enforce use of built-in type aliases for int, string, float, etc.

·         Require a blank line between elements

·         Disallow blank lines at the top or bottom of documentation headers

·         Disallow regions within method bodies (enabled by default)

·         Disallow the use of regions anywhere within the code (disabled by default)

·         Disallow empty static constructors

·         Disallow empty unsafe, lock, checked, and unchecked statements

·         Disallow unnecessary or empty try\catch\finally

The 4.3 release is available here: https://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=sourceanalysis&ReleaseId=1425

Posted by jasonall | 34 Comments

Clearing up Confusion

There has been some confusion and a few mixed messages coming out of Microsoft since the release of StyleCop, most notably around extensibility support for the tool, and licensing. We've gotten a lot of great feedback from the community, and in the last few weeks there have been some good discussions between various teams internally about how to position this tool, and how to best support extensibility.

Brian Harry, a Technical Fellow leading the VS TFS team, has recently written a great blog post explaining the context of these discussions and the decisions that have been made. You can read it here: http://blogs.msdn.com/bharry/archive/2008/07/19/clearing-up-confusion.aspx.

To summarize:

  • StyleCop is not part of the VS Code Analysis suite, and in fact has been developed outside of the VS team. It should be viewed as a complementary tool which focuses on code style and consistency. To help clear up this confusion, we are retiring the "Source Analysis" name and will be referring to the tool from now on as StyleCop, which is the original name of the tool!
  • We are planning to release an update which will introduce the naming change, and fix bugs that have been discovered by the community after the original release. This release will also include a handful of new rules which did not make it into the first release, and will incorporate some other great suggestions from the community.
  • We will be releasing a small SDK for the tool, describing the extensibility interface used to create custom rules, and explaining how to plug the tool into command-line based build tools.
  • We will be releasing documentation describing all of the default rules.

I would like to personally extend a big thank you to everyone who has taken the time to give us feedback about this tool. It's been very valuable and very much appreciated. A big thank you also goes out to Brian and others in the VS team who have been working hard to solve the issues around this tool.

We will spend the next couple of weeks getting the next version of the tool ready to ship, and getting all of the documentation ready to publish, and we'll get it out to you as quickly as we can!

Thank you!

 

Posted by jasonall | 4 Comments

A Brief History Of C# Style

A number of astute developers have noted that the C# code style enforced by Microsoft StyleCop differs in some ways from the style typically seen in sample code coming from the Microsoft Developer Division. For example, the very fine book Framework Design Guidelines by Krzysztof Cwalina and Brad Abrams includes many code samples which use a different style, and this style is briefly described in an appendix in the back of the book.

In fact, the differences between the "StyleCop style" and the "Framework Design Guidelines style" are relatively minor. One of the biggest differences is that the framework style prefixes private and internal fields with an underscore, while StyleCop style omits the underscore and instead prefixes all class members with this.

The reason for the differences between the two styles is largely historical. The team that developed the first version of the .Net CLR consisted almost entirely of C++ developers. Remember, at this time no-one had ever heard of C# and in fact the language only existed on paper. When the original CLR was stable enough for internal use, people from the CLR team began writing test and sample code in the new C# language, mainly to test the CLR itself. Being C++ developers, these people naturally wrote their first C# code in a style that very much resembled C++, with liberal use of the m_ prefix, very little whitespace or comments, short, cryptic variable names, lots of Hungarian notation, etc.

Soon after this, an offshoot of the CLR team began writing the first version of the .Net Framework. Most of this code was written in C#. This was the first production C# code written anywhere in the world! Again, the team chose a coding style that mostly resembled C++. Over time this style has changed slightly, but the Framework team still uses this style for its internal C# code, as well as sample C# code provided to customers and partners.

After the first version of the .Net Framework was released, many other teams within Microsoft began writing new code in C#. Some of the biggest early adopters were, naturally, the Office team and the Windows team. Within a couple of years, almost every product group at Microsoft was writing at least some percentage of its code in C#. The architects and managers in these teams (being architects and managers) each took the time to come up with their own, individual style guidelines for the new C# language. In some places these style guidelines differed wildly according to the whims and fancies of the leaders of these teams. However, over time some C# style trends began to form, and these trends did not always follow the original style used by the Framework team. C# style had begun to evolve.

A short time after this, a brilliant young developer at Microsoft (ok, it was me) decided to take it upon himself to write a little tool which could detect variances from the C# style used within his team. StyleCop was born. Over the next few years, we gathered up all of the C# style guidelines we could find from the various teams within Microsoft, and picked out all of best practices which were common to these styles. These formed the first set of StyleCop rules. One of the earliest rules that came out of this effort was the use of the this prefix to call out class members, and the removal of any underscore prefixes from field names. C# style had officially grown apart from its old C++ tribe.

Development on StyleCop continued on and off for the next five or six years, and over this time many new rules were introduced. As you might expect, many wars were fought over the nature of these rules, and much blood was shed. In the end, decisions about StyleCop rules always came down to the following:

  1. What are most teams doing already?
  2. Which option is the most readable (highly subjective)?
  3. Which option will be the easiest to maintain over time?

StyleCop rules tend to encourage whitespace and openness in the code, as well as lots of comments and documentation. The rules also encourage developers to be explicit about what they are doing, and to minimize the need for assumption or guesswork on the part of the reader.

Today, StyleCop is very widely used within Microsoft, although it is still not an official, mandated tool internally. The .Net Framework team still writes code and samples using the original style derived from C++, and there are still some teams that have chosen to go their own way (and still some architects and managers with big egos). However, that is happening less and less internally, as more and more teams adopt the tool.

Now we have continued the evolution by releasing StyleCop to the world!

Thanks.

Posted by jasonall | 34 Comments

StyleCop Build Integration

The following article describes how to integrate StyleCop into the build, so that the tool will run automatically whenever a build is performed:

 http://blogs.msdn.com/sourceanalysis/pages/source-analysis-msbuild-integration.aspx

Posted by jasonall | 1 Comments
Filed under:

Future Plans

Since the release of StyleCop, many people have pointed out that a number of the rules enforced by the tool could be automatically corrected by the tool, without requiring the developer to do the corrections manually.

As you might imagine, this functionality is also highly desired by the developers using StyleCop within Microsoft, and this will be the main focus of the next major release of the tool.

Early stages of development have begun on this effort, but at this time there is no annoucement about a potential release date. Expect this to show up at some point in the future.

Posted by jasonall | 10 Comments

Announcing the release of Microsoft StyleCop

We are very excited to announce the release of a new developer tool from Microsoft, Source Analysis for C#. This tool is known internally within Microsoft as StyleCop, and has been used for many years now to help teams enforce a common set of best practices for layout, readability, maintainability, and documentation of C# source code.

StyleCop is similar in many ways to Microsoft Code Analysis (specifically FxCop), but there are some important distinctions. FxCop performs its analysis on compiled binaries, while StyleCop analyzes the source code directly. For this reason, FxCop focuses more on the design of the code, while StyleCop focuses on layout, readability and documentation. Most of that information is stripped away during the compilation process, and thus cannot be analyzed by FxCop.

The ultimate goal of StyleCop is to allow you to produce elegant, consistent code that your team members and others who view your code will find highly readable. In order to accomplish this, StyleCop does not allow its rules to be very configurable. StyleCop takes a one-size-fits-all approach to code style, layout, and readability rules. It is highly likely that you will not agree with all of the rules and may even find some of the rules annoying at first! However, the majority of teams using this tool within Microsoft have found that after a short adjustment period, they came to appreciate the rules enforced by StyleCop, and even began to find it difficult to read code not written in this style. 

StyleCop comes with a set of default rules analyzers covering approximately 200 best practice rules. These rules are full compatible with the default layout settings in Visual Studio 2005 and Visual Studio 2008.

Specifically, these rules cover the following, in no particular order:

  • Layout of elements, statements, expressions, and query clauses
  • Placement of curly brackets, parenthesis, square brackets, etc
  • Spacing around keywords and operator symbols
  • Line spacing
  • Placement of method parameters within method declarations or method calls
  • Standard ordering of elements within a class
  • Formatting of documentation within element headers and file headers
  • Naming of elements, fields and variables
  • Use of the built-in types
  • Use of access modifiers
  • Allowed contents of files
  • Debugging text

After installation, StyleCop can be run from within the Visual Studio IDE, and can also be integrated into MSBuild-based command line builds.

StyleCop can be downloaded here: https://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=sourceanalysis. We're looking forward to hearing your feedback!

 

Posted by jasonall | 95 Comments
 
Page view tracker