Philips.CodeAnalysis.MaintainabilityAnalyzers.md

August 9, 2025 · View on GitHub

Rule IDTitleDescription
PH2001Avoid empty XML Summary commentsSummary XML comments for classes, methods, etc. must be non-empty or non-existent.
PH2006Match namespace and pathThe File Path and Namespace must match. To include folders in the namespace, add dotnet_code_quality.PH2006.folder_in_namespace = true to the .editorconfig.
PH2020Avoid Thread.SleepThis method is a code smell.
PH2021Avoid inline newDo not inline the constructor call. Instead, create a local variable or a field for the temporary instance.
PH2026Avoid SuppressMessage attributeSuppressMessage results in violations of codified coding guidelines.
PH2027Avoid static methodsStatic methods complicate Unit Testing.
PH2028Copyright presentThe top of the file should have a copyright statement. It should include: '©' or 'Copyright', the year and the company name if such is configured in the .editorconfig
PH2029Avoid #pragma#pragmas result in violations of codified coding guidelines.
PH2030Variable naming conventionsFields look like _foo. Locals look like foo. (This analyzer does not respect IntelliSense settings in the .editorconfig. It assumes this is your naming convention.)
PH2031Avoid TryParse without CultureWhen interpreting a string as a number, always specify culture information.
PH2032Avoid Empty Type InitializerEmpty type initializers are unnecessary.
PH2040ServiceContracts have InterfaceContractsInterfaces marked with [ServiceContract] must have methods marked with [OperationContract]
PH2042WinForms InitalizeComponentLegacy WinForms must call InitializeComponent exactly once. (As we moved away from static classes, and introduced construtor injection patterns, this pattern requires refactoring legacy code, and we found ourselves breaking these legacy forms.)
PH2044Avoid dynamic keywordThe dynamic keyword is not checked for type safety at compile time.
PH2045Avoid static classesStatic classes complicate Unite Testing. This rule supports a whitelist, one class per line, in a file named StaticClasses.Allowed.txt in the project marked as an AdditionalFile.
PH2047Avoid public member variablesAvoid public fields in a class. Declare public property if needed for static fields.
PH2051Avoid unnecessary range checksDo not superfluously check the length of a List or Array before iterating over it.
PH2060Bool naming conventionsBool names start with is, are, should, has, does, or was.
PH2061Public/Private #regionsRegions called Non-Public Data Members, Non-Public Properties/Methods or Public Interface must have appropriate contents
PH2064Avoid duplicate #regionsA class cannot have regions of the same name.
PH2066Readonly lockLocks are readonly.
PH2067Avoid nested string.FormatDon't nest string.Format (or similar) methods.
PH2068Avoid gotoAvoid goto.
PH2069Avoid unnecessary string.FormatDon't call string.Format unnecessarily.
PH2070Avoid protected fieldsAvoid protected fields.
PH2072Require local editorconfigDisabled by default. As of VS 16.3, Analyzers can now see settings of Editorconfig files in parent folders.
PH2073Call extension method as instanceIf Foo is an extension method of MyClass, call it as MyClass.Foo.
PH2074Avoid register in DisposeDispose methods should unregister rather than register.
PH2075Avoid AssemblyVersion changeDo not accidentally change AssemblyVersion, as it breaks runtime compatibility. Specify the intended dotnet_code_quality.PH2075.assembly_version in an .editorconfig specific to the project. Because this analyzer is not associated with a file, use a .globalconfig file when disabling this analyzer is desired, as described here.
PH2077Avoid Switch statement with no casesAvoid Switch statements when there are no cases
PH2078Avoid PrivateKey PropertyDo not use PrivateKey property on X509Certificate2 class as it might cause the Application to crash. Use a Getter instead. Eg: GetRSAPrivateKey(), GetDSAPrivateKey(), GetECDsaPrivateKey()
PH2079Namespace prefixSpecify a namespace prefix in the .editorconfig file Eg. dotnet_code_quality.PH2079.namespace_prefix = [OrganizationName].[ProductName] and use that prefix for all projects/namespaces
PH2080Avoid hardcoded absolute pathsAvoid hardcoded absolute paths (Windows only)
PH2081Avoid #regions within methodsA #region cannot start or end within a method. Consider refactoring long methods instead.
PH2082Positive namingName properties, fields and variables should be named using positive wording. People can handle double negations poorly, and by using positive wording these are prevented.
PH2083Avoid Pass By ReferenceParameters that are passed by reference should be written to, otherwise they should not be passed by reference
PH2084Don't lock on "new x()"Locking on a newly created object has no effect
PH2085Order property accessorsConsistently order property accessors as get, set, init
PH2086Avoid calling Task.ResultAvoid calling Task.Result
PH2087Do not use spaces in filenamesNot all tools handle files correctly that have spaces in their names. Homebrew scripts are prone to this for example.
PH2088Paths should not exceed 260 charactersThis prevents your code to run correctly on older Windows version.
PH2089Avoid assignments in conditionsConditions shouldn't have any side effects. Assign a variable outside of the condition instead.
PH2090Log ExceptionLog any of the caught exceptions. The Log method names are configurable either in the .editorconfig using key: 'dotnet_code_quality.PH2090.log_method_names' or by adding an named AllowedLogMethods.txt.
PH2091Throw Inner ExceptionWhen throwing an exception inside a catch block, include the original exception as arguments. This will show the inner exception also in a Callstack, aiding debugability.
PH2092Limit Condition ComplexityLimit the number of logical expressions in a single condition. Humans are not very good of keeping track of large logical expressions. The maximum allowed number is configurable in the .editorconfig using key: 'dotnet_code_quality.PH2092.max_operators'.
PH2093Prefer creating tuples with named fieldsWhen creating or accepting a tuple, provide names for the fields (IE, prefer (DateTime createdAt, int id) rather than (DateTime, int)
PH2094Prefer using the named tuple field, not ItemXWherever possible, use the provided name of a tuple field, not the generic name. (IE, (DateTime createdAt, int id) value; value.Item1.ToString(), prefer value.createdAt.ToString()
PH2096Prefer async Task methods over async void methodsWherever possible return Task rather then void for async methods. Exception are Event handlers
PH2097Avoid Empty Statement BlocksAvoid empty statement blocks
PH2098Avoid Empty Catch BlockAvoid try-catch-swallow pattern
PH2099Enforce FileVersion to be same as PackageVersionFor NuGet packages, this analyzer enforces that the .NET AssemblyFileVersion is equal to the AssemblyInformationalVersion. AssemblyFileVersion is not used at runtime, so it is helpful for it to match the Package Version. Set it with the <FileVersion> tag in the project file. If not set, it will inherit from <AssemblyVersion>, which if not set will inherit from <Version>
PH2101Detect Null Dereference after "as"After "as" include null checks; or, use static cast to set expectations.
PH2102Xml documentation should add valueThe content of the summary block of the inline XML code documentation, should add more information then merely repeating its name.
PH2103Avoid method calls as argumentsAvoid method calls as arguments to method calls. For example, avoid Foo(Meow())
PH2104Every Linq statement on separate linePut every linq statement on a separate line, this makes it easier for a reader to follow the steps.
PH2105Align number of + and - operatorsOverload the minus (-) operator, when you overload the plus (+) operator, as these are often used in combination with each other.
PH2106Align number of * and / operatorsOverload the divide (/) operator, when you overload the multiple (*) operator, as these are often used in combination with each other.
PH2107Align number of > and < operatorsOverload the smaller than (<) operator, when you overload the greater than (>) operator, as these are often used in combination with each other.
PH2108Align number of >= and <= operatorsOverload the smaller or equal (<=) operator, when you overload the greater or equal (>=) operator, as these are often used in combination with each other.
PH2109Align number of >> and << operatorsOverload the left shift (<<) operator, when you overload the right shift (>>) operator, as these are often used in combination with each other.
PH2110Align number of ++ and -- operatorsOverload the increment (--) operator, when you overload the increment (++) operator, as these are often used in combination with each other.
PH2111Reduce Cognitive LoadReduce the number of logical cases, negations, or especially nested blocks in this method. Extracting a method is the typical solution.
PH2112Avoid overridde with new keywordOverriding with the new keyword gives unexpected behavior for the callers of the overridden method or property.
PH2113Merge If StatementsNested If statements lacking else clauses and containing the same body can be safely merged to reduce cognitive load
PH2114Avoid empty statementAvoid empty statements.
PH2115Every Lambda expression on separate lineAvoid putting multiple lambda statements on a single line for readability.
PH2116Avoid ArrayListUsage of Arraylist is discouraged by Microsoft for performance reasons, use List instead.
PH2117Avoid Unnecessary Where()Move the predicate of the Where clause into the Any(), Count(), First(), Last(), or Single() clause
PH2118Avoid inline magic numbersAvoid inline magic number, define them as constant or include in an enumeration instead.
PH2119Cast complete objectA cast should include all information from the previous type. By casting to a type of one of the fields, the cast is losing information. Use an AsType() or ToType() method instead.
PH2120Document thrown exceptionsBe clear to your callers what exception can be thrown from your method by mentioning each of them in an element in the documentation of the method.
PH2121Throw informational exceptionsSpecify context to a thrown exception, by using a constructor overload that sets the Message property.
PH2122Avoid Exceptions from unexpected locationsAvoid throwing exceptions from unexpected locations, like Finalizers, Dispose, Static Constructors, some operators, and overidden methods of Object.
PH2123Pass sender to EventHandlerPrevent passing null values for sender/object to event handler (for instance-based events).
PH2124Document unhandled exceptionsBe clear to your callers what exception can be thrown from your method (or any called methods) by mentioning each of them in an element in the documentation of the method.
PH2125Align number of + and == operatorsOverload the equality operator (==), when you overload the addition (+) operator.
PH2126Avoid using Parameters as temporary variablesDon't use parameters as temporary variables, define a local variable instead.
PH2127Avoid changing loop variablesDon't change loop variables, this gives unexpected loop iterations. Use continue and break instead.
PH2128Split multi-line condition on logical operatorIn case that the condition of an "if" or "?" statement covers more then one line, its line endings should be right after the logical operators (&& and
PH2129Return immutable collectionsReturn only immutable or readonly collections from a public method, otherwise these collections can be changed by the caller without the callee noticing.
PH2130Avoid implementing finalizersAvoid implement a finalizer, use Dispose instead. If the class has unmanaged fields, finalizers are allowed if they only call Dispose.
PH2131Align filename and class nameName the file after the class, struct or enum it contains.
PH2132Remove commented codeRemove commented code.
PH2133Unmanaged objects need disposingEvery field which holds an unmanaged object needs to be declared in a class that implements IDisposable.
PH2134Set properties in any orderGetting other properties in a setter makes this setter dependent on the order in which these properties are set.
PH2135Match namespace and Assembly NameThe Assembly Name and Namespace must match.
PH2136Avoid duplicate stringsDuplicate strings are less maintainable.
PH2138Avoid void returnsMethods that return void are mysterious.
PH2139Enable documentation creationAdd XML documentation generation to the project file, to be able to see Diagnostics for XML documentation.
PH2140Avoid ExcludeFromCodeCoverage attributeAvoid the usage of the 'ExcludeFromCodeCoverage' attribute.
PH2141Avoid Empty RegionsAvoid writing regions that have no code inside.
PH2143Avoid Assembly.GetEntryAssembly()Avoid using Assembly.GetEntryAssembly(), as it might give different results when your code runs under a TestRunner.
PH2146Avoid calling ToString() on string typeCalling ToString() on an expression that is already of type string is redundant and should be removed.