Technology with opinion

Tuesday, November 25, 2008

Creating Custom StyleCop Rules in C#

Microsoft has released a new free static code analysis tool called StyleCop.  Named after the similar FxCop, this product is aimed to be more focused for cosmetic code consistency which can increase readability and maintainability.  StyleCop has built-in rules, which you can turn off, many of which are:
  • Ordering of members in a class from most visible to least visible
  • Order of Usings in alphabetical order, with System namespaces on top
  • Proper camel casing and pascal casing
  • Proper whitespace
I like about 3/4 of these rules so I think it's definitely worth considering using, even consider integrating into your automated build process using NAnt, CruiseControl or TFS.  That being said many will likely want to extend these rules to create your own.  Doing so is fairly simple but not documented very well at this time.  I created the following rule to make sure that all instance variables (private & protected class level variables) are prefixed with an underscore.  I realize not everybody follows this convention, but I like it because it's more concise than prefixing your instance variables with 'm_' or 'this' which is often needed to prevent name collisions.

First I created a C# Class assembly project and referenced "Microsoft.StyleCop" and "Microsoft.StyleCop.CSharp".  Next I added the following class, which implements my custom rule:

using Microsoft.StyleCop;
using Microsoft.StyleCop.CSharp;

namespace DotNetExtensions.StyleCop.Rules
    /// <summary>
    /// This StyleCop Rule makes sure that instance variables are prefixed with an underscore.
    /// </summary>
    public class InstanceVariablesUnderscorePrefix : SourceAnalyzer
        public override void AnalyzeDocument(CodeDocument document)
            CsDocument csdocument  = (CsDocument) document;
            if (csdocument.RootElement != null && !csdocument.RootElement.Generated)
                csdocument.WalkDocument(new CodeWalkerElementVisitor<object>(this.VisitElement), null, null);

        private bool VisitElement(CsElement element, CsElement parentElement, object context)
            // Flag a violation if the instance variables are not prefixed with an underscore.
            if (!element.Generated && element.ElementType == ElementType.Field && element.ActualAccess != AccessModifierType.Public && 
                element.ActualAccess != AccessModifierType.Internal && element.Declaration.Name.ToCharArray()[0] != '_')
                AddViolation(element, "InstanceVariablesUnderscorePrefix");
            return true;

The VisitElement function handles the main logic for this rule.  First it makes sure that the member isn't Generated code, which you have no control over so no sense in applying rules to.  Secondly it's making sure that the member's visibility isn't Public or Internal.  Finally we make sure that the instance variable starts with an underscore prefix..

Next we need to provide metadata so that StyleCop can categorize and describe our rule.  Add an XML file to your project, then change it's Build Action to 'Embedded Resource'

<?xml version="1.0" encoding="utf-8" ?>
<SourceAnalyzer Name="Extensions">
    These custom rules provide extensions to the ones provided with StyleCop.
    <Rule Name="InstanceVariablesUnderscorePrefix" CheckId="EX1001">
      <Context>Instance variables should be prefixed by underscore.</Context>
      <Description>Instance variables are easier to distinguish when prefixed with an underscore.</Description>

At the root level you are naming the main category for the rules in this file.  Next you describe your suite of rules.  Then in the Rules section you can add all the rules (note: you can use RuleGroup element to further categorize your rules).  Finally you name your rule and give it a unique CheckId.  The CheckId is what you can search for your rule by in the StyleCop Project Settings.  Important: for StyleCop to correlate your class to your metadata your class and xml file need to be named exactly the same.

Finally build your project and drop your new assembly's dll into the StyleCop directory (C:\Program Files\Microsoft StyleCop 4.3).  Now double-click your Settings.StyleCop to see your rule in the list.  It should look something like the following:

Now you can open your solutions/projects in Visual Studio and click Tools -> Run StyleCop and you should see warnings for your new rule.

StyleCop is a nice little accent to any C# project.  I'd like to see Microsoft make the following changes:
  • StyleCop should be OSS (open source software) - why not Microsoft, there really can't be any proprietary business technology in an application that is basically is performing string  parsing
  • StyleCop's documentation needs to be improved - Microsoft provides to help documents for StyleCop, a user manual and an SDK manual.  Both of them lack details and some of the examples simply do not even compile.  For instance the CodeWalkerElementVisitor delegate in a boolean, in their samples they do not even return a boolean value which will not allow their samples to compile.  They do not even document the purpose of this boolean.  Through trial and error I think that if you return a false that it will stop walking (parsing) the document for this rule.
  • Custom rules should be able to be categorized within the existing main ones: Naming Rules, Ordering Rules, etc.
  • Easier to create custom rules by using regex within an XML file.  This would eliminate having to create custom assemblies and classes.
  • Command-line interface should be available for testing or scripting purposes.


