How to Create StyleCop Custom Rule
This article gives simple step-by-step guide which could be useful for learning how to create own StyleCop rules.
Consider downloading the
complete Visual Studio project if needed.
Step 1. Create a project
Create a new Visual Studio class library project targeting .NET 3.5.
Step 2. Add references
Add references to the following binaries (can be found in StyleCop installation folder):
Step 3. Add analyzer class
After adding references, create a new class for StyleCop analyzer.

Analyzer could be understood as an "engine" containing several rules with similar behavior.
There could be several analyzers in one custom rules assembly.
Put the following code into your analyzer class:
using StyleCop;
using StyleCop.CSharp;
namespace MyCustomRules
{
/// <summary>
/// Custom analyzer for demo purposes.
/// </summary>
[SourceAnalyzer(typeof(CsParser))]
public class MyCustomAnalyzer : SourceAnalyzer
{
/// <summary>
/// Extremely simple analyzer for demo purposes.
/// </summary>
public override void AnalyzeDocument(CodeDocument document)
{
CsDocument doc = (CsDocument)document;
// skipping wrong or auto-generated documents
if (doc.RootElement == null || doc.RootElement.Generated)
return;
// check all class entries
doc.WalkDocument(CheckClasses);
}
/// <summary>
/// Checks whether specified element conforms custom rule CR0001.
/// </summary>
private bool CheckClasses(
CsElement element,
CsElement parentElement,
object context)
{
// if current element is not a class then continue walking
if (element.ElementType != ElementType.Class)
return true;
// check whether class name contains "a" letter
Class classElement = (Class)element;
if (classElement.Declaration.Name.Contains("a"))
{
// add violation
// (note how custom message arguments could be used)
AddViolation(
classElement,
classElement.Location,
"AvoidUsingAInClassNames",
classElement.FriendlyTypeText);
}
// continue walking in order to find all classes in file
return true;
}
}
}
Step 4. Add analyzer definition file
Each analyzer should be provided with an XML file containing rule definition.
Create a new XML file:
- named exactly as analyzer class
- specify build action as "Embedded Resource"

Put the following content into your analyzer definition file:
<?xml version="1.0" encoding="utf-8" ?>
<SourceAnalyzer Name="My Custom Rule">
<Description>
Custom rule for demo purposes.
</Description>
<Rules>
<Rule Name="AvoidUsingAInClassNames" CheckId="CR0001">
<Context>Do not use 'a' letter in {0} names.</Context>
<Description>Fires when 'a' letter is used in class name.</Description>
</Rule>
</Rules>
</SourceAnalyzer>
Step 5. Build and deploy
You custom rules are almost ready.
Build the library, and copy output file to the StyleCop installation directory.
Step 6. Check how it works
Exit Visual Studio and run it again.
Now your custom rules should be loaded and could be seen in StyleCop settings editor.

You can also make sure that rules are actually executed.
