the stylecop tool provides warnings ... - documentation & help · documentation rules (sa1600-)...
TRANSCRIPT
TheStyleCoptoolprovideswarningsthatindicatestyleandconsistencyruleviolationsinC#code.Bydefault,thetoolintegratesintoVisualStudio2008andVisualStudio2010,anditcanalsobeintegratedintoMSBuild-basedbuildsystems.Itisalsopossibletoauthorcustomrulestorunwithinthetool,andtocreateawrapperhosttointegratethetoolintoacustombuildenvironment.
StyleCopRulesDocumentation
StartingwithStyleCop4.3.2,itispossibletosuppressthereportingofruleviolationsbyaddingsuppressionattributeswithinthesourcecode.
RuleSuppressions
TheStyleCoptoolprovideswarningsthatindicatestyleandconsistencyruleviolationsinC#code.Thewarningsareorganizedintoruleareassuchasdocumentation,layout,naming,ordering,readability,spacing,andsoforth.Eachwarningsignifiesaviolationofastyleorconsistencyrule.ThissectionprovidesanexplanationofeachofthedefaultStyleCoprules.
InThisSectionDocumentationRules(SA1600-)
Ruleswhichverifythecontentandformattingofcodedocumentation.
LayoutRules(SA1500-)
Ruleswhichenforcecodelayoutandlinespacing.
MaintainabilityRules(SA1400-)
Ruleswhichimprovecodemaintainability.
NamingRules(SA1300-)
Ruleswhichenforcenamingrequirementsformembers,types,andvariables.
OrderingRules(SA1200-)
Ruleswhichenforceastandardorderingschemeforcodecontents.
ReadabilityRules(SA1100-)
Ruleswhichensurethatthecodeiswell-formattedandreadable.
SpacingRules(SA1000-)
Ruleswhichenforcespacingrequirementsaroundkeywordsandsymbolsinthecode.
RelatedTopicsStartingwithStyleCop4.3.2,itispossibletosuppressthereportingofruleviolationsbyaddingsuppressionattributeswithinthesourcecode.
RuleSuppressions
Ruleswhichverifythecontentandformattingofcodedocumentation.
SA1600:ElementsMustBeDocumented
SA1601:PartialElementsMustBeDocumented
SA1602:EnumerationItemsMustBeDocumented
SA1603:DocumentationMustContainValidXml
SA1604:ElementDocumentationMustHaveSummary
SA1605:PartialElementDocumentationMustHaveSummary
SA1606:ElementDocumentationMustHaveSummaryText
SA1607:PartialElementDocumentationMustHaveSummaryText
SA1608:ElementDocumentationMustNotHaveDefaultSummary
SA1609:PropertyDocumentationMustHaveValue
SA1610:PropertyDocumentationMustHaveValueText
SA1611:ElementParametersMustBeDocumented
SA1612:ElementParameterDocumentationMustMatchElementParameters
SA1613:ElementParameterDocumentationMustDeclareParameterName
SA1614:ElementParameterDocumentationMustHaveText
SA1615:ElementReturnValueMustBeDocumented
SA1616:ElementReturnValueDocumentationMustHaveValue
SA1617:VoidReturnValueMustNotBeDocumented
SA1618:GenericTypeParametersMustBeDocumented
SA1619:GenericTypeParametersMustBeDocumentedPartialClass
SA1620:GenericTypeParameterDocumentationMustMatchTypeParameters
SA1621:GenericTypeParameterDocumentationMustDeclareParameterName
SA1622:GenericTypeParameterDocumentationMustHaveText
SA1623:PropertySummaryDocumentationMustMatchAccessors
SA1624:
PropertySummaryDocumentationMustOmitSetAccessorWithRestricedAccess
SA1625:ElementDocumentationMustNotBeCopiedAndPasted
SA1626:SingleLineCommentsMustNotUseDocumentationStyleSlashes
SA1627:DocumentationTextMustNotBeEmpty
SA1628:DocumentationTextMustBeginWithACapitalLetter
SA1629:DocumentationTextMustEndWithAPeriod
SA1630:DocumentationTextMustContainWhitespace
SA1631:DocumentationTextMustMeetCharacterPercentage
SA1632:DocumentationTextMustMeetMinimumCharacterLength
SA1633:FileMustHaveHeader
SA1634:FileHeaderMustShowCopyright
SA1635:FileHeaderMustHaveCopyrightText
SA1636:FileHeaderCopyrightTextMustMatch
SA1637:FileHeaderMustContainFileName
SA1638:FileHeaderFileNameDocumentationMustMatchFileName
SA1639:FileHeaderMustHaveSummary
SA1640:FileHeaderMustHaveValidCompanyText
SA1641:FileHeaderCompanyNameTextMustMatch
SA1642:ConstructorSummaryDocumentationMustBeginWithStandardText
SA1643:DestructorSummaryDocumentationMustBeginWithStandardText
SA1644:DocumentationHeadersMustNotContainBlankLines
SA1645:IncludedDocumentationFileDoesNotExist
SA1646:IncludedDocumentationXPathDoesNotExist
SA1647:IncludeNodeDoesNotContainValidFileAndPath
SA1648:InheritDocMustBeUsedWithInheritingClass
SA1649:FileHeaderFileNameDocumentationMustMatchTypeName
TypeName ElementsMustBeDocumented
CheckId SA1600
Category DocumentationRules
CauseAC#codeelementismissingadocumentationheader.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccursifanelementiscompletelymissingadocumentationheader,oriftheheaderisempty.InC#thefollowingtypesofelementscanhavedocumentationheaders:classes,constructors,delegates,enums,events,finalizers,indexers,interfaces,methods,properties,andstructs.
HowtoFixViolationsTofixaviolationofthisrule,addorfill-inadocumentationheaderfortheelement.
thefollowingexampleshowsamethodwithavaliddocumentationheader:
///<summary>
///Joinsafirstnameandalastnametogetherintoasinglestring.
///</summary>
///<paramname="firstName">Thefirstnametojoin.</param>
///<paramname="lastName">Thelastnametojoin.</param>
///<returns>Thejoinednames.</returns>
publicstringJoinNames(stringfirstName,stringlastName)
{
returnfirstName+""+lastName;
}
TypeName PartialElementsMustBeDocumented
CheckId SA1601
Category DocumentationRules
CauseAC#partialelementismissingadocumentationheader.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccursifapartialelement(anelementwiththepartialattribute)iscompletelymissingadocumentationheader,oriftheheaderisempty.InC#thefollowingtypesofelementscanbeattributedwiththepartialattribute:classes,methods.
Whendocumentationisprovidedonmorethanonepartofthepartialclass,thedocumentationforthetwoclassesmaybemergedtogethertoformasinglesourceofdocumentation.Forexample,considerthefollowingtwopartsofapartialclass:
///<summary>
///DocumentationforthefirstpartofClass1.
///</summary>
publicpartialclassClass1
{
}
///<summary>
///DocumentationforthesecondpartofClass1.
///</summary>
publicpartialclassClass1
{
}
Thesetwodifferentpartsofthesamepartialclasseachprovidedifferentdocumentationfortheclass.WhenthedocumentationforthisclassisbuiltintoanSDK,thetoolbuildingthedocumentationwilleitherchoosetouseonlyonepartofthedocumentationfortheclassandignoretheotherparts,or,insomecases,itmaymergethetwosourcesofdocumentationtogether,toformastringlike:“DocumentationforthefirstpartofClass1.DocumentationforthesecondpartofClass1.”
Forthesereasons,itcanbeproblematictoprovideSDKdocumentationonmorethanonepartofthepartialclass.However,itisstilladvisabletodocumenteachpartoftheclass,toincreasethereadabilityandmaintainabilityofthecode,andStyleCopwillrequirethateachpartoftheclasscontainheaderdocumentation.
Thisproblemissolvedthroughtheuseofthe<content>tag,whichcanreplacethe<summary>tagforpartialclasses.TherecommendedpracticefordocumentingpartialclassesistoprovidetheofficialSDKdocumentationfortheclassonthemainpartofthepartialclass.Thisdocumentationshouldbewrittenusingthestandard<summary>tag.Allotherpartsofthepartialclassshouldomitthe<summary>tagcompletely,andreplaceitwitha<content>tag.ThisallowsthedevelopertodocumentallpartsofthepartialclasswhilestillcentralizingalloftheofficialSDKdocumentationfortheclassontoonepartoftheclass.The<content>tagswillbeignoredbytheSDKdocumentationtools.
HowtoFixViolationsTofixaviolationofthisrule,addorfill-inadocumentationheaderfortheelement.
Forexample,thefollowingexampleshowstwopartsofapartialclass,onecontaininga<summary>headerandanothercontaininga<content>header.
///<summary>
///Representsacustomerinthedatabase.
///</summary>
publicpartialclassCustomer
{
}
///<content>
///Containsauto-generatedfunctionalityfortheCustomerclass.
///</content>
publicpartialclassCustomer
{
}
TypeName EnumerationItemsMustBeDocumented
CheckId SA1602
Category DocumentationRules
CauseAnitemwithinaC#enumerationismissinganXmldocumentationheader.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccurswhenanitemwithinanenumerationismissingaheader.Forexample:
///<summary>
///Typesofanimals.
///</summary>
publicenumAnimals
{
Dog,
Cat,
Horse
}
HowtoFixViolationsTofixaviolationofthisrule,addadocumentationheaderforeachitemwithintheenum.Forexample:
///<summary>
///Typesofanimals.
///</summary>
publicenumAnimals
{
///<summary>
///Representsadog.
///</summary>
Dog,
///<summary>
///Representsacat.
///</summary>
Cat,
///<summary>
///Representsahorse.
///</summary>
Horse
}
TypeName DocumentationMustContainValidXml
CheckId SA1603
Category DocumentationRules
CauseTheXmlwithinaC#element’sdocumentheaderisbadlyformed.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
AviolationofthisruleoccurswhenthedocumentationXmlisbadlyformedandcannotbeparsed.ThiscanoccuriftheXmlcontainsinvalidcharacters,orifanXmlnodeismissingaclosingtag,forexample.
HowtoFixViolationsTofixaviolationofthisrule,replacethebadlyformedXmlwithvalidXmlthatcanbeparsedbyastandardXmlparser.
ThefollowingexampleshowsaclasscontaininginvalidXmlwithinitsdocumentationheader.Theclosingtagforthe<summary>nodeisinvalid.
///<summary>
///AnexampleofbadlyformedXml.
///</summa3ry>
publicclassExample
{
}
TypeName ElementDocumentationMustHaveSummary
CheckId SA1604
Category DocumentationRules
CauseTheXmlheaderdocumentationforaC#elementismissinga<summary>tag.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccurswhentheelementdocumentationismissinga<summary>tag.
HowtoFixViolationsTofixaviolationofthisrule,addandfill-ina<summary>tagfortheelement,containingadescriptionoftheelement.
ThefollowingexampleshowsaclasscontaininginvalidXmlwithinitsdocumentationheader.Theclosingtagforthe<summary>nodeisinvalid.
///<summary>
///Representsacustomerinthedatabase.
///</summary>
publicclassCustomer
{
}
TypeName PartialElementDocumentationMustHaveSummary
CheckId SA1605
Category DocumentationRules
CauseThe<summary>or<content>tagwithinthedocumentationheaderforaC#codeelementismissingorempty.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccurswhenthedocumentationheaderforapartialelement(anelementwiththepartialattribute)ismissinga<summary>or<content>tag,orcontainsanempty<summary>or<content>tagwhichdoesnotcontainadescriptionoftheelement.InC#thefollowingtypesofelementscanbeattributedwiththepartialattribute:classes,methods.
Whendocumentationisprovidedonmorethanonepartofthepartialclass,thedocumentationforthetwoclassesmaybemergedtogethertoformasinglesourceofdocumentation.Forexample,considerthefollowingtwopartsofapartialclass:
///<summary>
///DocumentationforthefirstpartofClass1.
///</summary>
publicpartialclassClass1
{
}
///<summary>
///DocumentationforthesecondpartofClass1.
///</summary>
publicpartialclassClass1
{
}
Thesetwodifferentpartsofthesamepartialclasseachprovidedifferentdocumentationfortheclass.WhenthedocumentationforthisclassisbuiltintoanSDK,thetoolbuildingthedocumentationwilleitherchoosetouseonlyonepartofthedocumentationfortheclassandignoretheotherparts,or,insomecases,itmaymergethetwosourcesofdocumentationtogether,toformastringlike:“DocumentationforthefirstpartofClass1.DocumentationforthesecondpartofClass1.”
Forthesereasons,itcanbeproblematictoprovideSDKdocumentationonmorethanonepartofthepartialclass.However,itisstilladvisabletodocumenteachpartoftheclass,toincreasethereadabilityandmaintainabilityofthecode,andStyleCopwillrequirethateachpartoftheclasscontainheaderdocumentation.
Thisproblemissolvedthroughtheuseofthe<content>tag,whichcanreplacethe<summary>tagforpartialclasses.TherecommendedpracticefordocumentingpartialclassesistoprovidetheofficialSDKdocumentationfortheclassonthemainpartofthepartialclass.Thisdocumentationshouldbewrittenusingthestandard<summary>tag.Allotherpartsofthepartialclassshouldomitthe<summary>tagcompletely,andreplaceitwitha<content>tag.ThisallowsthedevelopertodocumentallpartsofthepartialclasswhilestillcentralizingalloftheofficialSDKdocumentationfortheclassontoonepartoftheclass.The<content>tagswillbeignoredbytheSDKdocumentationtools.
HowtoFixViolationsTofixaviolationofthisrule,addandfill-ina<summary>or<content>tagwithadescriptionofthecodeelement.
Thefollowingexampleshowsapartialclasswithafill-in<summary>tag.
///<summary>
///Representsacustomerinthedatabase.
///</summary>
publicpartialclassCustomer
{
}
TypeName ElementDocumentationMustHaveSummaryText
CheckId SA1606
Category DocumentationRules
CauseThe<summary>tagwithinthedocumentationheaderforaC#codeelementisempty.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccurswhenthedocumentationheaderforanelementcontainsanempty<summary>tagwhichdoesnotcontainadescriptionoftheelement.
HowtoFixViolationsTofixaviolationofthisrule,fill-inthe<summary>tagwithadescriptionofthecodeelement.
Example:
Thefollowingexampleshowsamethodwhichcontainsanempty<summary>tag.
///<summary></summary>
///<paramname="customerId">TheIDofthecustomertofind.</param>
///<returns>Thecustomer,ornullifthecustomercouldnotbe
///found.</returns>
publicCustomerFindCustomer(intcustomerId)
{
//...findsthecustomer...
}
TypeName PartialElementDocumentationMustHaveSummaryText
CheckId SA1607
Category DocumentationRules
CauseThe<summary>or<content>tagwithinthedocumentationheaderforaC#codeelementisempty.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccurswhenthedocumentationheaderforapartialelement(anelementwiththepartialattribute)containsanempty<summary>tagor<content>tagwhichdoesnotcontainadescriptionoftheelement.InC#thefollowingtypesofelementscanbeattributedwiththepartialattribute:classes,methods.
Whendocumentationisprovidedonmorethanonepartofthepartialclass,thedocumentationforthetwoclassesmaybemergedtogethertoformasinglesourceofdocumentation.Forexample,considerthefollowingtwopartsofapartialclass:
///<summary>
///DocumentationforthefirstpartofClass1.
///</summary>
publicpartialclassClass1
{
}
///<summary>
///DocumentationforthesecondpartofClass1.
///</summary>
publicpartialclassClass1
{
}
Thesetwodifferentpartsofthesamepartialclasseachprovidedifferentdocumentationfortheclass.WhenthedocumentationforthisclassisbuiltintoanSDK,thetoolbuildingthedocumentationwilleitherchoosetouseonlyonepartofthedocumentationfortheclassandignoretheotherparts,or,insomecases,itmaymergethetwosourcesofdocumentationtogether,toformastringlike:“DocumentationforthefirstpartofClass1.DocumentationforthesecondpartofClass1.”
Forthesereasons,itcanbeproblematictoprovideSDKdocumentationonmorethanonepartofthepartialclass.However,itisstilladvisabletodocumenteachpartoftheclass,toincreasethereadabilityandmaintainabilityofthecode,andStyleCopwillrequirethateachpartoftheclasscontainheaderdocumentation.
Thisproblemissolvedthroughtheuseofthe<content>tag,whichcanreplacethe<summary>tagforpartialclasses.TherecommendedpracticefordocumentingpartialclassesistoprovidetheofficialSDKdocumentationfortheclassonthemainpartofthepartialclass.Thisdocumentationshouldbewrittenusingthestandard<summary>tag.Allotherpartsofthepartialclassshouldomitthe<summary>tagcompletely,andreplaceitwitha<content>tag.ThisallowsthedevelopertodocumentallpartsofthepartialclasswhilestillcentralizingalloftheofficialSDKdocumentationfortheclassontoonepartoftheclass.The<content>tagswillbeignoredbytheSDKdocumentationtools.
HowtoFixViolationsTofixaviolationofthisrule,fill-inthecontentsofthesummarytagorcontenttagwithadescriptionofthecodeelement.
Thefollowingexampleshowsamethodwhichcontainsanempty<summary>tag.
///<summary></summary>
///<paramname="customerId">TheIDofthecustomertofind.</param>
///<returns>Thecustomer,ornullifthecustomercouldnotbefound.</returns>
publicCustomerFindCustomer(intcustomerId)
{
//...findsthecustomer...
}
Tofixtheviolation,addvalidsummarytext.Forexample:
///<summary>AttemptstolocatearecordforthecustomerwiththegivenID.</summary>
///<paramname="customerId">TheIDofthecustomertofind.</param>
///<returns>Thecustomer,ornullifthecustomercouldnotbefound.</returns>
publicCustomerFindCustomer(intcustomerId)
{
//...findsthecustomer...
}
TypeName ElementDocumentationMustNotHaveDefaultSummary
CheckId SA1608
Category DocumentationRules
CauseThe<summary>tagwithinanelement’sXmlheaderdocumentationcontainsthedefaulttextgeneratedbyVisualStudioduringthecreationoftheelement.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
VisualStudioprovideshelperfunctionalityforaddingnewelementssuchasclassestoaproject.VisualStudiowillcreateadefaultdocumentationheaderforthenewclassandfillinthisheaderwithdefaultdocumentationtext.
Aviolationofthisruleoccurswhenthe<summary>tagforacodeelementstillcontainsthedefaultdocumentationtextgeneratedbyVisualStudio.
HowtoFixViolationsTofixaviolationofthisrule,replacethedefaultdocumentationtextwithnewtextdescribingthecontentsofthecodeelement.
ThefollowingexampleshowsaclasswhichcontainsthedefaultsummarytextgeneratedbyVisualStudio.
///<summary>
///SummarydescriptionfortheExampleclass.
///</summary>
publicclassExample
{
}
TypeName PropertyDocumentationMustHaveValue
CheckId SA1609
Category DocumentationRules
CauseTheXmlheaderdocumentationforaC#propertydoesnotcontaina<value>tag.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Thedocumentationforpropertiesmayincludea<value>tag,whichdescribesthevalueheldbytheproperty.
Aviolationofthisruleoccurswhenthe<value>tagforapropertyismissing.
HowtoFixViolationsTofixaviolationofthisrule,addandfill-ina<value>tagwithinthedocumentationheaderfortheproperty.
Thefollowingexampleshowsapropertywhichcontainsa<value>tagwithinitsdocumentationheader.
///<summary>
///Getsthenameofthecustomer.
///</summary>
///<value>Thenameofthecustomer.</value>
publicboolName
{
get{returnthis.name;}
}
TypeName PropertyDocumentationMustHaveValueText
CheckId SA1610
Category DocumentationRules
CauseTheXmlheaderdocumentationforaC#propertycontainsanempty<value>tag.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Thedocumentationforpropertiesmayincludea<value>tag,whichdescribesthevalueheldbytheproperty.
Aviolationofthisruleoccurswhenthe<value>tagforapropertyisempty.
HowtoFixViolationsTofixaviolationofthisrule,fill-inadescriptionofthevalueheldbythepropertywithinthe<value>tag.
Example:
Thefollowingexampleshowsapropertywhichcontainsa<value>tagwithinitsdocumentationheader.
///<summary>
///Getsthenameofthecustomer.
///</summary>
///<value>Thenameofthecustomer.</value>
publicboolName
{
get{returnthis.name;}
}
TypeName ElementParametersMustBeDocumented
CheckId SA1611
Category DocumentationRules
CauseAC#method,constructor,delegateorindexerelementismissingdocumentationforoneormoreofitsparameters.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccursifanelementcontainingparametersismissingdocumentationforoneormoreofitsparameters.
HowtoFixViolationsTofixaviolationofthisrule,addorfill-indocumentationtextwithina<param>tagforeachparameterwithintheelement.
Thefollowingexampleshowsamethodwithavaliddocumentationheader:
///<summary>
///Joinsafirstnameandalastnametogetherintoasinglestring.
///</summary>
///<paramname="firstName">Thefirstnametojoin.</param>
///<paramname="lastName">Thelastnametojoin.</param>
///<returns>Thejoinednames.</returns>
publicstringJoinNames(stringfirstName,stringlastName)
{
returnfirstName+""+lastName;
}
TypeName ElementParameterDocumentationMustMatchElementParameters
CheckId SA1612
Category DocumentationRules
CauseThedocumentationdescribingtheparameterstoaC#method,constructor,delegateorindexerelementdoesnotmatchtheactualparametersontheelement.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccursifthedocumentationforanelement’sparametersdoesnotmatchtheactualparametersontheelement,oriftheparameterdocumentationisnotlistedinthesameorderastheelement’sparameters.
HowtoFixViolationsTofixaviolationofthisrule,correcttheparameterdocumentationsothatthe<param>tagsinthedocumentationappearinthesameorderastheelement’sparameters,andsothatthereisone<param>tagforeachparameterontheelement.
Thefollowingexampleshowsamethodwithavaliddocumentationheader:
///<summary>
///Joinsafirstnameandalastnametogetherintoasinglestring.
///</summary>
///<paramname="firstName">Thefirstnametojoin.</param>
///<paramname="lastName">Thelastnametojoin.</param>
///<returns>Thejoinednames.</returns>
publicstringJoinNames(stringfirstName,stringlastName)
{
returnfirstName+""+lastName;
}
TypeName ElementParameterDocumentationMustDeclareParameterName
CheckId SA1613
Category DocumentationRules
CauseA<param>tagwithinaC#element’sdocumentationheaderismissinganameattributecontainingthenameoftheparameter.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccursifthedocumentationforanelementcontainsa<param>tagwhichismissinganameattribute,orwhichcontainsanemptynameattribute.
HowtoFixViolationsTofixaviolationofthisrule,addorfill-inthenameattributeforthe<param>tagtoindicatethenameoftheparameterthatthedocumentationisfor.
Thefollowingexampleshowsamethodwithavaliddocumentationheader:
///<summary>
///Joinsafirstnameandalastnametogetherintoasinglestring.
///</summary>
///<paramname="firstName">Thefirstnametojoin.</param>
///<paramname="lastName">Thelastnametojoin.</param>
///<returns>Thejoinednames.</returns>
publicstringJoinNames(stringfirstName,stringlastName)
{
returnfirstName+""+lastName;
}
TypeName ElementParameterDocumentationMustHaveText
CheckId SA1614
Category DocumentationRules
CauseA<param>tagwithinaC#element’sdocumentationheaderisempty.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccursifthedocumentationforanelementcontainsa<param>tagwhichisemptyanddoesnotcontainadescriptionoftheparameter.
HowtoFixViolationsTofixaviolationofthisrule,fill-inadescriptionoftheparameterwithinthe<param>tag.
Thefollowingexampleshowsamethodwithavaliddocumentationheader:
///<summary>
///Joinsafirstnameandalastnametogetherintoasinglestring.
///</summary>
///<paramname="firstName">Thefirstnametojoin.</param>
///<paramname="lastName">Thelastnametojoin.</param>
///<returns>Thejoinednames.</returns>
publicstringJoinNames(stringfirstName,stringlastName)
{
returnfirstName+""+lastName;
}
TypeName ElementReturnValueMustBeDocumented
CheckId SA1615
Category DocumentationRules
CauseAC#elementismissingdocumentationforitsreturnvalue.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccursifanelementcontainingareturnvalueismissinga<returns>tag.
HowtoFixViolationsTofixaviolationofthisrule,addandfill-indocumentationtextwithina<returns>tagdescribingthevaluereturnedfromtheelement.
Thefollowingexampleshowsamethodwithavaliddocumentationheader:
///<summary>
///Joinsafirstnameandalastnametogetherintoasinglestring.
///</summary>
///<paramname="firstName">Thefirstnametojoin.</param>
///<paramname="lastName">Thelastnametojoin.</param>
///<returns>Thejoinednames.</returns>
publicstringJoinNames(stringfirstName,stringlastName)
{
returnfirstName+""+lastName;
}
TypeName ElementReturnValueDocumentationMustHaveText
CheckId SA1616
Category DocumentationRules
CauseThe<returns>tagwithinaC#element’sdocumentationheaderisempty.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccursifanelementcontainsanempty<returns>tag.
HowtoFixViolationsTofixaviolationofthisrule,fill-indocumentationtextwithinthe<returns>tagdescribingthevaluereturnedfromtheelement.
Thefollowingexampleshowsamethodwithavaliddocumentationheader:
///<summary>
///Joinsafirstnameandalastnametogetherintoasinglestring.
///</summary>
///<paramname="firstName">Thefirstnametojoin.</param>
///<paramname="lastName">Thelastnametojoin.</param>
///<returns>Thejoinednames.</returns>
publicstringJoinNames(stringfirstName,stringlastName)
{
returnfirstName+""+lastName;
}
TypeName VoidReturnValueMustNotBeDocumented
CheckId SA1617
Category DocumentationRules
CauseAC#codeelementdoesnotcontainareturnvalue,orreturnsvoid,butthedocumentationheaderfortheelementcontainsa<returns>tag.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccursifanelementwhichreturnsvoidcontainsa<returns>tagwithinitsdocumentationheader.
HowtoFixViolationsTofixaviolationofthisrule,removethe<returns>tagfromtheelement.
Thefollowingexampleshowsamethodwithavaliddocumentationheader:
///<summary>
///Printsthegivenname.
///</summary>
///<paramname="firstName">Thefirstname.</param>
///<paramname="lastName">Thelastname.</param>
publicvoidPrintNames(stringfirstName,stringlastName)
{
Console.WriteLine(firstName+""+lastName);
}
TypeName GenericTypeParametersMustBeDocumented
CheckId SA1618
Category DocumentationRules
CauseAgenericC#elementismissingdocumentationforoneormoreofitsgenerictypeparameters.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccursifanelementcontaininggenerictypeparametersismissingdocumentationforoneormoreofitsgenerictypeparameters.
HowtoFixViolationsTofixaviolationofthisrule,addorfill-indocumentationtextwithina<typeparam>tagforeachgenerictypeparameterontheelement.
Thefollowingexampleshowsamethodwithavaliddocumentationheader:
///<summary>
///Asamplegenericclass.
///</summary>
///<typeparamname="S">Thefirstgenerictypeparameter.</typeparam>
///<typeparamname="T">Thesecondgenerictypeparameter.</typeparam>
publicclassClass1<S,T>
{
}
TypeName GenericTypeParametersMustBeDocumentedPartialClass
CheckId SA1619
Category DocumentationRules
CauseAgeneric,partialC#elementismissingdocumentationforoneormoreofitsgenerictypeparameters,andthedocumentationfortheelementcontainsa<summary>tag.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccurswhenageneric,partialelementismissingdocumentationforoneormoreofitsgenerictypeparameters,andthedocumentationfortheelementcontainsa<summary>tagratherthana<content>tag.
Whendocumentationisprovidedonmorethanonepartofthepartialclass,thedocumentationforthetwoclassesmaybemergedtogethertoformasinglesourceofdocumentation.Forexample,considerthefollowingtwopartsofapartialclass:
///<summary>
///DocumentationforthefirstpartofClass1.
///</summary>
publicpartialclassClass1
{
}
///<summary>
///DocumentationforthesecondpartofClass1.
///</summary>
publicpartialclassClass1
{
}
Thesetwodifferentpartsofthesamepartialclasseachprovidedifferentdocumentationfortheclass.WhenthedocumentationforthisclassisbuiltintoanSDK,thetoolbuildingthedocumentationwilleitherchoosetouseonlyonepartofthedocumentationfortheclassandignoretheotherparts,or,insomecases,itmaymergethetwosourcesofdocumentationtogether,toformastringlike:“DocumentationforthefirstpartofClass1.DocumentationforthesecondpartofClass1.”
Forthesereasons,itcanbeproblematictoprovideSDKdocumentationonmorethanonepartofthepartialclass.However,itisstilladvisabletodocumenteachpartoftheclass,toincreasethereadabilityandmaintainabilityofthecode,andStyleCopwillrequirethateachpartoftheclasscontainheaderdocumentation.
Thisproblemissolvedthroughtheuseofthe<content>tag,whichcanreplacethe<summary>tagforpartialclasses.TherecommendedpracticefordocumentingpartialclassesistoprovidetheofficialSDKdocumentationfortheclassonthemainpartofthepartialclass.Thisdocumentationshouldbewrittenusingthestandard<summary>tag.Allotherpartsofthepartialclassshouldomitthe<summary>tagcompletely,andreplaceitwitha<content>tag.ThisallowsthedevelopertodocumentallpartsofthepartialclasswhilestillcentralizingalloftheofficialSDKdocumentationfortheclassontoonepartoftheclass.The<content>tagswillbeignoredbytheSDKdocumentationtools.
Whenagenericelementcontainsa<summary>tagwithinitsdocumentationheader,StyleCopassumesthatthisisthemainpartoftheclass,andrequirestheheadertocontain<typeparam>tagsforeachofthegenerictypeparametersontheclass.However,ifthedocumentationheaderfortheclasscontainsa<content>tagratherthana<summary>tag,StyleCopwillassumethatthegenerictypeparametersaredefinedonanotherpartoftheclass,andwillnotrequire<typeparam>tagsonthispartoftheclass.
HowtoFixViolationsTofixaviolationofthisrule,addorfill-indocumentationtextwithina<typeparam>tagforeachgenerictypeparameterontheelement,orchangethe<summary>tagtoa<content>tagifthisisnotthemainpartofthepartialclass.
Thefollowingexampleshowsamethodwithavaliddocumentationheader:
///<summary>
///Asamplegenericclass.
///</summary>
///<typeparamname="S">Thefirstgenerictypeparameter.</typeparam>
///<typeparamname="T">Thesecondgenerictypeparameter.</typeparam>
publicclassClass1<S,T>
{
}
TypeName GenericTypeParameterDocumentationMustMatchTypeParameters
CheckId SA1620
Category DocumentationRules
CauseThe<typeparam>tagswithintheXmlheaderdocumentationforagenericC#elementdonotmatchthegenerictypeparametersontheelement.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccursifthe<typeparam>tagswithintheelement’sheaderdocumentationdonotmatchthegenerictypeparametersontheelement,ordonotappearinthesameorderastheelement’stypeparameters.
HowtoFixViolationsTofixaviolationofthisrule,addandfill-inone<typeparam>tagforeachgenerictypeparameterontheelement,andmakesurethatthe<typeparam>tagsappearinthesameorderastheelement’stypeparameters.
Thefollowingexampleshowsamethodwithavaliddocumentationheader:
///<summary>
///Asamplegenericclass.
///</summary>
///<typeparamname="S">Thefirstgenerictypeparameter.</typeparam>
///<typeparamname="T">Thesecondgenerictypeparameter.</typeparam>
publicclassClass1<S,T>
{
}
TypeName GenericTypeParameterDocumentationMustDeclareParameterName
CheckId SA1621
Category DocumentationRules
CauseA<typeparam>tagwithintheXmlheaderdocumentationforagenericC#elementismissinganameattribute,orcontainsanemptynameattribute.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccursiftheelementcontainsa<typeparam>tagwithinitsXmlheaderdocumentationwhichdoesnotdeclarethenameofthetypeparameter.
HowtoFixViolationsTofixaviolationofthisrule,addorfill-inthenameattributeforeach<typeparam>tag,indicatingthenameofthetypeparameterthatthedocumentationisfor.
Thefollowingexampleshowsamethodwithavaliddocumentationheader:
///<summary>
///Asamplegenericclass.
///</summary>
///<typeparamname="S">Thefirstgenerictypeparameter.</typeparam>
///<typeparamname="T">Thesecondgenerictypeparameter.</typeparam>
publicclassClass1<S,T>
{
}
TypeName GenericTypeParameterDocumentationMustHaveText
CheckId SA1622
Category DocumentationRules
CauseA<typeparam>tagwithintheXmlheaderdocumentationforagenericC#elementisempty.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccursiftheelementcontainsanempty<typeparam>tagwithinitsXmlheaderdocumentation.
HowtoFixViolationsTofixaviolationofthisrule,fill-ineach<typeparam>tagwithinadescriptionofthegenerictypeparameter.
Thefollowingexampleshowsamethodwithavaliddocumentationheader:
///<summary>
///Asamplegenericclass.
///</summary>
///<typeparamname="S">Thefirstgenerictypeparameter.</typeparam>
///<typeparamname="T">Thesecondgenerictypeparameter.</typeparam>
publicclassClass1<S,T>
{
}
TypeName PropertySummaryDocumentationMustMatchAccessors
CheckId SA1623
Category DocumentationRules
CauseThedocumentationtextwithinaC#property’s<summary>tagdoesnotmatchtheaccessorswithintheproperty.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccursifaproperty’ssummarydocumentationdoesnotmatchtheaccessorswithintheproperty.
Theproperty’ssummarytextmustbeginwithwordingdescribingthetypesofaccessorsexposedwithintheproperty.Ifthepropertycontainsonlyagetaccessor,thesummarymustbeginwiththeword“Gets”.Ifthepropertycontainsonlyasetaccessor,thesummarymustbeginwiththeword“Sets”.Ifthepropertyexposesbothagetandsetaccessor,thesummarytextmustbeginwith“Getsorsets”.
Forexample,considerthefollowingproperty,whichexposesbothagetandsetaccessor.Thesummarytextbeginswiththewords“Getsorsets”.
///<summary>
///Getsorsetsthenameofthecustomer.
///</summary>
publicstringName
{
get{returnthis.name;}
set{this.name=value;}
}
IfthepropertyreturnsaBooleanvalue,anadditionalruleisapplied.ThesummarytextforBooleanpropertiesmustcontainthewords“Getsavalueindicatingwhether”,“Setsavalueindicatingwhether”,or“Getsorsetsavalue
indicatingwhether”.Forexample,considerthefollowingBooleanproperty,whichonlyexposesagetaccessor:
///<summary>
///Getsavalueindicatingwhethertheitemisenabled.
///</summary>
publicboolEnabled
{
get{returnthis.enabled;}
}
Insomesituations,thesetaccessorforapropertycanhavemorerestrictedaccessthanthegetaccessor.Forexample:
///<summary>
///Getsthenameofthecustomer.
///</summary>
publicstringName
{
get{returnthis.name;}
privateset{this.name=value;}
}
Inthisexample,thesetaccessorhasbeengivenprivateaccess,meaningthatitcanonlybeaccessedbylocalmembersoftheclassinwhichitiscontained.Thegetaccessor,however,inheritsitsaccessfromtheparentproperty,thusitcanbe
accessedbyanycaller,sincethepropertyhaspublicaccess.
>Inthiscase,thedocumentationsummarytextshouldavoidreferringtothesetaccessor,sinceitisnotvisibletoexternalcallers.
StyleCopappliesaseriesofrulestodeterminewhenthesetaccessorshouldbereferencedintheproperty’ssummarydocumentation.Ingeneral,theserulesrequirethesetaccessortobereferencedwheneveritisvisibletothesamesetofcallersasthegetaccessor,orwheneveritisvisibletoexternalclassesorinheritingclasses.
Thespecificrulesfordeterminingwhethertoincludethesetaccessorintheproperty’ssummarydocumentationare:
1.Thesetaccessorhasthesameaccesslevelasthegetaccessor.Forexample:
///<summary>
///Getsorsetsthenameofthecustomer.
///</summary>
protectedstringName
{
get{returnthis.name;}
set{this.name=value;}
}
2.Thepropertyisonlyinternallyaccessiblewithintheassembly,andthesetaccessoralsohasinternalaccess.Forexample:
internalclassClass1
{
///<summary>
///Getsorsetsthenameofthecustomer.
///</summary>
protectedstringName
{
get{returnthis.name;}
internalset{this.name=value;}
}
}
internalclassClass1
{
publicclassClass2
{
///<summary>
///Getsorsetsthenameofthecustomer.
///</summary>
publicstringName
{
get{returnthis.name;}
internalset{this.name=value;}
}
}
}
3.Thepropertyisprivateoriscontainedbeneathaprivateclass,andthesetaccessorhasanyaccessmodifierotherthanprivate.Intheexamplebelow,theaccessmodifierdeclaredonthesetaccessorhasnomeaning,sincethesetaccessoriscontainedwithinaprivateclassandthuscannotbeseenbyotherclassesoutsideofClass1.Thiseffectivelygivesthesetaccessorthesameaccesslevelasthegetaccessor.
publicclassClass1
{
privateclassClass2
{
publicclassClass3
{
///<summary>
///Getsorsetsthenameofthecustomer.
///</summary>
publicstringName
{
get{returnthis.name;}
internalset{this.name=value;}
}
}
}
}
4.Wheneverthesetaccessorhasprotectedorprotectedinternalaccess,itshouldbereferencedinthedocumentation.Aprotectedorprotectedinternalsetaccessorcanalwaysbeenseenbyaclassinheritingfromtheclasscontainingtheproperty.
internalclassClass1
{
publicclassClass2
{
///<summary>
///Getsorsetsthenameofthecustomer.
///</summary>
internalstringName
{
get{returnthis.name;}
protectedset{this.name=value;}
}
}
privateclassClass3:Class2
{
publicClass3(stringname){this.Name=name;}
}
}
HowtoFixViolationsTofixaviolationofthisrule,updatetheproperty’ssummarytextsothatthedescriptionbeginswiththeproperwording,dependinguponthetypeofthepropertyandthetypesofaccessorswithintheproperty.
TypeName PropertySummaryDocumentationMustOmitSetAccessorWithRestrictedAccess
CheckId SA1624
Category DocumentationRules
CauseThedocumentationtextwithinaC#property’s<summary>tagtakesintoaccountalloftheaccessorswithintheproperty,butoneoftheaccessorshaslimitedaccess.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccurswhenoneoftheaccessorswithinthepropertyhaslimitedaccess(usuallythesetaccessor),butthesummarydocumentationtextforthepropertystillreferstobothaccessors.
Normally,aproperty’ssummarytextmustbeginwithwordingdescribingthetypesofaccessorsexposedwithintheproperty.Ifthepropertycontainsonlyagetaccessor,thesummarymustbeginwiththeword“Gets”.Ifthepropertycontainsonlyasetaccessor,thesummarymustbeginwiththeword“Sets”.Ifthepropertyexposesbothagetandsetaccessor,thesummarytextmustbeginwith“Getsorsets”.
However,whenanaccessorwithinthepropertyisgivenanaccesslevelwhichismorelimitedthantheaccessleveloftheproperty,thisaccessorshouldbeomittedfromthesummarydocumentation.
Itcansometimesbenon-obviouswhetherthesetaccessorwithinapropertyisactuallylessaccessiblethanthegetaccessor.Forexample,considerthecasewhereapublicpropertyiscontainedwithinaninternalclass,andthesetaccessorisgiveninternalaccessor.Ineffect,boththegetandsetaccessorshavethesameaccesslevel.Inthiscase,thesummarydocumentationshouldrefertoboththegetandsetaccessors,sincetheyeffectivelyhavethesameaccesslevel.
Insomesituations,thesetaccessorforapropertycanhavemorerestrictedaccessthanthegetaccessor.Forexample:
///<summary>
///Getsthenameofthecustomer.
///</summary>
publicstringName
{
get{returnthis.name;}
privateset{this.name=value;}
}
Inthisexample,thesetaccessorhasbeengivenprivateaccess,meaningthatitcanonlybeaccessedbylocalmembersoftheclassinwhichitiscontained.Thegetaccessor,however,inheritsitsaccessfromtheparentproperty,thusitcanbeaccessedbyanycaller,sincethepropertyhaspublicaccess.
Inthiscase,thedocumentationsummarytextshouldavoidreferringtothesetaccessor,sinceitisnotvisibletoexternalcallers.
StyleCopappliesaseriesofrulestodeterminewhenthesetaccessorshouldbereferencedintheproperty’ssummarydocumentation.Ingeneral,theserulesrequirethesetaccessortobereferencedwheneveritisvisibletothesamesetofcallersasthegetaccessor,orwheneveritisvisibletoexternalclassesorinheritingclasses.
Thespecificrulesfordeterminingwhethertoincludethesetaccessorintheproperty’ssummarydocumentationare:
1.Thesetaccessorhasthesameaccesslevelasthegetaccessor.Forexample:
///<summary>
///Getsorsetsthenameofthecustomer.
///</summary>
protectedstringName
{
get{returnthis.name;}
set{this.name=value;}
}
2.Thepropertyisonlyinternallyaccessiblewithintheassembly,andthesetaccessoralsohasinternalaccess.Forexample:
internalclassClass1
{
///<summary>
///Getsorsetsthenameofthecustomer.
///</summary>
protectedstringName
{
get{returnthis.name;}
internalset{this.name=value;}
}
}
internalclassClass1
{
publicclassClass2
{
///<summary>
///Getsorsetsthenameofthecustomer.
///</summary>
publicstringName
{
get{returnthis.name;}
internalset{this.name=value;}
}
}
}
3.Thepropertyisprivateoriscontainedbeneathaprivateclass,andthesetaccessorhasanyaccessmodifierotherthanprivate.Intheexamplebelow,theaccessmodifierdeclaredonthesetaccessorhasnomeaning,sincethesetaccessoriscontainedwithinaprivateclassandthuscannotbeseenbyotherclassesoutsideofClass1.Thiseffectivelygivesthesetaccessorthesameaccesslevelasthegetaccessor.
publicclassClass1
{
privateclassClass2
{
publicclassClass3
{
///<summary>
///Getsorsetsthenameofthecustomer.
///</summary>
publicstringName
{
get{returnthis.name;}
internalset{this.name=value;}
}
}
}
}
4.Wheneverthesetaccessorhasprotectedorprotectedinternalaccess,itshouldbereferencedinthedocumentation.Aprotectedorprotectedinternalsetaccessorcanalwaysbeenseenbyaclassinheritingfromtheclasscontainingtheproperty.
internalclassClass1
{
publicclassClass2
{
///<summary>
///Getsorsetsthenameofthecustomer.
///</summary>
internalstringName
{
get{returnthis.name;}
protectedset{this.name=value;}
}
}
privateclassClass3:Class2
{
publicClass3(stringname){this.Name=name;}
}
}
HowtoFixViolationsTofixaviolationofthisrule,updatetheproperty’ssummarytextandremovewordingwhichreferstothelimitedaccessaccessor.
TypeName ElementDocumentationMustNotBeCopiedAndPasted
CheckId SA1625
Category DocumentationRules
CauseTheXmldocumentationforaC#elementcontainstwoormoreidenticalentries,indicatingthatthedocumentationhasbeencopiedandpasted.Thiscansometimesindicateinvalidorpoorlywrittendocumentation.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccurswhenanelementcontainstwoormoreidenticaldocumentationtexts.Forexample:
///<summary>
///Joinsafirstnameandalastnametogetherintoasinglestring.
///</summary>
///<paramname="firstName">Partofthename.</param>
///<paramname="lastName">Partofthename.</param>
///<returns>Thejoinednames.</returns>
publicstringJoinNames(stringfirstName,stringlastName)
{
returnfirstName+""+lastName;
}
Insomecases,amethodmaycontainoneormoreparameterswhicharenotusedwithinthebodyofthemethod.Inthiscase,thedocumentationfortheparametercanbesetto"Theparameterisnotused."StyleCopwillallowmultipleparameterstocontainidenticaldocumentationaslongasthedocumentationstringis"Theparameterisnotused."
HowtoFixViolationsTofixaviolationofthisrule,editthedocumentationfortheelementandensurethateachoftheindividualdocumentationtextsareunique.Forexample:
///<summary>
///Joinsafirstnameandalastnametogetherintoasinglestring.
///</summary>
///<paramname="firstName">Thefirstnametojoin.</param>
///<paramname="lastName">Thelastnametojoin.</param>
///<returns>Thejoinednames.</returns>
publicstringJoinNames(stringfirstName,stringlastName)
{
returnfirstName+""+lastName;
}
TypeName SingleLineCommentsMustNotUseDocumentationStyleSlashes
CheckId SA1626
Category DocumentationRules
CauseTheC#codecontainsasingle-linecommentwhichbeginswiththreeforwardslashesinarow.
RuleDescriptionAviolationofthisruleoccurswhenthecodecontainsasingle-linecommentwhichbeginswiththreeslashes.CommentsbeginningwiththreeslashesarereservedforXmldocumentationheaders.Single-linecommentsshouldbeginwithonlytwoslashes.Whencommentingoutlinesofcode,itisadvisabletobeginthecommentwithfourslashestodifferentiateitfromnormalcomments.Forexample:
///<summary>
///Joinsafirstnameandalastnametogetherintoasinglestring.
///</summary>
///<paramname="firstName">Partofthename.</param>
///<paramname="lastName">Partofthename.</param>
///<returns>Thejoinednames.</returns>
publicstringJoinNames(stringfirstName,stringlastName)
{
Alegalcommentbeginningwithtwoslashes:
//Jointhenamestogether.
stringfullName=firstName+""+lastName;
Anillegalcommentbeginningwiththreeslashes:
///Trimthename.
fullName=fullName.Trim();
Alineofcommented-outcodebeginningwithfourslashes:
////fullName=asfd;
returnfullName;
}
HowtoFixViolationsTofixaviolationofthisrule,removeaslashfromthebeginningofthecommentsothatitbeginswithonlytwoslashes.
TypeName DocumentationTextMustNotBeEmpty
CheckId SA1627
Category DocumentationRules
CauseTheXmlheaderdocumentationforaC#codeelementcontainsanemptytag.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccurswhenthedocumentationheaderforanelementcontainsanemptytag.Forexample:
///<summary>
///Joinsafirstnameandalastnametogetherintoasinglestring.
///</summary>
///<paramname="firstName"></param>
///<paramname="lastName">Partofthename.</param>
///<returns>Thejoinednames.</returns>
publicstringJoinNames(stringfirstName,stringlastName)
{
...
}
HowtoFixViolationsTofixaviolationofthisrule,adddocumentationtextwithintheemptytag.
TypeName DocumentationTextMustBeginWithACapitalLetter
CheckId SA1628
Category DocumentationRules
CauseAsectionoftheXmlheaderdocumentationforaC#elementdoesnotbeginwithacapitalletter.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccurswhenpartofthedocumentationdoesnotbeginwithacapitalletter.Forexample,thesummarytextinthedocumentationbelowbeginswithalower-caseletter:
///<summary>
///joinsafirstnameandalastnametogetherintoasinglestring.
///</summary>
///<paramname="firstName">Thefirstname.</param>
///<paramname="lastName">Thelastname.</param>
///<returns>Thejoinednames.</returns>
publicstringJoinNames(stringfirstName,stringlastName)
{
...
}
HowtoFixViolationsTofixaviolationofthisrule,ensurethatallsectionsofthedocumentationbeginwithacapitalletter.
TypeName DocumentationTextMustEndWithAPeriod
CheckId SA1629
Category DocumentationRules
CauseAsectionoftheXmlheaderdocumentationforaC#elementdoesnotendwithaperiod(alsoknownasafullstop).
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccurswhenpartofthedocumentationdoesnotendwithaperiod.Forexample,thesummarytextinthedocumentationbelowdoesnotendwithaperiod:
///<summary>
///Joinsafirstnameandalastnametogetherintoasinglestring
///</summary>
///<paramname="firstName">Thefirstname.</param>
///<paramname="lastName">Thelastname.</param>
///<returns>Thejoinednames.</returns>
publicstringJoinNames(stringfirstName,stringlastName)
{
...
}
HowtoFixViolationsTofixaviolationofthisrule,ensurethatallsectionsofthedocumentationendwithaperiod.
TypeName DocumentationTextMustContainWhitespace
CheckId SA1630
Category DocumentationRules
CauseAsectionoftheXmlheaderdocumentationforaC#elementdoesnotcontainanywhitespacebetweenwords.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccurswhenpartofthedocumentationdoescontainanywhitespacebetweenwords.Thiscanindicatepoorlywrittenorpoorlyformatteddocumentation.Forexample:
///<summary>
///Joinsnames
///</summary>
///<paramname="firstName">First</param>
///<paramname="lastName">Last</param>
///<returns>Name</returns>
publicstringJoinNames(stringfirstName,stringlastName)
{
...
}
HowtoFixViolationsTofixaviolationofthisrule,ensurethatallsectionsofthedocumentationcontainatleastoneinstanceofwhitespacebetweenwords.
TypeName DocumentationTextMustMeetCharacterPercentage
CheckId SA1631
Category DocumentationRules
CauseAsectionoftheXmlheaderdocumentationforaC#elementdoesnotcontainenoughalphabeticcharacters.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccurswhenpartofthedocumentationdoescontainenoughcharacters.Thisruleiscalculatedbycountingthenumberofalphabeticcharactersandnumberswithinthedocumentationtext,andcomparingitagainstthenumberofsymbolsandothernon-alphabeticcharacters.Ifthepercentageofnon-alphabeticcharactersistoohigh,thisgenerallyindicatespoorlyformatteddocumentationwhichwillbedifficulttoread.Forexample,considerthefollowsummarydocumentation:
///<summary>
///@)$(*Aname--------
///</summary>
publicclassName
{
...
}
HowtoFixViolationsTofixaviolationofthisrule,rewritethedocumentationtextusinggrammaticallyproperlanguage,andensurethattheratioofsymbolsversuscharactersinthetextisnottoogreat.
TypeName DocumentationTextMustMeetMinimumCharacterLength
CheckId SA1632
Category DocumentationRules
CauseFromStyleCop4.5thisruleisdisabledbydefault.
AsectionoftheXmlheaderdocumentationforaC#elementistooshort.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccurswhenpartofthedocumentationistooshort.Thiscanoftenindicatethatthedocumentationisnotdescriptive.Forexample:
///<summary>
///Aname
///</summary>
publicclassName
{
...
}
HowtoFixViolationsTofixaviolationofthisrule,rewritethedocumentationtextusinggrammaticallyproperanddescriptivelanguage.Inmostcases,doingsowillcausethelengthofthedocumentationtexttobegreaterthantheminimumlengthwhichcausesthisruletofire.
TypeName FileMustHaveHeader
CheckId SA1633
Category DocumentationRules
CauseAC#codefileismissingastandardfileheader.
RuleDescriptionAviolationofthisruleoccurswhenaC#sourcefileismissingafileheader.Thefileheadermustbeginonthefirstlineofthefile,andmustbeformattedasablockofcommentscontainingXml,asfollows:
//-----------------------------------------------------------------------
//<copyrightfile="NameOfFile.cs"company="CompanyName">
//Companycopyrighttag.
//</copyright>
//-----------------------------------------------------------------------
Forexample,afilecalledWidget.csfromafictionalcompanycalledSprocketEnterprisesshouldcontainafileheadersimilartothefollowing:
//-----------------------------------------------------------------------
//<copyrightfile="Widget.cs"company="SprocketEnterprises">
//Copyright(c)SprocketEnterprises.Allrightsreserved.
//</copyright>
//-----------------------------------------------------------------------
Thedashedlinesatthetopandbottomoftheheaderarenotstrictlynecessary,sotheheadercouldbewrittenas:
//<copyrightfile="Widget.cs"company="SprocketEnterprises">
//Copyright(c)SprocketEnterprises.Allrightsreserved.
//</copyright>
Itispossibletoaddadditionaltags,althoughtheywillnotbecheckedorenforcedbyStyleCop:
//-----------------------------------------------------------------------
//<copyrightfile="Widget.cs"company="SprocketEnterprises">
//Copyright(c)SprocketEnterprises.Allrightsreserved.
//</copyright>
//<author>JohnDoe</author>
//-----------------------------------------------------------------------
Afilethatiscompletelyauto-generatedbyatool,andwhichshouldnotbecheckedorenforcedbyStyleCop,canincludean“auto-generated”headerratherthanthestandardfileheader.ThiswillcauseStyleCoptoignorethefile.Thistypeofheadershouldneverbeplacedontopofamanuallywrittencodefile.
//<auto-generated/>
namespaceSample.Something
{
//Thecontentsofthisfilearecompletelyauto-generatedbyatool.
}
HowtoFixViolationsTofixaviolationofthisrule,addastandardfileheaderatthetopofthefile.
TypeName FileHeaderMustShowCopyright
CheckId SA1634
Category DocumentationRules
CauseThefileheaderatthetopofaC#codefileismissingacopyrighttag.
RuleDescriptionAviolationofthisruleoccurswhenthefileheaderatthetopofaC#fileismissingacopyrighttag.Forexample:
//-----------------------------------------------------------------------
//<Tag>Afileheaderwhichdoesnotcontainacopyrighttag</Tag>
//-----------------------------------------------------------------------
Afileheadershouldincludeacopyrighttag,asfollows:
//-----------------------------------------------------------------------
//<copyrightfile="Widget.cs"company="MyCompany">
//Customcompanycopyrighttag.
//</copyright>
//-----------------------------------------------------------------------
HowtoFixViolationsTofixaviolationofthisrule,addastandardcopyrighttagtothefileheader.
TypeName FileHeaderMustHaveCopyrightText
CheckId SA1635
Category DocumentationRules
CauseThefileheaderatthetopofaC#codefileismissingcopyrighttext.
RuleDescriptionAviolationofthisruleoccurswhenthefileheaderatthetopofaC#filedoesnotcontaintextwithinitscopyrighttag.Forexample:
//-----------------------------------------------------------------------
//<copyrightfile="Widget.cs"company="SprocketEnterprises">
//</copyright>
//-----------------------------------------------------------------------
Afileheadershouldincludecopyrighttext,asfollows:
//-----------------------------------------------------------------------
//<copyrightfile="Widget.cs"company="SprocketEnterprises">
//Copyright(c)SprocketEnterprises.Allrightsreserved.
//</copyright>
//-----------------------------------------------------------------------
HowtoFixViolationsTofixaviolationofthisrule,addyourcompany’sstandardcopyrighttexttothecopyrighttag.
TypeName FileHeaderCopyrightTextMustMatch
CheckId SA1636
Category DocumentationRules
CauseThefileheaderatthetopofaC#codefiledoesnotcontaintheappropriatecopyrighttext.
RuleDescriptionAviolationofthisruleoccurswhenthefileheaderatthetopofaC#filedoesnotcontainthecopyrighttextthathasbeenspecifiedfortheproject.Toenablethisrule,navigatetotheStyleCopsettingsfortheprojectandchangetotheCompanyInformationtab,asshownbelow:
Checkthecheckboxatthetopofthesettingspage,andfillintherequiredcopyrighttextforyourcompany.ClickOKtosavethesettings.Withthesesettingsinplace,everyfilewithintheprojectmustcontaintherequiredcopyrighttextwithinitsfileheadercopyrighttag,asshownintheexamplebelow:
//-----------------------------------------------------------------------
//<copyrightfile="Widget.cs"company="MyCompany">
//Customcompanycopyrighttag.
//</copyright>
//-----------------------------------------------------------------------
HowtoFixViolationsTofixaviolationofthisrule,addyourcompany’sstandardcopyrighttexttothefileheadercopyrighttag.
TypeName FileHeaderMustContainFileName
CheckId SA1637
Category DocumentationRules
CauseThefileheaderatthetopofaC#codefileismissingthefilename.
RuleDescriptionAviolationofthisruleoccurswhenthefileheaderatthetopofaC#filedoesnotcontainavalidfilenametag.Forexample:
//-----------------------------------------------------------------------
//<copyrightcompany="MyCompany">
//Customcompanycopyrighttag.
//</copyright>
//-----------------------------------------------------------------------
Afileheadershouldincludeafiletagcontainingthenameofthefile,asfollows:
//-----------------------------------------------------------------------
//<copyrightfile="Widget.cs"company="MyCompany">
//Customcompanycopyrighttag.
//</copyright>
//-----------------------------------------------------------------------
HowtoFixViolationsTofixaviolationofthisrule,addafiletagcontainingthenameofthefile.
TypeName FileHeaderFileNameDocumentationMustMatchFileName
CheckId SA1638
Category DocumentationRules
CauseThefiletagwithinthefileheaderatthetopofaC#codefiledoesnotcontainthenameofthefile.
RuleDescriptionAviolationofthisruleoccurswhenthefiletagwithinthefileheaderatthetopofaC#filedoesnotcontainthenameofthefile.Forexample,consideraC#sourcefilenamedFile1.cs,withthefollowingheader:
//-----------------------------------------------------------------------
//<copyrightfile="File2.cs"company="MyCompany">
//Customcompanycopyrighttag.
//</copyright>
//-----------------------------------------------------------------------
Aviolationofthisrulewouldoccur,sincethefiletagdoesnotcontainthecorrectnameofthefile.Theheadershouldbewrittenas:
//-----------------------------------------------------------------------
//<copyrightfile="File1.cs"company="MyCompany">
//Customcompanycopyrighttag.
//</copyright>
//-----------------------------------------------------------------------
HowtoFixViolationsTofixaviolationofthisrule,addthenameofthefiletothefiletag.
TypeName FileHeaderMustHaveSummary
CheckId SA1639
Category DocumentationRules
CauseThefileheaderatthetopofaC#codefiledoesnotcontainafilled-insummarytag.
RuleDescriptionAviolationofthisruleoccurswhenthefileheaderatthetopofaC#filedoesnotcontainavalidsummarytag.Thisruleisdisabledbydefault.
Forexample:
//-----------------------------------------------------------------------
//<copyrightfile="Widget.cs"company="MyCompany">
//Customcompanycopyrighttag.
//</copyright>
//-----------------------------------------------------------------------
Ifthisruleisenabled,thefileheadershouldcontainasummarytag.Forexample:
//-----------------------------------------------------------------------
//<copyrightfile="Widget.cs"company="MyCompany">
//Customcompanycopyrighttag.
//</copyright>
//<summary>ThisistheWidgetclass.</summary>//-----------------------------------------------------------------------
HowtoFixViolationsTofixaviolationofthisrule,addandfill-inasummarytagdescribingthecontentsofthefile.
TypeName FileHeaderMustHaveValidCompanyText
CheckId SA1640
Category DocumentationRules
CauseThefileheaderatthetopofaC#codefiledoesnotcontaincompanynametext.
RuleDescriptionAviolationofthisruleoccurswhenthefileheaderatthetopofaC#filedoesnotcontainacompanytagwithcompanynametext.Forexample:
//-----------------------------------------------------------------------
//<copyrightfile="Widget.cs"company="">
//Customcompanycopyrighttag.
//</copyright>
//-----------------------------------------------------------------------
Thecompanyattributeshouldhavetextinit.Forexample:
//-----------------------------------------------------------------------
//<copyrightfile="Widget.cs"company="MyCompany">
//Customcompanycopyrighttag.
//</copyright>
//-----------------------------------------------------------------------
HowtoFixViolationsTofixaviolationofthisrule,addandfill-inacompanyattributecontainingthenameofthecompany.
TypeName FileHeaderCompanyNameTextMustMatch
CheckId SA1641
Category DocumentationRules
CauseThefileheaderatthetopofaC#codefiledoesnotcontaintheappropriatecompanynametext.
RuleDescriptionAviolationofthisruleoccurswhenthefileheaderatthetopofaC#filedoesnotcontainthecompanynametextthathasbeenspecifiedfortheproject.Toenablethisrule,navigatetotheStyleCopsettingsfortheprojectandchangetotheCompanyInformationtab,asshownbelow:
Checkthecheckboxatthetopofthesettingspage,andfillintherequiredcompanynametextforyourcompany.ClickOKtosavethesettings.Withthesesettingsinplace,everyfilewithintheprojectmustcontaintherequiredcompanynametextwithinitsfileheadercopyrighttag,asshownintheexamplebelow:
//-----------------------------------------------------------------------
//<copyrightfile="Widget.cs"company="MyCompany">
//Customcompanycopyrighttag.
//</copyright>
//-----------------------------------------------------------------------
HowtoFixViolationsTofixaviolationofthisrule,addyourcompany’sstandardcompanynametexttothefileheadercopyrighttag.
TypeName ConstructorSummaryDocumentationMustBeginWithStandardText
CheckId SA1642
Category DocumentationRules
CauseTheXmldocumentationheaderforaC#constructordoesnotcontaintheappropriatesummarytext.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccurswhenthesummarytagwithinthedocumentationheaderforaconstructordoesnotbeginwiththepropertext.
Theruleisintendedtostandardizethesummarytextforaconstructorbasedontheaccessleveloftheconstructor.Thesummaryforanon-privateinstanceconstructormustbeginwith“Initializesanewinstanceofthe{classname}class.”Forexample,thefollowingshowstheconstructorfortheCustomerclass.
///<summary>
///InitializesanewinstanceoftheCustomerclass.
///</summary>
publicCustomer()
{
}
Itispossibletoembedothertagsintothesummarytext.Forexample:
///<summary>
///Initializesanewinstanceofthe<seecref="Customer"/>class.
///</summary>
publicCustomer()
{
}
Iftheclasscontainsgenericparameters,thesecanbeannotatedwithinthecreflinkusingeitherofthefollowingtwoformats:
///<summary>
///Initializesanewinstanceofthe<seecref="Customer`1"/>class.
///</summary>
publicCustomer()
{
}
///<summary>
///Initializesanewinstanceofthe<seecref="Customer{T}"/>class.
///</summary>
publicCustomer()
{
}
Iftheconstructorisstatic,thesummarytextshouldbeginwith“Initializesstaticmembersofthe{classname}class.”Forexample:
///<summary>
///InitializesstaticmembersoftheCustomerclass.
///</summary>
publicstaticCustomer()
{
}
Privateinstanceconstructorsmustusethesummarytext“Preventsadefaultinstanceofthe{classname}classfrombeingcreated.”
///<summary>
///PreventsadefaultinstanceoftheCustomerclassfrombeingcreated.
///</summary>
privateCustomer()
{
}
HowtoFixViolationsTofixaviolationofthisrule,editthesummarytextfortheconstructorasdescribedabove.
TypeName DestructorSummaryDocumentationMustBeginWithStandardText
CheckId SA1643
Category DocumentationRules
CauseTheXmldocumentationheaderforaC#finalizerdoesnotcontaintheappropriatesummarytext.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccurswhenthesummarytagwithinthedocumentationheaderforafinalizerdoesnotbeginwiththepropertext.
Theruleisintendedtostandardizethesummarytextforafinalizer.Thesummaryforafinalizermustbeginwith“Finalizesaninstanceofthe{classname}class.”Forexample,thefollowingshowsthefinalizerfortheCustomerclass.
///<summary>
///FinalizesaninstanceoftheCustomerclass.
///</summary>
~Customer()
{
}
Itispossibletoembedothertagsintothesummarytext.Forexample:
///<summary>
///Finalizesaninstanceofthe<seecref="Customer"/>class.
///</summary>
~Customer()
{
}Iftheclasscontainsgenericparameters,thesecanbeannotatedwithinthecreflinkusingeitherofthefollowingtwoformats:
///<summary>
///Initializesanewinstanceofthe<seecref="Customer`1"/>class.
///</summary>
publicCustomer()
{
}
///<summary>
///Initializesanewinstanceofthe<seecref="Customer{T}"/>class.
///</summary>
publicCustomer()
{
}
HowtoFixViolationsTofixaviolationofthisrule,editthesummarytextforthefinalizerasdescribedabove.
TypeName DocumentationHeadersMustNotContainBlankLines
CheckId SA1644
Category DocumentationRules
CauseAsectionwithintheXmldocumentationheaderforaC#elementcontainsblanklines.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Aviolationofthisruleoccurswhenthedocumentationheadercontainsoneormoreblanklineswithinasectionofdocumentation.Forexample:
///<summary>
///Joinsafirstnameandalastnametogetherintoasinglestring.
///
///Usesasimpleformofstringconcatenation.
///</summary>
///<paramname="firstName">Thefirstnametojoin.</param>
///<paramname="lastName">Thelastnametojoin.</param>
///<returns>Thejoinednames.</returns>
publicstringJoinNames(stringfirstName,stringlastName)
{
returnfirstName+""+lastName;
}
Ratherthaninsertingblanklinesintothedocumentation,usethe<para>tagtodenoteparagraphs.Forexample:
///<summary>
///<para>
///Joinsafirstnameandalastnametogetherintoasinglestring.
///</para><para>
///Usesasimpleformofstringconcatenation.
///</para>
///</summary>
///<paramname="firstName">Thefirstnametojoin.</param>
///<paramname="lastName">Thelastnametojoin.</param>
///<returns>Thejoinednames.</returns>
publicstringJoinNames(stringfirstName,stringlastName)
{
returnfirstName+""+lastName;
}
HowtoFixViolationsTofixaviolationofthisrule,removetheblanklinesfromthedocumentationheader,andoptionallyreplacethemwith<para/>tags.
TypeName IncludedDocumentationFileDoesNotExist
CheckId SA1645
Category DocumentationRules
CauseAnincludedXmldocumentationfiledoesnotexist.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Asanalternativetoauthoringdocumentationdirectlywithinthecodefile,itispossibletoplacedocumentationformultipleelementswithinaseparateXmlfile,andthenreferenceasectionofthatfilewithinanelement'sdocumentationheader.Thiscausesthecompilertoimportthedocumentationforthatelementfromtheincludeddocument.Forexample:
///<includefile="IncludedDocumentation.xml"path="root/EnabledMethodDocs"/>publicboolEnabled(booltrue)
{
}
Aviolationofthisruleoccurswhentheincludedfiledoesnotexistatthegivenlocation,orcannotbeloaded.
HowtoFixViolationsTofixaviolationofthisrule,correctthepathtotheincludeddocumentationfiletopointtoavalidfilelocation.
TypeName IncludedDocumentationXPathDoesNotExist
CheckId SA1646
Category DocumentationRules
CauseAnincludedXmldocumentationlinkcontainsaninvalidpath.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Asanalternativetoauthoringdocumentationdirectlywithinthecodefile,itispossibletoplacedocumentationformultipleelementswithinaseparateXmlfile,andthenreferenceasectionofthatfilewithinanelement'sdocumentationheader.Thiscausesthecompilertoimportthedocumentationforthatelementfromtheincludeddocument.Forexample:
///<includefile="IncludedDocumentation.xml"path="root/EnabledMethodDocs"/>publicboolEnabled(booltrue)
{
}
Aviolationofthisruleoccurswhenthepathattributedoesnotlinktoavalidpathwithintheincludeddocumentationfile.
HowtoFixViolationsTofixaviolationofthisrule,correctthevalueofthepathattributetopointtoavalidpathwithinthefile.
TypeName IncludeNodeDoesNotContainValidFileAndPath
CheckId SA1647
Category DocumentationRules
CauseAnincludetagwithinanXmldocumentationheaderdoesnotcontainvalidfileandpathattribute.
RuleDescriptionC#syntaxprovidesamechanismforinsertingdocumentationforclassesandelementsdirectlyintothecode,throughtheuseofXmldocumentationheaders.Foranintroductiontotheseheadersandadescriptionoftheheadersyntax,seethefollowingarticle:http://msdn.microsoft.com/en-us/magazine/cc302121.aspx.
Asanalternativetoauthoringdocumentationdirectlywithinthecodefile,itispossibletoplacedocumentationformultipleelementswithinaseparateXmlfile,andthenreferenceasectionofthatfilewithinanelement'sdocumentationheader.Thiscausesthecompilertoimportthedocumentationforthatelementfromtheincludeddocument.Forexample:
///<includefile="IncludedDocumentation.xml"path="root/EnabledMethodDocs"/>publicboolEnabled(booltrue)
{
}
Aviolationofthisruleoccurswhentheincludetagismissingafileorpathattribute,orcontainsanimproperlyformattedfileorpathattribute.
HowtoFixViolationsTofixaviolationofthisrule,addorcorrectthefileandpathattributes.
TypeName InheritDocMustBeUsedWithInheritingClass
CheckId SA1648
Category DocumentationRules
Cause<inheritdoc>hasbeenusedonanelementthatdoesntinheritfromabaseclassorimplementaninterface..
RuleDescriptionVerifiesthatan'inheritdoc'tagisnotusedwhentheclassorinterfacedoesnotinheritfromabaseclassorinterface.
Aviolationofthisruleoccurswhentheelementhavingtheinheritdoctagdoesn'tinheritfromabasecaseorimplementaninterface.
HowtoFixViolationsTofixaviolationofthisrule,removethe<inheritdoc>taganddocumenttheelementappropriately.
TypeName FileHeaderFileNameDocumentationMustMatchTypeName
CheckId SA1649
Category DocumentationRules
CauseThefiletagwithinthefileheaderatthetopofaC#codefiledoesnotmatchthefirsttypedeclaredinthefile.ForgenericsthataredefinedasClass1<T>thenameofthefileneedstobeClass1{T}.csandthisshouldappearintheheaderalso.Partialclassesareignored.
RuleDescriptionAviolationofthisruleoccurswhenthefiletagwithinthefileheaderatthetopofaC#filedoesnotcontainthenameofthefirsttypeinthefile.Forexample,consideraC#sourcefilenamedClass1.cs,withthefollowingheader:
//-----------------------------------------------------------------------
//<copyrightfile="ThisIsNotTheCorrectTypeName.cs"company="MyCompany">
//Customcompanycopyrighttag.
//</copyright>
//-----------------------------------------------------------------------
publicclassClass1{
}
Aviolationofthisrulewouldoccur,sincethefiletagdoesnotcontainthecorrectnameofthefirsttypeinthefile.Theheadershouldbewrittenas:
//-----------------------------------------------------------------------
//<copyrightfile="Class1.cs"company="MyCompany">
//Customcompanycopyrighttag.
//</copyright>
//-----------------------------------------------------------------------
publicclassClass1{
}
Agenericclassshouldbewrittenas:
//-----------------------------------------------------------------------
//<copyrightfile="Class1{T}.cs"company="MyCompany">
//Customcompanycopyrighttag.
//</copyright>
//-----------------------------------------------------------------------
publicclassClass1<T>{
}
HowtoFixViolationsTofixaviolationofthisrule,addthenameofthefirsttypefromthefiletothefiletag.
Ruleswhichenforcecodelayoutandlinespacing.
SA1500:CurlyBracketsForMultiLineStatementsMustNotShareLine
SA1501:StatementMustNotBeOnSingleLine
SA1502:ElementMustNotBeOnSingleLine
SA1503:CurlyBracketsMustNotBeOmitted
SA1504:AllAccessorMustBeMultiLineOrSingleLine
SA1505:OpeningCurlyBracketsMustNotBeFollowedByBlankLine
SA1506:ElementDocumentationHeadersMustNotBeFollowedByBlankLine
SA1507:CodeMustNotContainMultipleBlankLinesInARow
SA1508:ClosingCurlyBracketsMustNotBePrecededByBlankLine
SA1509:OpeningCurlyBracketsMustNotBePrecedededByBlankLine
SA1510:ChainedStatementBlocksMustNotBePrecededByBlankLine
SA1511:WhileDoFooterMustNotBePrecededByBlankLine
SA1512:SingleLineCommentsMustNotBeFollowedByBlankLine
SA1513:ClosingCurlyBracketMustBeFollowedByBlankLine
SA1514:ElementDocumentationHeaderMustBePrecededByBlankLine
SA1515:SingleLineCommentMustBePrecededByBlankLine
SA1516:ElementsMustBeSeparatedByBlankLine
SA1517:CodeMustNotContainBlankLinesAtStartOfFile
SA1518:CodeMustNotContainBlankLinesAtEndOfFile
TypeName CurlyBracketsForMultiLineStatementsMustNotShareLine
CheckId SA1500
Category LayoutRules
CauseTheopeningorclosingcurlybracketwithinaC#statement,element,orexpressionisnotplacedonitsownline.
RuleDescriptionAviolationofthisruleoccurswhentheopeningorclosingcurlybracketwithinastatement,element,orexpressionisnotplacedonitsownline.Forexample:
publicobjectMethod()
{
lock(this){
returnthis.value;
}
}
WhenStyleCopchecksthiscode,aviolationofthisrulewilloccurbecausetheopeningcurlybracketofthelockstatementisplacedonthesamelineasthelockkeyword,ratherthanbeingplacedonitsownline,asfollows:
publicobjectMethod()
{
lock(this)
{
returnthis.value;
}
}
Aviolationwillalsooccuriftheclosingcurlybracketsharesalinewithothercode.Forexample:
publicobjectMethod()
{
lock(this)
{
returnthis.value;}
}
HowtoFixViolationsTofixaviolationofthisrule,ensurethatboththeopeningandclosingcurlybracketsareplacedontheirownline,anddonotsharethelinewithanyothercode,otherthancomments.
TypeName StatementMustNotBeOnASingleLine
CheckId SA1501
Category LayoutRules
CauseAC#statementcontainingopeningandclosingcurlybracketsiswrittencompletelyonasingleline.
RuleDescriptionAviolationofthisruleoccurswhenastatementthatiswrappedinopeningandclosingcurlybracketsiswrittenonasingleline.Forexample:
publicobjectMethod()
{
lock(this){returnthis.value;}
}
WhenStyleCopchecksthiscode,aviolationofthisrulewilloccurbecausetheentirelockstatementiswrittenononeline.Thestatementshouldbewrittenacrossmultiplelines,withtheopeningandclosingcurlybracketseachontheirownline,asfollows:
publicobjectMethod()
{
lock(this)
{
returnthis.value;
}
}
HowtoFixViolationsTofixaviolationofthisrule,rewritethestatementsothatitexpandsacrossmultiplelines.
TypeName ElementMustNotBeOnASingleLine
CheckId SA1502
Category LayoutRules
CauseAC#elementcontainingopeningandclosingcurlybracketsiswrittencompletelyonasingleline.
RuleDescriptionAviolationofthisruleoccurswhenanelementthatiswrappedinopeningandclosingcurlybracketsiswrittenonasingleline.Forexample:
publicobjectMethod(){returnnull;}
WhenStyleCopchecksthiscode,aviolationofthisrulewilloccurbecausetheentiremethodiswrittenononeline.Themethodshouldbewrittenacrossmultiplelines,withtheopeningandclosingcurlybracketseachontheirownline,asfollows:
publicobjectMethod()
{
returnnull;
}
Asanexceptiontothisrule,accessorswithinproperties,events,orindexersareallowedtobewrittenallonasingleline,aslongastheaccessorisshort.
HowtoFixViolationsTofixaviolationofthisrule,rewritetheelementsothatitexpandsacrossmultiplelines.
TypeName CurlyBracketsMustNotBeOmitted
CheckId SA1503
Category LayoutRules
CauseTheopeningandclosingcurlybracketsforaC#statementhavebeenomitted.
RuleDescriptionAviolationofthisruleoccurswhentheopeningandclosingcurlybracketsforastatementhavebeenomitted.InC#,sometypesofstatementsmayoptionallyincludecurlybrackets.Examplesincludeif,while,andforstatements.Forexample,anif-statementmaybewrittenwithoutcurlybrackets:
if(true)
returnthis.value;
AlthoughthisislegalinC#,StyleCopalwaysrequiresthecurlybracketstobepresent,toincreasethereadabilityandmaintainabilityofthecode.
Whenthecurlybracketsareomitted,itispossibletointroduceanerrorinthecodebyinsertinganadditionalstatementbeneaththeif-statement.Forexample:
if(true)
this.value=2;
returnthis.value;
Glancingatthiscode,itappearsasifboththeassignmentstatementandthereturnstatementarechildrenoftheif-statement.Infact,thisisnottrue.Onlytheassignmentstatementisachildoftheif-statement,andthereturnstatementwillalwaysexecuteregardlessoftheoutcomeoftheif-statement.
StyleCopalwaysrequirestheopeningandclosingcurlybracketstobepresent,topreventthesekindsoferrors:
if(true)
{
this.value=2;
returnthis.value;
}
HowtoFixViolationsTofixaviolationofthisrule,wrapthebodyofthestatementincurlybrackets.
TypeName AllAccessorsMustBeSingleLineOrMultiLine
CheckId SA1504
Category LayoutRules
CauseWithinaC#property,indexerorevent,atleastoneofthechildaccessorsiswrittenonasingleline,andatleastoneofthechildaccessorsiswrittenacrossmultiplelines.
RuleDescriptionAviolationofthisruleoccurswhentheaccessorswithinaproperty,indexeroreventarenotconsistentlywrittenonasinglelineoronmultiplelines.Thisruleisintendedtoincreasethereadabilityofthecodebyrequiringalloftheaccessorswithinanelementtobeformattedinthesameway.
Forexample,thefollowingpropertywouldgenerateaviolationofthisrule,becauseoneaccessoriswrittenonasinglelinewhiletheotheraccessorsnapsmultiplelines.
publicboolEnabled
{
get{returnthis.enabled;}
set
{
this.enabled=value;
}
}
Theviolationcanbeavoidedbyplacingbothaccessorsonasingleline,orexpandingbothaccessorsacrossmultiplelines:
publicboolEnabled
{
get{returnthis.enabled;}
set{this.enabled=value;}
}
publicboolEnabled
{
get
{
returnthis.enabled;
}
set
{
this.enabled=value;
}
}
HowtoFixViolationsTofixaviolationofthisrule,writeeachaccessoronasinglelineiftheaccessorsareshort,orexpandbothaccessorsacrossmultiplelinesiftheaccessorsarelonger.
TypeName OpeningCurlyBracketsMustNotBeFollowedByBlankLine
CheckId SA1505
Category LayoutRules
CauseAnopeningcurlybracketwithinaC#element,statement,orexpressionisfollowedbyablankline.
RuleDescriptionToimprovethereadabilityofthecode,StyleCoprequiresblanklinesincertainsituations,andprohibitsblanklinesinothersituations.Thisresultsinaconsistentvisualpatternacrossthecode,whichcanimproverecognitionandreadabilityofunfamiliarcode.
Aviolationofthisruleoccurswhenanopeningcurlybracketisfollowedbyablankline.Forexample:
publicboolEnabled
{
get
{
returnthis.enabled;
}
}
Thecodeabovewouldgeneratetwoinstancesofthisviolation,sincetherearetwoplaceswhereopeningcurlybracketsarefollowedbyblanklines.
HowtoFixViolationsTofixaviolationofthisrule,removetheblanklinefollowingtheopeningcurlybracket.
TypeName ElementDocumentationHeadersMustNotBeFollowedByBlankLine
CheckId SA1506
Category LayoutRules
CauseAnelementdocumentationheaderaboveaC#elementisfollowedbyablankline.
RuleDescriptionToimprovethereadabilityofthecode,StyleCoprequiresblanklinesincertainsituations,andprohibitsblanklinesinothersituations.Thisresultsinaconsistentvisualpatternacrossthecode,whichcanimproverecognitionandreadabilityofunfamiliarcode.
Aviolationofthisruleoccurswhentheelementdocumentationheaderaboveanelementisfollowedbyablankline.Forexample:
///<summary>
///Getsavalueindicatingwhetherthecontrolisenabled.
///</summary>
publicboolEnabled
{
get{returnthis.enabled;}
}
Thecodeabovewouldgenerateaninstanceofthisviolation,sincethedocumentationheaderisfollowedbyablankline.
HowtoFixViolationsTofixaviolationofthisrule,removetheblanklinefollowingthedocumentationheader.
TypeName CodeMustNotContainMultipleBlankLinesInARow
CheckId SA1507
Category LayoutRules
CauseTheC#codecontainsmultipleblanklinesinarow.
RuleDescriptionToimprovethereadabilityofthecode,StyleCoprequiresblanklinesincertainsituations,andprohibitsblanklinesinothersituations.Thisresultsinaconsistentvisualpatternacrossthecode,whichcanimproverecognitionandreadabilityofunfamiliarcode.
Aviolationofthisruleoccurswhenthecodecontainsmorethanoneblanklineinarow.Forexample:
publicboolEnabled
{
get
{
Console.WriteLine("Gettingtheenabledflag.");
returnthis.enabled;
}
}
Thecodeabovewouldgenerateaninstanceofthisviolation,sinceitcontainsblankmultiplelinesinarow.
HowtoFixViolationsTofixaviolationofthisrule,removetheextrablanklines.
TypeName ClosingCurlyBracketsMustNotBePrecededByBlankLine
CheckId SA1508
Category LayoutRules
CauseAclosingcurlybracketwithinaC#element,statement,orexpressionisprecededbyablankline.
RuleDescriptionToimprovethereadabilityofthecode,StyleCoprequiresblanklinesincertainsituations,andprohibitsblanklinesinothersituations.Thisresultsinaconsistentvisualpatternacrossthecode,whichcanimproverecognitionandreadabilityofunfamiliarcode.
Aviolationofthisruleoccurswhenaclosingcurlybracketisprecededbyablankline.Forexample:
publicboolEnabled
{
get
{
returnthis.enabled;
}
}
Thecodeabovewouldgeneratetwoinstancesofthisviolation,sincetherearetwoplaceswhereclosingcurlybracketsareprecededbyblanklines.
HowtoFixViolationsTofixaviolationofthisrule,removetheblanklineprecedingtheclosingcurlybracket.
TypeName OpeningCurlyBracketsMustNotBePrecededByBlankLine
CheckId SA1509
Category LayoutRules
CauseAnopeningcurlybracketwithinaC#element,statement,orexpressionisprecededbyablankline.
RuleDescriptionToimprovethereadabilityofthecode,StyleCoprequiresblanklinesincertainsituations,andprohibitsblanklinesinothersituations.Thisresultsinaconsistentvisualpatternacrossthecode,whichcanimproverecognitionandreadabilityofunfamiliarcode.
Aviolationofthisruleoccurswhenanopeningcurlybracketisprecededbyablankline.Forexample:
publicboolEnabled
{
get
{
returnthis.enabled;
}
}
Thecodeabovewouldgeneratetwoinstancesofthisviolation,sincetherearetwoplaceswhereopeningcurlybracketsareprecededbyblanklines.
HowtoFixViolationsTofixaviolationofthisrule,removetheblanklineprecedingtheopeningcurlybracket.
TypeName ChainedStatementBlocksMustNotBePrecededByBlankLine
CheckId SA1510
Category LayoutRules
CauseChainedC#statementsareseparatedbyablankline.
RuleDescriptionToimprovethereadabilityofthecode,StyleCoprequiresblanklinesincertainsituations,andprohibitsblanklinesinothersituations.Thisresultsinaconsistentvisualpatternacrossthecode,whichcanimproverecognitionandreadabilityofunfamiliarcode.
SometypesofC#statementscanonlybeusedwhenchainedtothebottomofanotherstatement.Examplesincludecatchandfinallystatements,whichmustalwaysbechainedtothebottomofatry-statement.Anotherexampleisanelse-statement,whichmustalwaysbechainedtothebottomofanif-statement,ortoanotherelse-statement.Thesetypesofchainedstatementsmustnotbeseparatedbyablankline.Forexample:
try
{
this.SomeMethod();
}
catch(Exceptionex)
{
Console.WriteLine(ex.ToString());
}
HowtoFixViolationsTofixaviolationofthisrule,removeanyblanklinesbetweenthechainedstatements.
TypeName WhileDoFooterMustNotBePrecededByBlankLine
CheckId SA1511
Category LayoutRules
CauseThewhilefooteratthebottomofado-whilestatementisseparatedfromthestatementbyablankline.
RuleDescriptionToimprovethereadabilityofthecode,StyleCoprequiresblanklinesincertainsituations,andprohibitsblanklinesinothersituations.Thisresultsinaconsistentvisualpatternacrossthecode,whichcanimproverecognitionandreadabilityofunfamiliarcode.
Aviolationofthisruleoccurswhenthewhilekeywordatthebottomofado-whilestatementisseparatedfromthemainpartofthestatementbyoneormoreblanklines.Forexample:
do
{
Console.WriteLine("Loopforever");
}
while(true);
HowtoFixViolationsTofixaviolationofthisrule,removeanyblanklinesbeforethewhilekeyword.
TypeName SingleLineCommentsMustNotBeFollowedByBlankLine
CheckId SA1512
Category LayoutRules
CauseAsingle-linecommentwithinC#codeisfollowedbyablankline.
RuleDescriptionToimprovethereadabilityofthecode,StyleCoprequiresblanklinesincertainsituations,andprohibitsblanklinesinothersituations.Thisresultsinaconsistentvisualpatternacrossthecode,whichcanimproverecognitionandreadabilityofunfamiliarcode.
Aviolationofthisruleoccurswhenasingle-linecommentisfollowedbyablankline.Forexample:
publicboolEnabled
{
get
{
//Returnthevalueofthe'enabled'field.
returnthis.enabled;
}
}
Thecodeabovewouldgenerateaninstanceofthisviolation,sincethesingle-linecommentisfollowedbyablankline.
Itisallowedtoplaceablanklineinbetweentwoblocksofsingle-linecomments.Forexample:
publicboolEnabled
{
get
{
//Thisisasamplecommentwhichdoesn'treallysayanything.
//Thisisanotherpartofthecomment.
//Thereisablanklineabovethiscommentbutthatisok.
returnthis.enabled;
}
}
Ifthecommentisbeingusedtocommentoutalineofcode,placefourforwardslashesatthebeginningofthecomment,ratherthantwo.ThiswillcauseStyleCoptoignorethisviolation.Forexample:
publicboolEnabled
{
get
{
////returnfalse;
returnthis.enabled;
}
}
HowtoFixViolationsTofixaviolationofthisrule,removetheblanklinefollowingthesingle-linecomment.
TypeName ClosingCurlyBracketMustBeFollowedByBlankLine
CheckId SA1513
Category LayoutRules
CauseAclosingcurlybracketwithinaC#element,statement,orexpressionisnotfollowedbyablankline.
RuleDescriptionToimprovethereadabilityofthecode,StyleCoprequiresblanklinesincertainsituations,andprohibitsblanklinesinothersituations.Thisresultsinaconsistentvisualpatternacrossthecode,whichcanimproverecognitionandreadabilityofunfamiliarcode.
Aviolationofthisruleoccurswhenaclosingcurlybracketisnotfollowedbyablankline.Forexample:
publicboolEnabled
{
get
{
returnthis.enabled;
}}
Thecodeabovewouldgenerateoneinstanceofthisviolation,sincethereisoneplacewhereaclosingcurlybracketisnotfollowedbyablankline.
HowtoFixViolationsTofixaviolationofthisrule,ensureablanklinefollowsclosingcurlybrackets.
TypeName ElementDocumentationHeadersMustBePrecededByBlankLine
CheckId SA1514
Category LayoutRules
CauseAnelementdocumentationheaderaboveaC#elementisnotprecededbyablankline.
RuleDescriptionToimprovethereadabilityofthecode,StyleCoprequiresblanklinesincertainsituations,andprohibitsblanklinesinothersituations.Thisresultsinaconsistentvisualpatternacrossthecode,whichcanimproverecognitionandreadabilityofunfamiliarcode.
Aviolationofthisruleoccurswhentheelementdocumentationheaderaboveanelementisnotprecededbyablankline.Forexample:
publicboolVisible
{
get{returnthis.visible;}
}
///<summary>
///Getsavalueindicatingwhetherthecontrolisenabled.
///</summary>
publicboolEnabled
{
get{returnthis.enabled;}
}
Thecodeabovewouldgenerateaninstanceofthisviolation,sincethedocumentationheaderisnotprecededbyablankline.
Anexceptiontothisruleoccurswhenthedocumentationheaderisthefirstitemwithinitsscope.Inthiscase,theheadershouldnotbeprecededbyablankline.Forexample:
publicclassClass1
{
///<summary>
///Getsavalueindicatingwhetherthecontrolisenabled.
///</summary>
publicboolEnabled
{
get{returnthis.enabled;}
}
}
Inthecodeabove,theheaderisthefirstitemwithinitsscope,andthusitshouldnotbeprecededbyablankline.
HowtoFixViolationsTofixaviolationofthisrule,addablanklineabovethedocumentationheader.
TypeName SingleLineCommentsMustBePrecededByBlankLine
CheckId SA1515
Category LayoutRules
CauseAsingle-linecommentwithinC#codeisnotprecededbyablankline.
RuleDescriptionToimprovethereadabilityofthecode,StyleCoprequiresblanklinesincertainsituations,andprohibitsblanklinesinothersituations.Thisresultsinaconsistentvisualpatternacrossthecode,whichcanimproverecognitionandreadabilityofunfamiliarcode.
Aviolationofthisruleoccurswhenasingle-linecommentisnotprecededbyablankline.Forexample:
publicboolEnabled
{
get
{
Console.WriteLine("Gettingtheenabledflag.");
//Returnthevalueofthe'enabled'field.
returnthis.enabled;
}
}
Thecodeabovewouldgenerateaninstanceofthisviolation,sincethesingle-linecommentisnotprecededbyablankline.
Anexceptiontothisruleoccurswhenthesingle-linecommentisthefirstitemwithinitsscope.Inthiscase,thecommentshouldnotbeprecededbyablankline.Forexample:
publicboolEnabled
{
get
{
//Returnthevalueofthe'enabled'field.
returnthis.enabled;
}
}
Inthecodeabove,thecommentisthefirstitemwithinitsscope,andthusitshouldnotbeprecededbyablankline.
Ifthecommentisbeingusedtocommentoutalineofcode,beginthecommentwithfourforwardslashesratherthantwo.ThiswillcauseStyleCoptoignorethisviolation.Forexample:
publicboolEnabled
{
get
{
Console.WriteLine("Gettingtheenabledflag.");
////returnfalse;returnthis.enabled;
}
}
HowtoFixViolationsTofixaviolationofthisrule,addablanklineabovethecomment.
TypeName ElementsMustBeSeparatedByBlankLine
CheckId SA1516
Category LayoutRules
CauseAdjacentC#elementsarenotseparatedbyablankline.
RuleDescriptionToimprovethereadabilityofthecode,StyleCoprequiresblanklinesincertainsituations,andprohibitsblanklinesinothersituations.Thisresultsinaconsistentvisualpatternacrossthecode,whichcanimproverecognitionandreadabilityofunfamiliarcode.
Aviolationofthisruleoccurswhentwoadjacentelementarenotseparatedbyablankline.Forexample:
publicvoidMethod1()
{
}
publicboolProperty
{
get{returntrue;}
}
Intheexampleabove,themethodandpropertyarenotseparatedbyablankline,soaviolationofthisrulewouldoccur.
publiceventEventHandlerSomeEvent{add{//addeventsubscriberhere}
remove
{//removeeventsubscriberhere}
}
Intheexampleabove,theaddandremoveoftheeventneedtobeseparatedbyablanklinebecausetheaddismultiline.
HowtoFixViolations>HowtoFixViolationsTofixaviolationofthisrule,addablanklinebetweentheadjacentelements.
TypeName CodeMustNotContainBlankLinesAtStartOfFile
CheckId SA1517
Category LayoutRules
CauseThecodefilehasblanklinesatthestart.
RuleDescriptionToimprovethelayoutofthecode,StyleCoprequiresnoblanklinesatthestartoffiles.
Aviolationofthisruleoccurswhenoneormoreblanklinesareatthestartofthefile.
HowtoFixViolationsTofixaviolationofthisrule,removetheblanklinesfromthestartofthefile.
TypeName CodeMustNotContainBlankLinesAtEndOfFile
CheckId SA1518
Category LayoutRules
CauseThecodefilehasblanklinesattheend.
RuleDescriptionToimprovethelayoutofthecode,StyleCoprequiresnoblanklinesattheendoffiles.
Aviolationofthisruleoccurswhenoneormoreblanklinesareattheendofthefile.
HowtoFixViolationsTofixaviolationofthisrule,removetheblanklinesfromtheendofthefile.
Ruleswhichimprovecodemaintainability.
SA1119:StatementMustNotUseUnnecessaryParenthesis
SA1400:AccessModifierMustBeDeclared
SA1401:FieldsMustBePrivate
SA1402:FileMayOnlyContainASingleClass
SA1403:FileMayOnlyContainASingleNamespace
SA1404:CodeAnalysisSuppressionMustHaveJustification
SA1405:DebugAssertMustProvideMessageText
SA1406:DebugFailMustProvideMessageText
SA1407:ArithmeticExpressionsMustDeclarePrecedence
SA1408:ConditionalExpressionsMustDeclarePrecendence
SA1409:RemoveUnnecessaryCode
SA1410:RemoveDelegateParenthesisWhenPossible
SA1411:AttributeConstructorMustNotUseUnnecessaryParenthesis
TypeName StatementMustNotUseUnnecessaryParenthesis
CheckId SA1119
Category MaintainabilityRules
CauseAC#statementcontainsparenthesiswhichareunnecessaryandshouldberemoved.
RuleDescriptionItispossibleinC#toinsertparenthesisaroundvirtuallyanytypeofexpression,statement,orclause,andinmanysituationsuseofparenthesiscangreatlyimprovethereadabilityofthecode.However,excessiveuseofparenthesiscanhavetheoppositeeffect,makingitmoredifficulttoreadandmaintainthecode.
Aviolationofthisruleoccurswhenparenthesisareusedinsituationswheretheyprovidenopracticalvalue.Typically,thishappensanytimetheparenthesissurroundanexpressionwhichdoesnotstrictlyrequiretheuseofparenthesis,andtheparenthesisexpressionislocatedattherootofastatement.Forexample,thefollowinglinesofcodeallcontainunnecessaryparenthesiswhichwillresultinviolationsofthisrule:
intx=(5+b);
stringy=(this.Method()).ToString();
return(x.Value);
Ineachofthesestatements,theextraparenthesiscanberemovedwithoutsacrificingthereadabilityofthecode:
intx=5+b;
stringy=this.Method().ToString();
returnx.Value;
HowtoFixViolationsTofixaviolationofthisrule,removetheunnecessaryparenthesis.
TypeName AccessModifierMustBeDeclared
CheckId SA1400
Category MaintainabilityRules
CauseTheaccessmodifierforaC#elementhasnotbeenexplicitlydefined.
RuleDescriptionC#allowselementstobedefinedwithoutanaccessmodifier.Dependinguponthetypeofelement,C#willautomaticallyassignanaccessleveltotheelementinthiscase.
Thisrulerequiresanaccessmodifiertobeexplicitlydefinedforeveryelement.Thisremovestheneedforthereadertomakeassumptionsaboutthecode,improvingthereadabilityofthecode.
HowtoFixViolationsTofixaviolationofthisrule,addanaccessmodifiertothedeclarationoftheelement.
TypeName FieldsMustBePrivate
CheckId SA1401
Category MaintainabilityRules
CauseAfieldwithinaC#classhasanaccessmodifierotherthanprivate.
RuleDescriptionAviolationofthisruleoccurswheneverafieldinaclassisgivennon-privateaccess.Formaintainabilityreasons,propertiesshouldalwaysbeusedasthemechanismforexposingfieldsoutsideofaclass,andfieldsshouldalwaysbedeclaredwithprivateaccess.Thisallowstheinternalimplementationofthepropertytochangeovertimewithoutchangingtheinterfaceoftheclass.
FieldslocatedwithinC#structsareallowedtohaveanyaccesslevel.
HowtoFixViolationsTofixaviolationofthisrule,makethefieldprivateandaddapropertytoexposethefieldoutsideoftheclass.
TypeName FileMayOnlyContainASingleClass
CheckId SA1402
Category MaintainabilityRules
CauseAC#codefilecontainsmorethanoneuniqueclass.
RuleDescriptionAviolationofthisruleoccurswhenaC#filecontainsmorethanoneclass.Toincreaselong-termmaintainabilityofthecode-base,eachclassshouldbeplacedinitsownfile,andfilenamesshouldreflectthenameoftheclasswithinthefile.
Itispossibletoplaceothersupportingelementswithinthesamefileastheclass,suchasdelegates,enums,etc.,iftheyarerelatedtotheclass.
Itisalsopossibletoplacemultiplepartsofthesamepartialclasswithinthesamefile.
HowtoFixViolationsTofixaninstanceofthisviolation,moveeachclassintoitsownfile.
TypeName FileMayOnlyContainASingleNamespace
CheckId SA1403
Category MaintainabilityRules
CauseAC#codefilecontainsmorethanonenamespace.
RuleDescriptionAviolationofthisruleoccurswhenaC#filecontainsmorethanonenamespace.Toincreaselong-termmaintainabilityofthecode-base,eachfileshouldcontainatmostonenamespace.
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthefileonlycontainsasinglenamespace.
TypeName CodeAnalysisSuppressionMustHaveJustification
CheckId SA1404
Category MaintainabilityRules
CauseACodeAnalysisSuppressMessageattributedoesnotincludeajustification.
RuleDescriptionAviolationofthisruleoccurswhenthecodecontainsaCodeAnalysisSuppressMessageattribute,butajustificationforthesuppressionhasnotbeenprovidedwithintheattribute.WheneveraCodeAnalysisruleissuppressed,ajustificationshouldbeprovided.Thiscanincreasethelong-termmaintainabilityofthecode.
[SuppressMessage("Microsoft.Performance","CA1804:RemoveUnusedLocals",Justification="Usedduringunittesting")]
publicboolEnable(){
}
HowtoFixViolationsTofixaninstanceofthisviolation,addaJustificationtagandjustificationtexttotheSuppressMessageattributedescribingthereasonforthesuppression.
TypeName DebugAssertMustProvideMessageText
CheckId SA1405
Category MaintainabilityRules
CauseAcalltoDebug.AssertinC#codedoesnotincludeadescriptivemessage.
RuleDescriptionAviolationofthisruleoccurswhenthecodecontainsacalltoDebug.Assertwhichdoesnotprovideadescriptionfortheend-user.Forexample,thefollowingassertincludesadescriptionmessage:
Debug.Assert(value!=true,"Thevaluemustalwaysbetrue.");
HowtoFixViolationsTofixaviolationofthisrule,addadescriptivemessagetotheassertwhichwillappeartotheenduserwhentheassertisfired.
TypeName DebugFailMustProvideMessageText
CheckId SA1406
Category MaintainabilityRules
CauseAcalltoDebug.FailinC#codedoesnotincludeadescriptivemessage.
RuleDescriptionAviolationofthisruleoccurswhenthecodecontainsacalltoDebug.Failwhichdoesnotprovideadescriptionfortheend-user.Forexample,thefollowingcallincludesadescriptionmessage:
Debug.Fail("Thecodeshouldneverreachthispoint.");
HowtoFixViolationsTofixaninstanceofthisviolation,addadescriptivemessagetotheDebug.Failcallwhichwillappeartotheenduserwhentheassertisfired.
TypeName ArithmeticExpressionsMustDeclarePrecedence
CheckId SA1407
Category MaintainabilityRules
CauseAC#statementcontainsacomplexarithmeticexpressionwhichomitsparenthesisaroundoperators.
RuleDescriptionC#maintainsahierarchyofprecedenceforarithmeticoperators.ItispossibleinC#tostringmultiplearithmeticoperationstogetherinonestatementwithoutwrappinganyoftheoperationsinparenthesis,inwhichcasethecompilerwillautomaticallysettheorderandprecedenceoftheoperationsbasedonthesepre-establishedrules.Forexample:
intx=5+y*b/6%z-2;
Althoughthiscodeislegal,itisnothighlyreadableormaintainable.Inordertoachievefullunderstandingofthiscode,thedevelopermustknowandunderstandthebasicoperatorprecedencerulesinC#.
Thisruleisintendedtoincreasethereadabilityandmaintainabilityofthistypeofcode,andtoreducetheriskofintroducingbugslater,byforcingthedevelopertoinsertparenthesistoexplicitlydeclaretheoperatorprecedence.Theexamplebelowshowsmultiplearithmeticoperationssurroundedbyparenthesis:
intx=5+(y*((b/6)%z))-2;
Insertingparenthesismakesthecodemoreobviousandeasytounderstand,andremovestheneedforthereadertomakeassumptionsaboutthecode.
HowtoFixViolationsTofixaviolationofthisrule,insertparenthesiswithinthearithmeticexpressiontodeclaretheprecedenceoftheoperations.
TypeName ConditionalExpressionsMustDeclarePrecedence
CheckId SA1408
Category MaintainabilityRules
CauseAC#statementcontainsacomplexconditionalexpressionwhichomitsparenthesisaroundoperators.
RuleDescriptionC#maintainsahierarchyofprecedenceforconditionaloperators.ItispossibleinC#tostringmultipleconditionaloperationstogetherinonestatementwithoutwrappinganyoftheoperationsinparenthesis,inwhichcasethecompilerwillautomaticallysettheorderandprecedenceoftheoperationsbasedonthesepre-establishedrules.Forexample:
if(x||y&&z&&a||b)
{
}
Althoughthiscodeislegal,itisnothighlyreadableormaintainable.Inordertoachievefullunderstandingofthiscode,thedevelopermustknowandunderstandthebasicoperatorprecedencerulesinC#.
Thisruleisintendedtoincreasethereadabilityandmaintainabilityofthistypeofcode,andtoreducetheriskofintroducingbugslater,byforcingthedevelopertoinsertparenthesistoexplicitlydeclaretheoperatorprecedence.Forexample,adevelopercouldwritethiscodeas:
if((x||y)&&z&&(a||b))
{
}
or
if(x||(y&&z&&a)||b)
{
}
Insertingparenthesismakesthecodemoreobviousandeasytounderstand,andremovestheneedforthereadertomakeassumptionsaboutthecode.
HowtoFixViolationsInsertparenthesiswithintheconditionalexpressiontodeclaretheprecedenceoftheoperations.
TypeName RemoveUnnecessaryCode
CheckId SA1409
Category MaintainabilityRules
CauseAC#filecontainscodewhichisunnecessaryandcanberemovedwithoutchangingtheoveralllogicofthecode.
RuleDescriptionAviolationofthisruleoccurswhenthefilecontainscodewhichcanberemovedwithoutchangingtheoveralllogicofthecode.
Forexample,thefollowingtry-catchstatementcouldberemovedcompletelysincethetryandcatchblocksarebothempty.
try
{
}
catch(Exceptionex)
{
}
Thetry-finallystatementbelowdoescontaincodewithinthetryblock,butitdoesnotcontainanycatchblocks,andthefinallyblockisempty.Thus,thetry-finallyisnotperforminganyusefulfunctionandcanberemoved.
try
{
this.Method();
}
finally
{
}
Asafinalexample,theunsafestatementbelowisempty,andthusprovidesnovalue.
unsafe
{
}
HowtoFixViolationsThefixaviolationofthisrule,removetheunnecessarycode,orfillinthecodewithadditionalstatements.
TypeName RemoveDelegateParenthesisWhenPossible
CheckId SA1410
Category MaintainabilityRules
CauseAcalltoaC#anonymousmethoddoesnotcontainanymethodparameters,yetthestatementstillincludesparenthesis.
RuleDescriptionWhenananonymousmethoddoesnotcontainanymethodparameters,theparenthesisaroundtheparametersareoptional.
Aviolationofthisruleoccurswhentheparenthesisarepresentonananonymousmethodcallwhichtakesnomethodparameters.Forexample:
this.Method(delegate(){return2;});
Theparenthesisareunnecessaryandshouldberemoved:
this.Method(delegate{return2;});
HowtoFixViolationsRemovetheunnecessaryparenthesisafterthedelegatekeyword.
TypeName AttributeConstructorMustNotUseUnnecessaryParenthesis
CheckId SA1411
Category MaintainabilityRules
CauseTODO.
RuleDescriptionTODO
Aviolationofthisruleoccurswhenunneccsaryparenthesishavebeenusedinanattributeconstructor.Forexample:
[Serializable()]Theparenthesisareunnecessaryandshouldberemoved:
[Serializable]
HowtoFixViolationsRemovetheunnecessaryparenthesis.
Ruleswhichenforcenamingrequirementsformembers,types,andvariables.
SA1300:ElementMustBeginWithUpperCaseLetter
SA1301:ElementMustBeginWithLowerCaseLetter
SA1302:InterfaceNamesMustBeginWithI
SA1303:ConstFieldNamesMustBeginWithUpperCaseLetter
SA1304:NonPrivateReadonlyFieldsMustBeginWithUpperCaseLetter
SA1305:FieldNamesMustNotUseHungarianNotation
SA1306:FieldNamesMustBeginWithLowerCaseLetter
SA1307:AccessibleFieldsMustBeginWithUpperCaseLetter
SA1308:VariableNamesMustNotBePrefixed
SA1309:FieldNamesMustNotBeginWithUnderscore
SA1310:FieldNamesMustNotContainUnderscore
TypeName ElementMustBeginWithUpperCaseLetter
CheckId SA1300
Category NamingRules
CauseThenameofaC#elementdoesnotbeginwithanupper-caseletter.
RuleDescriptionAviolationofthisruleoccurswhenthenamesofcertaintypesofelementsdonotbeginwithanupper-caseletter.Thefollowingtypesofelementsshoulduseanupper-caseletterasthefirstletteroftheelementname:namespaces,classes,enums,structs,delegates,events,methods,andproperties.
Inaddition,anyfieldwhichispublic,internal,ormarkedwiththeconstattributeshouldbeginwithanupper-caseletter.Non-privatereadonlyfieldsmustalsobenamedusinganupper-caseletter.
IfthefieldorvariablenameisintendedtomatchthenameofanitemassociatedwithWin32orCOM,andthusneedstobeginwithalower-caseletter,placethefieldorvariablewithinaspecialNativeMethodsclass.ANativeMethodsclassisanyclasswhichcontainsanameendinginNativeMethods,andisintendedasaplaceholderforWin32orCOMwrappers.StyleCopwillignorethisviolationiftheitemisplacedwithinaNativeMethodsclass.
HowtoFixViolationsTofixaviolationofthisrule,changethenameoftheelementsothatitbeginswithanupper-caseletter,orplacetheitemwithinaNativeMethodsclassifappropriate.
TypeName ElementMustBeginWithLowerCaseLetter
CheckId SA1301
Category NamingRules
CauseTherearecurrentlynosituationsinwhichthisrulewillfire.
TypeName InterfaceNamesMustBeginWithI
CheckId SA1302
Category NamingRules
CauseThenameofaC#interfacedoesnotbeginwiththecapitalletterI.
RuleDescriptionAviolationofthisruleoccurswhenthenameofaninterfacedoesnotbeginwiththecapitalletterI.InterfacenamesshouldalwaysbeginwithI.Forexample,ICustomer.
IfthefieldorvariablenameisintendedtomatchthenameofanitemassociatedwithWin32orCOM,andthuscannotbeginwiththeletterI,placethefieldorvariablewithinaspecialNativeMethodsclass.ANativeMethodsclassisanyclasswhichcontainsanameendinginNativeMethods,andisintendedasaplaceholderforWin32orCOMwrappers.StyleCopwillignorethisviolationiftheitemisplacedwithinaNativeMethodsclass.
HowtoFixViolationsTofixaviolationofthisrule,addthecapitalletterItothefrontoftheinterfacename,orplacetheitemwithinaNativeMethodsclassifappropriate.
TypeName ConstFieldNamesMustBeginWithUpperCaseLetter
CheckId SA1303
Category NamingRules
CauseThenameofaconstantC#fieldmustbeginwithanupper-caseletter.
RuleDescriptionAviolationofthisruleoccurswhenthenameofafieldmarkedwiththeconstattributedoesnotbeginwithanupper-caseletter.
IfthefieldorvariablenameisintendedtomatchthenameofanitemassociatedwithWin32orCOM,andthusneedstobeginwithalower-caseletter,placethefieldorvariablewithinaspecialNativeMethodsclass.ANativeMethodsclassisanyclasswhichcontainsanameendinginNativeMethods,andisintendedasaplaceholderforWin32orCOMwrappers.StyleCopwillignorethisviolationiftheitemisplacedwithinaNativeMethodsclass.
HowtoFixViolationsTofixaviolationofthisrule,changethenameoftheconstantfieldsothatitbeginswithanupper-caseletter,orplacetheitemwithinaNativeMethodsclassifappropriate.
TypeName NonPrivateReadonlyFieldsMustBeginWithUpperCaseLetter
CheckId SA1304
Category NamingRules
CauseThenameofanon-privatereadonlyC#fieldmustbeingwithanupper-caseletter.
RuleDescriptionAviolationofthisruleoccurswhenthenameofareadonlyfieldwhichisnotprivatedoesnotbeginwithanupper-caseletter.Non-privatereadonlyfieldsmustalwaysstartwithanupper-caseletter.
IfthefieldorvariablenameisintendedtomatchthenameofanitemassociatedwithWin32orCOM,andthusneedstobeginwithalower-caseletter,placethefieldorvariablewithinaspecialNativeMethodsclass.ANativeMethodsclassisanyclasswhichcontainsanameendinginNativeMethods,andisintendedasaplaceholderforWin32orCOMwrappers.StyleCopwillignorethisviolationiftheitemisplacedwithinaNativeMethodsclass.
HowtoFixViolationsTofixaviolationofthisrule,changethenameofthereadonlyfieldsothatitbeginswithanupper-caseletter,makethefieldprivate,orplacetheitemwithinaNativeMethodsclassifappropriate.
TypeName FieldNamesMustNotUseHungarianNotation
CheckId SA1305
Category NamingRules
CauseThenameofafieldorvariableinC#usesHungariannotation.
RuleDescriptionAviolationofthisruleoccurswhenHungariannotationisusedinthenamingoffieldsandvariables.TheuseofHungariannotationhasbecomewidespreadinC++code,butthetrendinC#istouselonger,moredescriptivenamesforvariables,whicharenotbasedonthetypeofthevariablebutwhichinsteaddescribewhatthevariableisusedfor.
Inaddition,moderncodeeditorssuchasVisualStudiomakeiteasytoidentifytypeinformationforavariableorfield,typicallybyhoveringthemousecursoroverthevariablename.ThisreducestheneedforHungariannotation.
StyleCopassumesthatanyvariablenamethatbeginswithoneortwolower-caselettersfollowedbyanupper-caseletterismakinguseofHungariannotation,andwillflagaviolationofthisruleineachcase.Itispossibletodeclarecertainprefixesaslegal,inwhichcasetheywillbeignored.Forexample,avariablenamedonExecutewillappeartoStyleCoptobeusingHungariannotation,wheninrealityitisnot.Thus,theonprefixshouldbeflaggedasanallowedprefix.
Toconfigurethelistofallowedprefixes,bringuptheStyleCopsettingsforaproject,andnavigatetotheHungariantab,asshownbelow:
AddingaoneortwoletterprefixtothislistwillcauseStyleCoptoignore
variablesorfieldswhichbeginwiththisprefix.
IfthefieldorvariablenameisintendedtomatchthenameofanitemassociatedwithWin32orCOM,andthusneedstouseHungariannotation,placethefieldorvariablewithinaspecialNativeMethodsclass.ANativeMethodsclassisanyclasswhichcontainsanameendinginNativeMethods,andisintendedasaplaceholderforWin32orCOMwrappers.StyleCopwillignorethisviolationiftheitemisplacedwithinaNativeMethodsclass.
HowtoFixViolationsTofixaviolationofthisrule,removetheHungariannotationfromthefieldorvariablename,orplacetheitemwithinaNativeMethodsclassifappropriate.
TypeName FieldNamesMustBeginWithLowerCaseLetter
CheckId SA1306
Category NamingRules
CauseThenameofafieldorvariableinC#doesnotbeginwithalower-caseletter.
RuleDescriptionAviolationofthisruleoccurswhenthenameofafieldorvariablebeginswithanupper-caseletter.Constantsmustalwaysstartwithanuppercaseletter,whilstreadonlyfieldsmaystartwitheitheranuppercaseoralowercaseletter.Also,publicorinternalfieldsmustalwaysstartwithanuppercaseletter.
IfthefieldorvariablenameisintendedtomatchthenameofanitemassociatedwithWin32orCOM,andthusneedstobeginwithanupper-caseletter,placethefieldorvariablewithinaspecialNativeMethodsclass.ANativeMethodsclassisanyclasswhichcontainsanameendinginNativeMethods,andisintendedasaplaceholderforWin32orCOMwrappers.StyleCopwillignorethisviolationiftheitemisplacedwithinaNativeMethodsclass.
HowtoFixViolationsTofixaviolationofthisrule,changethenameofthefieldorvariablesothatitbeginswithalower-caseletter,orplacetheitemwithinaNativeMethodsclassifappropriate.
TypeName AccessibleFieldsMustBeginWithUpperCaseLetter
CheckId SA1307
Category NamingRules
CauseThenameofapublicorinternalfieldinC#doesnotbeginwithanupper-caseletter.
RuleDescriptionAviolationofthisruleoccurswhenthenameofapublicorinternalfieldbeginswithalower-caseletter.Publicorinternalfieldsmustbeingwithanupper-caseletter.
IfthefieldorvariablenameisintendedtomatchthenameofanitemassociatedwithWin32orCOM,andthusneedstostartwithalower-caseletter,placethefieldorvariablewithinaspecialNativeMethodsclass.ANativeMethodsclassisanyclasswhichcontainsanameendinginNativeMethods,andisintendedasaplaceholderforWin32orCOMwrappers.StyleCopwillignorethisviolationiftheitemisplacedwithinaNativeMethodsclass.
HowtoFixViolationsTofixaviolationofthisrule,changethenameofthefieldsothatitbeginswithanupper-caseletter,orplacetheitemwithinaNativeMethodsclassifappropriate.
TypeName VariableNamesMustNotBePrefixed
CheckId SA1308
Category NamingRules
CauseAfieldnameinC#isprefixedwithm_ors_.
RuleDescriptionAviolationofthisruleoccurswhenafieldnameisprefixedbym_ors_.
Bydefault,StyleCopdisallowstheuseofunderscores,m_,etc.,tomarklocalclassfields,infavorofthe‘this.’prefix.Theadvantageofusing‘this.’isthatitappliesequallytoallelementtypesincludingmethods,properties,etc.,andnotjustfields,makingallcallstoclassmembersinstantlyrecognizable,regardlessofwhicheditorisbeingusedtoviewthecode.Anotheradvantageisthatitcreatesaquick,recognizabledifferentiationbetweeninstancemembersandstaticmembers,whichwillnotbeprefixed.
IfthefieldorvariablenameisintendedtomatchthenameofanitemassociatedwithWin32orCOM,andthusneedstobeginwiththeprefix,placethefieldorvariablewithinaspecialNativeMethodsclass.ANativeMethodsclassisanyclasswhichcontainsanameendinginNativeMethods,andisintendedasaplaceholderforWin32orCOMwrappers.StyleCopwillignorethisviolationiftheitemisplacedwithinaNativeMethodsclass.
HowtoFixViolationsTofixaviolationofthisrule,removetheprefixfromthebeginningofthefieldname,orplacetheitemwithinaNativeMethodsclassifappropriate.
TypeName FieldNamesMustNotBeginWithUnderscore
CheckId SA1309
Category NamingRules
CauseAfieldnameinC#beginswithanunderscore.
RuleDescriptionAviolationofthisruleoccurswhenafieldnamebeginswithanunderscore.
Bydefault,StyleCopdisallowstheuseofunderscores,m_,etc.,tomarklocalclassfields,infavorofthe‘this.’prefix.Theadvantageofusing‘this.’isthatitappliesequallytoallelementtypesincludingmethods,properties,etc.,andnotjustfields,makingallcallstoclassmembersinstantlyrecognizable,regardlessofwhicheditorisbeingusedtoviewthecode.Anotheradvantageisthatitcreatesaquick,recognizabledifferentiationbetweeninstancemembersandstaticmembers,whichwillnotbeprefixed.
IfthefieldorvariablenameisintendedtomatchthenameofanitemassociatedwithWin32orCOM,andthusneedstobeginwithanunderscore,placethefieldorvariablewithinaspecialNativeMethodsclass.ANativeMethodsclassisanyclasswhichcontainsanameendinginNativeMethods,andisintendedasaplaceholderforWin32orCOMwrappers.StyleCopwillignorethisviolationiftheitemisplacedwithinaNativeMethodsclass.
HowtoFixViolationsTofixaviolationofthisrule,removetheunderscorefromthebeginningofthefieldname,orplacetheitemwithinaNativeMethodsclassifappropriate.
TypeName FieldNamesMustNotContainUnderscore
CheckId SA1310
Category NamingRules
CauseAfieldnameinC#containsanunderscore.
RuleDescriptionAviolationofthisruleoccurswhenafieldnamecontainsanunderscore.Fieldsandvariablesshouldbenamedusingdescriptive,readablewordingwhichdescribesthefunctionofthefieldorvariable.Typically,thesenameswillbewrittenusingcamelcase,andshouldnotuseunderscores.Forexample,usecustomerPostCoderatherthancustomer_post_code.
IfthefieldorvariablenameisintendedtomatchthenameofanitemassociatedwithWin32orCOM,andthusneedstoincludeunderscores,placethefieldorvariablewithinaspecialNativeMethodsclass.ANativeMethodsclassisanyclasswhichcontainsanameendinginNativeMethods,andisintendedasaplaceholderforWin32orCOMwrappers.StyleCopwillignorethisviolationiftheitemisplacedwithinaNativeMethodsclass.
HowtoFixViolationsTofixaviolationofthisrule,removetheunderscorefromthenameofthefield,orplacetheitemwithinaNativeMethodsclassifappropriate.
Ruleswhichenforceastandardorderingschemeforcodecontents.
SA1200:UsingDirectivesMustBePlacedWithinNamespace
SA1201:ElementsMustAppearInTheCorrectOrder
SA1202:ElementsMustBeOrderedByAccess
SA1203:ConstantsMustAppearBeforeFields
SA1204:StaticElementsMustAppearBeforeInstanceElements
SA1205:PartialElementsMustDeclareAccess
SA1206:DeclarationKeywordsMustFollowOrder
SA1207:ProtectedMustComeBeforeInternal
SA1208:SystemUsingDirectivesMustBePlacedBeforeOtherUsingDirectives
SA1209:UsingAliasDirectivesMustBePlacedAfterOtherUsingDirectives
SA1210:UsingDirectivesMustBeOrderedAlphabeticallyByNamespace
SA1211:UsingAliasDirectivesMustBeOrderedAlphabeticallyByAliasName
SA1212:PropertyAccessorsMustFollowOrder
SA1213:EventAccessorsMustFollowOrder
TypeName UsingDirectivesMustBePlacedWithinNamespace
CheckId SA1200
Category OrderingRules
CauseAC#usingdirectiveisplacedoutsideofanamespaceelement.
RuleDescriptionAviolationofthisruleoccurswhenausingdirectiveorausing-aliasdirectiveisplacedoutsideofanamespaceelement,unlessthefiledoesnotcontainanynamespaceelements.
Forexample,thefollowingcodewouldresultintwoviolationsofthisrule.
usingSystem;
usingGuid=System.Guid;
namespaceMicrosoft.Sample
{
publicclassProgram
{
}
}
Thefollowingcode,however,wouldnotresultinanyviolationsofthisrule:
namespaceMicrosoft.Sample
{
usingSystem;
usingGuid=System.Guid;
publicclassProgram
{
}
}
Therearesubtledifferencesbetweenplacingusingdirectiveswithinanamespaceelement,ratherthanoutsideofthenamespace,including:
1.Placingusing-aliasdirectiveswithinthenamespaceeliminatescompilerconfusionbetweenconflictingtypes.
2.Whenmultiplenamespacesaredefinedwithinasinglefile,placingusingdirectiveswithinthenamespaceelementsscopesreferencesandaliases.
1.EliminatingTypeConfusion
Considerthefollowingcode,whichcontainsausing-aliasdirectivedefinedoutsideofthenamespaceelement.ThecodecreatesanewclasscalledGuid,andalsodefinesausing-aliasdirectivetomapthenameGuidtothetypeSystem.Guid.Finally,thecodecreatesaninstanceofthetypeGuid:
usingGuid=System.Guid;
namespaceMicrosoft.Sample
{
publicclassGuid
{
publicGuid(strings)
{
}
}
publicclassProgram
{
publicstaticvoidMain(string[]args)
{
Guidg=newGuid("hello");
}
}
}
Thiscodewillcompilecleanly,withoutanycompilererrors.However,itisunclearwhichversionoftheGuidtypeisbeingallocated.Iftheusingdirectiveismovedinsideofthenamespace,asshownbelow,acompilererrorwilloccur:
namespaceMicrosoft.Sample
{
usingGuid=System.Guid;
publicclassGuid
{
publicGuid(strings)
{
}
}
publicclassProgram
{
publicstaticvoidMain(string[]args)
{
Guidg=newGuid("hello");
}
}
}
Thecodefailsonthefollowingcompilererror,foundonthelinecontainingGuidg=newGuid("hello");
CS0576:Namespace'Microsoft.Sample'containsadefinitionconflictingwithalias'Guid'
ThecodecreatesanaliastotheSystem.GuidtypecalledGuid,andalsocreatesitsowntypecalledGuidwithamatchingconstructorinterface.Later,thecodecreatesaninstanceofthetypeGuid.Tocreatethisinstance,thecompilermustchoosebetweenthetwodifferentdefinitionsofGuid.Whentheusing-aliasdirectiveisplacedoutsideofthenamespaceelement,thecompilerwillchoosethelocaldefinitionofGuiddefinedwithinthelocalnamespace,andcompletelyignoretheusing-aliasdirectivedefinedoutsideofthenamespace.This,unfortunately,isnotobviouswhenreadingthecode.
Whentheusing-aliasdirectiveispositionedwithinthenamespace,however,thecompilerhastochoosebetweentwodifferent,conflictingGuidtypesbothdefinedwithinthesamenamespace.Bothofthesetypesprovideamatchingconstructor.Thecompilerisunabletomakeadecision,soitflagsthecompilererror.
Placingtheusing-aliasdirectiveoutsideofthenamespaceisabadpracticebecauseitcanleadtoconfusioninsituationssuchasthis,whereitisnotobviouswhichversionofthetypeisactuallybeingused.Thiscanpotentiallyleadtoabugwhichmightbedifficulttodiagnose.
Placingusing-aliasdirectiveswithinthenamespaceelementeliminatesthisasasourceofbugs.
2.MultipleNamespaces
Placingmultiplenamespaceelementswithinasinglefileisgenerallyabadidea,butifandwhenthisisdone,itisagoodideatoplaceallusingdirectiveswithineachofthenamespaceelements,ratherthangloballyatthetopofthefile.Thiswillscopethenamespacestightly,andwillalsohelptoavoidthekindofbehaviordescribedabove.
Itisimportanttonotethatwhencodehasbeenwrittenwithusingdirectivesplacedoutsideofthenamespace,careshouldbetakenwhenmovingthesedirectiveswithinthenamespace,toensurethatthisisnotchangingthesemanticsofthecode.Asexplainedabove,placingusing-aliasdirectiveswithinthenamespaceelementallowsthecompilertochoosebetweenconflictingtypesinwaysthatwillnothappenwhenthedirectivesareplacedoutsideofthenamespace.
HowtoFixViolationsTofixaviolationofthisrule,moveallusingdirectivesandusing-aliasdirectiveswithinthenamespaceelement.
TypeName ElementsMustAppearInTheCorrectOrder
CheckId SA1201
Category OrderingRules
CauseAnelementwithinaC#codefileisoutoforderinrelationtotheotherelementsinthecode.
RuleDescriptionAviolationofthisruleoccurswhenthecodeelementswithinafiledonotfollowastandardorderingscheme.
Tocomplywiththisrule,elementsatthefilerootlevelorwithinanamespacemustbepositionedinthefollowingorder:
ExternAliasDirectives
UsingDirectives
Namespaces
Delegates
Enums
Interfaces
Structs
Classes
Withinaclass,struct,orinterface,elementsmustbepositionedinthefollowingorder:
Fields
Constructors
Finalizers(Destructors)
Delegates
Events
Enums
Interfaces
Properties
Indexers
Methods
Structs
Classes
Complyingwithastandardorderingschemebasedonelementtypecanincreasethereadabilityandmaintainabilityofthefileandencouragecodereuse.
Whenimplementinganinterface,itissometimesdesirabletogroupallmembersoftheinterfacenexttooneanother.Thiswillsometimesrequireviolatingthisrule,iftheinterfacecontainselementsofdifferenttypes.Thisproblemcanbesolvedthroughtheuseofpartialclasses.
1.Addthepartialattributetotheclass,iftheclassisnotalreadypartial.
2.Addasecondpartialclasswiththesamename.Itispossibletoplacethisinthesamefile,justbelowtheoriginalclass,orwithinasecondfile.
3.Movetheinterfaceinheritanceandallmembersoftheinterfaceimplementationtothesecondpartoftheclass.
Forexample:
///<summary>
///Representsacustomerofthesystem.
///</summary>
publicpartialclassCustomer
{
//Containsthemainfunctionalityoftheclass.
}
///<content>
///ImplementstheICollectionclass.
///</content>
publicpartialclassCustomer:ICollection
{
publicintCount
{
get{returnthis.count;}
}
publicboolIsSynchronized
{
get{returnfalse;}
}
publicobjectSyncRoot
{
get{returnnull;}
}
publicvoidCopyTo(Arrayarray,intindex)
{
thrownewNotImplementedException();
}
}
HowtoFixViolationsTofixaninstanceofthisviolation,ordertheelementsinthefileintheorderdescribedabove.
TypeName ElementsMustBeOrderedByAccess
CheckId SA1202
Category OrderingRules
CauseAnelementwithinaC#codefileisoutoforderwithinregardtoaccesslevel,inrelationtootherelementsinthecode.
RuleDescriptionAviolationofthisruleoccurswhenthecodeelementswithinafiledonotfollowastandardorderingschemebasedonaccesslevel.
Tocomplywiththisrule,adjacentelementsofthesametypemustbepositionedinthefollowingorderbyaccesslevel:
public
internal
protectedinternal
protected
private
Complyingwithastandardorderingschemebasedonaccesslevelcanincreasethereadabilityandmaintainabilityofthefileandmakeiteasiertoidentifythepublicinterfacethatisbeingexposedfromaclass.
HowtoFixViolationsTofixaninstanceofthisviolation,ordertheelementsinthefileintheorderdescribedabove.
TypeName ConstantsMustAppearBeforeFields
CheckId SA1203
Category OrderingRules
CauseAconstfieldisplacedbeneathanon-constfield.
RuleDescriptionAviolationofthisruleoccurswhenaconstfieldisplacedbeneathanon-constfield.Constantsmustbeplacedabovefieldstoindicatethatthetwoarefundamentallydifferenttypesofelementswithdifferentconsiderationsforthecompiler,differentnamingrequirements,etc.
HowtoFixViolationsTofixaninstanceofthisviolation,placeallconstsaboveallfields.
TypeName StaticElementsMustAppearBeforeInstanceElements
CheckId SA1204
Category OrderingRules
CauseAstaticelementispositionedbeneathaninstanceelementofthesametype.
RuleDescriptionAviolationofthisruleoccurswhenastaticelementispositionedbeneathaninstanceelementofthesametype.Allstaticelementsmustbeplacedaboveallinstanceelementsofthesametypetomakeiteasiertoseetheinterfaceexposedfromtheinstanceandstaticversionoftheclass.
HowtoFixViolationsTofixaninstanceofthisviolation,placeallstaticelementsaboveallinstanceelementsofthesametype.
TypeName PartialElementsMustDeclareAccess
CheckId SA1205
Category OrderingRules
CauseThepartialelementdoesnothaveanaccessmodifierdefined.StyleCopmaynotbeabletodeterminethecorrectplacementoftheelementsinthefile.Pleasedeclareanaccessmodifierforallpartialelements.
RuleDescriptionAviolationofthisruleoccurswhenthepartialelementsdoesnothaveanaccessmodifierdefined.
HowtoFixViolationsTofixaninstanceofthisviolation,specifyanacessmodifierforthepartialelement.
TypeName DeclarationKeywordsMustFollowOrder
CheckId SA1206
Category OrderingRules
CauseThekeywordswithinthedeclarationofanelementdonotfollowastandardorderingscheme.
RuleDescriptionAviolationofthisruleoccurswhenthekeywordswithinanelement’sdeclarationdonotfollowastandardorderingscheme.
Withinanelementdeclaration,keywordsmustappearinthefollowingorder:
Accessmodifiers
static
Allotherkeywords
Usingastandardorderingschemeforelementdeclarationkeywordscanmakethecodemorereadablebyhighlightingtheaccesslevelofeachelement.Thiscanhelppreventelementsfrombeinggivenahigheraccesslevelthanneeded.
HowToFixViolationsTofixaninstanceofthisviolation,orderthekeywordsintheelement’sdeclarationasdescribedabove.
TypeName ProtectedMustComeBeforeInternal
CheckId SA1207
Category OrderingRules
CauseThekeywordprotectedispositionedafterthekeywordinternalwithinthedeclarationofaprotectedinternalC#element.
RuleDescriptionAviolationofthisruleoccurswhenaprotectedinternalelement’saccessmodifiersarewrittenasinternalprotected.Inreality,anelementwiththekeywordsprotectedinternalwillhavethesameaccesslevelasanelementwiththekeywordsinternalprotected.Tomakethecodeeasiertoreadandmoreconsistent,StyleCopstandardizestheorderingofthesekeywords,sothataprotectedinternalelementwillalwaysbedescribedassuch,andneverasinternalprotected.Thiscanhelptoreduceconfusionaboutwhethertheseaccesslevelsareindeedthesame.
HowtoFixViolationsTofixaninstanceofthisviolation,placetheprotectedkeywordbeforetheinternalkeyword.
TypeName SystemUsingDirectivesMustBePlacedBeforeOtherUsingDirectives
CheckId SA1208
Category OrderingRules
CauseAusingdirectivewhichdeclaresamemberoftheSystemnamespaceappearsafterausingdirectivewhichdeclaresamemberofadifferentnamespace,withinaC#codefile.
RuleDescriptionAviolationofthisruleoccurswhenausingdirectivefortheSystemnamespaceisplacedafteranon-Systemusingdirective.PlacingallSystemusingdirectivesatthetopoftheusingdirectivescanmakethecodecleanerandeasiertoread,andcanhelpmakeiteasiertoidentifythenamespacesthatarebeingusedbythecode.
HowtoFixViolationsTofixaninstanceofthisviolation,placetheSystemusingdirectiveaboveallusingdirectivesforothernamespaces.
TypeName UsingAliasDirectivesMustBePlacedAfterOtherUsingDirectives
CheckId SA1209
Category OrderingRules
CauseAusing-aliasdirectiveispositionedbeforearegularusingdirective.
RuleDescriptionAviolationofthisruleoccurswhenausing-aliasdirectiveisplacedbeforeanormalusingdirective.Using-aliasdirectiveshavespecialbehaviorwhichcanalterthemeaningoftherestofthecodewithinthefileornamespace.Placingtheusing-aliasdirectivestogetherbelowallotherusing-directivescanmakethecodecleanerandeasiertoread,andcanhelpmakeiteasiertoidentifythetypesusedthroughoutthecode.
HowtoFixViolationsTofixaninstanceofthisviolation,placeallusing-aliasdirectivesbeneathallnormalusingdirectives.
TypeName UsingDirectivesMustBeOrderedAlphabeticallyByNamespace
CheckId SA1210
Category OrderingRules
CauseTheusingdirectiveswithinaC#codefilearenotsortedalphabeticallybynamespace.
RuleDescriptionAviolationofthisruleoccurswhentheusingdirectivesarenotsortedalphabeticallybynamespace.Sortingtheusingdirectivesalphabeticallymakesthecodecleanerandeasiertoread,andcanhelpmakeiteasiertoidentifythenamespacesthatarebeingusedbythecode.TheSystemnamespacesareanexceptiontothisruleandwillalwaysprecedeallothernamespaces.SeeSA1208formoredetails.
HowtoFixViolationsTofixaninstanceofthisviolation,ordertheusingdirectivesalphabeticallybynamespacewithalltheSystemnamespaceentriesfirst.
TypeName UsingAliasDirectivesMustBeOrderedAlphabeticallyByAliasName
CheckId SA1211
Category OrderingRules
CauseTheusing-aliasdirectiveswithinaC#codefilearenotsortedalphabeticallybyaliasname.
RuleDescriptionAviolationofthisruleoccurswhentheusing-aliasdirectivesarenotsortedalphabeticallybyaliasname.Sortingtheusing-aliasdirectivesalphabeticallycanmakethecodecleanerandeasiertoread,andcanhelpmakeiteasiertoidentifythenamespacesthatarebeingusedbythecode.
HowtoFixViolationsTofixaninstanceofthisviolation,ordertheusing-aliasdirectivesalphabeticallybyaliasname.
TypeName PropertyAccessorsMustFollowOrder
CheckId SA1212
Category OrderingRules
CauseAgetaccessorappearsafterasetaccessorwithinapropertyorindexer.
RuleDescriptionAviolationofthisruleoccurswhenagetaccessorisplacedafterasetaccessorwithinapropertyorindexer.Tocomplywiththisrule,thegetaccessorshouldappearbeforethesetaccessor.
Forexample,thefollowingcodewouldraiseaninstanceofthisviolation:
publicstringName{
set{this.name=value;}
get{returnthis.name;}
}Thecodebelowwouldnotraisethisviolation:
publicstringName{get{returnthis.name;}
set{this.name=value;}
}
HowtoFixViolationsTofixaninstanceofthisviolation,placethegetaccessorbeforethesetaccessor.
TypeName EventAccessorsMustFollowOrder
CheckId SA1213
Category OrderingRules
CauseAnaddaccessorappearsafteraremoveaccessorwithinanevent.
RuleDescriptionAviolationofthisruleoccurswhenanaddaccessorisplacedafteraremoveaccessorwithinanevent.Tocomplywiththisrule,theaddaccessorshouldappearbeforetheremoveaccessor.
Forexample,thefollowingcodewouldraiseaninstanceofthisviolation:
publiceventEventHandlerNameChanged{
remove{this.nameChanged-=value;}
add{this.nameChanged+=value;}
}Thecodebelowwouldnotraisethisviolation:
publiceventEventHandlerNameChanged{add{this.nameChanged+=value;}
remove{this.nameChanged-=value;}
}
HowtoFixViolationsTofixaninstanceofthisviolation,placetheaddaccessorbeforetheremoveaccessor.
Ruleswhichensurethatthecodeiswell-formattedandreadable.
SA1100:DoNotPrefixCallsWithBaseUnlessLocalImplementationExists
SA1101:PrefixLocalCallsWithThis
SA1102:QueryClauseMustFollowPreviousClause
SA1103:QueryClausesMustBeOnSeparateLinesOrAllOnOneLine
SA1104:QueryClauseMustBeginOnNewLineWhenPreviousClauseSpansMultipleLines
SA1105:QueryClausesSpanningMultipleLinesMustBeginOnOwnLine
SA1106:CodeMustNotContainEmptyStatements
SA1107:CodeMustNotContainMultipleStatementsOnOneLine
SA1108:BlockStatementsMustNotContainEmbeddedComments
SA1109:BlockStatementsMustNotContainEmbeddedRegions
SA1110:OpeningParenthesisMustBeOnDeclarationLine
SA1111:ClosingParenthesisMustBeOnLineOfOpeningParenthesis
SA1112:ClosingParenthesisMustBeOnLineOfOpeningParenthesis
SA1113:CommaMustBeOnSameLineAsPreviousParameter
SA1114:ParameterListMustFollowDeclaration
SA1115:ParameterMustFollowComma
SA1116:SplitParametersMustStartOnLineAfterDeclaration
SA1117:ParametersMustBeOnSameLineOrSeparateLines
SA1118:ParameterMustNotSpanMultipleLines
SA1120:CommentsMustContainText
SA1121:UseBuiltInTypeAlias
SA1122:UseStringEmptyForEmptyStrings
SA1123:DoNotPlaceRegionsWithinElements
SA1124:DoNotUseRegions
SA1125:UseShorthandForNullableTypes
TypeName DoNotPrefixCallsWithBaseUnlessLocalImplementationExists
CheckId SA1100
Category ReadabilityRules
CauseAcalltoamemberfromaninheritedclassbeginswith‘base.’,andthelocalclassdoesnotcontainanoverrideorimplementationofthemember.
RuleDescriptionAviolationofthisruleoccurswheneverthecodecontainsacalltoamemberfromthebaseclassprefixedwith‘base.’,andthereisnolocalimplementationofthemember.Forexample:
stringname=base.JoinName("John","Doe");
Thisruleisinplacetopreventapotentialsourceofbugs.Considerabaseclasswhichcontainsthefollowingvirtualmethod:
publicvirtualstringJoinName(stringfirst,stringlast)
{
}
Anotherclassinheritsfromthisbaseclassbutdoesnotprovidealocaloverrideofthismethod.Somewherewithinthisclass,thebaseclassmethodiscalledusingbase.JoinName(...).Thisworksasexpected.Atalaterdate,someoneaddsalocaloverrideofthismethodtotheclass:
publicoverridestringJoinName(stringfirst,stringlast)
{
return“Bob”;
}
Atthispoint,thelocalcalltobase.JoinName(...)mostlikelyintroducesabugintothecode.Thiscallwillalwayscallthebaseclassmethodandwillcausethelocaloverridetobeignored.
Forthisreason,callstomembersfromabaseclassshouldnotbeginwith‘base.’,unlessalocaloverrideisimplemented,andthedeveloperwantsto
specificallycallthebaseclassmember.Whenthereisnolocaloverrideofthebaseclassmember,thecallshouldbeprefixedwith'this.'ratherthan'base.'.
HowtoFixViolationsTofixaviolationofthisrule,changethe‘base.’prefixto‘this.’.
TypeName PrefixLocalCallsWithThis
CheckId SA1101
Category ReadabilityRules
CauseAcalltoaninstancememberofthelocalclassorabaseclassisnotprefixedwith‘this.’,withinaC#codefile.
RuleDescriptionAviolationofthisruleoccurswheneverthecodecontainsacalltoaninstancememberofthelocalclassorabaseclasswhichisnotprefixedwith‘this.’.Anexceptiontothisruleoccurswhenthereisalocaloverrideofabaseclassmember,andthecodeintendstocallthebaseclassmemberdirectly,bypassingthelocaloverride.Inthiscasethecallcanbeprefixedwith‘base.’ratherthan‘this.’.
Bydefault,StyleCopdisallowstheuseofunderscoresorm_tomarklocalclassfields,infavorofthe‘this.’prefix.Theadvantageofusing‘this.’isthatitappliesequallytoallelementtypesincludingmethods,properties,etc.,andnotjustfields,makingallcallstoclassmembersinstantlyrecognizable,regardlessofwhicheditorisbeingusedtoviewthecode.Anotheradvantageisthatitcreatesaquick,recognizabledifferentiationbetweeninstancemembersandstaticmembers,whicharenotbeprefixed.
Afinaladvantageofusingthe‘this.’prefixisthattypingthis.willcauseVisualStudiotoshowtheIntelliSensepopup,makingitquickandeasyforthedevelopertochoosetheclassmembertocall.
HowtoFixViolationsTofixaviolationofthisrule,insertthe‘this.’prefixbeforethecalltotheclassmember.
TypeName QueryClauseMustFollowPreviousClause
CheckId SA1102
Category ReadabilityRules
CauseAC#queryclausedoesnotbeginonthesamelineasthepreviousclause,oronthenextline.
RuleDescriptionAviolationofthisruleoccurswhenaclausewithinaqueryexpressiondoesnotbeginonthesamelineasthepreviousclause,oronthelineafterthequeryclause.Forexample:
objectx=selectainb
fromc;
Thequeryclausecancorrectlybewrittenas:
objectx=selectainbfromc;
or:
objectx=
selecta
inb
fromc;
HowtoFixViolationsTofixaviolationofthisrule,ensurethateachclauseinthequeryexpressionbeginsonthesamelineasthepreviousclause,oronthefollowingline.
TypeName QueryClausesMustBeOnSeparateLinesOrAllOnOneLine
CheckId SA1103
Category ReadabilityRules
CauseTheclauseswithinaC#queryexpressionarenotallplacedonthesameline,andeachclauseisnotplacedonitsownline.
RuleDescriptionAviolationofthisruleoccurswhenthequeryclausesarenoteitherplacedallonthesameline,oreachonitsownline.Forexample:
objectx=selectainb
fromc;
Thequeryclausecancorrectlybewrittenas:
objectx=selectainbfromc;
or:
objectx=
selecta
inb
fromc;
HowtoFixViolationsTofixaviolationofthisrule,ensurethatallclausesareplacedtogetheronthesameline,oreachclausebeginsonitsownline.
TypeName QueryClauseMustBeginOnNewLineWhenPreviousClauseSpansMultipleLines
CheckId SA1104
Category ReadabilityRules
CauseAclausewithinaC#queryexpressionbeginsonthesamelineasthepreviousclause,whenthepreviousclausespansacrossmultiplelines.
RuleDescriptionAviolationofthisruleoccurswhenaqueryclausespansacrossmultiplelines,andthenextclausebeginsonthesamelineastheendofthepreviousclause.
objectx=
selecta
inb.GetCustomers(
2,“x”)fromc;
Thequeryclausecancorrectlybewrittenas:
objectx=
selecta
inb.GetCustomers(
2,“x”)
fromc;
HowtoFixViolationsTofixaviolationofthisrule,movetheclausedowntostartonthenextline.
TypeName QueryClausesSpanningMultipleLinesMustBeginOnOwnLine
CheckId SA1105
Category ReadabilityRules
CauseAclausewithinaC#queryexpressionspansacrossmultiplelines,anddoesnotbeginonitsownline.
RuleDescriptionAviolationofthisruleoccurswhenaqueryclausespansacrossmultiplelines,butdoesnotbeginonitsownline.Forexample:
objectx=
selectainbfromc.GetCustomers(
2,“x”);
Thequeryclausecancorrectlybewrittenas:
objectx=
selecta
inbfromc.GetCustomers(
2,“x”);
HowtoFixViolationsTofixaviolationofthisrule,movetheclausedowntostartonthenextline.
TypeName CodeMustNotContainEmptyStatements
CheckId SA1106
Category ReadabilityRules
CauseTheC#codecontainsanextrasemicolon.
RuleDescriptionAviolationofthisruleoccurswhenthecodecontainanextrasemicolon.Syntactically,thisresultsinanextra,emptystatementinthecode.
HowtoFixViolationsTofixaviolationofthisrule,removetheunneededsemicolon.
TypeName CodeMustNotContainMultipleStatementsOnOneLine
CheckId SA1107
Category ReadabilityRules
CauseTheC#codecontainsmorethanonestatementonasingleline.
RuleDescriptionAviolationofthisruleoccurswhenthecodecontainmorethanonestatementonthesameline.Eachstatementmustbeginonanewline.
HowtoFixViolationsTofixaviolationofthisrule,moveeachstatementtobeginonitsownline.
TypeName BlockStatementsMustNotContainEmbeddedComments
CheckId SA1108
Category ReadabilityRules
CauseAC#statementcontainsacommentbetweenthedeclarationofthestatementandtheopeningcurlybracketofthestatement.
RuleDescriptionAviolationofthisruleoccurswhenthecodecontainsacommentinbetweenthedeclarationandtheopeningcurlybracket.Forexample:
if(x!=y)
//Makesurexdoesnotequaly
{
}
Thecommentcanlegallybeplacedabovethestatement,orwithinthebodyofthestatement:
//Makesurexdoesnotequaly
if(x!=y)
{
}
if(x!=y)
{
//Makesurexdoesnotequaly
}
Ifthecommentisbeingusedtocommentoutalineofcode,beginthecommentwithfourforwardslashesratherthantwo:
if(x!=y)
////if(x==y)
{
}
HowtoFixViolationsTofixaviolationofthisrule,movethecommentabovethestatement,withinthebodyofthestatement,orremovethecomment.
TypeName BlockStatementsMustNotContainEmbeddedRegions
CheckId SA1109
Category ReadabilityRules
CauseAC#statementcontainsaregiontagbetweenthedeclarationofthestatementandtheopeningcurlybracketofthestatement.
RuleDescriptionAviolationofthisruleoccurswhenthecodecontainsaregiontaginbetweenthedeclarationandtheopeningcurlybracket.Forexample:
if(x!=y)
#region
{
}
#endregion
Thiswillresultinthebodyofthestatementbeinghiddenwhentheregioniscollapsed.
HowtoFixViolationsTofixaviolationofthisrule,removetheregionormoveitoutsideofthestatement.
TypeName OpeningParenthesisMustBeOnDeclarationLine
CheckId SA1110
Category ReadabilityRules
CauseTheopeningparenthesisorbracketinacalltoaC#methodorindexer,orthedeclarationofamethodorindexer,isnotplacedonthesamelineasthemethodorindexername.
RuleDescriptionAviolationofthisruleoccurswhentheopeningbracketofamethodorindexercallordeclarationisnotplacedonthesamelineasthemethodorindexer.Thefollowingexamplesshowcorrectplacementoftheopeningbracket:
publicstringJoinName(stringfirst,stringlast)
{
returnJoinStrings(
first,last);
}
publicintthis[intx]
{
get{returnthis.items[x];}
}
HowtoFixViolationsTofixaviolationofthisrule,ensurethattheopeningbracketisplacedonthesamelineasthenameofthemethodorindexer.
TypeName ClosingParenthesisMustBeOnLineOfLastParameter
CheckId SA1111
Category ReadabilityRules
CauseTheclosingparenthesisorbracketinacalltoaC#methodorindexer,orthedeclarationofamethodorindexer,isnotplacedonthesamelineasthelastparameter.
RuleDescriptionAviolationofthisruleoccurswhentheclosingbracketofamethodorindexercallordeclarationisnotplacedonthesamelineasthelastparameter.Thefollowingexamplesshowcorrectplacementofthebracket:
publicstringJoinName(stringfirst,stringlast)
{
stringname=JoinStrings(
first,
last);
}
publicintthis[intx]
{
get{returnthis.items[x];}
}
HowtoFixViolationsTofixaviolationofthisrule,ensurethattheclosingbracketisplacedonthesamelineasthelastparameter.
TypeName ClosingParenthesisMustBeOnLineOfOpeningParenthesis
CheckId SA1112
Category ReadabilityRules
CauseTheclosingparenthesisorbracketinacalltoaC#methodorindexer,orthedeclarationofamethodorindexer,isnotplacedonthesamelineastheopeningbracketwhentheelementdoesnottakeanyparameters.
RuleDescriptionAviolationofthisruleoccurswhenamethodorindexerdoesnottakeanyparametersandtheclosingbracketofacallordeclarationforthemethodorindexerisnotplacedonthesamelineastheopeningbracket.Thefollowingexampleshowscorrectplacementoftheclosingparenthesis:
publicstringGetName()
{
returnthis.name.Trim();
}
HowtoFixViolationsTofixaviolationofthisrule,ensurethattheclosingbracketisplacedonthesamelineastheopeningbracket.
TypeName CommaMustBeOnSameLineAsPreviousParameter
CheckId SA1113
Category ReadabilityRules
CauseAcommabetweentwoparametersinacalltoaC#methodorindexer,orinthedeclarationofamethodorindexer,isnotplacedonthesamelineasthepreviousparameter.
RuleDescriptionAviolationofthisruleoccurswhenacommabetweentwoparameterstoamethodorindexerisnotplacedonthesamelineasthepreviousparameter.Thefollowingexamplesshowcorrectplacementofthecomma:
publicstringJoinName(stringfirst,stringlast)
{
stringname=JoinStrings(
first,
last);
}
publicintthis[intx,
inty]
{
get{returnthis.items[x,y];}
}
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthecommaisplacedonthesamelineasthepreviousparameter.
TypeName ParameterListMustFollowDeclaration
CheckId SA1114
Category ReadabilityRules
CauseThestartoftheparameterlistforamethodorindexercallordeclarationdoesnotbeginonthesamelineastheopeningbracket,oronthelineaftertheopeningbracket.
RuleDescriptionAviolationofthisruleoccurswhenthereareoneormoreblanklinesbetweentheopeningbracketandthestartoftheparameterlist.Forexample:
publicstringJoinName(
stringfirst,stringlast)
{
}
Theparameterlistmustbeginonthesamelineastheopeningbracket,oronthenextline.Forexample:
publicstringJoinName(stringfirst,stringlast)
{
}
publicstringJoinName(
stringfirst,stringlast)
{
}
HowtoFixViolationsTofixaviolationofthisrule,ensurethattheparameterlistbeginsonthesamelineastheopeningbracket,oronthenextline.
TypeName ParameterMustFollowComma
CheckId SA1115
Category ReadabilityRules
CauseAparameterwithinaC#methodorindexercallordeclarationdoesnotbeginonthesamelineasthepreviousparameter,oronthenextline.
RuleDescriptionAviolationofthisruleoccurswhenthereareoneormoreblanklinesbetweenaparameterandthepreviousparameter.Forexample:
publicstringJoinName(
stringfirst,
stringlast)
{
}
Theparametermustbeginonthesamelineasthepreviouscomma,oronthenextline.Forexample:
publicstringJoinName(stringfirst,stringlast)
{
}
publicstringJoinName(
stringfirst,
stringlast)
{
}
HowtoFixViolationsTofixaviolationofthisrule,ensurethattheparameterbeginsonthesamelineasthepreviouscomma,oronthenextline.
TypeName SplitParametersMustStartOnLineAfterDeclaration
CheckId SA1116
Category ReadabilityRules
CauseTheparameterstoaC#methodorindexercallordeclarationspanacrossmultiplelines,butthefirstparameterdoesnotstartonthelineaftertheopeningbracket.
RuleDescriptionAviolationofthisruleoccurswhentheparameterstoamethodorindexerspanacrossmultiplelines,butthefirstparameterdoesnotstartonthelineaftertheopeningbracket.Forexample:
publicstringJoinName(stringfirst,
stringlast)
{
}
Theparametersmustbeginonthelineafterthedeclaration,whenevertheparameterspanacrossmultiplelines:
publicstringJoinName(
stringfirst,
stringlast)
{
}
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthefirstparameterstartsonthelineaftertheopeningbracket,orplaceallparametersonthesamelineiftheparametersarenottoolong.
TypeName ParametersMustBeOnSameLineOrSeparateLines
CheckId SA1117
Category ReadabilityRules
CauseTheparameterstoaC#methodorindexercallordeclarationarenotallonthesamelineoreachonaseparateline.
RuleDescriptionAviolationofthisruleoccurswhentheparameterstoamethodorindexerarenotallonthesamelineoreachonitsownline.Forexample:
publicstringJoinName(stringfirst,stringmiddle,
stringlast)
{
}
Theparameterscanallbeplacedonthesameline:
publicstringJoinName(stringfirst,stringmiddle,stringlast)
{
}
publicstringJoinName(
stringfirst,stringmiddle,stringlast)
{
}
Alternatively,eachparametercanbeplacedonitsownline:
publicstringJoinName(
stringfirst,
stringmiddle,
stringlast)
{
}
HowtoFixViolationsTofixaviolationofthisrule,placeallparametersonthesameline,orplaceeachparameteronitsownline.
TypeName ParameterMustNotSpanMultipleLines
CheckId SA1118
Category ReadabilityRules
CauseAparametertoaC#methodorindexer,otherthanthefirstparameter,spansacrossmultiplelines.
RuleDescriptionTopreventmethodcallsfrombecomingexcessivelycomplicatedandunreadable,onlythefirstparametertoamethodorindexercallisallowedtospanacrossmultiplelines.Theexceptionisananonymousmethodpassedasaparameter,whichisalwaysallowedtospanmultiplelines.Aviolationofthisruleoccurswheneveraparameterotherthanthefirstparameterspansacrossmultiplelines,andtheparameterdoesnotcontainananonymousmethod.
Forexample,thefollowingcodewouldviolatethisrule,sincethesecondparameterspansacrossmultiplelines:
returnJoinStrings(
"John",
"Smith"+
"Doe");
Whenparametersotherthanthefirstparameterspanacrossmultiplelines,itcanbedifficulttotellhowmanyparametersarepassedtothemethod.Ingeneral,thecodebecomesdifficulttoread.
Tofixtheexampleabove,ensurethattheparametersafterthefirstparameterdonotspanacrossmultiplelines.Ifthiswillcauseaparametertobeexcessivelylong,storethevalueoftheparameterwithinatemporaryvariable.Forexample:
stringlast="Smith"+
"Doe";
returnJoinStrings(
"John",
last);
Insomecases,thiswillallowthemethodtobewrittenevenmoreconcisely,suchas:
returnJoinStrings("John",last);
HowtoFixViolationsTofixaviolationofthisrule,ensurethattheparametersafterthefirstparameterdonotspanmultiplelines,unlesstheparametercontainsananonymousmethod.
TypeName CommentsMustContainText
CheckId SA1120
Category ReadabilityRules
CauseTheC#commentdoesnotcontainanycommenttext.
RuleDescriptionAviolationofthisruleoccurswheneverthecodecontainsaC#commentwhichdoesnotcontainanytext.
HowtoFixViolationsTofixaviolationofthisrule,addtexttothecomment,orremovethecomment.
TypeName UseBuiltInTypeAlias
CheckId SA1121
Category ReadabilityRules
CauseThecodeusesoneofthebasicC#types,butdoesnotusethebuilt-inaliasforthetype.
RuleDescriptionAviolationofthisruleoccurswhenoneofthefollowingtypesareusedanywhereinthecode:Boolean,Byte,Char,Decimal,Double,Int16,Int32,Int64,Object,SByte,Single,String,UInt16,UInt32,UInt64.
Aviolationalsooccurswhenanyofthesetypesarerepresentedinthecodeusingthefullnamespaceforthetype:System.Boolean,System.Byte,System.Char,System.Decimal,System.Double,System.Int16,System.Int32,System.Int64,System.Object,System.SByte,System.Single,System.String,System.UInt16,System.UInt32,System.UInt64.
Ratherthanusingthetypenameorthefully-qualifiedtypename,thebuilt-inaliasesforthesetypesshouldalwaysbeused:bool,byte,char,decimal,double,short,int,long,object,sbyte,float,string,ushort,uint,ulong.
Thefollowingtablelistseachofthesetypesinallthreeformats:
TypeAlias Type FullyQualifiedType
bool Boolean System.Boolean
byte Byte System.Byte
char Char System.Char
decimal Decimal System.Decimal
double Double System.Double
short Int16 System.Int16
int Int32 System.Int32
long Int64 System.Int64
object Object System.Object
sbyte SByte System.SByte
float Single System.Single
string String System.String
ushort UInt16 System.UInt16
uint UInt32 System.UInt32
ulong UInt64 System.UInt64
HowtoFixViolationsTofixaviolationofthisrule,replacethetypewiththebuilt-inaliasforthetype.
TypeName UseStringEmptyForEmptyStrings
CheckId SA1122
Category ReadabilityRules
CauseTheC#codeincludesanemptystring,writtenas“”.
RuleDescriptionAviolationofthisruleoccurswhenthecodecontainsanemptystring.Forexample:
strings="";
Thiswillcausethecompilertoembedanemptystringintothecompiledcode.Ratherthanincludingahard-codedemptystring,usethestaticstring.Emptyproperty:
strings=string.Empty;
HowtoFixViolationsTofixaviolationofthisrule,replacethehard-codedemptystringwithstring.Empty.
TypeName DoNotPlaceRegionsWithinElements
CheckId SA1123
Category ReadabilityRules
CauseTheC#codecontainsaregionwithinthebodyofacodeelement.
RuleDescriptionAviolationofthisruleoccurswheneveraregionisplacedwithinthebodyofacodeelement.Inmanyeditors,includingVisualStudio,theregionwillappearcollapsedbydefault,hidingthecodewithintheregion.Itisgenerallyabadpracticetohidecodewithinthebodyofanelement,asthiscanleadtobaddecisionsasthecodeismaintainedovertime.
HowtoFixViolationsTofixaviolationofthisrule,removetheregionfromthecode.
TypeName DoNotUseRegions
CheckId SA1124
Category ReadabilityRules
CauseTheC#codecontainsaregion.
RuleDescriptionAviolationofthisruleoccurswheneveraregionisplacedanywherewithinthecode.Inmanyeditors,includingVisualStudio,theregionwillappearcollapsedbydefault,hidingthecodewithintheregion.Itisgenerallyabadpracticetohidecode,asthiscanleadtobaddecisionsasthecodeismaintainedovertime.
HowtoFixViolationsTofixaviolationofthisrule,removetheregionfromthecode.
TypeName UseShorthandForNullableTypes
CheckId SA1125
Category ReadabilityRules
CauseTheNullabletypehasbeendefinednotusingtheC#shorthand.Forexample,Nullable<DateTime>hasbeenusedinsteadofthepreferredDateTime?
RuleDescriptionAviolationofthisruleoccurswhenevertheNullabletypehasbeendefinedwithoutusingtheshorthandC#style.
HowtoFixViolationsTofixaviolationofthisrule,usetheshorthandversionofthenullabletypeie.int?,DateTime?,etc.
Ruleswhichenforcespacingrequirementsaroundkeywordsandsymbolsinthecode.
SA1000:KeywordsMustBeSpacedCorrectly
SA1001:CommasMustBeSpacedCorrectly
SA1002:SemicolonsMustBeSpacedCorrectly
SA1003:SymbolsMustBeSpacedCorrectly
SA1004:DocumentationLinesMustBeginWithSingleSpace
SA1005:SingleLineCommentsMustBeginWithSingeSpace
SA1006:PreprocessorKeywordsMustNotBePrecededBySpace
SA1007:OperatorKeywordMustBeFollowedBySpace
SA1008:OpeningParenthesisMustBeSpacedCorrectly
SA1009:ClosingParenthesisMustBeSpacedCorrectly
SA1010:OpeningSquareBracketsMustBeSpacedCorrectly
SA1011:ClosingSquareBracketsMustBeSpacedCorrectly
SA1012:OpeningCurlyBracketsMustBeSpacedCorrectly
SA1013:ClosingCurlyBracketsMustBeSpacedCorrectly
SA1014:OpeningGenericBracketsMustBeSpacedCorrectly
SA1015:ClosingGenericBracketsMustBeSpacedCorrectly
SA1016:OpeningAttributeBracketsMustBeSpacedCorrectly
SA1017:ClosingAttributeBracketsMustBeSpacedCorrectly
SA1018:NullableTypeSymbolsMustNotBePrecededBySpace
SA1019:MemberAccessSymbolsMustBeSpacedCorrectly
SA1020:IncrementDecrementSymbolsMustBeSpacedCorrectly
SA1021:NegativeSignsMustBeSpacedCorrectly
SA1022:PositiveSignsMustBeSpacedCorrectly
SA1023:DereferenceAndAccessOfSymbolsMustBeSpacedCorrectly
SA1024:ColonsMustBeSpacedCorrectly
SA1025:CodeMustNotContainMultipleWhitespaceInARow
SA1026:CodeMustNotContainSpaceAfterNewKeywordInImplicitlyTypedArrayAllocation
SA1027:TabsMustNotBeUsed
TypeName KeywordsMustBeSpacedCorrectly
CheckId SA1000
Category SpacingRules
CauseThespacingaroundaC#keywordisincorrect.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundakeywordisincorrect.
ThefollowingC#keywordsmustalwaysbefollowedbyasinglespace:catch,fixed,for,foreach,from,group,if,in,into,join,let,lock,orderby,return,select,stackalloc,switch,throw,using,where,while,yield.
Thefollowingkeywordsmustnotbefollowedbyanyspace:checked,default,sizeof,typeof,unchecked.
Thenewkeywordshouldalwaysbefollowedbyaspace,unlessitisusedtocreateanewarray,inwhichcasethereshouldbenospacebetweenthenewkeywordandtheopeningarraybracket.
HowtoFixViolationsTofixaviolationofthisrule,addorremoveaspaceafterthekeyword,accordingtothedescriptionabove.
TypeName CommasMustBeSpacedCorrectly
CheckId SA1001
Category SpacingRules
CauseThespacingaroundacommaisincorrect,withinaC#codefile.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundacommaisincorrect.
Acommashouldalwaysbefollowedbyasinglespace,unlessitisthelastcharacterontheline,andacommashouldneverbeprecededbyanywhitespace,unlessitisthefirstcharacterontheline.
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthecommaisfollowedbyasinglespace,andisnotprecededbyanyspace.
TypeName SemicolonsMustBeSpacedCorrectly
CheckId SA1002
Category SpacingRules
CauseThespacingaroundasemicolonisincorrect,withinaC#codefile.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundasemicolonisincorrect.
Asemicolonshouldalwaysbefollowedbyasinglespace,unlessitisthelastcharacterontheline,andasemicolonshouldneverbeprecededbyanywhitespace,unlessitisthefirstcharacterontheline.
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthesemicolonisfollowedbyasinglespace,andisnotprecededbyanyspace.
TypeName SymbolsMustBeSpacedCorrectly
CheckId SA1003
Category SpacingRules
CauseThespacingaroundanoperatorsymbolisincorrect,withinaC#codefile.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundanoperatorsymbolisincorrect.
Thefollowingtypesofoperatorsymbolsmustbesurroundedbyasinglespaceoneitherside:colons,arithmeticoperators,assignmentoperators,conditionaloperators,logicaloperators,relationaloperators,shiftoperators,andlambdaoperators.Forexample:
intx=4+y;
Incontrast,unaryoperatorsmustbeprecededbyasinglespace,butmustneverbefollowedbyanyspace.Forexample:
boolx=!value;
Anexceptionoccurswheneverthesymbolisprecededorfollowedbyaparenthesisorbracket,inwhichcasethereshouldbenospacebetweenthesymbolandthebracket.Forexample:
if(!value)
{
}
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthespacingaroundthesymbolfollowstheruledescribedabove.
TypeName DocumentationLinesMustBeginWithSingleSpace
CheckId SA1004
Category SpacingRules
CauseAlinewithinadocumentationheaderaboveaC#elementdoesnotbeginwithasinglespace.
RuleDescriptionAviolationofthisruleoccurswhenalinewithinadocumentationheaderdoesnotbeginwithasinglespace.Forexample:
///<summary>
///Thesummarytext.
///</summary>
///<paramname="x">Thedocumentroot.</param>
///<paramname="y">TheXmlheadertoken.</param>
privatevoidMethod1(intx,inty)
{
}
Theheaderlinesshouldbeginwithasinglespaceafterthethreeleadingforwardslashes:
///<summary>
///Thesummarytext.
///</summary>
///<paramname="x">Thedocumentroot.</param>
///<paramname="y">TheXmlheadertoken.</param>
privatevoidMethod1(intx,inty)
{
}
HowtoFixViolationsTofixaviolationofthisrule,ensurethattheheaderlinebeginswithasinglespace.
TypeName SingleLineCommentsMustBeginWithSingleSpace
CheckId SA1005
Category SpacingRules
CauseAsingle-linecommentwithinaC#codefiledoesnotbeginwithasinglespace.
RuleDescriptionAviolationofthisruleoccurswhenasingle-linecommentdoesnotbeginwithasinglespace.Forexample:
privatevoidMethod1()
{
//Asingle-linecomment.
//Asingle-linecomment.
}
Thecommentsshouldbeginwithasinglespaceaftertheleadingforwardslashes:
privatevoidMethod1()
{
//Asingle-linecomment.
//Asingle-linecomment.
}
Anexceptiontothisruleoccurswhenthecommentisbeingusedtocommentoutalineofcode.Inthiscase,thespacecanbeomittedifthecommentbeginswithfourforwardslashestoindicateout-commentedcode.Forexample:
privatevoidMethod1()
{
////intx=2;
////returnx;
}
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthecommentbeginswithasinglespace.Ifthecommentisbeingusedtocommentoutalineofcode,ensurethatthecommentbeginswithfourforwardslashes,inwhichcasetheleadingspacecanbeomitted.
TypeName PreprocessorKeywordsMustNotBePrecededBySpace
CheckId SA1006
Category SpacingRules
CauseAC#preprocessor-typekeywordisprecededbyspace.
RuleDescriptionAviolationofthisruleoccurswhenthepreprocessor-typekeywordinapreprocessordirectiveisprecededbyspace.Forexample:
#ifDebug
Thereshouldnotbeanywhitespacebetweentheopeninghashmarkandthepreprocessor-typekeyword:
#ifDebug
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthereisnowhitespacebetweentheopeninghashmarkandthepreprocessor-typekeyword.
TypeName OperatorKeywordMustBeFollowedBySpace
CheckId SA1007
Category SpacingRules
CauseTheoperatorkeywordwithinaC#operatoroverloadmethodisnotfollowedbyanywhitespace.
RuleDescriptionAviolationofthisruleoccurswhentheoperatorkeywordwithinanoperatoroverloadmethodisnotfollowedbyanywhitespace.Theoperatorkeywordshouldalwaysbefollowedbyasinglespace.Forexample:
publicMyClassoperator+(MyClassa,MyClassb)
{
}
HowtoFixViolationsTofixaviolationofthisrule,addasinglespaceaftertheoperatorkeyword.
TypeName OpeningParenthesisMustBeSpacedCorrectly
CheckId SA1008
Category SpacingRules
CauseAnopeningparenthesiswithinaC#statementisnotspacedcorrectly.
RuleDescriptionAviolationofthisruleoccurswhentheopeningparenthesiswithinastatementisnotspacedcorrectly.Anopeningparenthesisshouldnotbeprecededbyanywhitespace,unlessitisthefirstcharacterontheline,oritisprecededbycertainC#keywordssuchasif,while,orfor.Inaddition,anopeningparenthesisisallowedtobeprecededbywhitespacewhenitfollowsanoperatorsymbolwithinanexpression.
Anopeningparenthesisshouldnotbefollowedbywhitespace,unlessitisthelastcharacterontheline.
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthespacingaroundtheopeningparenthesisfollowstheruledescribedabove.
TypeName ClosingParenthesisMustBeSpacedCorrectly
CheckId SA1009
Category SpacingRules
CauseAclosingparenthesiswithinaC#statementisnotspacedcorrectly.
RuleDescriptionAviolationofthisruleoccurswhentheclosingparenthesiswithinastatementisnotspacedcorrectly.
Aclosingparenthesisshouldneverbeprecededbywhitespace.Inmostcases,aclosingparenthesisshouldbefollowedbyasinglespace,unlesstheclosingparenthesiscomesattheendofacast,ortheclosingparenthesisisfollowedbycertaintypesofoperatorsymbols,suchaspositivesigns,negativesigns,andcolons.
Iftheclosingparenthesisisfollowedbywhitespace,thenextnon-whitespacecharactermustnotbeanopeningorclosingparenthesisorsquarebracket,orasemicolonorcomma.
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthespacingaroundtheclosingparenthesisfollowstheruledescribedabove.
TypeName OpeningSquareBracketsMustBeSpacedCorrectly
CheckId SA1010
Category SpacingRules
CauseAnopeningsquarebracketwithinaC#statementisnotspacedcorrectly.
RuleDescriptionAviolationofthisruleoccurswhenanopeningsquarebracketwithinastatementisprecededorfollowedbywhitespace.
Anopeningsquarebracketmustneverbeprecededbywhitespace,unlessitisthefirstcharacterontheline,andanopeningsquaremustneverbefollowedbywhitespace,unlessitisthelastcharacterontheline.
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthereisnowhitespaceoneithersideoftheopeningsquarebracket.
TypeName ClosingSquareBracketsMustBeSpacedCorrectly
CheckId SA1011
Category SpacingRules
CauseAclosingsquarebracketwithinaC#statementisnotspacedcorrectly.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundaclosingsquarebracketisnotcorrect.
Aclosingsquarebracketmustneverbeprecededbywhitespace,unlessitisthefirstcharacterontheline.
Aclosingsquarebracketmustbefollowedbywhitespace,unlessitisthelastcharacterontheline,itisfollowedbyaclosingbracketoranopeningparenthesis,itisfollowedbyacommaorsemicolon,oritisfollowedbycertaintypesofoperatorsymbols.
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthespacingaroundtheclosingsquarebracketfollowstheruledescribedabove.
TypeName OpeningCurlyBracketsMustBeSpacedCorrectly
CheckId SA1012
Category SpacingRules
CauseAnopeningcurlybracketwithinaC#elementisnotspacedcorrectly.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundanopeningcurlybracketisnotcorrect.
Anopeningcurlybracketshouldalwaysbeprecededbyasinglespace,unlessitisthefirstcharacterontheline,orunlessitisprecededbyanopeningparenthesis,inwhichcasethereshouldbenospacebetweentheparenthesisandthecurlybracket.
Anopeningcurlybracketmustalwaysbefollowedbyasinglespace,unlessitisthelastcharacterontheline.
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthespacingaroundtheopeningcurlybracketfollowstheruledescribedabove.
TypeName ClosingCurlyBracketsMustBeSpacedCorrectly
CheckId SA1013
Category SpacingRules
CauseAclosingcurlybracketwithinaC#elementisnotspacedcorrectly.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundaclosingcurlybracketisnotcorrect.
Aclosingcurlybracketshouldalwaysbefollowedbyasinglespace,unlessitisthelastcharacterontheline,orunlessitisfollowedbyaclosingparenthesis,acomma,orasemicolon.
Aclosingcurlybracketmustalwaysbeprecededbyasinglespace,unlessitisthefirstcharacterontheline.
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthespacingaroundtheclosingcurlybracketfollowstheruledescribedabove.
TypeName OpeningGenericBracketsMustBeSpacedCorrectly
CheckId SA1014
Category SpacingRules
CauseAnopeninggenericbracketwithinaC#elementisnotspacedcorrectly.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundanopeninggenericbracketisnotcorrect.
Anopeninggenericbracketshouldneverbeprecededorfollowedbywhitespace,unlessthebracketisthefirstorlastcharacterontheline.
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthereisnowhitespaceoneithersideoftheopeninggenericbracket.
TypeName ClosingGenericBracketsMustBeSpacedCorrectly
CheckId SA1015
Category SpacingRules
CauseAclosinggenericbracketwithinaC#elementisnotspacedcorrectly.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundaclosinggenericbracketisnotcorrect.
Aclosinggenericbracketshouldneverbeprecededbywhitespace,unlessthebracketisthefirstcharacterontheline.
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthereisnowhitespacebeforetheclosinggenericbracket.
TypeName OpeningAttributeBracketsMustBeSpacedCorrectly
CheckId SA1016
Category SpacingRules
CauseAnopeningattributebracketwithinaC#elementisnotspacedcorrectly.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundanopeningattributebracketisnotcorrect.
Anopeningattributebracketshouldneverbefollowedbywhitespace,unlessthebracketisthelastcharacterontheline.
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthereisnowhitespaceaftertheopeningattributebracket.
TypeName ClosingAttributeBracketsMustBeSpacedCorrectly
CheckId SA1017
Category SpacingRules
CauseAclosingattributebracketwithinaC#elementisnotspacedcorrectly.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundaclosingattributebracketisnotcorrect.
Aclosingattributebracketshouldneverbeprecededbywhitespace,unlessthebracketisthefirstcharacterontheline.
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthereisnowhitespacebeforetheclosingattributebracket.
TypeName NullableTypeSymbolsMustNotBePrecededBySpace
CheckId SA1018
Category SpacingRules
CauseAnullabletypesymbolwithinaC#elementisnotspacedcorrectly.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundanullabletypesymbolisnotcorrect.
Anullabletypesymbolshouldneverbeprecededbywhitespace,unlessthesymbolisthefirstcharacterontheline.
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthereisnowhitespacebeforethenullabletypesymbol.
TypeName MemberAccessSymbolsMustBeSpacedCorrectly
CheckId SA1019
Category SpacingRules
CauseThespacingaroundamemberaccesssymbolisincorrect,withinaC#codefile.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundamemberaccesssymbolisincorrect.Amemberaccesssymbolshouldnothavewhitespaceoneitherside,unlessitisthefirstcharacterontheline.
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthememberaccesssymbolisnotsurroundedbyanywhitespace.
TypeName IncrementDecrementSymbolsMustBeSpacedCorrectly
CheckId SA1020
Category SpacingRules
CauseAnincrementordecrementsymbolwithinaC#elementisnotspacedcorrectly.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundanincrementordecrementsymbolisnotcorrect.
Thereshouldbenowhitespacebetweentheincrementordecrementsymbolandtheitemthatisbeingincrementedordecremented.
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthereisnowhitespacebetweentheincrementordecrementsymbolandtheitemthatisbeingincrementedordecremented.
TypeName NegativeSignsMustBeSpacedCorrectly
CheckId SA1021
Category SpacingRules
CauseAnegativesignwithinaC#elementisnotspacedcorrectly.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundanegativesignisnotcorrect.
Anegativesignshouldalwaysbeprecededbyasinglespace,unlessitcomesafteranopeningsquarebracket,aparenthesis,oristhefirstcharacterontheline.
Anegativesignshouldneverbefollowedbywhitespace,andshouldneverbethelastcharacteronaline.
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthespacingaroundthenegativesignfollowstheruledescribedabove.
TypeName PositiveSignsMustBeSpacedCorrectly
CheckId SA1022
Category SpacingRules
CauseApositivesignwithinaC#elementisnotspacedcorrectly.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundapositivesignisnotcorrect.
Apositivesignshouldalwaysbeprecededbyasinglespace,unlessitcomesafteranopeningsquarebracket,aparenthesis,oristhefirstcharacterontheline.
Apositivesignshouldneverbefollowedbywhitespace,andshouldneverbethelastcharacteronaline.>
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthespacingaroundthepositivesignfollowstheruledescribedabove.
TypeName DereferenceAndAccessOfMustBeSpacedCorrectly
CheckId SA1023
Category SpacingRules
CauseAdereferencesymboloranaccess-ofsymbolwithinaC#elementisnotspacedcorrectly.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundadereferenceoraccess-ofsymbolisnotcorrect.
Thespacingaroundthesymboldependsuponwhetherthesymbolisusedwithinatypedeclaration.Ifso,thesymbolmustalwaysbefollowedbyasinglespace,unlessitisthelastcharacterontheline,orisfollowedbyanopeningsquarebracketoraparenthesis.Inaddition,thesymbolshouldnotbeprecededbywhitespace,andshouldnotbethefirstcharacterontheline.Anexampleofaproperlyspaceddereferencesymbolusedwithinatypedeclarationis:
object*x=null;
Whenadereferenceoraccess-ofsymbolisusedoutsideofatypedeclaration,theoppositeruleapplies.Inthiscase,thesymbolmustalwaysbeprecededbyasinglespace,unlessitisthefirstcharacterontheline,orisprecededbyanopeningsquarebracketoraparenthesis.Thesymbolshouldnotbefollowedbywhitespace,andshouldnotbethelastcharacterontheline.Forexample:
y=*x;
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthespacingaroundthedereferenceoraddress-ofsymbolfollowstheruledescribedabove.
TypeName ColonsMustBeSpacedCorrectly
CheckId SA1024
Category SpacingRules
CauseAcolonwithinaC#elementisnotspacedcorrectly.
RuleDescriptionAviolationofthisruleoccurswhenthespacingaroundacolonisnotcorrect.
Thespacingaroundacolondependsuponthetypeofcolonandhowitisusedwithinthecode.Acolonappearingwithinanelementdeclarationmustalwayshaveasinglespaceoneitherside,unlessitisthefirstorlastcharacterontheline.Forexampleallofthecolonsbelowfollowthisrule:
publicclassClass2<T>:Class1whereT:MyType
{
publicClass2(intx):base(x)
{
}
}
Whenthecoloncomesattheendofalabelorcasestatement,itmustalwaysbefollowedbywhitespaceorbethelastcharacterontheline,butshouldneverbeprecededbywhitespace.Forexample:
_label:
switch(x)
{
case2:
returnx;
}
Finally,whenacolonisusedwithinaconditionalstatement,itmustalwayscontainasinglespaceoneitherside,unlessthecolonisthefirstorlastcharacterontheline.Forexample:
intx=y?2:3;
HowtoFixViolationsTofixaviolationofthisrule,ensurethatthespacingaroundthecolonfollowstheruledescribedabove.
TypeName CodeMustNotContainMultipleWhitespaceInARow
CheckId SA1025
Category SpacingRules
CauseThecodecontainsmultiplewhitespacecharactersinarow.
RuleDescriptionAviolationofthisruleoccurswheneverthecodecontainsmultiplewhitespacecharactersinarow,unlessthecharacterscomeatthebeginningorendofalineofcode,orcomeafteracommaorsemicolon.
HowtoFixViolationsTofixaviolationofthisrule,removetheextrawhitespacecharactersareleaveonlyasinglespace.
TypeName CodeMustNotContainSpaceAfterNewKeywordInImplicitlyTypedArrayAllocation
CheckId SA1026
Category SpacingRules
CauseAnimplicitlytypednewarrayallocationwithinaC#codefileisnotspacedcorrectly.
RuleDescriptionAviolationofthisruleoccurswheneverthecodecontainsanimplicitlytypednewarrayallocationwhichisnotspacedcorrectly.Withinanimplicitlytypednewarrayallocation,thereshouldnotbeanyspacebetweenthenewkeywordandtheopeningarraybracket.Forexample:
vara=new[]{1,10,100,1000};
HowtoFixViolationsTofixaviolationofthisrule,removeanywhitespacebetweenthenewkeywordandtheopeningarraybracket.
TypeName TabsMustNotBeUsed
CheckId SA1027
Category SpacingRules
CauseTheC#codecontainsatabcharacter.
RuleDescriptionAviolationofthisruleoccurswheneverthecodecontainsatabcharacter.
TabsshouldnotbeusedwithinC#code,becausethelengthofthetabcharactercanvarydependingupontheeditorbeingusedtoviewthecode.Thiscancausethespacingandindexingofthecodetovaryfromthedeveloper’soriginalintention,andcaninsomecasesmakethecodedifficulttoread.
Forthesereasons,tabsshouldnotbeused,andeachlevelofindentationshouldconsistoffourspaces.Thiswillensurethatthecodelooksthesamenomatterwhicheditorisbeingusedtoviewthecode.
HowtoFixViolationsTofixaviolationofthisrule,removethetabcharacterfromthecode.
StartingwithStyleCop4.3.2,itispossibletosuppressthereportingofruleviolationsbyaddingsuppressionattributeswithinthesourcecode.ThesyntaxforthesesuppressionsissimilartothatforVisualStudioCodeAnalysis,orFxCop.FormoreinformationaboutCodeAnalysissuppressions,seethefollowingarticle:InSourceSuppressionsOverview.
StyleCoprulesuppressionsareregisteredincodeusingtheSuppressMessageattribute.TheSuppressMessageattributeisaconditionalattribute,whichisincludedintheILmetadataofyourmanagedcodeassemblyonlyiftheCODE_ANALYSIScompilationsymbolisdefinedatcompiletime.
Werecommendusingin-sourcesuppressionsondebugbuilds,inordertoeliminatethepossibilityofmistakenlyshippingthein-sourcesuppressionmetadataandcompromisingexecutionorperformancebecauseofthemetadatabloat.
TheSuppressMessageattributehasthefollowingformat:
[SuppressMessage("RuleCategory,"RuleId","Justification")]
Where:
RuleCategory-TheStyleCoprulenamespaceinwhichtheruleisdefined.Forexample,StyleCop.CSharp.DocumentationRulesRuleId-Theidentifierfortherule,usingtheformatshortname:longname.Forexample,SA1600:ElementsMustBeDocumentedJustification-Thetextthatisusedtodocumentthereasonforsuppressingthemessage.
TheSuppressMessageattributealsotakesthefollowingoptionalparameters.TheseparametersarecompletelyignoredbyStyleCopanddonotneedtobefilledinforStyleCopsuppressions.
MessageIdScopeTarget
SuppressMessageUsage
StyleCopviolationsaresuppressedattheleveltowhichaninstanceofthe
SuppressMessageattributeisapplied.Thepurposeofthisistotightlycouplethesuppressioninformationtothecodewheretheviolationoccurs.
Forexample,aStyleCopSuppressMessageattributeplacedonaclasswillsuppresstheruleforallcontentsoftheclass.Thesameattributeplacedonamethodwillonlysuppresstherulewithinthemethod.
GlobalSuppressions
StyleCopdoesnotsupportthenotionofglobalsuppressionsorfile-levelsuppressions.Suppressionsmustbeplacedonacodeelement.
Examples:
ThefollowingcodesuppressestheElementsMustBeDocumentedruleforthegivenclassandallitscontents:
[SuppressMessage("StyleCop.CSharp.DocumentationRules","SA1600:ElementsMustBeDocumented")]
publicclassMyUndocumentedClass
{
publicvoidMyUndocumentedMethod
{
}
}BeginningwithStyleCop4.4.0,itisalsopossibletosuppressalloftheruleswithinarulenamespace,usingasinglesuppressionattribute.ThisisindicatedbyreplacingtheruleCheckIDandrulenamewithasingleasterisk.ThefollowingcodeexamplesuppressesallofStyleCop'sdefaultdocumentationruleswithintheinnerclass.Inthiscase,StyleCopwouldstillflagaviolationindicatingthattheouterclassismissingdocumentation,butitwouldignorealldocumentationrulesfortheinnerclassanditscontents.
publicclassOuterClass
{
[SuppressMessage("StyleCop.CSharp.DocumentationRules","*")]
publicclassInnerClass
{
publicvoidMyUndocumentedMethod
{
}
}}