Walker said...

I need the rule to you implement for using underscore prefix for private or protected instance level variables for SyleCop.

More thanks for help me.

My email es:

Anonymous said...

Many institutions limit access to their online information. Making this information available will be an asset to all.
Custom Paper Writing

Unknown said...


I have a problem.

When I open the settings file via visual studio (right-click a project and click StyleCop Settings) my custom rules appear. All good there. However if I open the same file by double-clicking it in windows explorer my custom rules don't show up. Any idea why?


Sharepoint said...

In your Article there is mentioned that "Proper camel casing and pascal casing" in build function in StyleCop, but i am unable to find that rule. Can you help me


Unknown said...


I posted the code to Google Code.


If you modify the stylecop settings file in the Program Files location then it will make the settings global to Visual Studio unless a projects settings override the default.

Unknown said...

I followed your guide (actually I just copy and pasted your code), but I can't get Microsoft StyleCop to pick the rule up. I'm using .NET framework 2.0 and Visual Studio 2005. The dll is getting picked up because I can't edit or delete it. I've made sure that the file names match. Any help would be appreciated

Jackson...!!! said...

My issue is same as what Ivan had told in his comment, i also but created same project, which got compiled without errors, but I can't get Microsoft StyleCop to pick the rule. Is there any other setting to integrate our custom rule in StypeCop?

Jackson C.

Zeor said...

If anyone should come by this; The project is now opensource and by looking it up I found out that the assembly should be build with .NET 3.5. If using another version, then the assembly will not be picked up and you can not see your own rules.

EnThu said...

I need to count lines of code in a method in c#. Can i add my custom rule for the same. Please help.
Thanks in advance for help.

EnThu said...

Hwy i am not able to see my custom created rule in the setting.stylecop. Can anyone help my assembly is 3.5 built my name of the XML file is same as name of class.
Please help.

D. Maymone said...

I have exactly the same problem as En Thu.
I am not able to see my custom created rule in the setting.stylecop. My assembly is 3.5. Same name to XML and class file. But I don't see the "Extensions" entry in the setting file.
Please help.

graydo64 said...

I had the same problem as EnThu and D. Maymone. I'd followed your post to the letter, checked it against the SDK but couldn't get my custom rule to load. I had used the nuget package in my project to get the references for StyleCop and StyleCop.CSharp. I found that removing the nuget package and referenced the dlls in %programfiles%\StyleCop 4.7 instead fixed the problem.

D. Maymone said...

I am not able yet to see my custom created rule in the setting.stylecop. My assembly is 3.5. Same name to XML and class file. But I don't see the "Extensions" entry in the setting file.
When I double click the Settings file this error is displayed:
An exception occurred while loading one of the StyleCop add-ins: System.IO.FileLoadException,
Could not load file or assembly 'StyleCop, Version=, Culture=neutral,
PublicKeyToken=f904653c63bc2738' or one of its dependencies.
The located assembly's manifest definition does not match the assembly reference. (
Exception from HRESULT: 0x80131040)

Allan said...

Custom software development specialists explore exactly what it is a company does - what the necessities of the company are on a day to day basis and what they need from their IT system in order to operate to their optimum. In order to perform efficient functionality, a company would ideally need its software to do exactly what they want it to.

Unknown said...
This comment has been removed by the author.
Unknown said...

I can able to create my own custom rule in stylecop.When I open the settings file via visual studio my custom rules appear in separate Rule Group.I need to add it with stylecop rule ( e.g Documentation Rule ).Any idea?

yosabrams0918 said...

?I used to be very happy to search out this net-site.I needed to thanks for your time for this wonderful read!! I undoubtedly enjoying every little little bit of it and I have you bookmarked to check out new stuff you blog post. usa online casino

Catabatic Technology said...

What is the Creating Custom StyleCop Rules in C#. I have no idea but after reading this post i have this rule. thanks for sharing this info.

Travel Software Development Solution India | Travel Portal Development | Software Development Solutions

Best Digital Marketing Agency said...

Great Post Thanks for sharing with us and it is very helpful for us. Check this link also here: Software Development Company India

Prachi Kalra said...

Highly Commendable blog! Keep up the great work

SRDV Technologies | Web Development | Mobile App Development said...

what is fantastic post? this is so chock full of useful information I cannot wait to dig deep and start utilizing the resource give me.your exuberance is refreshing.
Software Development Travel portal development Travel white label Travel Portal Solution B2C Travel Portal B2B Travel Portal Flight Booking API System Flight api integration

