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!


 


Comments (95)

  1. Peck's Blog says:

    I’ve been using StyleCop within Microsoft for some time now. I’m a big fan, and really excited to see

  2. Announcing the release of Microsoft Source Analysis for C#Source Analysis is similar in many ways to…

  3. Excerpt from the post… We are very excited to announce the release of a new developer tool from Microsoft

  4. Microsoft відповіла тулзам, що використовують парсінг коду. Офіційний анонс – http://blogs.msdn.com/sourceanalysis/archive/2008/05/23/announcing-the-release-of-microsoft-source-analysis.aspx

  5. You’ve been kicked (a good thing) – Trackback from DotNetKicks.com

  6. Dustin Norman says:

    Unlike FxCop, it would be trivial for tool to actually fix the many violations it detects. For example:

    Invalid spacing around the closing parenthesis.

    Tabs are not allowed. Use spaces instead.

    As someone who just ran this tool on a rather small assembly, I’m kind of overwhelmed at the idea of fixing 561 violations manually when the tool could fix them for me automatically without affecting the semantics of the code.

    Has any thought been given to adding support for this?

  7. steve says:

    it might be nice for examples.  like the file has no header the header xml is invalid or the header is not located at the top of the file.  i guess for punter’s like me who don’t know what headers look like it makes it a little difficult to add one.

  8. This is a great thing for MS to release to the developer community – StyleCop is a very interesting tool

  9. rams says:

    But what about vb.net? Why are all these new fancy tools being released for C#? Do VB.net developers not need the kind of analysis like C# or does every one write sloppy C# code?

  10. Bo Lund says:

    Yes we are contemplating adding auto fixing for a future release.

  11. I just ran this on a fairly large project and share the sentiments of Dustin.

    Some of this stuff could very well be done by the tool – adding a blank line after the closing brace etc.

  12. superjason says:

    Is there documentation for what it checks, or at least a document I can reference with the rules?

    Most coding standards I have seen disagree with the rules. For example, using spaces instead of tabs. Tabs can be resized for preference, spaces cannot.

  13. Benoit Martin says:

    The company I work for is stuck on VB.net. Is there any plan to have a VB.net version of this tool?

  14. Monty Evans says:

    Great Tool!! I’d like to see my shop use something like this.

    Would like to see a document on what the rule are though. I get "the spacing around the keywork ‘using’ is invalid"… not sure what the rule is for this. (For this matter though why doesn’t the IDE add these spaces?)

    Also would like to see the tool be able to fix some of these types of things.

  15. I would find it very helpful if it was configurable. I work for various clients and each has their own coding standards and conventions that they dictate to me and the development team here. It would be great to associate a project with a customized set of rules that vary from the standard so that I can deliver the code in the way the client expects and wants.

    Beyond that, any open source work I do in C# would conform to the strict standard. Another one I have used it Code Style Enforcer which does allow you to customize the rules.

    http://joel.fjorden.se/static.php?page=CodeStyleEnforcer

  16. Nick Berardi says:

    Are you kidding me.  Tabs are not allowed.  Use spaces instead.  This is a horrible idea, because it throws blocking layout off, if one variable uses 3 spaces and the other uses 4.  This there anyway to disable some of the more pointless rules like this tab one.

  17. nberardi says:

    It would be nice if you were able to disable some of these rules.  I know you said they are for the best.  But I totally disagree with this tab over spaces.  There is no logical reason for it.  Except some holy war that has been battled out between developers since Vi first came to market.  I would love to run this over my source code, but it blows up because it alerts me about every line that has a tab in it.

  18. steve says:

    anyone know how to add a header file to their c# documents?

  19. FYI – The code site is now offline.

  20. El día de hoy ha sido liberado Microsoft Source Analysis para C# , la cual es una herramienta que nos

  21. El día de hoy ha sido liberado Microsoft Source Analysis para C# , la cual es una herramienta que nos

  22. Daniel Stolt says:

    This is a very welcome addition to the set of tools available for .NET developers – but why only for C#? Enforcement of code formatting rules is just as sorely needed for VB developers!

    Admittedly, the VB code editor has some rudimentary support for automatic formatting when it comes to indentation and spacing around keywords and symbols, but nothing that even comes close to what StyleCop supports.

    By the way, I totally agree with "nberardi" on the tabs vs. spaces issue: what is the problem with tabs? Is it somehow an advantage to have to press the arrow key 4-5 times more to get to a given point? Is it somehow an advantage to have to store 4-5 times as many whitespace characters in a source file?

  23. People just love to write code. One tool that is used inside Microsoft is StyleCop which enforces code

  24. Amazing news!  …

    downloading…

  25. Christopher Cox says:

    Some of these rules do seem quite silly to me. Particularly SA1500, What do you have against Java style formatting? I find it looks a lot nicer that way. (In fact, there’s an option for it in Visual Studio, should you really penalize somebody for something that you let them autoformat it to?)

  26. 青松阳光 says:

    最近微软发布了一款代码分析工具,和微软内部使用的FxCop有些不同,目的大致一样,其工具的规则覆盖到: Layoutofelements,statements,expressions…

  27. FLYabroad says:

    引言:SourceAnalysis(StyleCop)的终极目标是让所有人都能写出优雅和一致的代码,因此这些代码具有最高的可读性。早就听说了微软内部的静态代码检查和代码强制格式美化工具Style…

  28. I don’t want to get into a flame war about spaces v.s. tabs in general, but the purpose of Source Analysis is consistency across you organization. I would say that spaces offered the only way to make the code look the same on all screens, which is important for peer programming for instance.

    Disclosure: I am pro-space and anti-tab because I use a lot of TSV data and need to set my tab stops to be very high. This is just my opinion – don’t flame me bro!

  29. Martin says:

    How does a valid file header look like. StyleCop keeps complaining with "S1633 The file has no header, the header XML is invalid, or the header is not located a the top of the file". There seems to be no further rule documentation to lookup.

  30. Microsoft announces Source Analysis for C#. It is very similar to Static Code Analysis (FxCop), but instead

  31. James says:

    Very neat tool. I think the XML comment enforcement is probably the best part (being the lazy bastard that I am).

    I did find what I think is a syntax false-positive. This fails:

    if (blah as SomeStruct? == whatever)

    but this seems OK:

    if ((blah as SomeStruct?) == whatever)

    It’s hard to tell if that fixes it though because my list doesn’t seem to shrink below 1000. :)

  32. Jason Allor anunciaba ayer mismo el lanzamiento de una nueva herramienta, Microsoft Source Analysis for

  33. podi says:

    Hi,

    Is there any tool that would help me automatically organize members in my class like:

    – All fields

    – All constructors

    – Public and protected properties

    – methods

    – events

    – all explicit inteface implementations

    – internal members

    – private members

    – all nested types

    this list is taken from Krzysztof Cwalina & Brad Abrams: "Framework Design Guidelines"

  34. For the people who want it to be more configurable — the lack of configuration is the big point.  This is an internal tool that they released because it is useful, not a product they sell.  The, obvious, initial purpose is to make all microsoft code look like microsoft code.  Configurability would have defeated it purpose.

    Now if microsoft sends you a paycheck every other week, then they have the right to tell you what your code will look like — by any means they choose.  If they don’t, then code however you like, and don’t use the free tool if you don’t like it.  

    Think of this as a gift from devdiv.  If you want to live by the rules of the castle, enjoy the consistency it provides.  If you don’t, please don’t scorn microsoft for allowing us to use their internal tools for free without buffing them to consumer quality.

  35. Andy Maggs says:

    For the VB’ers out there, you can always try VS Law which does much the same as StyleCop but unlike StyleCop is fully configurable (you can switch rules off an on, you can even create your own).  At the moment it is not free, but as the authors (I am one) no longer have the time to keep up it up to date with the language developments Microsoft are releasing, we are considering making it open source.  Is this of interest to anyone?

  36. Bo Lund says:

    To all the people who desires more configuration option I would like to point out that the tool already supports this:

    Right click on the project node in the solution explorer and choose the menu item “Source Analysis Settings”. There you can customize which rules to run.

  37. Nagyon rendes a Microsoft-tól hogy megosztja a fejlesztőkkel az egyik belső fejlesztői toolját. A Microsfton

  38. Microsoft released the internal tool StyleCop to public under the fancy yet boring name of Microsoft

  39. Christian Zachariasen says:

    The tool is nice and all, but when run on a Windows Application project, it complains about how the Form designer files are laid out. Now – those files are generated automatically. Why am I supposed to go in and edit the layout in them?

  40. Microsoft has published a great tool called Microsoft Source Analysis for C# , also known as StyleCop

  41. jasonall says:

    "…when run on a Windows Application project, it complains about how the Form designer files are laid out. Now – those files are generated automatically. Why am I supposed to go in and edit the layout in them?"

    There is a difference between auto-generated code that will later be overwritten again by a tool, and auto-generated code that will never again be overwritten. In the Forms case, the code is originally created for you by a tool, but after that you own the code and it’s up to you to maintain it. There is a special region at the bottom of that file containing the code that can actually be overwritten again by the tool, and StyleCop will ignore that part of the code.

  42. rnHelps teams enforce a common set of best practices for layout, readability, maintainability, and

  43. Integration continue : Partie 4, Microsoft Source Analysis Tool for C#

  44. Integration continue : Partie 4, Microsoft Source Analysis Tool for C#

  45. CoqBlog says:

    Un nouvel outil est disponible pour les développeurs C#. Comme son nom l’indique il s’agit d’un analyseur

  46. I will need more time to go through the tool (just downloaded it), but already can see few little issues:

    1. Violation SA1027 (Tabs are not allowed. Use spaces instead) is definitely not making any sense. Tabs have many advantages compared to spaces, but the most important one is that each team member can set tab’s width according to his personal preference (I prefer 3, someone else – 4, 2, or even 8!), and there is no need for "religious wars" because of this non-issue.

    2. Source Analisys tab (the one listing violations) should have numbered lines – it is very difficult to navigate in the list if it has more items.

    3. As some people already mentioned above, the tool has very limited applicability if the user has to fix violations manually. Some kind of automatic fixing (e.g. via context menu in the Source Analisys tab) is absolutely must. Otherwise "fixing" existing codebase is really not an option – in simple (25 lines of not that bad code!) file the tool found 28 "violations" (from which 16 were "tabs").

  47. Hi,

       With FxCop and this program, my codes are even better. But i suggestion, maybe do a program like that to WCF Contracts and Services, to create better WCF Services mainly because SOA, the exposed methods are growing.

    Regards,

             Alan – Enterprise Architect

  48. Hi,

       With FxCop and this program, my codes are even better. But i suggestion, maybe do a program like that to WCF Contracts and Services, to create better WCF Services mainly because SOA, the exposed methods are growing.

    Regards,

             Alan – Enterprise Architect

  49. Bill says:

    It says it will help your code to be more "elegant, consistent…" so naturally it must work with C#.

    I wish I had a dollar for every library, tool, whitepaper, msdn article, etc. that came out of MS for C# only.

  50. dpwebs says:

    I think it is an excellent idea, and I found some constraints very helpful. The tool itself is configurable in its basic form, but it would be nice if the toll somehow could copy settings from VS. For example, I personally prefer opening braces in same line as method or class declaration, and tool should read already set settings in VS editor options.

    Keep up with good work!

  51. Som thomas skriver, så har Microsoft udgive et værktøj til analyse af din kode – og som sædvanlig er

  52. IMHO rule SA1600 should be split up in private members and members with a higher visibility. I get a lot of SA1600 “errors” because I did not write comments for my private fields:

    Error SA1600: The field must have a documentation header.

     

    [Note from jasonall – This can be configured by bringing up Source Analysis project settings, navigating to Rules tab, and selecting the Documentation node. A detailed setting allows you to control this]

  53. Wojtek says:

    On <a href="http://wojciech.zimirski.net/2008/5/24/microsoft-source-analysis-for-c"&gt;

    my blog</a> you can find list of all rules analysed by the tool.

  54. AndrewSeven says:

    It would be nice to have some global settings or at least solution-wide settings.

    For tabs vs. spaces, it would be nice to be easily able to remove it for our whole company.

    [Note from jasonall – It is  possible to configure settings for all projects, or to share settings across multiple projects. Check the following post: http://blogs.msdn.com/sourceanalysis/pages/sharing-source-analysis-settings-across-projects.aspx]

     

  55. Maor David says:

    Microsoft announce the public release of a new developer tool -&#160; Source Analysis for C# . Inside

  56. Steve's blog says:

    The static analysis tool FXCop, and its later relation Visual Studio Code Analysis, have been well known

  57. KetszeriCs says:

    Defently a good tool but I am almost 100% sure it will mainly by used by control freaks to force the …. out of their teams. Automatical style fixing (at least indentations and spaces) seems so trivial to me it must be a concious decision to leave it out. I have to say it is a sad thing.

  58. Dave Cameron says:

    The community would obviously like more configurability than Microsoft needs internally. Any possibility of releasing the source so the community can add the configurability?

  59. Benoit Martin says:

    Jsaon,

    Several people (including me) asked about the availability of this tool for VB.NET. It would be nice if this question was not ignored. Even if we get the usual "no support for vb.net planned at the moment" type of response, at least we’ll know where we stand

    Thank you

  60. Oscar says:

    Exsits any similar tool for C++ ? Thanks

  61. Derek says:

    The reason Microsoft won’t have a similar tool for VB.Net is that internally they don’t use VB.Net for anything – all their .Net coding efforts are in C#

  62. When I left Microsoft, I felt pretty sad. Not only would I leave a bunch of great friends behind (and

  63. Hugo Ribeiro says:

    After almost two months working on this , things are finally falling on their correct place. Today the

  64. bob53050 says:

    /// <summary>

    /// Sample method to add two number together

    /// </summary>

    /// <param name=”first”></param>

    /// <param name=”second”></param>

    /// <returns>sum of the two params passed</returns>

    public double AddTwoNumbers(double first, double second)

    {

    return first + second;

    }

    Any ideas why I get SA1614 on this?

     

    [jasonall] You are missing documentation text for the ‘first’ and ‘second’ parameters.

  65. Bjørn Reppen says:

    I don’t like with the coding standard this tool enforces.. it gives me the "enterprise developer" chills..

  66. Fabian says:

    It would be nice to see a VB.NET version. Judging from the posts here, there is certainly some interest.

  67. Qgar says:

    Considering SA1633: FileMustHaveHeader I think that file header should start with 3 slashes (///) not 2 (//) to be consistent to other documentation comments generated in Visual Studio.

  68. I’d like to have a context menu entry as we can find in the regular build error list "Show Error Help" which links to a brief description of the specific analysis error (which means integration into the VS help Database). That would be way more convenient than having to do a MSDN search.

  69. ASP.NET ASP.NET MVC Preview 3 : It just keeps getting better and better, folks! Scott Guthrie shares all the juicy details on the latest drop of this fantabulous toolkit! Using jQuery To Call ASP.NET AJAX Page Methods : Not a fan of ASP.NET AJAX? Love

  70. SSIS Junkie says:

    My learned colleague Howard van Rooijen recently blogged about the new release of Microsoft Source Analysis

  71. Corgy says:

    I have no detailed section for:

    SA1600: The field must have a documentation header.

    If I open up Source Analysis project settings, navigate to Rules tab, and select the Documentation node, the detailed section is empty.

  72. vinipl87 says:

    podi, you’re looking for NArrange: http://www.codeproject.com/KB/codegen/narrange.aspx

  73. I’ve learned from a fellow GASP er of the release of Microsoft Source Analysis for C# (aka StyleCop)

  74. I’ve learned from a fellow GASP er of the release of Microsoft Source Analysis for C# (aka StyleCop)

  75. Tomei conhecimento, através do colega GASP iano, do lançamento da Microsoft Source Analysis for C# (aka

  76. geekEleet says:

    Announcing the release of Microsoft Source Analysis for C#

  77. Continuous Integration Part 3 : Integrating Microsoft Source Analyzer Tool to our build process

  78. Chris Wedgwood says:

    Might be a great tool. It would be better if you hadn’t made it so ‘tightly coupled’ to C#.

    Couldn’t you have just wrote a core engine and then allowed each language team to write an add-in to make it work for other languages, along with a best practice ruleset for each language which could be altered as needed by individual shops using the tool in order to fit with their internal coding standards(which may not always match Microsoft’s)?

    8/10 for effort. Could try harder.

  79. Dave's Box says:

    For the past couple of years, I spent considerable time saying the same statement over and over again

  80. If you do have Microsoft Source Analysis Tools for C# and JetBrains ReSharper 4.0 installed in you development

  81. Jon Galloway says:

    h2.entry-title { font-size: 1.1em; clear: left; } ul.hfeed { list-style-type: none; } li.xfolkentry

  82. I&#39;d like to collect some good links about Team System from the community and Microsoft: MSBuild tasks

  83. Hi.

    Does this tool work with express editions?

    Just a doubt, because I tryied at home using express ed. and could not find the option.

    Thanks!

  84. fhanggi says:

    I would love to see a VB.NET version of this tool.

  85. Elena says:

    I would also like to see StyleCop for VB.Net. …Yes, I read that many of you asked for it, but I anyway decided to write, as I hope that if Microsoft sees how many people demand the tool for VB.Net they might consider adapting it for us.

    Thanks.

  86. Søren Lindstrøm says:

    Great idea, however, it is absolutly nessessary that youu build in an option to ommit rules that do not apply to your code. I.e.

    In my company we are 100% agile, thus our unittests are our documentation. We do not want 1000 errors just because we havn’t written 1.000.000 lines of code comments.

    Second, some of the formatting rules are in conflict with production-enhancing tools like resharper (i.e. where using statements should be). As much as i like the MSCop-idea, I would NEVER trade my resharper for MSCop.

  87. Claudio says:

    Wishlist request: turn this into a standalone tool, separated from VS.

    Reason: I have been bit (as have others) by the dreaded "Package ‘Visual Studio Explorers and Designers Package’ has failed to load properly" error in VS after using this add-in.

  88. bob53050 says:

    Any idea on the release date of version 4.3?

    Thanks :)

  89. Crusty Applesniffer says:

    Hi,

    I get an SA1611 error with the following lines.

    /// <summary>

           /// The main entry point for the application.

           /// <param name="args">Arguments passed through the command line</param>

           /// </summary>

           public static void Main(string[] args)

           {

    Any help is welcome

  90. Ray Akkanson says:

    Should we expect the release in September?

    Ray Akkanson

  91. B.Moeller says:

    What about VB.NET! Our company insists on VB.Net and i think we could use this tool for our commenting addle devs…

    I saw the comments for VB.NET but as many people asking for it, it will be developed once…

  92. Nithya K says:

    Just i went through the topic,thank u so much

  93. jasonall says:

    Please use the StyleCop Discussion Forum for further comments as it provides a better mechanism for tracking topics and follow-ups.

  94. Tomei conhecimento, através do colega GASP iano, do lançamento da Microsoft Source Analysis for C# (aka