C# rules
tx0 checks .cs files with 344 rules, 66 of them in the default tier. Files that say a tool generated them are skipped. Each rule's page explains what it finds and what it leaves alone.
Default: 66 rules
Bugs and security problems with measured precision. They run without a tx0.toml.
-
tx0/csharp:array-equals-referencedefaultEqualsis called on an array, which compares references and not elements -
tx0/csharp:async-lambda-as-actiondefaultAn
asynclambda is passed toForEachorParallel.For, which take an action and do not wait for its task -
tx0/csharp:bool-assigned-in-conditiondefaultA condition assigns a boolean with
=where a comparison with==was likely meant -
tx0/csharp:char-as-builder-capacitydefaultA
StringBuilderis created with achar, which is taken as its capacity and not as its text -
tx0/csharp:compare-to-signdefaultThe result of
CompareToorCompareis tested for being exactly 1 or -1 -
tx0/csharp:component-parameter-not-publicdefaultA Blazor
[Parameter]property is not public, so the component cannot receive it -
tx0/csharp:discarded-iterator-calldefaultAn iterator method is called as a statement, so none of its body runs
-
tx0/csharp:disposed-object-returneddefaultA method returns the variable of a
using, which is disposed as the method returns -
tx0/csharp:dropped-delaydefaultTask.Delayis called without awaiting the task, so nothing waits -
tx0/csharp:duplicate-conditiondefaultA condition of an
if/else ifchain repeats an earlier one -
tx0/csharp:ecb-modedefaultA block cipher is used in ECB mode, which shows patterns of the plaintext
-
tx0/csharp:equals-nulldefaultEquals(null)is called on a value, which is either false or throws -
tx0/csharp:exception-not-throwndefaultAn exception is created and then dropped without being thrown
-
tx0/csharp:fact-with-parametersdefaultAn xUnit
[Fact]or MSTest[TestMethod]has parameters, which nothing supplies -
tx0/csharp:format-argumentsdefaultA composite format string refers to more arguments than are passed, or is malformed
-
tx0/csharp:identical-branchesdefaultThe two branches of an
ifor a conditional expression are the same -
tx0/csharp:identical-operandsdefaultBoth operands of a binary operator are the same expression
-
tx0/csharp:ignored-immutable-resultdefaultA method of a date, time span or immutable collection is called for its result, and the result is dropped
-
tx0/csharp:ignored-pure-calldefaultA static method that only computes a value, such as
Math.MaxorPath.Combine, is called and its result dropped -
tx0/csharp:ignored-string-resultdefaultThe result of a string method is ignored, although strings never change
-
tx0/csharp:impossible-mask-testdefaultA value masked with
&or|is compared with a constant that the mask can never produce -
tx0/csharp:impossible-rangedefaultTwo comparisons of the same value with constants are joined so that the result is always false or always true
-
tx0/csharp:index-at-lengthdefaultAn array or list is indexed with its own length, one past its last element
-
tx0/csharp:lambda-unsubscribedefaultA lambda or anonymous method is removed from an event, which removes nothing
-
tx0/csharp:lock-on-new-objectdefaultA
locktakes an object created on the spot, so it excludes nobody -
tx0/csharp:loop-condition-unchangeddefaultA
whileloop tests only local variables that its body never changes, and has no other exit -
tx0/csharp:loop-steps-other-variabledefaultA
forloop tests one variable and steps another, so its condition never changes -
tx0/csharp:modified-while-iteratingdefaultA collection is changed inside a
foreachover it, which throws on the next step -
tx0/csharp:nan-comparisondefaultA value is compared with
NaNusing==or!= -
tx0/csharp:negative-size-checkdefaultA
CountorLengthis tested for being negative, which it never is -
tx0/csharp:null-check-wrong-operatordefaultA value is used on the side of
&&or||where it is known to be null -
tx0/csharp:null-dereferenced-when-nulldefaultA variable is dereferenced in the branch where it was just tested to be null
-
tx0/csharp:null-task-returneddefaultA method that returns a task returns
null, which throws when awaited -
tx0/csharp:overwritten-before-readdefaultA local variable is assigned and then assigned again on the next statement, so the first value is never read
-
tx0/csharp:overwritten-incrementdefaultA variable is assigned its own postfix increment or decrement, as in
i = i++ -
tx0/csharp:recursive-methoddefaultA method calls itself with the same arguments on every path, which recurses forever
-
tx0/csharp:recursive-propertydefaultA property's accessor reads or assigns the property itself, which recurses until the stack overflows
-
tx0/csharp:reference-equals-value-typedefaultReferenceEqualsis given a value type, which is boxed into a new object, so the result is always false -
tx0/csharp:regex-exponential-backtrackingdefaultA regular expression takes exponential time on some inputs, confirmed with an input that shows it
-
tx0/csharp:repeated-order-bydefaultOrderByfollowsOrderBy, which discards the first ordering -
tx0/csharp:rethrow-loses-stackdefaultA caught exception is thrown again with
throw ex;, which loses its stack trace -
tx0/csharp:returned-postfix-incrementdefaultA local variable is returned with a postfix
++or--, so the change is lost -
tx0/csharp:rooted-path-combineddefaultPath.Combineis given a later argument that starts with a slash or drive, which discards everything before it -
tx0/csharp:rounded-integer-divisiondefaultAn integer division is rounded with
Math.Ceiling,Floor,RoundorTruncate, after its fraction is already gone -
tx0/csharp:same-argument-twicedefaultA method that compares or combines two values is given the same expression twice
-
tx0/csharp:self-assignmentdefaultA variable, field or property is assigned to itself
-
tx0/csharp:several-unmatched-value-parametersdefaultA Blazor component declares more than one parameter that captures unmatched values
-
tx0/csharp:shift-rangedefaultA shift count is at least the number of bits of the shifted value
-
tx0/csharp:short-rsa-keydefaultAn RSA or DSA key shorter than 2048 bits is created
-
tx0/csharp:start-new-async-lambdadefaultAn
asynclambda is started withTask.Factory.StartNew, whose task ends at the lambda's firstawait -
tx0/csharp:stray-semicolon-bodydefaultAn
if,while,fororforeachis followed directly by;, so its body is empty -
tx0/csharp:suppress-finalize-other-objectdefaultGC.SuppressFinalizeis called with something other thanthis -
tx0/csharp:swapped-argument-exception-argumentsdefaultAn argument exception gets a sentence where it takes the parameter name, or a parameter name where it takes the message
-
tx0/csharp:test-class-not-publicdefaultAn MSTest
[TestClass]is not public, so none of its tests run -
tx0/csharp:test-data-aritydefaultA data row of a test has a different number of values than the test has parameters
-
tx0/csharp:test-method-not-publicdefaultA method marked as a test is not public, so the test framework does not run it
-
tx0/csharp:test-setup-wrong-signaturedefaultAn MSTest setup or cleanup method has a signature the framework does not accept, so it never runs
-
tx0/csharp:thread-static-misusedefaultA
[ThreadStatic]field is not static, or has an initializer that runs only once -
tx0/csharp:to-string-returns-nulldefaultAn override of
ToStringreturnsnull -
tx0/csharp:type-of-typedefaultGetType()is called on aType, which gives the type of type objects -
tx0/csharp:unawaited-throws-assertiondefaultAssert.ThrowsAsyncis called withoutawait, so the test ends before the assertion is checked -
tx0/csharp:unity-message-wrong-casedefaultA method of a Unity script is named like a Unity message but with different letter case, so Unity never calls it
-
tx0/csharp:unity-object-created-with-newdefaultA
MonoBehaviourorScriptableObjectdeclared in the file is created withnew, which Unity does not support -
tx0/csharp:unsafe-type-resolverdefaultJavaScriptSerializeris given aSimpleTypeResolver, which lets the input choose types -
tx0/csharp:unsigned-sign-testdefaultAn unsigned value is tested for being negative or non-negative, which has a fixed answer
-
tx0/csharp:wrong-loop-directiondefaultA
forloop moves its counter away from the bound of its condition
Recommended: 146 rules
Likely bugs, resource and performance problems.
-
tx0/csharp:abs-of-hash-coderecommendedMath.Absis applied to a hash code, which throws forint.MinValue -
tx0/csharp:accessor-wrong-fieldrecommendedA property accessor reads or writes another field than the one the property is named after
-
tx0/csharp:antiforgery-disabledrecommendedThe antiforgery check is switched off for an action, controller or endpoint
-
tx0/csharp:archive-entry-path-traversalrecommendedThe name of an archive entry is joined to a directory without checking that the result stays inside it
-
tx0/csharp:argument-exception-namerecommendedAn argument exception names a parameter that the method does not have
-
tx0/csharp:array-to-stringrecommendedToString()is called on an array, which gives its type name and not its elements -
tx0/csharp:async-voidrecommendedAn
asyncmethod returnsvoid, so its caller cannot await it or see its exceptions -
tx0/csharp:async-without-awaitrecommendedA method is declared
asyncbut never awaits, so it runs synchronously and pays for a state machine -
tx0/csharp:blocking-in-asyncrecommendedAn
asyncmethod blocks on a task or sleeps instead of awaiting -
tx0/csharp:blocking-wait-all-in-asyncrecommendedAn
asyncmethod waits withTask.WaitAllorTask.WaitAny, which block the thread whereWhenAllandWhenAnywould await -
tx0/csharp:body-on-get-actionrecommendedA GET action reads a parameter from the request body, which GET requests do not reliably carry
-
tx0/csharp:bool-literal-operandrecommendedtrueorfalseis an operand of&&or||, so the condition is fixed or the literal does nothing -
tx0/csharp:cast-after-asrecommendedThe result of
asis used directly, which throwsNullReferenceExceptioninstead of a clear cast error -
tx0/csharp:catch-null-referencerecommendedA
NullReferenceExceptionorIndexOutOfRangeExceptionis caught instead of prevented -
tx0/csharp:cause-dropped-in-catchrecommendedA
catchthrows a new exception without passing the caught one as its inner exception -
tx0/csharp:certificate-validation-disabledrecommendedTLS certificate validation is switched off by a callback that accepts every certificate
-
tx0/csharp:class-name-comparisonrecommendedA type is tested by comparing the name of
GetType()with a string -
tx0/csharp:complex-conditionrecommendedA condition combines more
&&and||operators than the configured maximum -
tx0/csharp:component-parameter-with-logicrecommendedA Blazor
[Parameter]property has code in its accessors, which runs on every render of the parent -
tx0/csharp:constant-assertionrecommendedAn assertion checks a literal,
Assert.True(true)or the like, so it can never fail or always fails -
tx0/csharp:constant-conditionrecommendedAn
ifor loop tests the literaltrueorfalse -
tx0/csharp:constant-initialization-vectorrecommendedA cipher gets an initialization vector that is all zeros or derived from a literal, so equal messages encrypt equally
-
tx0/csharp:cookie-protection-offrecommendedA cookie is set to be sent without TLS or to be readable by scripts
-
tx0/csharp:cors-any-originrecommendedA CORS policy allows every origin
-
tx0/csharp:count-instead-of-anyrecommendedCount()is compared with zero whereAny()would stop at the first element -
tx0/csharp:debug-assert-effectrecommendedThe condition of
Debug.Asserthas an effect, which release builds drop -
tx0/csharp:deep-nestingrecommendedStatements are nested deeper than the configured maximum
-
tx0/csharp:delegate-begin-invokerecommendedA delegate is called asynchronously with
BeginInvoke, which .NET Core and later do not support -
tx0/csharp:disposable-field-not-disposedrecommendedA disposable class creates a resource in a field that none of its dispose methods mentions
-
tx0/csharp:disposable-not-disposedrecommendedA stream, reader, writer or connection created in a method is never disposed
-
tx0/csharp:disposable-owner-not-disposablerecommendedA class creates a stream, timer, connection or similar resource in a field but does not implement
IDisposable -
tx0/csharp:dispose-without-base-callrecommendedAn override of
Dispose(bool)does not call the base class'sDispose(bool), so the base resources are not released -
tx0/csharp:doubled-unaryrecommendedA unary operator is applied twice in a row, as in
!!xor- -x -
tx0/csharp:dsa-signaturerecommendedDSA is used for signatures, an algorithm that current standards no longer approve
-
tx0/csharp:dtd-processing-enabledrecommendedAn XML reader is set to process DTDs, which can read files and exhaust memory
-
tx0/csharp:duplicate-test-datarecommendedA test has the same data row twice, so one case runs twice and was probably meant to be another
-
tx0/csharp:eager-boolean-operatorrecommendedTwo comparisons are joined with
&or|, which evaluate both sides where&&and||would stop early -
tx0/csharp:empty-blockrecommendedA branch or loop has an empty body without a comment
-
tx0/csharp:empty-catchrecommendedAn exception is caught and ignored without a comment
-
tx0/csharp:empty-finalizerrecommendedA finalizer has an empty body
-
tx0/csharp:empty-finallyrecommendedA
finallyblock is empty -
tx0/csharp:empty-guid-createdrecommendednew Guid()creates the all-zero GUID, whereGuid.NewGuid()was likely meant -
tx0/csharp:equality-operator-without-equalsrecommendedA type defines
==but does not overrideEquals, so the two kinds of equality disagree -
tx0/csharp:equals-casts-uncheckedrecommendedEquals(object)casts its argument without checking its type, so comparing with another type throws -
tx0/csharp:equals-without-get-hash-coderecommendedA type overrides
Equalsbut notGetHashCode, so equal objects may hash differently -
tx0/csharp:equatable-without-object-equalityrecommendedA type implements typed equality but keeps the inherited object equality or hash code, so the two disagree
-
tx0/csharp:event-raised-without-subscribers-checkrecommendedAn event is raised by calling it directly, which throws when nobody has subscribed
-
tx0/csharp:exception-details-in-responserecommendedA caught exception's stack trace or full text is sent back in a response
-
tx0/csharp:expected-value-secondrecommendedAn equality assertion gets the literal expected value as its second argument, so failures report expected and actual swapped
-
tx0/csharp:exposed-static-arrayrecommendedA public static readonly array can still have its elements changed by any code
-
tx0/csharp:few-key-iterationsrecommendedA key is derived from a password with fewer than 10,000 iterations
-
tx0/csharp:finalizer-not-suppressedrecommendedA class with a finalizer has a
Dispose()that does not callGC.SuppressFinalize -
tx0/csharp:forwarded-headers-from-any-proxyrecommendedThe forwarded headers of every sender are trusted, so clients can claim any address
-
tx0/csharp:hardcoded-credentialrecommendedA password or secret is written in the code as a string literal
-
tx0/csharp:high-complexityrecommendedA method has more independent paths than the configured maximum
-
tx0/csharp:https-metadata-not-requiredrecommendedThe signing keys of an authentication issuer may be fetched over plain HTTP
-
tx0/csharp:ignored-linq-resultrecommendedThe result of a LINQ query method is ignored, so the query never runs
-
tx0/csharp:ignored-read-countrecommendedThe number of bytes or characters a
Readcall returns is ignored -
tx0/csharp:index-of-above-zerorecommendedThe result of
IndexOfis tested with> 0, which misses a match at the first position -
tx0/csharp:insecure-deserializerrecommendedA serializer that can create any type from its input is used
-
tx0/csharp:int-product-widenedrecommendedTwo
intvalues are multiplied and the product is stored aslong, after it may have overflowed -
tx0/csharp:integer-divisionrecommendedAn integer division is stored in a floating-point variable and loses its fraction
-
tx0/csharp:key-derivation-default-hashrecommendedRfc2898DeriveBytesis created without a hash algorithm, so it uses SHA-1 -
tx0/csharp:last-error-without-set-last-errorrecommendedThe last native error is read after a call of a native method that does not save it
-
tx0/csharp:ldap-anonymous-bindrecommendedA directory connection binds anonymously or with a clear text password
-
tx0/csharp:ldap-filter-from-requestrecommendedAn LDAP search filter or path contains a value taken from an HTTP request
-
tx0/csharp:ldap-filter-from-stringsrecommendedAn LDAP search filter is built by concatenating or interpolating values
-
tx0/csharp:literal-crypto-keyrecommendedA cryptographic key is made from a string literal in the code
-
tx0/csharp:lock-on-mutable-fieldrecommendedA
locktakes a field that is assigned again outside the constructors, so threads may lock different objects -
tx0/csharp:lock-on-weak-identityrecommendedA
locktakes an object that other code can lock too:this, a type or a string -
tx0/csharp:log-template-argumentsrecommendedA log message template has a different number of placeholders than arguments
-
tx0/csharp:long-methodrecommendedA method has more lines of code than the configured maximum
-
tx0/csharp:long-parameter-listrecommendedA method or constructor has more parameters than the configured maximum
-
tx0/csharp:loop-counter-assignedrecommendedThe counter of a
forloop is also changed inside its body -
tx0/csharp:materialized-to-countrecommendedA sequence is copied into a list or array only to count it or to test it for elements
-
tx0/csharp:misleading-indentationrecommendedThe indentation around a body without braces suggests other statements belong to it than do
-
tx0/csharp:monitor-without-finallyrecommendedMonitor.Enteris called outside atrywhosefinallycallsMonitor.Exit -
tx0/csharp:mutable-static-fieldrecommendedA public static field can be changed by any code
-
tx0/csharp:native-charset-mismatchrecommendedA native function for wide or narrow text is declared with the other character set, so its strings are garbled
-
tx0/csharp:negative-hash-indexrecommendedA hash code taken modulo a size is used as an index, which is negative for negative hash codes
-
tx0/csharp:new-http-clientrecommendedAn
HttpClientis created for a single use, which can exhaust sockets -
tx0/csharp:nullable-value-uncheckedrecommended.Valueis read from a nullable value that the method never tests for a value -
tx0/csharp:object-identity-in-value-equalityrecommendedA class that compares values calls object's identity-based hash code or equality from its overrides
-
tx0/csharp:obsolete-tls-versionrecommendedSSL 3.0, TLS 1.0 or TLS 1.1 is selected explicitly, protocols with known attacks
-
tx0/csharp:odd-test-with-onerecommendedA remainder by 2 is compared with 1, which is false for negative odd numbers
-
tx0/csharp:open-redirectrecommendedAn action redirects to a location taken from the request without a check
-
tx0/csharp:overwritten-entryrecommendedAn element of a collection is assigned twice in a row with the same key, so the first value is lost
-
tx0/csharp:parallel-loop-shared-collectionrecommendedThe body of
Parallel.FororParallel.ForEachadds to aList,DictionaryorHashSetdeclared outside it, which is not thread-safe -
tx0/csharp:parameter-overwritten-unreadrecommendedA parameter is assigned in the first statement of its method, before its value is ever read
-
tx0/csharp:permissive-content-security-policyrecommendedA content security policy lets pages run inline scripts or code built from strings
-
tx0/csharp:predictable-random-secretrecommendedSystem.Randomproduces a token, password, key, salt or nonce, which an attacker can predict -
tx0/csharp:query-enumerated-twicerecommendedA deferred LINQ query held in a local is enumerated more than once, so it runs again each time
-
tx0/csharp:random-created-in-looprecommendedA
Randomis created inside a loop, so instances made in quick succession may give the same numbers -
tx0/csharp:raw-html-from-valuerecommendedA value is written out as raw HTML with
Html.Raw,HtmlStringorMarkupString, without encoding -
tx0/csharp:recursive-equality-operatorrecommendedAn
==or!=operator compares its own operands with==or!=, which calls itself until the stack overflows -
tx0/csharp:regex-built-in-looprecommendedA
Regexis created inside a loop, so its pattern is parsed again on every round -
tx0/csharp:request-size-unlimitedrecommendedThe limit on the size of request bodies is removed
-
tx0/csharp:request-validation-disabledrecommendedASP.NET request validation is switched off with
[ValidateInput(false)]or[AllowHtml] -
tx0/csharp:request-value-deserializedrecommendedData taken from an HTTP request is deserialized into objects of classes it names
-
tx0/csharp:request-value-in-commandrecommendedA process is started with a command or arguments taken from an HTTP request
-
tx0/csharp:request-value-in-pagerecommendedA value taken from an HTTP request is written into an HTML response without escaping
-
tx0/csharp:reserved-exception-thrownrecommendedA too general or runtime-reserved exception type is thrown
-
tx0/csharp:revocation-check-disabledrecommendedThe revocation check of certificates is switched off
-
tx0/csharp:rsa-pkcs1-encryptionrecommendedRSA encryption uses PKCS#1 v1.5 padding, which is open to padding oracle attacks
-
tx0/csharp:save-changes-in-asyncrecommendedAn
asyncmethod callsSaveChanges, which blocks on the database whereSaveChangesAsyncwould not -
tx0/csharp:save-changes-in-looprecommendedSaveChangesis called inside a loop, so each round trip saves one change -
tx0/csharp:second-service-providerrecommendedBuildServiceProvideris called while services are still being registered, which creates a second container -
tx0/csharp:self-bulk-operationrecommendedA collection is passed to a set or bulk operation of its own, which is a no-op or has a fixed result
-
tx0/csharp:singleton-db-contextrecommendedAn Entity Framework
DbContextis registered as a singleton, though it is not thread-safe -
tx0/csharp:sql-from-stringsrecommendedSQL text is built by concatenating or interpolating values
-
tx0/csharp:sql-query-from-requestrecommendedThe text of an SQL query is built from a value taken from an HTTP request
-
tx0/csharp:sta-thread-missingrecommendedThe entry point of a Windows Forms application lacks the single-threaded apartment attribute
-
tx0/csharp:static-field-read-before-initializedrecommendedA static field initializer reads a static field that is initialized further down, so it sees the default value
-
tx0/csharp:task-returned-from-usingrecommendedA method that is not
asyncreturns a task from inside ausing, which disposes the resource before the task ends -
tx0/csharp:task-without-schedulerrecommendedContinueWithorTaskFactory.StartNewruns on whatever scheduler is current, as no scheduler is passed -
tx0/csharp:test-without-assertionrecommendedA test method calls no assertion, so it passes as long as nothing throws
-
tx0/csharp:theory-without-datarecommendedAn xUnit
[Theory]has no data attribute, so it has no cases to run -
tx0/csharp:thread-abortrecommendedA thread is aborted, suspended or resumed, which can corrupt state or deadlock
-
tx0/csharp:throw-in-finallyrecommendedA
finallyblock throws, which replaces any exception already on its way -
tx0/csharp:throw-in-getterrecommendedA property getter throws an exception other than the few that a getter is expected to throw
-
tx0/csharp:throw-in-identity-memberrecommendedEquals,GetHashCode,ToString,Dispose, an equality operator, an implicit conversion or a static constructor throws -
tx0/csharp:throwing-finalizerrecommendedA finalizer throws an exception, which ends the process
-
tx0/csharp:token-validation-disabledrecommendedA security token check is switched off: issuer, audience, lifetime, signature or HTTPS metadata
-
tx0/csharp:transfer-without-tlsrecommendedA mail or file transfer client is set to send without encryption
-
tx0/csharp:type-name-handlingrecommendedJson.NET is set to read type names from the JSON, which lets the input choose types
-
tx0/csharp:unawaited-async-callrecommendedAn
asyncmethod calls a method ending inAsyncas a statement, without awaiting or keeping its task -
tx0/csharp:unguarded-developer-exception-pagerecommendedThe developer exception page is enabled without checking that the app runs in development
-
tx0/csharp:unity-empty-messagerecommendedA Unity message such as
UpdateorStartis declared with an empty body, which Unity still calls -
tx0/csharp:unity-lookup-every-framerecommendedA Unity object or component is looked up in
Update,LateUpdate,FixedUpdateorOnGUI, once per frame -
tx0/csharp:unity-object-null-propagationrecommended?.or??is used on a Unity object, which skips Unity's own check for destroyed objects -
tx0/csharp:unprotected-semaphore-releaserecommendedA semaphore is released outside a
finallyblock, so an exception between wait and release keeps it taken -
tx0/csharp:unreachable-statementrecommendedA statement follows a
return,throw,break,continueorgotoin the same block and never runs -
tx0/csharp:unused-localrecommendedA local variable is declared and never used afterwards
-
tx0/csharp:unused-private-fieldrecommendedA private field is never used
-
tx0/csharp:unused-private-methodrecommendedA private method is never called
-
tx0/csharp:useless-catchrecommendedA
catchclause only rethrows what it caught -
tx0/csharp:using-variable-disposedrecommendedA variable declared by
usingis also disposed by an explicitDispose()call -
tx0/csharp:virtual-call-in-constructorrecommendedA constructor calls a virtual or abstract method of its own class
-
tx0/csharp:volatile-compoundrecommendedA
volatilefield is updated with++,--or a compound assignment, which is not atomic -
tx0/csharp:weak-cipherrecommendedA weak or obsolete cipher, DES, triple DES or RC2, is used
-
tx0/csharp:weak-cookie-policyrecommendedA cookie policy sends cookies over plain HTTP or lets scripts read them
-
tx0/csharp:weak-hashrecommendedA broken hash algorithm, MD5 or SHA-1, is used
-
tx0/csharp:world-writable-file-moderecommendedA file is given permissions that let every user write to it
-
tx0/csharp:xml-resolver-enabledrecommendedAn XML reader or document is given an
XmlUrlResolver, which lets the input load external files and URLs -
tx0/csharp:xpath-from-requestrecommendedAn XPath expression is built from a value taken from an HTTP request
-
tx0/csharp:xpath-from-stringsrecommendedAn XPath query is built by concatenating or interpolating values
Strict: 93 rules
Code that can be written more plainly.
-
tx0/csharp:append-of-concatenationstrictStringBuilder.Appendis given a string built with+, which allocates the joined string first -
tx0/csharp:append-of-to-stringstrictStringBuilder.Appendis given the result ofToString(), which allocates a string the builder did not need -
tx0/csharp:array-propertystrictA public property returns an array, whose elements any caller can change
-
tx0/csharp:assembly-loaded-from-pathstrictAn assembly is loaded from a file path, which runs whatever code is at that path
-
tx0/csharp:bool-literal-comparisonstrictA boolean is compared with
trueorfalse -
tx0/csharp:boolean-ternarystrictA conditional expression yields
trueandfalse, which is its condition -
tx0/csharp:caller-info-parameter-not-laststrictA caller information parameter is followed by an ordinary parameter, which positional calls fill into it
-
tx0/csharp:case-conversion-comparisonstrictStrings are compared after converting both to the same case
-
tx0/csharp:char-array-iterationstrictA string is copied into a
chararray only to be iterated -
tx0/csharp:check-then-addstrictA set or dictionary is searched with
ContainsorContainsKeyand then added to, where one call would do both -
tx0/csharp:collapsible-ifstrictAn
ifis the only statement in anotherifwithoutelse, and both can be merged -
tx0/csharp:command-from-stringsstrictA process is started with a command line built from strings
-
tx0/csharp:commented-out-codestrictA line comment contains code that was switched off
-
tx0/csharp:concrete-list-in-public-apistrictA public member exposes
List<T>, which ties callers to one implementation and lets them change it freely -
tx0/csharp:constant-aead-noncestrictAn authenticated cipher encrypts with a nonce fixed in the code, which repeats for every message
-
tx0/csharp:constant-array-argumentstrictAn array of constants is created anew as an argument on every call, where a static field would create it once
-
tx0/csharp:constant-password-saltstrictA password hash is derived with a salt fixed in the code
-
tx0/csharp:count-method-on-collectionstrictCount()is called on a list, array or other collection that knows its size -
tx0/csharp:culture-dependent-parsestrictA number or date is parsed with the culture of the current thread, so the same text parses differently on other machines
-
tx0/csharp:culture-sensitive-comparisonstrictStrings are compared or searched with the current culture's rules, though no
StringComparisonis given -
tx0/csharp:double-checked-lock-not-volatilestrictA field is initialized with double-checked locking but is not
volatile, so another thread can see it half built -
tx0/csharp:empty-array-allocationstrictAn empty array is allocated where
Array.Emptywould reuse one -
tx0/csharp:empty-database-passwordstrictA database connection string in the code has an empty password
-
tx0/csharp:empty-interfacestrictAn interface declares no members
-
tx0/csharp:empty-string-comparisonstrictA string is compared with
""orstring.Emptyto test whether it is empty -
tx0/csharp:exception-without-standard-constructorsstrictA public exception class lacks one of the usual constructors: none, a message, or a message and an inner exception
-
tx0/csharp:expected-exception-attributestrictA test expects an exception with
[ExpectedException], which passes when any line of the test throws it -
tx0/csharp:filter-after-materializingstrictA query is turned into a list or enumerable and then filtered, so the filter runs in memory and not in the database
-
tx0/csharp:filter-before-terminalstrictWhere(...)is followed byFirst,Single,Any,Countor a similar call without arguments, which takes the condition itself -
tx0/csharp:flags-enum-valuesstrictA
[Flags]enum has a member whose value is neither a single bit nor a combination of others -
tx0/csharp:flags-enum-without-zerostrictA
[Flags]enum has no member with the value 0 -
tx0/csharp:floating-point-equalitystrictA floating-point value is compared with
==or!=to a fractional literal, which rounding rarely matches exactly -
tx0/csharp:format-without-placeholdersstrictstring.Formatis given a format string without placeholders and no arguments -
tx0/csharp:gc-collectstrictGC.Collectis called explicitly -
tx0/csharp:general-catchstrictEvery exception is caught and not thrown again
-
tx0/csharp:goto-statementstrictgotojumps to a label -
tx0/csharp:hash-code-of-mutable-fieldstrictA hash code is computed from a field that can change while the object is in a hash table
-
tx0/csharp:header-added-twice-throwsstrictA response header is set with
Headers.Add, which throws when the header is already present -
tx0/csharp:include-by-stringstrictA navigation is loaded with
Include("Name"), which the compiler cannot check -
tx0/csharp:interpolated-log-messagestrictA log message is built with string interpolation instead of a template
-
tx0/csharp:interpolation-without-holesstrictAn interpolated string has no holes
-
tx0/csharp:js-invokable-not-publicstrictA method that script code is to invoke is not public, so the call from script fails at run time
-
tx0/csharp:keys-containsstrictKeys.ContainsorValues.Containsis called on a dictionary, whereContainsKeyorContainsValuesays it directly -
tx0/csharp:linq-on-indexablestrictFirst(),Last()orElementAt()is called on a list or array, where indexing says the same -
tx0/csharp:local-clock-readstrictDateTime.Nowis read, the local time, which jumps with daylight saving time and differs between servers -
tx0/csharp:local-shadows-fieldstrictA local variable has the same name as a field of its type, which it hides
-
tx0/csharp:long-filestrictA file has more lines of code than the configured maximum
-
tx0/csharp:lookup-then-indexstrictA dictionary is searched with
ContainsKeyand then again with its indexer -
tx0/csharp:loop-runs-oncestrictA loop body always ends in a jump out of the loop, so it runs at most once
-
tx0/csharp:many-returnsstrictA method has more
returnstatements than the configured maximum -
tx0/csharp:many-type-parametersstrictA public type or method has more than two type parameters
-
tx0/csharp:midpoint-rounding-defaultstrictMath.Roundrounds halves to the nearest even number, as noMidpointRoundingis given -
tx0/csharp:mismatched-unlockstrictA reader-writer lock is released in another mode than the one the method took it in
-
tx0/csharp:nested-conditionalstrictA conditional expression is nested in another
-
tx0/csharp:not-implemented-thrownstrictNotImplementedExceptionis thrown, which marks code that was never written -
tx0/csharp:obsolete-without-messagestrict[Obsolete]is applied without a message saying what to use instead -
tx0/csharp:one-way-operation-returns-valuestrictA one-way service operation declares a return value, which the service host rejects
-
tx0/csharp:out-parameterstrictA public method returns a value through an
outparameter -
tx0/csharp:predictable-temp-filestrictA temporary file is created with
Path.GetTempFileName, in a shared directory under a guessable name -
tx0/csharp:process-exit-in-librarystrictEnvironment.Exitends the whole process from code other than the program's entry point -
tx0/csharp:public-abstract-constructorstrictAn abstract class has a public constructor, which only subclasses can call
-
tx0/csharp:public-fieldstrictAn instance field of a class is public
-
tx0/csharp:public-nested-typestrictA public type is declared inside another public type
-
tx0/csharp:readonly-static-literalstrictA
static readonlyfield of a primitive type orstringis initialized with a literal and could beconst -
tx0/csharp:regex-without-timeoutstrictA regular expression built from a variable pattern runs without a timeout
-
tx0/csharp:request-path-in-file-accessstrictA file is opened, written or included at a path taken from an HTTP request without a check
-
tx0/csharp:request-url-fetchedstrictA server connects to an address taken from an incoming request without a check
-
tx0/csharp:request-value-in-headerstrictA response header is set from a value taken from an HTTP request
-
tx0/csharp:request-value-loggedstrictA value taken from an HTTP request is written to a log as it is
-
tx0/csharp:reversed-assign-operatorstrictAn assignment is written
=+,=-or=!where a compound operator was likely meant -
tx0/csharp:sealed-type-protected-memberstrictA sealed class declares a new
protectedmember, which no subclass can ever use -
tx0/csharp:serialization-callback-signaturestrictA serialization callback does not have the signature the serializer calls, so serializing fails at run time
-
tx0/csharp:settable-collection-propertystrictA public property of a collection type has a public setter, so callers can replace the whole collection
-
tx0/csharp:setter-ignores-valuestrictA property's setter never uses
value, so the assigned value is lost -
tx0/csharp:single-character-string-argumentstrictA one-character string is passed where an overload takes a
char, such asIndexOf("x")orSplit(",") -
tx0/csharp:skipped-test-without-reasonstrictA test is skipped or ignored without a reason
-
tx0/csharp:sleep-in-teststrictA test waits with
Thread.SleeporTask.Delay, which makes it slow and flaky -
tx0/csharp:sort-then-reversestrictA sequence is sorted with
OrderByand then reversed, whichOrderByDescendingdoes in one pass -
tx0/csharp:static-field-set-by-instancestrictAn instance method or constructor assigns a static field, which every instance shares
-
tx0/csharp:static-holder-classstrictA class has only static members but is not declared
static -
tx0/csharp:static-member-of-generic-typestrictA public generic type declares a public static method, which callers must call with type arguments
-
tx0/csharp:string-concat-in-loopstrictA string is built with
+=inside a loop, which copies it every round -
tx0/csharp:swapped-argumentsstrictTwo arguments of a call are named like each other's parameters, so they are likely passed in the wrong order
-
tx0/csharp:sync-over-asyncstrictA task is waited for synchronously with
Wait(),.ResultorGetAwaiter().GetResult() -
tx0/csharp:task-commentstrictA comment marks unfinished work with
TODO,FIXMEorHACK -
tx0/csharp:token-none-despite-parameterstrictA method that receives a
CancellationTokenpassesCancellationToken.Noneordefaulton to another call -
tx0/csharp:type-check-then-caststrictA value is tested with
isand then cast to the same type -
tx0/csharp:type-tested-in-catchstrictA
catchtests the type of the caught exception withis, where a more specificcatchor a filter would do -
tx0/csharp:unity-method-by-namestrictA Unity method is invoked by its name in a string, which the compiler cannot check
-
tx0/csharp:unity-tag-compared-as-stringstrictA Unity tag is compared as a string, which allocates, where
CompareTagdoes not -
tx0/csharp:unused-cancellation-tokenstrictA method takes a
CancellationTokenand never uses it, so cancelling has no effect -
tx0/csharp:unused-parameterstrictA parameter of a private method or local function is never used
-
tx0/csharp:write-only-propertystrictA property has a setter but no getter
: 39 rules
-
tx0/csharp:async-suffix-on-sync-methodallA method is named with the suffix
Asyncbut returns neither a task nor an async stream -
tx0/csharp:await-without-configureallA task is awaited in library code without
ConfigureAwait, so the rest of the method resumes on the caller's context -
tx0/csharp:base-only-overrideallAn override only calls the base method with the same arguments
-
tx0/csharp:boolean-assert-of-comparisonallAssert.TrueorAssert.IsTrueis given an equality comparison, which hides both values when it fails -
tx0/csharp:conditional-null-fallbackallA conditional expression tests a value for
nulland falls back to another, which??says directly -
tx0/csharp:count-asserted-zeroallAn assertion compares a collection's count with 0, where
Assert.Emptyreports the elements on failure -
tx0/csharp:default-value-initializerallA field is explicitly initialized to the default value of its type, which it has anyway
-
tx0/csharp:duplicated-string-literalallThe same string literal appears more often in a file than the configured maximum
-
tx0/csharp:else-after-returnallAn
elsefollows a branch that always leaves withreturn,throw,breakorcontinue -
tx0/csharp:enum-type-suffixallAn enum's name ends in
EnumorFlags -
tx0/csharp:equality-assert-of-null-or-boolallAn equality assertion compares with
null,trueorfalse, where a dedicated assertion reads better -
tx0/csharp:exception-name-suffixallA class derives from an exception type but its name does not end in
Exception -
tx0/csharp:field-could-be-readonlyallA private field is assigned only in its declaration or in constructors and could be
readonly -
tx0/csharp:identity-selectallSelect(x => x)returns every element unchanged -
tx0/csharp:if-return-boolallAn
ifreturnstruein one branch andfalsein the other, which is returning its condition -
tx0/csharp:implicit-access-modifierallA member or type is declared without an access modifier and gets the default one
-
tx0/csharp:interface-without-i-prefixallAn interface's name does not start with
Ifollowed by a capital letter -
tx0/csharp:local-name-casingallA local variable or parameter starts with a capital letter
-
tx0/csharp:long-lambdaallA lambda or anonymous method has more lines of code than the configured maximum
-
tx0/csharp:many-methodsallA type declares more methods than the configured maximum
-
tx0/csharp:method-name-casingallA method's name starts with a lowercase letter
-
tx0/csharp:negated-comparisonallA comparison is negated with
!, where the opposite operator says it directly -
tx0/csharp:null-dereference-across-callsallThe result of a call that can return
nullis dereferenced without a check -
tx0/csharp:null-or-empty-written-outallA string is tested for
nulland then for emptiness by hand, whichstring.IsNullOrEmptydoes -
tx0/csharp:redundant-empty-constructorallA class has a single public parameterless constructor with an empty body, which the compiler would generate
-
tx0/csharp:redundant-to-stringallToString()is called on something that is already a string -
tx0/csharp:regex-backtracking-on-inputallA regular expression that takes super-linear time is matched against request input
-
tx0/csharp:regex-polynomial-backtrackingallA regular expression takes quadratic or higher polynomial time on some inputs, confirmed with an input that shows it
-
tx0/csharp:region-directiveallCode is grouped with
#region -
tx0/csharp:return-of-fresh-localallA local variable is declared and returned right away, without being used in between
-
tx0/csharp:several-declaratorsallOne declaration introduces several fields or local variables
-
tx0/csharp:several-types-in-fileallA file declares more than one top-level type
-
tx0/csharp:small-switchallA
switchstatement has fewer than three sections and reads more simply as anif -
tx0/csharp:switch-without-defaultallA
switchstatement has nodefaultsection -
tx0/csharp:task-method-without-async-suffixallA method returns a task but its name does not end in
Async -
tx0/csharp:type-filter-then-castallElements are filtered with
x is Tand then cast withCast<T>(), whichOfType<T>()does in one step -
tx0/csharp:type-name-casingallA type's name starts with a lowercase letter
-
tx0/csharp:type-name-differs-from-fileallThe only top-level type of a file has a name different from the file
-
tx0/csharp:type-parameter-without-t-prefixallA type parameter is named neither
TnorTfollowed by a capitalized word