DedicatedHosting4u said...

We will certainly see your enthusiasm in the work you have written. Incredible post. Articles that have important and well-informed notes are also enjoyable. Beautiful piece of article.

Pankaj Singh said...

Nice blog. OGEN Infosystem is leading Web Designing Company in Delhi, India, visit our website for web designing and SEO Services.
SEO Service in Delhi

Pradeep Appslure said...

Appslure is Best app development company in mumbai and you can get website development service at a very affordable price.
App development company in mumbai

keylinesnet said...

I am really impressed with your blog article, such great & useful knowledge you mentioned here. Your post is very informative. Also check out the best web development company in Kolkata | web hosting company in Kolkata | hotel management colleges in Kolkata

jeewangarg said...

Jeewangarg is a Leading Digital Marketing Company which is helping your brand to cut through the Digital Clutter with its best SEO Company in Delhi. Our range of Services includes SEO Services, PPC Company in Delhi, Website Designing Services and Social Media Marketing Services. Being a Google Partner in India, we provide our client with 100% satisfaction in every aspect of their marketing goals. So, what are you waiting for Connect to the team of best SEO Expert in India, Google Ads Experts, Website Designing Experts, Social Media Experts & more to boost your Digital Presence today with the high quality Digital Marketing Services.

Servo said...

Servo Stabilizer Manufacturer in India, Servo Star offers a wide range of single phase to three-phase Servo Voltage Stabilizer units to suit various types of domestic and industrial applications such as metal processing equipment, production lines, construction devices, elevators, medical equipment, air-conditioners, etc. Call us on 9250809090 to get the best quote for Servo Stabilizer Price & Transformer Price in India.

Video Production Company said...

TVH, Best Video & Film Production Houses/Company in Delhi Ncr. we Provides Corporate Films, Documentary Films, Short Makers, Explainer Videos, & promotional video services in delhi ncr. Call us @ 8178662477. Best Video & Film Production Houses/company in Delhi NCR Visit Us: film production companies in india, corporate video production company

Arrowaircraft said...

Arrow Aircraft is one of the reliable private jet india. We offer Aircraft Charter Services in Delhi, Mumbai as well as all over the World.

Kedarnath Yatra by Helicopter
Chardham Yatra by Helicopter
Book Helicopter for Wedding Price

Appslure said...

Great information shared through this post. It helps me in many ways.Thanks for posting this again. We are top Mobile App Development | Mobile App Development Company in India | Website Development Company in Delhi | Website Designing Company in Gurgaon.

pankaj shukla said...

Thanks for sharing useful information. We are leading mobile app development companies in dubai.

Video Production Company said...

Well I definitely enjoyed reading it. This tip procured by you is very constructive for correct planning.

event management companies
event management companies in delhi

chouaih mohammed said...

i am browsing this website dailly and get nice facts from here all the time

Servomax Ltd said...

Servo Stabilizers, Servomax offers a wide range of Servo Voltage Stabilizer units to suit various types of domestic and industrial applications such as metal processing equipment, production lines, construction devices, elevators, medical equipment, etc. Call us on +91 9111234567 to get the best quote for Servo Stabilizer Price.

Jordan said...

You can create backlinks to your website from these links…...Most beautiful places in the world  | bordeaux France  | things to do in bordeaux | beautiful places in Pakistan | Bali Indonesia | Explore Worldwide | lake Tahoe attractions | Kumrat Valley |

Kettysmith said...

Towing Elite is the best service providers for towing cars, trucks and more. We are offering our services in multiple locations and in best charges. Call us to get more information.
Towing Services in Beaverton
Tow Truck Company near Mt St Helens
Towing Services near Cougar
Tow Truck Company in Portland
Tow Truck Company in Gresham
Tow Truck Company in Tigard

Village Talkies said...

Best Corporate Video Production Company in Bangalore and top Explainer Video Company in Bangalore , 3d, 2d Animation Video Makers in Chennai.
Great tips! But one more thing we would like to add here i.e Browser compatibility is also a must.

SEO said...

Move a step forward and connect with your audience with our PPC Experts India

Thinking PPC advertising? Think Us. Get in touch with our team and coordinate with the experts around. We will help you take your business a step forward and build your customers regularly. Our comprehensive approach and dedication make us a company one can rely on for PPC services in India. Share your thoughts and ideas with us and we will make sure that each and every one of them gets fulfilled in no time professionally.

Home Refurbishment in London said...

Hiring The Equitable Local Builders In London For Home Improvements Services

