Is it possible to write custom C# StyleCop rules that can evaluate conditional compilation preprocessor directives like #if, #elif, #else, #endif?
We're developing in an environment which requires us to use conditional compilation symbols, and I want to add our custom coding conventions on top of that.
Is this possible with the CsDocument.WalkDocument
- method, or do I have to utilize something else?
(FxCop is not going to work here as it works on already compiled binaries).
Yes, it's possible, but the CsDocument.WalkDocument
overloads won't help since pre-processor directives are represented as tokens only. They have no corresponding element, statement, or expression.
To write a rule for conditional compilation directives, you need to examine the CsDocument.Tokens collection. e.g.:
foreach (var directive in document.Tokens
.Where(t => t.CsTokenClass == CsTokenClass.ConditionalCompilationDirective)
.Cast<ConditionalCompilationDirective>())
{
// ...
}