It is always said that people often desire to be in a house that could give them a desired luxury and comfort and that could only be done with some efforts. Although some manage to furnish their home by themselves, at times this can be tedious to them and also time taking.

Kettysmith said...

Nearest Facility Maintenance Company based in USA and offering it services in multiple locations. We are helping in parking lot repairing, roof repairing, home repairing and more. Call us to get more information.
Nearest Facility Maintenance
Nearest General Contractor Company
Nearest Construction Facility
Nearest Fencing Company
Home Maintenance Services
Nearest Parking Lot Signs Company

Tech said...

Microsoft Office suite has become a must-have not only for large corporations but for individual users as well. The latter face the necessity to download Office programs once they understand that apps integrated into their OS are too basic and can’t satisfy their needs.
Microsoft Office Torrent

davidclauses said...

Now you can move to various location safely with Taipan Express Movers. Shift your high value items, pets, kids and more with us in genuine charges.
Packers and Movers in Malaysia
International Movers in Malaysia
Packers & Movers Near Me
International relocation services
Furniture Storage Solutions
Moving with Kids
Moving with Pets
Moving High Value Items

Test Marketing said...

The number of people looking for Microsoft Office torrent is growing every day. The tendency is obvious since this package of programs has long become popular among millions of users all over the globe, supplying them with all the necessary tools for work with text, spreadsheets and presentations.

Microsoft office torrent

Quickbooks Phone Number said...

Nice Blog!
Facing error while using QuickBooks get instant solution with our QuickBooks experts.Dial +1-(855)533-6333 QuickBooks Enterprise Support Phone Number

Unknown said...

We are an experienced team in one of the Best software company and product specialist for software development and implementation. Sovereign provides Website Design, Web Development and Mobile App Development, Digital marketing and SEO Services.

Prashant Baghel said...

lTop 10 Best Event Management Companies In Delhi

Wismarketing said...

Nice post thanks for sharing with us and it is very informative and helplful for us. Gain today's most in-demand skills. Gain the skills you need, whether you're growing your business, starting a career, or just want to try something new. Learn Digital Marketing course in Thailand from Wismarketing. Digital Marketing can be used to plan business development. Call us to Book Now - +66 64 942 2452 or visit - Digital Marketing Courses In Thailand

Sapna Rajput said...

Hritika is a Call Girl in Town who isn’t afraid to walk on the wild side, as you can see from her lengthy services list. Hritika is a tall and young beautiful Call Girl in Town, the first time in town. Not only does this Town sensation look like a million dollars, but she has a seductive playfulness and open-minded attitude which sets her apart from other Town.
Chas Escorts
Dumka Escorts
Simdega Escorts
Ranchi Escorts
Jamshedpur Escorts
Manali Escorts
Arki Escorts
Baddi Escorts
Bhuntar Escorts

Diinfotech said...

Software Development Company in Delhi

Wismarketing said...

Great Post Thanks For Sharing With Us. Not sure which digital marketing strategies are right for your business? Find out in our breakdown of this year's best Internet marketing strategies! Boost your Business online with our best digital marketing courses in thailand. We provide SEO, PPC advertising and marketing courses to boost your online growth and achieve your success. Call us to Book Now - +66 64 942 2452 or visit - Digital Marketing Training In Thailand|{Digital Marketing Courses In Thailand}

Wismarketing said...

Hire Wismarketing a best Social Media Marketing Services In Thailand to build your brand awareness. Social media marketing is the use of social media platforms to connect with your audience to build your brand, increase sales, and drive website traffic. To Know More Visit
Social Media Marketing Services In Thailand or Call us to Book Now +66 64 942 2452

Britney Wilson said...

Nice Post Thanks For Sharing With Us. Belly fat is generally exhausting to affect, as factors including diet, stress, and health conditions among others make it easy for the world to expand, but nearly impossible for it to shrink. Try Beyond 40 LeanBelly 3X and Reduce Your Weight Loss in Weeks. Learn More Weight Loss Supplement LeanBelly 3X
Buy Now LeanBelly 3x Weight Loss Supplement

Buy Now At Shoperstylez a best Online Shopping Store In USA

Wismarketing said...

Nice Post Thanks For Sharing With Us. Advantage of digital marketing for Startup or business is that a targeted audience can be reached in a cost-effective and measurable way. Boost their visibility. Increase online conversion rates. Reduce their marketing budget.Increase online conversion rates.
To Know More Call us to Book Now +66 64 942 2452 Visit
Digital Marketing Courses In Thailand
Content marketing services in Thailand
SEO Company In Thailand
Social Media Marketing Services In Thailand
Website Design And Development Company In Thailand

Sally T. Durgan said...

Benefits of Online Shopping over normal brick-and-mortar shopping. Is buying something online cheaper than buying it offline People increasingly choosing to shop online at Shopperstylez instead of shopping at their local stores.

Wismarketing said...

Great Post Thanks For Sharing. Wismarketing is a Website Design and Development Company In Thailand Most Trusted Brand at Affordable Prices. Call Now. Experience Team of Designers and Developers. Amazing Skills. Creative Designs. Hire Now. Get Free Quote. 24/7 Free Support. Best Website Designer. Free Website Analysis.
To Know More Call us to Book Now +66 64 942 2452 Visit
Digital Marketing Courses In Thailand
Content marketing services in Thailand
SEO Company In Thailand
Social Media Marketing Services In Thailand
Website Design And Development Company In Thailand

Wismarketing said...

Great Post Thanks For Sharing. Get more than just a pretty website - get a site that converts your traffic into customers. Website design, SEO, marketing, and more. Get real results. Wismarketing is a best Website Development Company In Thailand build or transform a website that functions to worldwide standards and represents your business in a whole new way.
To Know More Call us to Book Now +66 64 942 2452 Visit
Digital Marketing Courses In Thailand
Content marketing services in Thailand
SEO Company In Thailand
Social Media Marketing Services In Thailand
Website Design And Development Company In Thailand

Wismarketing said...

Great Post Thanks For Sharing. Today we'll take a look at the best content marketing companies in the industry. Content marketing services in Thailand can be utilized by businesses across a variety of industries that aim to expand their user base - — Think Web. Think Smart. Partner with the #1 Rated Digital Marketing Company In Thailand
To Know More Call us to Book Now +66 64 942 2452 Visit
Digital Marketing Courses In Thailand
Content marketing services in Thailand
SEO Company In Thailand
Social Media Marketing Services In Thailand
Website Design And Development Company In Thailand

Wismarketing said...

Nice Post Thanks For Sharing With Us. Designing a great website is not at all an easy task; it requires creativity, understanding of business needs, Lots of efforts and communication. Hire our expert web developers to make your website unique. Check out our company's unique design and development portfolio, services and offers. Join @wismarketing Today!

To Know More Call us to Book Now +66 64 942 2452 Visit
Digital Marketing Courses In Thailand
Content marketing services in Thailand
SEO Company In Thailand
Social Media Marketing Services In Thailand
Website Design And Development Company In Thailand

Rohan Singh said...

This is a great blog; it has all the covered topics I was looking for. You can also visit they have the same domain and posts some really good content. Also visit: mobile application development company

Unknown said...

Wow! Such an amazing and helpful post this is. I really really love it. It's so good and so awesome. I am just amazed. I hope that you continue to do your work like this in the future also. learn more about magento development.

Village Talkies said...

Informative blog! it was very useful for me.Thanks for sharing. Do share more ideas regularly.
Village Talkies a top-quality professional corporate video production company in Bangalore and also best explainer video company in Bangalore & animation video makers in Bangalore, Chennai, India & Maryland, Baltimore, USA provides Corporate & Brand films, Promotional, Marketing videos & Training videos, Product demo videos, Employee videos, Product video explainers, eLearning videos, 2d Animation, 3d Animation, Motion Graphics, Whiteboard Explainer videos Client Testimonial Videos, Video Presentation and more for all start-ups, industries, and corporate companies. From scripting to corporate video production services, explainer & 3d, 2d animation video production , our solutions are customized to your budget, timeline, and to meet the company goals and objectives.
As a best video production company in Bangalore, we produce quality and creative videos to our clients.

Jon Hendo said...

event planner. partnership also significantly reduces the lift for event planners by recruiting partners on each end of the production and virtual and onsite also who can anticipate each other’s needs and coordinate accordingly behind the scenes and Their experience working together on a number of events. networking invitation

Susunia Hill said...

Susunia Hill Hotel
Hotel in Susunia Hill
Resort in Susunia Hill
Susunia Hill Resort
Hotels in Susunia Hill
Visit Site Hotel in Susunia Hill
For Booking Resort in Susunia Hill

tejaswani blogs said...

You've offered some excellent resources for users. Reading the post was a fascinating experience for me. Thank you very much. Such issues, as well as everything related to them, appeal to me.

digital marketing training in hyderabad
digital marketing course in ameerpet
digital marketing course training in hyderabad ameerpet
digital marketing online training in hyderabad

haritha said...

informative content. Thanks for sharing your knowledge.
Best Web designing company in Hyderabad
Best Web development company in Hyderabad