Skip to main content

C# Coding Violations


'l' Suffix Easily Confused with '1'

Description: The 'l' suffix is easily confused with the digit '1'

Label Label Label

Bad Example
long value = 1000000l;
Good Example
long value = 1000000L;

Access in Text

Description: Cannot access symbol in text argument

Label Label Label

Bad Example
var message = "Value is " + myInstance.PrivateField;
Good Example
var message = $"Value is {myInstance.GetPrivateField()}"; // Use a getter method

Access to Disposed Closure

Description: Access to disposed captured variable

Label Label Label

Bad Example
using (var resource = new Resource()) { Task.Run(() => resource.Use()); }
Good Example
var localResource = new Resource(); Task.Run(() => { localResource.Use(); localResource.Dispose(); });

Access to For Each Variable

Description: Access to foreach variable in closure

Label Label Label

Bad Example
foreach (var item in items) { tasks.Add(() => Console.WriteLine(item)); }
Good Example
foreach (var item in items) { var localItem = item; tasks.Add(() => Console.WriteLine(localItem)); }

Access to Modified Closure

Description: Access to modified captured variable

Label Label Label

Bad Example
int count = 0; tasks.Add(() => Console.WriteLine(count++));
Good Example
int localCount = count; tasks.Add(() => Console.WriteLine(localCount));

Access to Static Member via Derived Type

Description: Access to a static member of a type via a derived type

Label Label Label

Bad Example
class Base { public static void Log() {} } class Derived : Base {} Derived.Log(); // Accessed via derived type
Good Example
class Base { public static void Log() {} } class Derived : Base {} Base.Log(); // Accessed via base type

Accessor Owner Body

Description: Use preferred body style (convert to property, indexer or event with preferred body style)

Label Label Label

Bad Example
public int MyProperty { get { return _value; } }
Good Example
public int MyProperty => _value;

Address of Marshal by Ref Object

Description: Captured field reference of a marshal-by-reference class may cause a runtime exception

Label Label Label

Bad Example
MarshalByRefObject obj = new MyRemoteObject(); Task.Run(() => obj.DoSomething());
Good Example
var localObj = new MyRemoteObject(); Task.Run(() => localObj.DoSomething());

Annotate not Null Parameter

Description: Declaration nullability inferred (parameter is inferred to be not null)

Label Label Label

Bad Example
public void DoSomething(string value) { }
Good Example
public void DoSomething([NotNull] string value) { }

Annotate not Null Type Member

Description: Declaration nullability inferred (type member is inferred to be not null)

Label Label Label

Bad Example
public string Name { get; set; }
Good Example
[NotNull] public string Name { get; set; }

Annotate Null Parameter

Description: Declaration nullability inferred (parameter is inferred to be nullable)

Label Label Label

Bad Example
public void DoSomething(string? value) { }
Good Example
public void DoSomething([CanBeNull] string? value) { }

Annotate Null Type Member

Description: Declaration nullability inferred (type member is inferred to be nullable)

Label Label Label

Bad Example
public string? Name { get; set; }
Good Example
[CanBeNull] public string? Name { get; set; }

Annotation Conflict in Hierarchy

Description: Annotation conflict in hierarchy

Label Label Label

Bad Example
class BaseClass { public virtual string? Name { get; } } class DerivedClass : BaseClass { public override string Name { get; } }
Good Example
class BaseClass { public virtual string Name { get; } } class DerivedClass : BaseClass { public override string Name { get; } }

Annotation Redundancy at Value Type

Description: Nullability attribute usage with declaration of void or value type

Label Label Label

Bad Example
[AllowNull] public int Age; // Nullable attribute on a value type is redundant
Good Example
public int Age; // Removed nullable attribute on value type

Annotation Redundancy in Hierarchy

Description: Annotation duplicate in hierarchy

Label Label Label

Bad Example
[Obsolete] class Base {} [Obsolete] class Derived : Base {} // Duplicate annotation
Good Example
[Obsolete] class Base {} class Derived : Base {} // Avoid duplicate annotation

Argument In Test Case Attribute

Description: NUnit. Redundant argument in TestCase attribute.

Label Label Label

Bad Example
[TestCase(1, ExpectedResult = 1)] public int Method(int x) { return x; }
Good Example
[TestCase(ExpectedResult = 1)] public int Method() { return 1; }

Argument Instead of Expected Result

Description: NUnit. Redundant argument instead of ExpectedResult.

Label Label Label

Bad Example
[TestCase(1)] public int Method(int x) { return x; }
Good Example
[TestCase(ExpectedResult = 1)] public int Method() { return 1; }

Arguments Style Anonymous Function

Description: Use preferred argument style for anonymous functions

Label Label Label

Bad Example
(x) => { return x * x; };
Good Example
x => x * x;

Arguments Style Literal

Description: Use preferred argument style for literal values

Label Label Label

Bad Example
MethodCall( 42 );
Good Example
MethodCall(42);

Arguments Style Named Expression

Description: Use preferred argument style for named expressions

Label Label Label

Bad Example
MethodCall(argument: 42);
Good Example
MethodCall(42);

Arguments Style Other

Description: Use preferred argument style

Label Label Label

Bad Example
MethodCall( a ,b );
Good Example
MethodCall(a, b);

Assign Null to not Null Attribute

Description: Possible 'null' assignment to non-nullable entity

Label Label Label

Bad Example
public string NotNullProperty { get; set; } = null;
Good Example
public string NotNullProperty { get; set; } = "Default Value";

Assignment Fully Discarded

Description: Assignment results are fully discarded

Label Label Label

Bad Example
value = 10; // Assignment result is never used
Good Example
// Remove or refactor assignment if not used

Assignment in Conditional Expression

Description: Operator = used instead of ==

Label Label Label

Bad Example
if (a = b) { Console.WriteLine("Equal"); }
Good Example
if (a == b) { Console.WriteLine("Equal"); }

Assignment in Conditional Expression

Description: Assignment in conditional expression

Label Label Label

Bad Example
if ((value = GetValue()) != null) { /* ... */ }
Good Example
value = GetValue(); if (value != null) { /* ... */ }

Assignment to Same Variable

Description: Assignment made to same variable

Label Label Label

Bad Example
int x = 5; x = x;
Good Example
int x = 5; x = y;

Async Function without Await

Description: Async function without await expression

Label Label Label

Bad Example
async Task ExampleAsync() { Console.WriteLine("Hello"); }
Good Example
async Task ExampleAsync() { await Task.Delay(1000); Console.WriteLine("Hello"); }

Async Invocation without Await Foreach

Description: Async iterator invocation without 'await foreach'

Label Label Label

Bad Example
var items = GetAsyncItems(); foreach (var item in items) { /* ... */ }
Good Example
var items = GetAsyncItems(); await foreach (var item in items) { /* ... */ }

Async Method Task

Description: NUnit. Async test method must return Task or Task

Label Label Label

Bad Example
public async void TestMethodAsync() { /* ... */ }
Good Example
public async Task TestMethodAsync() { /* ... */ }

Async Void Lambda

Description: Avoid using 'async' lambda when delegate type returns 'void'

Label Label Label

Bad Example
Action action = async () => await Task.Delay(1000);
Good Example
Func<Task> action = async () => await Task.Delay(1000);

Async Void Method

Description: Avoid using 'async' methods with the 'void' return type

Label Label Label

Bad Example
public async void Method() { await Task.Delay(1000); }
Good Example
public async Task Method() { await Task.Delay(1000); }

Async without Await

Description: Async method invocation without await expression

Label Label Label

Bad Example
MethodAsync();
Good Example
await MethodAsync();

Attribute Bounds out of Range

Description: NUnit. Values in range do not fit the type of the test parameter.

Label Label Label

Bad Example
[Range(int.MinValue, int.MaxValue + 1)] public void Method(int x) { /* ... */ }
Good Example
[Range(1, 10)] public void Method(int x) { /* ... */ }

Attribute Modifier Invalid Location

Description: 'attribute modifier' is not a valid attribute location for this declaration. All attributes in this block will be ignored

Label Label Label

Bad Example
[module: Obsolete] class MyClass { }
Good Example
[Obsolete] class MyClass { }

Attribute Produces too Many Tests

Description: NUnit. Specified attribute values produce too many tests.

Label Label Label

Bad Example
[Values(1, 2, 3, ... ,10000)] public void Method(int x) { /* ... */ }
Good Example
[Values(1, 2, 3)] public void Method(int x) { /* ... */ }

Attributes in Section

Description: Join or separate attributes in section

Label Label Label

Bad Example
[Serializable][Obsolete] class Sample {}
Good Example
[Serializable, Obsolete] class Sample {}

Auto Global Property Get Only

Description: Auto-property can be made get-only (non-private accessibility)

Label Label Label

Bad Example
public int Value { get; set; } // Setter is unnecessary
Good Example
public int Value { get; } // Get-only property as no setter needed

Auto Local Property Get Only

Description: Auto-property can be made get-only (private accessibility)

Label Label Label

Bad Example
private int Value { get; set; } // Setter is unnecessary
Good Example
private int Value { get; } // Get-only property as no setter needed

Bad Attribute Brackets Spaces

Description: Incorrect spacing (around attributes).

Label Label Label

Bad Example
[ Obsolete ] public void Method() {}
Good Example
[Obsolete] public void Method() {}

Bad Braces Spaces

Description: Incorrect spacing (around braces).

Label Label Label

Bad Example
public void Method() { int x = 5; }
Good Example
public void Method() {
int x = 5;
}

Bad Child Statement Indent

Description: Incorrect indent (around child statement).

Label Label Label

Bad Example
if (condition) {
int x = 5;
}
Good Example
if (condition) {
int x = 5;
}

Bad Colon Spaces

Description: Incorrect spacing (around colon).

Label Label Label

Bad Example
case 1 : Console.WriteLine("One");
Good Example
case 1: Console.WriteLine("One");

Bad Comma Spaces

Description: Incorrect spacing (around comma)

Label Label Label

Bad Example
var items = new[] {1,2, 3};
Good Example
var items = new[] { 1, 2, 3 };

Bad Control Braces Indent

Description: Incorrect indent (around statement braces)

Label Label Label

Bad Example
if (condition)
{
doSomething();
}
Good Example
if (condition)
{
doSomething();
}

Bad Control Braces Line Breaks

Description: Incorrect line breaks (around statement braces).

Label Label Label

Bad Example
if (condition) { action(); }
Good Example
if (condition)
{
action();
}

Bad Declaration Braces Indent

Description: Incorrect indent (around declaration braces).

Label Label Label

Bad Example
public class Example {
int x = 5;
}
Good Example
public class Example {
int x = 5;
}

Bad Declaration Braces Line Breaks

Description: Incorrect line breaks (around declaration braces)

Label Label Label

Bad Example
public class MyClass
{
public void MyMethod() { doSomething(); }
}
Good Example
public class MyClass
{
public void MyMethod()
{
doSomething();
}
}

Bad Empty Braces Line Breaks

Description: Incorrect line breaks (around empty braces).

Label Label Label

Bad Example
public class Example {
}
Good Example
public class Example {

}

Bad Expression Braces Indent

Description: Incorrect indent (around expression braces).

Label Label Label

Bad Example
var result = (x + y);
if (result > 0) { x = 1; }
Good Example
var result = (x + y);
if (result > 0) {
x = 1;
}

Bad Expression Braces Line Breaks

Description: Incorrect line breaks (around expression braces).

Label Label Label

Bad Example
var result = (x + y);
Good Example
var result = (
x + y
);

Bad Generic Brackets Spaces

Description: Incorrect spacing (around generic brackets)

Label Label Label

Bad Example
List <int> numbers = new List <int>();
Good Example
List<int> numbers = new List<int>();

Bad Indent

Description: Incorrect indent (line indent should not be changed relative to the previous line elsewhere)

Label Label Label

Bad Example
int a = 10;
int b = 20;
int c = 30;
Good Example
int a = 10;
int b = 20;
int c = 30;

Bad Linq Line Breaks

Description: Incorrect line breaks (around LINQ queries).

Label Label Label

Bad Example
var results = items.Where(x => x > 5).Select(x => x * 2);
Good Example
var results = items
.Where(x => x > 5)
.Select(x => x * 2);

Bad List Line Breaks

Description: Incorrect line breaks (around comma in lists)

Label Label Label

Bad Example
var list = new List<int> {
1,
2, 3
};
Good Example
var list = new List<int> {
1,
2,
3
};

Bad Member Access Spaces

Description: Incorrect spacing (around member access symbols)

Label Label Label

Bad Example
myObject . MyMethod ();
Good Example
myObject.MyMethod();

Bad Namespace Braces Indent

Description: Incorrect indent (around namespace braces).

Label Label Label

Bad Example
namespace Example {
class MyClass {}
}
Good Example
namespace Example {
class MyClass {}
}

Bad Parens Line Breaks

Description: Incorrect line breaks (around parenthesis).

Label Label Label

Bad Example
var result = Method(param1, param2, param3);
Good Example
var result = Method(
param1,
param2,
param3
);

Bad Parens Spaces

Description: Incorrect spacing (around parenthesis)

Label Label Label

Bad Example
Console.WriteLine ( "Hello" );
Good Example
Console.WriteLine("Hello");

Bad Preprocessor Indent

Description: Incorrect indent (around preprocessor directive).

Label Label Label

Bad Example
    #if DEBUG
Console.WriteLine("Debug mode");
#endif
Good Example
#if DEBUG
Console.WriteLine("Debug mode");
#endif

Bad Semicolon Spaces

Description: Incorrect spacing (around semicolon)

Label Label Label

Bad Example
int a = 5 ;
Good Example
int a = 5;

Bad Spaces After Keyword

Description: Incorrect spacing (between keyword and parenthesis)

Label Label Label

Bad Example
if( condition )
Good Example
if (condition)

Bad Square Brackets Spaces

Description: Incorrect spacing (around square brackets within a statement)

Label Label Label

Bad Example
var item = array [ i ];
Good Example
var item = array[i];

Bad Switch Braces Indent

Description: Incorrect indent (around switch statement)

Label Label Label

Bad Example
switch (value)
{
case 1:
doSomething();
break;
}
Good Example
switch (value)
{
case 1:
doSomething();
break;
}

Bad Symbol Spaces

Description: Incorrect spacing (around operator symbols)

Label Label Label

Bad Example
int result = a +  b *c;
Good Example
int result = a + b * c;

Base Member Params

Description: Base member has 'params' parameter, but overrider hasn't

Label Label Label

Bad Example
class Base { public virtual void DoSomething(params int[] values) {} } class Derived : Base { public override void DoSomething(int[] values) {} } // 'params' missing
Good Example
class Base { public virtual void DoSomething(params int[] values) {} } class Derived : Base { public override void DoSomething(params int[] values) {} } // Maintained 'params' keyword

Base Method Call With Default Parameter

Description: Call to base member with implicit default parameters

Label Label Label

Bad Example
base.Method(); // Implicit use of default parameter values
Good Example
base.Method(defaultValue); // Explicitly specify default values

Base Object Equals

Description: Call to 'base.Equals(...)' is reference equality

Label Label Label

Bad Example
base.Equals(obj); // Compares reference equality
Good Example
object.Equals(this, obj); // Explicitly call equality method

Base Object Get Hash Code Call

Description: Overridden GetHashCode calls base 'Object.GetHashCode()'

Label Label Label

Bad Example
public override int GetHashCode() { return base.GetHashCode(); }
Good Example
public override int GetHashCode() { return field1.GetHashCode() ^ field2.GetHashCode(); }

Base Type for Parameter

Description: Parameter can be declared with base type

Label Label Label

Bad Example
public void ProcessData(List<int> data) { }
Good Example
public void ProcessData(IEnumerable<int> data) { }

Base Type Parameter

Description: Parameter can be declared with base type

Label Label Label

Bad Example
public ExampleClass(List<int> data) { }
Good Example
public ExampleClass(IEnumerable<int> data) { }

Bitwise Operator Without Flags

Description: Bitwise operation on enum which is not marked by [Flags] attribute

Label Label Label

Bad Example
MyEnum result = MyEnum.Option1 | MyEnum.Option2;
Good Example
[Flags] public enum MyEnum { Option1 = 1, Option2 = 2 } MyEnum result = MyEnum.Option1 | MyEnum.Option2;

By Ref Argument Volatile Field

Description: Captured reference to 'volatile' field will not be treated as 'volatile'

Label Label Label

Bad Example
volatile int field = 0; Task.Run(() => { var value = field; });
Good Example
int localField = field; Task.Run(() => { var value = localField; });

C Sharp Warnings:: C S0108, C S0114

Description: Keyword 'new' is required

Label Label Label

Bad Example
public int Property { get; set; } // Hides base class member without 'new'
Good Example
public new int Property { get; set; }

C Sharp Warnings:: C S0675

Description: Bitwise-or operator used on a sign-extended operand.

Label Label Label

Bad Example
int result = value | 0xFF;
Good Example
int result = value & 0xFF;

C Sharp Warnings:: C S1030

Description: '#warning' directive

Label Label Label

Bad Example
#warning This code needs revision
Good Example
// Consider adding logging here if revision is needed

C Sharp Warnings:: C S1572

Description: XML comment has a 'param' tag for 'Parameter', but there is no parameter by that name

Label Label Label

Bad Example
/// <param name="nonexistentParam">This parameter does not exist</param>
Good Example
/// <param name="actualParam">Description of actual parameter</param>

C Sharp Warnings:: C S1574, C S1584, C S1581, C S1580

Description: Cannot resolve reference in XML comment

Label Label Label

Bad Example
/// <see cref="NonExistentMethod"/>
Good Example
/// <see cref="ExistingMethod"/>

C Sharp Warnings:: C S1587

Description: XML comment is not placed on a valid language element

Label Label Label

Bad Example
/// This is an invalid XML comment
Good Example
/// <summary>This is a valid XML comment for a method or class</summary>

C Sharp Warnings:: C S1711

Description: XML comment has a 'typeparam' tag for 'TypeParameter', but there is no type parameter by that name

Label Label Label

Bad Example
/// <typeparam name="NonexistentType">This type does not exist</typeparam>
Good Example
/// <typeparam name="T">Description of actual type parameter</typeparam>

C Sharp Warnings:: C S1723

Description: XML comment has cref attribute that refers to a type parameter

Label Label Label

Bad Example
/// <see cref="T" />
Good Example
/// <typeparamref name="T" />

C Sharp Warnings:: C S8094

Description: Alignment value 'value' has a magnitude greater than 'magnitude limit' and may result in a large formatted string.

Label Label Label

Bad Example
Console.WriteLine("{0,10000}", value);
Good Example
Console.WriteLine("{0,20}", value);

C Sharp Warnings:: C S8607

Description: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull].

Label Label Label

Bad Example
void Process([NotNull] string data) { Console.WriteLine(data.Length); }
Good Example
void Process([NotNull] string data) { if (data == null) throw new ArgumentNullException(nameof(data)); Console.WriteLine(data.Length); }

C Sharp Warnings:: C S8620

Description: Argument cannot be used for corresponding parameter due to differences in the nullability of reference types.

Label Label Label

Bad Example
void Example(string nonNullable) { AcceptNullable(null); }
Good Example
void Example(string? nullableParam) { AcceptNullable(nullableParam); }

C Sharp Warnings:: C S8624

Description: Argument cannot be used as an output for parameter due to differences in the nullability of reference types.

Label Label Label

Bad Example
void UpdateValue([NotNull] out string? result) { result = null; }
Good Example
void UpdateValue([NotNull] out string result) { result = string.Empty; }

C Sharp Warnings:: C S8625

Description: Cannot convert null literal to non-nullable reference type.

Label Label Label

Bad Example
string nonNullableString = null;
Good Example
string? nullableString = null;

C Sharp Warnings:: C S8656

Description: Call to a non-readonly member from a 'readonly' member results in an implicit copy of 'this'

Label Label Label

Bad Example
readonly void ReadonlyMethod() { NonReadonlyMethod(); }
Good Example
void ReadonlyMethod() { /* Access only readonly members here */ }

C Sharp Warnings:: C S8763

Description: A method marked [DoesNotReturn] should not return.

Label Label Label

Bad Example
[DoesNotReturn] void Terminate() { return; }
Good Example
[DoesNotReturn] void Terminate() { throw new InvalidOperationException(); }

C Sharp Warnings:: C S8971

Description: [InterpolatedStringHandlerArgument] has no effect when applied to lambda parameters and will be ignored at the call site.

Label Label Label

Bad Example
Func<string, bool> func = ([InterpolatedStringHandlerArgument] string input) => true;
Good Example
Func<string, bool> func = (string input) => true;

C Sharp Warnings:: CS0612

Description: Use of obsolete symbol (without message).

Label Label Label

Bad Example
[Obsolete] public int OldProperty { get; set; }
Good Example
public int NewProperty { get; set; }

C Sharp Warnings:: CS0618

Description: Use of obsolete symbol.

Label Label Label

Bad Example
[Obsolete] public void OldMethod() {}
Good Example
public void NewMethod() {}

C Sharp Warnings:: CS0693

Description: Type parameter has the same name as a type parameter from the outer type.

Label Label Label

Bad Example
class Outer { class Inner {} }
Good Example
class Outer { class Inner<U> {} }

C Sharp Warnings:: CS1589

Description: Unable to include XML fragment.

Label Label Label

Bad Example
/// <include file='NonExistent.xml' />
Good Example
/// <include file='ValidFile.xml' />

C Sharp Warnings:: CS1712

Description: Type parameter has no matching typeparam tag in the XML comment.

Label Label Label

Bad Example
/// <summary>Example method</summary>
void Method() {}
Good Example
/// <summary>Example method</summary>
/// <typeparam name="T">Type parameter</typeparam>
void Method() {}

C Sharp Warnings:: CS1981

Description: Using 'is' to test compatibility with 'dynamic' is essentially identical to testing compatibility with 'Object' and will succeed for all non-null values.

Label Label Label

Bad Example
if (obj is dynamic) {}
Good Example
if (obj is not null) {}

C Sharp Warnings:: CS8383

Description: The tuple element name is ignored because a different name or no name is specified on the other side of the tuple == or != operator.

Label Label Label

Bad Example
(int first, int second) == (int one, int two);
Good Example
(int first, int second) == (int first, int second);

C Sharp Warnings:: CS8597

Description: Thrown value may be null.

Label Label Label

Bad Example
throw null;
Good Example
throw new InvalidOperationException("Error message");

C Sharp Warnings:: CS8605

Description: Unboxing a possibly null value.

Label Label Label

Bad Example
int value = (int)nullableObject;
Good Example
int? value = nullableObject as int?;

C Sharp Warnings:: CS8645

Description: Type is already listed in the interface list with different nullability of reference types.

Label Label Label

Bad Example
interface IExample<T, T?> {}
Good Example
interface IExample {}

C Sharp Warnings:: CS8860

Description: Types and aliases should not be named 'record'.

Label Label Label

Bad Example
class record {}
Good Example
class RecordExample {}

Call to GetType

Description: Possible mistaken call to GetType()

Label Label Label

Bad Example
if (obj.GetType() == typeof(string)) { }
Good Example
if (obj is string) { }

Call to GetType

Description: Possible mistaken call to GetType()

Label Label Label

Bad Example
if (this.GetType() == typeof(MyClass)) { }
Good Example
if (this is MyClass) { }

CallerArgumentExpression Invalid Parameter Name

Description: The CallerArgumentExpressionAttribute is applied with an invalid parameter name.

Label Label Label

Bad Example
public void Log(string message, [CallerArgumentExpression("invalidParam")] string paramName = "") {}
Good Example
public void Log(string message, [CallerArgumentExpression("message")] string paramName = "") {}

CallerArgumentExpression Is Self-Referential

Description: The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-referential.

Label Label Label

Bad Example
public void Validate(string value, [CallerArgumentExpression("value")] string? message = null) {}
Good Example
public void Validate(string value, [CallerArgumentExpression("value")] string? paramName = null) {}

CallerArgumentExpression Overridden by CallerFilePathAttribute

Description: The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerFilePathAttribute

Label Label Label

Bad Example
public void Log([CallerArgumentExpression("message")] string filePath = "") {}
Good Example
public void Log(string message, string filePath = "") {}

CallerArgumentExpression Overridden by CallerLineNumberAttribute

Description: The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerLineNumberAttribute

Label Label Label

Bad Example
public void Log([CallerArgumentExpression("message")] string lineNumber = "") {}
Good Example
public void Log(string message, int lineNumber = 0) {}

CallerArgumentExpression Overridden by CallerMemberNameAttribute

Description: The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerMemberNameAttribute

Label Label Label

Bad Example
public void Log([CallerArgumentExpression("message")] string callerName = "") {}
Good Example
public void Log(string message, [CallerMemberName] string callerName = "") {}

CallerArgumentExpression Used in Invalid Context

Description: The CallerArgumentExpressionAttribute will have no effect because it applies to a member that is used in contexts that do not allow optional arguments

Label Label Label

Bad Example
public void LogMessage([CallerArgumentExpression("message")] string paramName) {}
Good Example
public void LogMessage(string message, [CallerArgumentExpression("message")] string paramName = "") {}

Cannot Apply Equality Operator

Description: Compare with '==' types marked by 'CannotApplyEqualityOperatorAttribute'

Label Label Label

Bad Example
if (customType1 == customType2) {}
Good Example
if (customType1.Equals(customType2)) {}

Cast to non Nullable

Description: Converting null literal or possible null value to non-nullable type.

Label Label Label

Bad Example
string nonNullableString = (string)null;
Good Example
string? nullableString = null; /* Or handle possible null */

Check for Reference Equality

Description: Check for reference equality instead

Label Label Label

Bad Example
if (str1 == str2) { // Risky, checks for value equality rather than reference equality }
Good Example
if (ReferenceEquals(str1, str2)) { // Checks for reference equality }

Check for Reference Equality

Description: Check for reference equality instead

Label Label Label

Bad Example
if (object1 == object2) { // Value equality check, not reference }
Good Example
if (ReferenceEquals(object1, object2)) { // Proper reference equality check }

Check for Reference Equality

Description: Check for reference equality instead

Label Label Label

Bad Example
if (item1 == item2) { // Value equality check instead of reference }
Good Example
if (ReferenceEquals(item1, item2)) { // Proper reference equality check }

Check for Reference Equality

Description: Check for reference equality instead

Label Label Label

Bad Example
if (objA == objB) { // Checks value equality instead of reference }
Good Example
if (ReferenceEquals(objA, objB)) { // Uses reference equality as preferred }

Check Namespace

Description: Namespace does not correspond to file location

Label Label Label

Bad Example
namespace IncorrectNamespace {}
Good Example
namespace CorrectNamespace {}

Class Instantiation

Description: Class cannot be instantiated.

Label Label Label

Bad Example
var obj = new AbstractClass();
Good Example
// Use a derived class instead
var obj = new ConcreteClass();

Co-variant Array Conversion

Description: Co-variant array conversion

Label Label Label

Bad Example
object[] array = new string[10];
Good Example
string[] array = new string[10];

Collection Count Property

Description: Use collection's count property

Label Label Label

Bad Example
if (list.Length > 0) { /* do something */ }
Good Example
if (list.Count > 0) { /* do something */ }

Comment Typo

Description: Typo in comment

Label Label Label

Bad Example
// This is a cmment with a typo.
Good Example
// This is a comment with correct spelling.

Compare non Constrained Generic with Null

Description: Possible comparison of value type with 'null'

Label Label Label

Bad Example
public bool IsNull(T value) { return value == null; } // Comparisons with null on value types
Good Example
public bool IsNull(T? value) where T : struct { return value == null; } // Nullable constraint

Compiler Unused Local Function

Description: Compiler: local function is never used

Label Label Label

Bad Example
void UnusedFunction() { /* some code */ }
Good Example
// Remove or use the local function if necessary

Conditional Ternary Equal Branch

Description: '?:' expression has identical true and false branches

Label Label Label

Bad Example
var result = condition ? value : value;
Good Example
var result = value;

Conditional Ternary Expression

Description: Simplify conditional ternary expression

Label Label Label

Bad Example
var result = condition ? true : false;
Good Example
var result = condition;

Confusing Char as Integer

Description: Char is possibly unintentionally used as integer

Label Label Label

Bad Example
var number = new MyClass('A');
Good Example
var number = new MyClass((int)'A');

Constant Conditional Access Qualifier

Description: Conditional access qualifier expression is known to be null or not null

Label Label Label

Bad Example
var length = obj?.Length; // if obj is guaranteed non-null
Good Example
var length = obj.Length; // Remove conditional access if obj is non-null

Constant Null Coalescing Condition

Description: '??' condition is known to be null or not null

Label Label Label

Bad Example
string result = value ?? "default"; // if value is always non-null
Good Example
string result = value; // Remove null coalescing if unnecessary

Constructor Initializer Loop

Description: Possible cyclic constructor call

Label Label Label

Bad Example
public ClassA() : this(0) { } public ClassA(int x) : this() { } // Recursive call causes stack overflow
Good Example
public ClassA() : this(0) { } public ClassA(int x) { } // Avoid recursive constructor calls

Constructor Invocation

Description: Remove constructor invocation

Label Label Label

Bad Example
var date = new DateTime(); // Redundant constructor invocation
Good Example
var date = DateTime.Now; // Uses DateTime's Now property instead of constructor

Constructor Or Destructor Body

Description: Use preferred body style (convert to constructor or destructor with preferred body style)

Label Label Label

Bad Example
public MyClass() { /* constructor code */ }
Good Example
public MyClass() => /* constructor code */;

Container Annotation Redundancy

Description: Container nullability attribute usage with declaration of non-container type

Label Label Label

Bad Example
[NotNull] int number; // Non-container type annotated with container nullability
Good Example
int number; // Container nullability attribute removed from non-container type

Contract Annotation not Parsed

Description: Problem in contract annotation definition

Label Label Label

Bad Example
[ContractAnnotation("null=>null;")]
Good Example
[ContractAnnotation("=>null; notnull=>notnull")]

Control Transfer Statement

Description: Separate control transfer statement with blank line

Label Label Label

Bad Example
return;continue;
Good Example
return;

continue;

Convert Closure to Method Group

Description: Convert lambda expression to method group.

Label Label Label

Bad Example
Action action = () => Method();
Good Example
Action action = Method;

Convert Global to Constant

Description: Convert local variable or field to constant (non-private accessibility)

Label Label Label

Bad Example
public int exampleValue = 10;
Good Example
public const int ExampleValue = 10;

Convert Local to Constant

Description: Convert local variable or field to constant (private accessibility)

Label Label Label

Bad Example
private int exampleValue = 10;
Good Example
private const int ExampleValue = 10;

Convert to Lambda Expression

Description: Convert to lambda expression

Label Label Label

Bad Example
Func<int, int> square = delegate(int x) { return x * x; };
Good Example
Func<int, int> square = x => x * x;

Convert to Lambda Expression

Description: Convert to lambda expression (when possible)

Label Label Label

Bad Example
Action action = delegate { Console.WriteLine("Hello"); };
Good Example
Action action = () => Console.WriteLine("Hello");

Convert to Static Class

Description: Convert to static class

Label Label Label

Bad Example
public class Helper { public static void DoWork() { } }
Good Example
public static class Helper { public static void DoWork() { } }

Convert to Using Declaration

Description: Convert to 'using' declaration

Label Label Label

Bad Example
using (var reader = new StreamReader(path)) { /* ... */ }
Good Example
using var reader = new StreamReader(path);

Default Namespace

Description: Namespace should be default namespace of this project

Label Label Label

Bad Example
namespace AnotherNamespace { }
Good Example
namespace ProjectNamespace { }

Default Value Applied to Member

Description: Default value specified for parameter will have no effect because it applies to a member that is used in contexts that do not allow optional arguments

Label Label Label

Bad Example
void Method(int x = 5) { }
Good Example
void Method(int x) { } /* Move optional value to calling code */

Default Value Attribute for Optional Parameter

Description: Possibly misleading 'DefaultValueAttribute' usage to define optional parameter value

Label Label Label

Bad Example
public void Method([DefaultValue(5)] int param = 0) { } // Misleading use of DefaultValueAttribute
Good Example
public void Method(int param = 5) { } // Correctly defines default value for parameter

Default Value Evident Type

Description: Use preferred style of default value expression when type is evident

Label Label Label

Bad Example
int number = default(int);
Good Example
int number = 0;

Default Value Not Evident Type

Description: Use preferred style of default value expression when type is not evident

Label Label Label

Bad Example
var items = new List<int> { default(int) };
Good Example
var items = new List<int> { 0 };

Disallowed Tabs

Description: Usage of tabulation character for indentation is prohibited

Label Label Label

Bad Example
	int value = 42;
Good Example
    int value = 42;

Discard Declaration Var Style

Description: Use preferred style for discard declaration

Label Label Label

Bad Example
var _ = GetValue();
Good Example
_ = GetValue();

Division by Zero

Description: Division by zero in at least one execution path.

Label Label Label

Bad Example
int result = value / divisor; // Potential division by zero
Good Example
int result = divisor != 0 ? value / divisor : 0; // Check for zero divisor

Do While Statement Braces

Description: Use preferred braces style (enforce braces in 'do-while' statement)

Label Label Label

Bad Example
do Console.WriteLine("Hello"); while(condition);
Good Example
do { Console.WriteLine("Hello"); } while(condition);

Double Negation in Pattern

Description: Simplify negated pattern

Label Label Label

Bad Example
if (!!isActive) { ... }
Good Example
if (isActive) { ... }

Double Negation in Pattern

Description: Simplify negated pattern

Label Label Label

Bad Example
if (!!isActive) { ... }
Good Example
if (isActive) { ... }

Double Negation Operator

Description: Double negation operator

Label Label Label

Bad Example
bool result = !!isTrue; // Double negation
Good Example
bool result = isTrue; // Removes unnecessary negation

Duplicate Values

Description: NUnit. Duplicate values

Label Label Label

Bad Example
[TestCase(1)] [TestCase(1)] public void Test(int value) { /* ... */ }
Good Example
[TestCase(1)] [TestCase(2)] public void Test(int value) { /* ... */ }

Dynamic Shift Right

Description: Right operand of dynamic shift operation should be convertible to 'int'

Label Label Label

Bad Example
dynamic shiftAmount = 2.5; int value = 1 << shiftAmount;
Good Example
int shiftAmount = 2; int value = 1 << shiftAmount;

Empty Catch Clause

Description: Empty general catch clause

Label Label Label

Bad Example
try { /* code */ } catch { /* Empty catch block */ }
Good Example
try { /* code */ } catch (Exception ex) { Console.WriteLine(ex.Message); }

Empty Constructor

Description: Empty constructor

Label Label Label

Bad Example
public MyClass() { } // Constructor is empty
Good Example
// Removed empty constructor

Empty Destructor

Description: Empty destructor

Label Label Label

Bad Example
~MyClass() { } // Destructor is empty
Good Example
// Removed empty destructor

Empty Embedded Statement

Description: Empty control statement body

Label Label Label

Bad Example
if (condition) ;
Good Example
if (condition) { DoSomething(); }

Empty For Statement

Description: Empty 'for' loop is redundant

Label Label Label

Bad Example
for (int i = 0; i < 10; i++); // Empty for loop
Good Example
for (int i = 0; i < 10; i++) { /* meaningful work */ }

Empty Namespace

Description: Empty namespace declaration

Label Label Label

Bad Example
namespace MyNamespace { } // Namespace is empty
Good Example
// Removed empty namespace declaration

Empty Statement

Description: Empty statement is redundant

Label Label Label

Bad Example
;
Good Example
// Removed unnecessary statement

Empty Switch Block

Description: A switch block must have one or more case or default statements.

Label Label Label

Bad Example
switch (value) { }
Good Example
switch (value) { case 1: /* handle case */ break; default: /* handle default */ break; }

Entity Name Non-Private Accessibility

Description: Entity is only used to capture its name (non-private accessibility)

Label Label Label

Bad Example
public class MyEntity { } // Only declared to capture its name
Good Example
// Removed unused entity declaration

Entity Name Private Accessibility

Description: Entity is only used to capture its name (private accessibility)

Label Label Label

Bad Example
private class MyEntity { } // Only declared to capture its name
Good Example
// Removed unused entity declaration

Enum Underlying Type

Description: Underlying type of enum is 'int'

Label Label Label

Bad Example
enum Status : int { Active, Inactive }
Good Example
enum Status { Active, Inactive } // int is default underlying type

Enumerable Sum Unchecked Context

Description: 'Enumerable.Sum' invocation in explicit unchecked context

Label Label Label

Bad Example
unchecked { var sum = numbers.Sum(); }
Good Example
var sum = numbers.Sum(); // Avoid explicit unchecked context

EnumeratorCancellation Attribute Misused

Description: The 'EnumeratorCancellation' attribute is only effective on a parameter of type 'CancellationToken' in an async-iterator method returning 'IAsyncEnumerable'.

Label Label Label

Bad Example
[EnumeratorCancellation] int count;
Good Example
public async IAsyncEnumerable<int> GenerateAsync([EnumeratorCancellation] CancellationToken cancellationToken) {}

Equal Expression Comparison

Description: Similar expressions comparison

Label Label Label

Bad Example
if (a == a) { /* always true */ }
Good Example
if (a == b) { /* logic */ }

Equality Operator without Equals or GetHashCode Override

Description: Operator '==' or operator '!=' with 'Object.Equals(object o)' and 'Object.GetHashCode()' not overridden

Label Label Label

Bad Example
public class MyClass { public static bool operator ==(MyClass a, MyClass b) => a.Equals(b); }
Good Example
public class MyClass { public static bool operator ==(MyClass a, MyClass b) => a.Equals(b); public override bool Equals(object obj) { /*implementation*/ } public override int GetHashCode() { /*implementation*/ } }

Event Never Invoked

Description: Event never invoked

Label Label Label

Bad Example
public event EventHandler MyEvent; // Declared but never invoked
Good Example
public event EventHandler MyEvent; protected void OnMyEvent() { MyEvent?.Invoke(this, EventArgs.Empty); }

Event Unsubscription

Description: Event unsubscription via anonymous delegate

Label Label Label

Bad Example
eventHandler -= (s, e) => { /* anonymous delegate */ };
Good Example
EventHandler handler = (s, e) => { /* named handler */ }; eventHandler -= handler;

Expected Result in Test Case Attribute

Description: NUnit. Redundant expected result for void test method.

Label Label Label

Bad Example
[TestCase(ExpectedResult = 2)] public void Method() { /* ... */ }
Good Example
[TestCase] public void Method() { /* ... */ }

Explicit Caller Info Argument

Description: Explicit argument passed to parameter with caller info attribute

Label Label Label

Bad Example
LogMessage("Log", "explicitFileName.cs");
Good Example
LogMessage("Log"); // Caller info auto-populated

Expression Always False

Description: The given expression of 'is' operator is never of the provided type

Label Label Label

Bad Example
if (obj is int) { } // obj is never an int in this context
Good Example
// Avoid redundant type checks in code

Expression Always Matches Constant

Description: The given expression always matches the provided constant.

Label Label Label

Bad Example
if (value == 5 && value == 5) { /* code */ }
Good Example
if (value == 5) { /* code */ }

Expression Always Null

Description: Expression is always 'null'

Label Label Label

Bad Example
if (obj == null) { obj.ToString(); } // Expression is always null
Good Example
if (obj != null) { obj.ToString(); } // Proper null check

Expression Always of Provided Type

Description: Given expression is always of the provided type

Label Label Label

Bad Example
if (myString is string) { /* Always true */ }
Good Example
if (myString != null) { /* Check for non-null string */ }

Expression Always True

Description: The given expression of 'is' operator is always of the provided type

Label Label Label

Bad Example
if (obj is string) { } // 'obj' is always a string in this context
Good Example
if (obj is string str && str.Length > 0) { } // Check used meaningfully

Expression Constant Result

Description: According to values of the bit masks, expression result will always be the same.

Label Label Label

Bad Example
bool result = (value & mask) == mask;
Good Example
bool result = value == mask;

Expression Matching Pattern

Description: Given expression always matches the provided pattern

Label Label Label

Bad Example
if (obj is object) { /* Always true */ }
Good Example
if (obj != null) { /* Null check */ }

Expression Never Matches Pattern

Description: The given expression never matches the provided pattern.

Label Label Label

Bad Example
if (value is string s && value is int) { /* code */ }
Good Example
if (value is int v) { /* code */ }

Expression not of Provided Type

Description: Given expression is never of the provided type

Label Label Label

Bad Example
if (myInt is string) { /* Always false */ }
Good Example
if (myObj is string str) { /* Only execute if myObj is a string */ }

Expression Same Value

Description: Expression is always 'true' or always 'false'

Label Label Label

Bad Example
if (5 > 3) { ... } // Condition always true
Good Example
if (x > 3) { ... } // Condition depends on variable value

Field Property Default Implementation

Description: Field hides property with default implementation in interface

Label Label Label

Bad Example
public class MyClass : IMyInterface { public int MyProperty; }
Good Example
public class MyClass : IMyInterface { public int MyProperty { get; set; } }

Field Property Method Test Case Source

Description: NUnit. Test case source must be field, property, or method.

Label Label Label

Bad Example
[TestCaseSource("nonFieldPropertyOrMethod")] public void Method() { /* ... */ }
Good Example
[TestCaseSource("DataSource")] public void Method() { /* ... */ }

Filter Expression Constant

Description: Filter expression is a constant, consider removing the filter

Label Label Label

Bad Example
catch (Exception) when (true) { /* This filter is redundant */ }
Good Example
catch (Exception ex) when (ex is SomeSpecificException) { /* Valid conditional handling */ }

Finalize Method Interfere

Description: Introducing a 'Finalize' method can interfere with destructor invocation

Label Label Label

Bad Example
public void Finalize() { /* Interferes with destructor */ }
Good Example
~MyClass() { /* Use destructor instead */ }

Fixed Statement Braces

Description: Use preferred braces style (enforce braces in 'fixed' statement)

Label Label Label

Bad Example
fixed (int* p = arr) Console.WriteLine(*p);
Good Example
fixed (int* p = arr) { Console.WriteLine(*p); }

Float Comparison

Description: Equality comparison of floating point numbers

Label Label Label

Bad Example
if (a == b) { /* risky float comparison */ }
Good Example
if (Math.Abs(a - b) < 0.0001) { /* safer float comparison */ }

For Converted to Foreach

Description: For-loop can be converted into foreach-loop

Label Label Label

Bad Example
for (int i = 0; i < items.Length; i++) { Console.WriteLine(items[i]); }
Good Example
foreach (var item in items) { Console.WriteLine(item); }

For Statement Braces

Description: Use preferred braces style (enforce braces in 'for' statement)

Label Label Label

Bad Example
for (int i = 0; i < 10; i++) Console.WriteLine(i);
Good Example
for (int i = 0; i < 10; i++) { Console.WriteLine(i); }

For Statement Condition Always True

Description: 'true' is redundant as 'for'-statement condition

Label Label Label

Bad Example
for (; true;) { ... } // Condition 'true' is redundant
Good Example
for (;;) { ... } // Simplified by removing redundant 'true'

Foreach Converted to Query

Description: Foreach loop can be converted into LINQ-expression but another 'GetEnumerator' method will be used

Label Label Label

Bad Example
foreach (var item in collection) { if (item.IsValid) result.Add(item); }
Good Example
result.AddRange(collection.Where(item => item.IsValid));

Foreach Partly Converted to Query

Description: Part of foreach loop can be converted into LINQ-expression but another 'GetEnumerator' method will be used

Label Label Label

Bad Example
foreach (var item in collection) { if (item.IsActive) result.Add(item); }
Good Example
result.AddRange(collection.Where(item => item.IsActive));

Foreach Statement Braces

Description: Use preferred braces style (enforce braces in 'foreach' statement)

Label Label Label

Bad Example
foreach (var item in collection) Console.WriteLine(item);
Good Example
foreach (var item in collection) { Console.WriteLine(item); }

Format Specifier in Format String

Description: Use format specifier in format strings

Label Label Label

Bad Example
string result = string.Format("Value: {0}", value);
Good Example
string result = string.Format("Value: {0:F2}", value); // Use format specifier

Format String Problem

Description: String formatting method problems

Label Label Label

Bad Example
string message = string.Format("Value: {0}");
Good Example
string message = string.Format("Value: {0}", value);

Function Complexity Overflow

Description: Function body is too complex to analyze

Label Label Label

Bad Example
public void ComplexFunction() { /* Highly nested logic */ }
Good Example
public void ComplexFunction() { /* Refactored into smaller methods */ }

Function never Returns

Description: Function never returns

Label Label Label

Bad Example
int InfiniteLoop() { while (true) { } }
Good Example
int FiniteLoop(int limit) { int i = 0; while (i < limit) { i++; } return i; }

Function Recursive Paths

Description: Function is recursive on all execution paths

Label Label Label

Bad Example
int RecursiveFunction(int n) { return RecursiveFunction(n - 1); }
Good Example
int RecursiveFunction(int n) { return n > 0 ? RecursiveFunction(n - 1) : 0; }

GC Suppress Finalize Missing Destructor

Description: 'GC.SuppressFinalize' is invoked for type without destructor

Label Label Label

Bad Example
GC.SuppressFinalize(this);
Good Example
public class MyClass { ~MyClass() { } public void Dispose() { GC.SuppressFinalize(this); } }

Generic Enumerator not Disposed

Description: Instance of IEnumerator is never disposed

Label Label Label

Bad Example
IEnumerator enumerator = collection.GetEnumerator(); while (enumerator.MoveNext()) { /* ... */ }
Good Example
using (IEnumerator enumerator = collection.GetEnumerator()) { while (enumerator.MoveNext()) { /* ... */ } }

GetCurrentMethod Declared to Return a Null Value

Description: Dereference of a possibly null reference.

Label Label Label

Bad Example
int length = nullableString.Length;
Good Example
if (nullableString != null) { int length = nullableString.Length; }

GetHashCode No Override

Description: Class overrides Object.Equals(object o) but not Object.GetHashCode()

Label Label Label

Bad Example
public override bool Equals(object obj) { /* Equality logic */ }
Good Example
public override bool Equals(object obj) { /* Equality logic */ } public override int GetHashCode() { /* Hash logic */ }

Global Class Never Instantiated

Description: Class is never instantiated (non-private accessibility)

Label Label Label

Bad Example
public class UnusedClass { /* class implementation */ }
Good Example
public class UsedClass { /* class implementation */ } new UsedClass();

Global Class Sealed

Description: Class can be made sealed (non-inheritable) (non-private accessibility)

Label Label Label

Bad Example
public class MyClass { /* Implementation */ } // Can be inherited, even though inheritance is unnecessary
Good Example
public sealed class MyClass { /* Implementation */ } // Sealed to prevent inheritance where it is not intended

Global Collection Never Queried

Description: Collection's content is never queried (non-private accessibility)

Label Label Label

Bad Example
public List<int> numbers = new List<int> { 1, 2, 3 };
Good Example
public List<int> numbers = new List<int> { 1, 2, 3 }; Console.WriteLine(numbers.Count);

Global Collection Never Updated

Description: Collection is never updated (non-private accessibility)

Label Label Label

Bad Example
public List<int> numbers = new List<int>();
Good Example
public List<int> numbers = new List<int> { 1, 2, 3 };

Global Event Never Invoked

Description: Abstract or virtual (overridable) event is never invoked

Label Label Label

Bad Example
public virtual event EventHandler MyEvent;
Good Example
public virtual event EventHandler MyEvent; protected void RaiseMyEvent() { MyEvent?.Invoke(this, EventArgs.Empty); }

Global Field Read Only

Description: Field can be made readonly (non-private accessibility)

Label Label Label

Bad Example
public int Value = 10; // Field can be modified outside constructor
Good Example
public readonly int Value = 10; // Field is readonly and cannot be modified after initialization

Global Member Private

Description: Member can be made private (non-private accessibility)

Label Label Label

Bad Example
public int exampleValue = 10;
Good Example
private int exampleValue = 10;

Global Member Protected

Description: Member can be made protected (non-private accessibility)

Label Label Label

Bad Example
public int exampleValue = 10;
Good Example
protected int exampleValue = 10;

Global Member Static

Description: Member can be made static (shared) (non-private accessibility)

Label Label Label

Bad Example
public int exampleValue = 10;
Good Example
public static int ExampleValue = 10;

Global Parameter Type

Description: Parameter type can be IEnumerable (non-private accessibility)

Label Label Label

Bad Example
public void PrintData(List<string> data) { }
Good Example
public void PrintData(IEnumerable<string> data) { }

Global Property Init Only

Description: Property can be made init-only (non-private accessibility)

Label Label Label

Bad Example
public string Name { get; set; } // Allows modification after initialization
Good Example
public string Name { get; init; } // Init-only property, only settable during object initialization

Global Return Type IEnumerable

Description: Return type can be IEnumerable (non-private accessibility)

Label Label Label

Bad Example
public List<int> GetValues() { return new List<int>(); }
Good Example
public IEnumerable<int> GetValues() { return new List<int>(); }

GoTo Value not Convertible

Description: 'goto case' value is not implicitly convertible to required type

Label Label Label

Bad Example
switch (value) { case 1: goto case 2.0; }
Good Example
switch (value) { case 1: /* handle */ break; case 2: /* handle */ break; }

Hidden Static Member

Description: Member hides static member from outer class

Label Label Label

Bad Example
public class Outer { public static int value; class Inner { int value; } } // Hides static 'value'
Good Example
public class Outer { public static int value; class Inner { int innerValue; } } // Clear variable naming

Identifier Typo

Description: Typo in identifier

Label Label Label

Bad Example
int mispelledVariable = 10;
Good Example
int misspelledVariable = 10;

IEnumerable Test Case Source

Description: NUnit. Test case source must be non-abstract and implement IEnumerable.

Label Label Label

Bad Example
[TestCaseSource(typeof(NonEnumerableSource))] public void Method() { /* ... */ }
Good Example
[TestCaseSource(typeof(EnumerableSource))] public void Method() { /* ... */ }

If Statement Braces

Description: Use preferred braces style (enforce braces in 'if' statement)

Label Label Label

Bad Example
if (condition) Console.WriteLine("Hello");
Good Example
if (condition) { Console.WriteLine("Hello"); }

Ignored Parameter Attribute

Description: NUnit. Ignored parameter attribute

Label Label Label

Bad Example
[TestCase(Ignore="Reason")] public void Test() { /* ... */ }
Good Example
[Ignore("Reason")] public void Test() { /* ... */ }

Implicit Dereference of Possibly Null Member

Description: Object or collection initializer implicitly dereferences possibly null member.

Label Label Label

Bad Example
var obj = new MyClass { Name = nullableName }; // nullableName may be null
Good Example
var obj = new MyClass { Name = nullableName ?? "Default" }; // Provides default if null

Implicit Unspecified Null Values

Description: NUnit. Implicitly unspecified null values

Label Label Label

Bad Example
[TestCase(null)] public void Test(string value) { /* ... */ }
Good Example
[TestCase((string?)null)] public void Test(string? value) { /* ... */ }

Inconsistent Naming

Description: Inconsistent Naming

Label Label Label

Bad Example
public int myVariable;
Good Example
public int MyVariable;

Inconsistent Nullability in Partial Method Declaration

Description: Partial method declarations have inconsistent nullability for type parameter.

Label Label Label

Bad Example
partial void ProcessData(T? data); partial void ProcessData(T data);
Good Example
partial void ProcessData(T data); partial void ProcessData(T data);

Inconsistent Order of Locks

Description: Inconsistent order of taken locks

Label Label Label

Bad Example
lock (lock1) { lock (lock2) { /* Code */ } } // Reversed order elsewhere
Good Example
lock (lock2) { lock (lock1) { /* Code */ } } // Consistent locking order

Inconsistently Synchronized Field

Description: Inconsistent synchronization on field

Label Label Label

Bad Example
lock (lockObject) { field++; } // Field accessed without lock elsewhere
Good Example
lock (lockObject) { field++; } // Always accessed within lock

Incorrect Argument Type

Description: NUnit. Incompatible argument type or incorrect argument value

Label Label Label

Bad Example
[TestCase(1.5)] public void Test(int value) { /* ... */ }
Good Example
[TestCase(1)] public void Test(int value) { /* ... */ }

Incorrect Argument Type

Description: NUnit.AutoFixture. Incompatible argument type or incorrect argument value.

Label Label Label

Bad Example
[AutoData] public void Method(string x) { /* ... */ }
Good Example
[AutoData] public void Method(int x) { /* ... */ }

Incorrect Blank Lines Near Braces

Description: Incorrect blank lines (incorrect number of blank lines near braces).

Label Label Label

Bad Example
public class Example {

void Method() {

}
Good Example
public class Example {

void Method() {
}

}

Incorrect Expected Result Type

Description: NUnit. Incompatible expected result type or incorrect value

Label Label Label

Bad Example
[TestCase(5, ExpectedResult="5")] public int Test(int value) { return value; }
Good Example
[TestCase(5, ExpectedResult=5)] public int Test(int value) { return value; }

Incorrect Range Bounds

Description: NUnit. Incorrect range bounds. 'to' must be greater than or equal to 'from'

Label Label Label

Bad Example
[Range(10, 5, 1)] public void Test(int value) { /* ... */ }
Good Example
[Range(5, 10, 1)] public void Test(int value) { /* ... */ }

Incorrect signature in XML comment

Description: Invalid Type for 'parameter number' in XML comment

Label Label Label

Bad Example
/// <param name="str">String parameter</param> void Method(int number) { }
Good Example
/// <param name="number">Integer parameter</param> void Method(int number) { }

Indexing by Invalid Range

Description: Possible 'System.ArgumentOutOfRangeException'. Start index should be less than or equal to end index

Label Label Label

Bad Example
var substring = text.Substring(5, 2); // when text.Length < 7
Good Example
if (text.Length >= 7) { var substring = text.Substring(5, 2); }

Inheritdoc Consider Usage

Description: Use on root level to inherit documentation from base candidate.

Label Label Label

Bad Example
/// <summary>Does something.</summary>
Good Example
<inheritdoc /> // Use to inherit documentation when available

Inheritdoc Invalid Usage

Description: Usage of is invalid.

Label Label Label

Bad Example
<inheritdoc /> // in a non-root element
Good Example
<inheritdoc /> // in a root-level element inheriting from a base class or interface

Initializer Value Ignored

Description: Member initialized value ignored

Label Label Label

Bad Example
public int Value { get; set; } = 10; // Later set to a different value, ignoring initializer
Good Example
public int Value { get; set; } = 10; // Initial value honored in logic

Inline out Variable Declaration

Description: Inline 'out' variable declaration

Label Label Label

Bad Example
int result; bool success = int.TryParse(input, out result);
Good Example
bool success = int.TryParse(input, out int result);

Inline Temporary Variable

Description: Inline temporary variable

Label Label Label

Bad Example
int temp = GetResult(); return temp;
Good Example
return GetResult();

Int Variable Overflow

Description: Possible overflow.

Label Label Label

Bad Example
int overflow = int.MaxValue + 1;
Good Example
int max = int.MaxValue; /* handle overflow scenario */

Int Variable Overflow in Checked Context

Description: Possible overflow in checked context.

Label Label Label

Bad Example
checked { int max = int.MaxValue + 1; }
Good Example
checked { int max = int.MaxValue; /* handle overflow */ }

Int Variable Overflow in Unchecked Context

Description: Possible overflow in unchecked context.

Label Label Label

Bad Example
unchecked { int max = int.MaxValue + 1; }
Good Example
unchecked { int max = int.MaxValue; /* handle overflow */ }

Interpolated String Expression Not IFormattable

Description: Formatting is specified, but interpolated string expression is not IFormattable

Label Label Label

Bad Example
Console.WriteLine($"Value: {myObject:F2}");
Good Example
Console.WriteLine($"Value: {((IFormattable)myObject).ToString("F2", null)}");

Introduce Optional Global Parameters

Description: Introduce optional parameters (non-private accessibility).

Label Label Label

Bad Example
public void Method(int x) { /* ... */ }
Good Example
public void Method(int x = 0) { /* ... */ }

Introduce Optional Local Parameters

Description: Introduce optional parameters (private accessibility).

Label Label Label

Bad Example
private void Method(int x) { /* ... */ }
Good Example
private void Method(int x = 0) { /* ... */ }

Invalid Attribute Modifier Specified

Description: 'attribute modifier' is not a recognized attribute location. All attributes in this block will be ignored

Label Label Label

Bad Example
[method: Obsolete] void Example() { }
Good Example
[Obsolete] void Example() { }

Invalid Module Name

Description: Module with this name does not exist

Label Label Label

Bad Example
PublicDependencyModuleNames.Add("NonExistentModule");
Good Example
PublicDependencyModuleNames.Add("ValidModule");

Invalid Xml Comment

Description: Invalid XML documentation comment

Label Label Label

Bad Example
/// Summary with unmatched < tags
Good Example
/// <summary>Valid XML documentation comment</summary>

Invalid XML in XML comment

Description: XML Comment on 'construct' badly formed XML

Label Label Label

Bad Example
/// <summary> This is an <unclosed> tag </summary>
Good Example
/// <summary> This is a properly closed tag </summary>

Invalid XML Include Element

Description: Invalid XML include element

Label Label Label

Bad Example
/// <include file='NonExistentFile.xml' />
Good Example
/// <include file='ValidFile.xml' path='Docs/Member[@name="M:Method"]' />

Invert Condition

Description: Invert condition

Label Label Label

Bad Example
if (!isAvailable) { /* Action if unavailable */ } else { /* Action if available */ }
Good Example
if (isAvailable) { /* Action if available */ } else { /* Action if unavailable */ } // Inverted condition for readability

Invert if

Description: Invert 'if' statement to reduce nesting.

Label Label Label

Bad Example
if (condition) { /* nested code */ } else { return; }
Good Example
if (!condition) { return; } /* flattened code */

Invocation Skipped

Description: Method invocation is skipped

Label Label Label

Bad Example
int x = 5; x; // x is evaluated, but the result is not used, effectively skipping any invocation
Good Example
int x = 5; Console.WriteLine(x); // Properly invoking a method to use the value of x

Invoke as Extension Method

Description: Convert static method invocation to extension method call

Label Label Label

Bad Example
StringExtensions.DoSomething(myString);
Good Example
myString.DoSomething();

Iterator Method Result Ignored

Description: Return value of iterator is not used

Label Label Label

Bad Example
GetItems(); // Result ignored
Good Example
foreach (var item in GetItems()) { /* process item */ }

Iterator Never Returns

Description: Iterator never returns

Label Label Label

Bad Example
IEnumerable<int> EndlessIterator() { while (true) { yield return 1; } }
Good Example
IEnumerable<int> LimitedIterator() { for (int i = 0; i < 10; i++) { yield return i; } }

Join Declaration and Initializer

Description: Join local variable declaration and assignment

Label Label Label

Bad Example
int count; count = 10; // Declaration and assignment are separate
Good Example
int count = 10; // Declaration and assignment are joined

Lambda Expression Made Static

Description: Lambda expression/anonymous method can be made 'static'.

Label Label Label

Bad Example
Func<int, int> square = x => x * x;
Good Example
static int Square(int x) => x * x;

Lambda Expression Static

Description: Lambda expression/anonymous method must be 'static' to avoid allocations.

Label Label Label

Bad Example
Func<int, int> square = x => x * x;
Good Example
static Func<int, int> square = x => x * x;

Lambda Should not Capture Context

Description: Lambda expression/anonymous method should not have captures of the containing context.

Label Label Label

Bad Example
int a = 5; Func<int> getA = () => a;
Good Example
int GetA(int a) => a;

Linq Expression Use All

Description: Simplify LINQ expression (use 'All')

Label Label Label

Bad Example
var allActive = !collection.Any(item => !item.IsActive);
Good Example
var allActive = collection.All(item => item.IsActive);

Linq Expression Use All

Description: Simplify LINQ expression (use 'All')

Label Label Label

Bad Example
var allActive = !collection.Any(item => !item.IsActive);
Good Example
var allActive = collection.All(item => item.IsActive);

Linq Expression Use Any

Description: Simplify LINQ expression (use 'Any')

Label Label Label

Bad Example
var hasActiveItems = collection.Count(item => item.IsActive) > 0;
Good Example
var hasActiveItems = collection.Any(item => item.IsActive);

Linq Expression Use Any

Description: Simplify LINQ expression (use 'Any')

Label Label Label

Bad Example
var hasActiveItems = collection.Count(item => item.IsActive) > 0;
Good Example
var hasActiveItems = collection.Any(item => item.IsActive);

Local Class Never Instantiated

Description: Class is never instantiated (private accessibility)

Label Label Label

Bad Example
private class UnusedClass { /* class implementation */ }
Good Example
private class UsedClass { /* class implementation */ } new UsedClass();

Local Class Sealed

Description: Class can be made sealed (non-inheritable) (private accessibility)

Label Label Label

Bad Example
internal class InternalClass { /* Implementation */ } // Can be inherited within assembly
Good Example
internal sealed class InternalClass { /* Implementation */ } // Sealed to prevent unintended inheritance

Local Collection Never Queried

Description: Collection's content is never queried (private accessibility)

Label Label Label

Bad Example
private List<int> numbers = new List<int> { 1, 2, 3 };
Good Example
private List<int> numbers = new List<int> { 1, 2, 3 }; Console.WriteLine(numbers.Count);

Local Collection Never Updated

Description: Collection is never updated (private accessibility)

Label Label Label

Bad Example
private List<int> numbers = new List<int>();
Good Example
private List<int> numbers = new List<int> { 1, 2, 3 };

Local Field Read Only

Description: Field can be made readonly (private accessibility)

Label Label Label

Bad Example
private int _counter = 0; // Field can be modified in other methods
Good Example
private readonly int _counter = 0; // Field is readonly and cannot be modified after initialization

Local Function Body

Description: Use preferred body style (convert to local function with preferred body style)

Label Label Label

Bad Example
void LocalFunction() { Console.WriteLine("Hello"); }
Good Example
void LocalFunction() => Console.WriteLine("Hello");

Local Function Hides Method

Description: Local function hides method

Label Label Label

Bad Example
void MyMethod() { void MyMethod() { /* Local function */ } }
Good Example
void MyMethod() { void LocalHelper() { /* Local function */ } }

Local Function Static

Description: Local function can be made static

Label Label Label

Bad Example
void ProcessData() { /* Function does not access instance members */ }
Good Example
static void ProcessData() { /* Marked as static to clarify no access to instance members */ }

Local Member Private

Description: Member can be made private (private accessibility)

Label Label Label

Bad Example
public int exampleValue = 10;
Good Example
private int exampleValue = 10;

Local Member Protected

Description: Member can be made protected (private accessibility)

Label Label Label

Bad Example
public int exampleValue = 10;
Good Example
protected int exampleValue = 10;

Local Member Static

Description: Member can be made static (shared) (private accessibility)

Label Label Label

Bad Example
private int exampleValue = 10;
Good Example
private static int ExampleValue = 10;

Local Parameter Type

Description: Parameter type can be IEnumerable (private accessibility)

Label Label Label

Bad Example
private void PrintData(List<string> data) { }
Good Example
private void PrintData(IEnumerable<string> data) { }

Local Property Init Only

Description: Property can be made init-only (private accessibility)

Label Label Label

Bad Example
private string Name { get; set; } // Allows modification after initialization
Good Example
private string Name { get; init; } // Init-only, settable only during object initialization

Local Return Type IEnumerable

Description: Return type can be IEnumerable (private accessibility)

Label Label Label

Bad Example
private List<string> GetItems() { return new List<string>(); }
Good Example
private IEnumerable<string> GetItems() { return new List<string>(); }

Local Variable Hides Member

Description: Local variable hides member

Label Label Label

Bad Example
public int value; void SetValue() { int value = 10; /* Local variable hides member */ }
Good Example
public int value; void SetValue() { int localValue = 10; value = localValue; }

Localizable Element

Description: Element is localizable

Label Label Label

Bad Example
Console.WriteLine("Hello, World!");
Good Example
Console.WriteLine(Resources.GreetingMessage); // Use resource for localization

Lock Statement Braces

Description: Use preferred braces style (enforce braces in 'lock' statement)

Label Label Label

Bad Example
lock (myLock) DoSomething();
Good Example
lock (myLock) { DoSomething(); }

Loop Converted to Query

Description: Loop can be converted into LINQ-expression.

Label Label Label

Bad Example
foreach (var item in items) { if (item.IsActive) activeItems.Add(item); }
Good Example
var activeItems = items.Where(item => item.IsActive).ToList();

Loop Partly Converted to Query

Description: Part of loop's body can be converted into LINQ-expression

Label Label Label

Bad Example
for (int i = 0; i < list.Count; i++) { if (list[i] > 0) positiveItems.Add(list[i]); }
Good Example
positiveItems.AddRange(list.Where(item => item > 0));

Loop Variable Never Changes

Description: Loop control variable is never changed inside loop

Label Label Label

Bad Example
for (int i = 0; i < 10; ) { Console.WriteLine(i); } // 'i' is not incremented inside loop
Good Example
for (int i = 0; i < 10; i++) { Console.WriteLine(i); } // 'i' is incremented inside loop

Main Method Ignored Due to Top-Level Statements

Description: The 'Main' method will not be used as an entry point because compilation unit with top-level statements was found.

Label Label Label

Bad Example
public static void Main() { Console.WriteLine("Hello"); }
Good Example
// Top-level statement Console.WriteLine("Hello");

Math Clamp Invalid Values

Description: Inconsistent arguments passed to 'Math.Clamp()' method.

Label Label Label

Bad Example
var result = Math.Clamp(value, 10, 5);
Good Example
var result = Math.Clamp(value, 5, 10);

Meaningless Default Parameter Value

Description: 'DefaultParameterValueAttribute' should be used in conjunction with 'OptionalAttribute'

Label Label Label

Bad Example
[DefaultParameterValue(5)] public void MyMethod(int value) { } // Lacks 'OptionalAttribute'
Good Example
[DefaultParameterValue(5), Optional] public void MyMethod(int value) { } // Added 'OptionalAttribute'

Member 'name' Overriding 'method'

Description: Multiple override candidates at run-time

Label Label Label

Bad Example
public override void Method(int x) { } public override void Method(object x) { }
Good Example
public override void Method(int x) { } public void AnotherMethod(object x) { }

Member Internal

Description: Member or type can be made internal(friend)

Label Label Label

Bad Example
public class Example { }
Good Example
internal class Example { }

Member non Null Value when Exiting

Description: Member must have a non-null value when exiting.

Label Label Label

Bad Example
public void Initialize() { /* myObject might still be null */ }
Good Example
public void Initialize() { myObject = new Object(); }

Member non Null Value when Exiting Function

Description: Member must conditionally have a non-null value when exiting a function.

Label Label Label

Bad Example
if (condition) { return; }
Good Example
if (condition) { myObject = new Object(); } return;

Member not Documented

Description: Missing XML comment for private or internal type or member

Label Label Label

Bad Example
internal class DataProcessor { /* No XML documentation */ }
Good Example
/// <summary>
/// Processes data for analytics.
/// </summary>
internal class DataProcessor { /* XML documentation added */ }

Member not Used in Attribute

Description: Member cannot be used in this attribute.

Label Label Label

Bad Example
[MyAttribute(Name)]
Good Example
[MyAttribute("ValidValue")]

Member with Default Implementation

Description: Non-public member in implementation class hides default implementation in interface

Label Label Label

Bad Example
public interface ITest { void Display() { Console.WriteLine("Interface"); } } class Test : ITest { private void Display() { } }
Good Example
public interface ITest { void Display() { Console.WriteLine("Interface"); } } class Test : ITest { public void Display() { Console.WriteLine("Test"); } }

Merge and Pattern

Description: Merge 'and' pattern.

Label Label Label

Bad Example
if (x is >= 1 && x is <= 10) { /* ... */ }
Good Example
if (x is >= 1 and <= 10) { /* ... */ }

Merge Cast with Type Check

Description: Type check and casts can be merged

Label Label Label

Bad Example
if (obj is MyClass) { MyClass myObj = (MyClass)obj; }
Good Example
if (obj is MyClass myObj) { /* use myObj directly */ }

Merge Conditional Expression

Description: Merge conditional ?: expression into conditional access.

Label Label Label

Bad Example
var result = obj != null ? obj.Property : null;
Good Example
var result = obj?.Property;

Merge Conditional Expression

Description: Merge conditional ?: expression into conditional access (when possible)

Label Label Label

Bad Example
var result = condition ? obj.Property : null;
Good Example
var result = obj?.Property;

Merge Into Logical Pattern

Description: Merge null/pattern/value checks into 'or'/'and' patterns

Label Label Label

Bad Example
if (value is null || value == 0) { /* ... */ }
Good Example
if (value is null or 0) { /* ... */ }

Merge into Negated Pattern

Description: Merge negated null/pattern checks into complex pattern

Label Label Label

Bad Example
if (!(value is null || value == "")) { /* ... */ }
Good Example
if (value is not null and not "") { /* ... */ }

Merge into Pattern

Description: Merge null/pattern checks into complex pattern

Label Label Label

Bad Example
if (value != null && value is int) { /* ... */ }
Good Example
if (value is not null and int) { /* ... */ }

Merge Nested Property Patterns

Description: Merge nested property patterns

Label Label Label

Bad Example
if (person is { Address: { City: { Name: "New York" } } }) { /* ... */ }
Good Example
if (person is { Address.City.Name: "New York" }) { /* ... */ }

Merge Sequential Checks

Description: Merge sequential checks into single conditional access check

Label Label Label

Bad Example
if (obj != null && obj.Property != null) { /* ... */ }
Good Example
if (obj?.Property != null) { /* ... */ }

Merge Sequential Checks

Description: Merge sequential checks into single conditional access check (when possible)

Label Label Label

Bad Example
if (list != null && list.Count > 0) { /* ... */ }
Good Example
if (list?.Count > 0) { /* ... */ }

Method 'method' not Used

Description: Asynchronous 'Main' method will not be used as an entry point because a synchronous entry point was found.

Label Label Label

Bad Example
public static async Task Main() { await Task.Delay(1000); }
Good Example
public static void Main() { Task.Run(async () => await Task.Delay(1000)).Wait(); }

Method Async Overload

Description: Method has async overload

Label Label Label

Bad Example
public void SaveData() { /* Synchronous implementation */ }
Good Example
public async Task SaveDataAsync() { /* Asynchronous implementation using async/await */ } // Async overload provides non-blocking support

Method Async Overload Cancellation

Description: Method has async overload with cancellation support

Label Label Label

Bad Example
public async Task SaveDataAsync() { /* Async without cancellation support */ }
Good Example
public async Task SaveDataAsync(CancellationToken cancellationToken) { /* Async with cancellation token support */ } // Adds cancellation support

Method or Operator Body

Description: Use preferred body style (convert to method or operator with preferred body style)

Label Label Label

Bad Example
public int Add(int a, int b) { return a + b; }
Good Example
public int Add(int a, int b) => a + b;

Method Supports Cancellation

Description: Method supports cancellation

Label Label Label

Bad Example
public async Task ProcessDataAsync() { /* Lacks cancellation handling */ }
Good Example
public async Task ProcessDataAsync(CancellationToken cancellationToken) { /* Adds cancellation handling */ } // Supports cancellation for async operations

Method with Parameters

Description: NUnit. Values for test method parameters are not provided.

Label Label Label

Bad Example
[Test] public void TestMethod(int x) { /* ... */ }
Good Example
[TestCase(1)] public void TestMethod(int x) { /* ... */ }

Missed Test Attribute

Description: NUnit.AutoFixture. Missed Test or TestFixture attribute

Label Label Label

Bad Example
public void TestMethod() { /* ... */ }
Good Example
[Test] public void TestMethod() { /* ... */ }

Missing Arguments in Test Case Attribute

Description: NUnit. Missing arguments in TestCase attribute

Label Label Label

Bad Example
[TestCase] public void Test(string value) { /* ... */ }
Good Example
[TestCase("example")] public void Test(string value) { /* ... */ }

Missing Blank Lines

Description: Incorrect blank lines (blank lines are missing elsewhere).

Label Label Label

Bad Example
public class Example
{
void Method() {}
}
Good Example
public class Example
{

void Method() {}

}

Missing DoesNotReturn Annotation

Description: Method lacks '[DoesNotReturn]' annotation in order to match implemented or overridden member.

Label Label Label

Bad Example
public void Terminate() { throw new Exception(); }
Good Example
[DoesNotReturn] public void Terminate() { throw new Exception(); }

Missing GetHashCode in Record

Description: Record defined 'Equals' but not 'GetHashCode'

Label Label Label

Bad Example
public record MyRecord { public bool Equals(MyRecord other) { /* custom equality logic */ } }
Good Example
public record MyRecord { public override int GetHashCode() { /* custom hash logic */ } public bool Equals(MyRecord other) { /* custom equality logic */ } }

Missing Indent

Description: Incorrect indent (line should be indented or outdented elsewhere)

Label Label Label

Bad Example
if (condition)
doSomething();
Good Example
if (condition)
doSomething();

Missing Linebreak

Description: Incorrect line breaks (line break is missing elsewhere).

Label Label Label

Bad Example
public void Method() { int x = 5; int y = 10; }
Good Example
public void Method() {
int x = 5;
int y = 10;
}

Missing Parentheses

Description: Add parentheses to avoid non-obvious precedence

Label Label Label

Bad Example
int result = a + b * c;
Good Example
int result = a + (b * c);

Missing Plugin Dependency

Description: Dependency for plugin is missing in project file

Label Label Label

Bad Example
// Plugin dependency is missing from .uproject file
Good Example
"Plugins": [ { "Name": "MyPlugin", "Enabled": true } ]

Missing Space

Description: Incorrect spacing (space is missing elsewhere)

Label Label Label

Bad Example
int a=10;
Good Example
int a = 10;

Missing XML Comment

Description: Missing XML comment for publicly visible type or member

Label Label Label

Bad Example
public class MyClass { public void Method() { } }
Good Example
/// <summary>My class</summary> public class MyClass { /// <summary>My method</summary> public void Method() { } }

Missing XML Comment for Parameter

Description: Parameter has no matching param tag in the XML comment

Label Label Label

Bad Example
/// <summary>Processes data.</summary> public void ProcessData(string data) {}
Good Example
/// <summary>Processes data.</summary> /// <param name="data">The data to process.</param> public void ProcessData(string data) {}

Modifiers Order

Description: Adjust modifiers declaration order

Label Label Label

Bad Example
static public int Count;
Good Example
public static int Count;

More Specific Foreach

Description: Iteration variable can be declared with a more specific type

Label Label Label

Bad Example
foreach (object item in list) { /* Use item as a specific type */ }
Good Example
foreach (string item in list) { /* Use item as a specific type */ } // Declared with a more specific type

Multiple OrderBy

Description: Multiple sequential 'OrderBy' invocation

Label Label Label

Bad Example
items.OrderBy(x => x.Name).OrderBy(x => x.Age); // Multiple OrderBy causes issues
Good Example
items.OrderBy(x => x.Name).ThenBy(x => x.Age); // Chain with ThenBy for correct ordering

Multiple Resolve Candidates in Text

Description: Ambiguous symbols in text argument

Label Label Label

Bad Example
Console.WriteLine("Value: " + ambiguousSymbol);
Good Example
Console.WriteLine("Value: " + resolvedSymbol);

Multiple Spaces

Description: Incorrect spacing (multiple spaces are prohibited)

Label Label Label

Bad Example
int    count = 10;
Good Example
int count = 10;

Multiple Statements on One Line

Description: Incorrect line breaks (multiple statements on one line).

Label Label Label

Bad Example
int x = 5; int y = 10;
Good Example
int x = 5;
int y = 10;

Multiple Type Members

Description: Incorrect line breaks (multiple type members on one line).

Label Label Label

Bad Example
public int X { get; set; } public int Y { get; set; }
Good Example
public int X { get; set; }
public int Y { get; set; }

Must Use Return Value

Description: Return value of [MustUseReturnValue] annotated method is not used

Label Label Label

Bad Example
CalculateValue(); // Ignoring return value of a method marked with MustUseReturnValue
Good Example
var result = CalculateValue(); // Correctly uses the return value

Negated Pattern in is Expression

Description: Convert negated 'is' expression to 'is' expression with negated pattern.

Label Label Label

Bad Example
if (!(value is SomeType)) { /* ... */ }
Good Example
if (value is not SomeType) { /* ... */ }

Negated Pattern Matching

Description: Convert 'as' expression type check and the following null check into negated pattern matching.

Label Label Label

Bad Example
if (!(obj is SomeType)) { /* ... */ }
Good Example
if (obj is not SomeType) { /* ... */ }

Negation of Relational Pattern

Description: Simplify negated relational pattern

Label Label Label

Bad Example
if (!(value > 10)) { ... }
Good Example
if (value <= 10) { ... }

Negation of Relational Pattern

Description: Simplify negated relational pattern

Label Label Label

Bad Example
if (!(value > 10)) { ... }
Good Example
if (value <= 10) { ... }

Negative Equality Expression

Description: Simplify negative equality expression

Label Label Label

Bad Example
if (!(status == Status.Active)) { ... }
Good Example
if (status != Status.Active) { ... }

Negative Equality Expression

Description: Simplify negative equality expression

Label Label Label

Bad Example
if (!(status == Status.Active)) { ... }
Good Example
if (status != Status.Active) { ... }

Negative Index

Description: Possible 'System.ArgumentOutOfRangeException'. Index must be a non-negative integer

Label Label Label

Bad Example
var value = array[-1];
Good Example
var value = array[0];

Nested String Interpolation

Description: Nested string interpolation can be inlined

Label Label Label

Bad Example
string name = $"{GetFirstName()} {GetLastName()}"; // Nested interpolation
Good Example
string name = $"{GetFullName()}"; // Inlined interpolation by combining into a single method

New Keyword not Required

Description: Keyword 'new' is redundant

Label Label Label

Bad Example
public new int Property { get; set; }
Good Example
public int Property { get; set; }

New Protected Member Sealed Class

Description: Declaring new protected member in sealed class is the same as declaring it as private

Label Label Label

Bad Example
sealed class MyClass { protected void MyMethod() { } }
Good Example
sealed class MyClass { private void MyMethod() { } }

No Values Provided

Description: NUnit. No values provided in the attributes.

Label Label Label

Bad Example
[TestCase] public void TestMethod(int value) { /* ... */ }
Good Example
[TestCase(1)] public void TestMethod(int value) { /* ... */ }

Non Atomic Compound Operator

Description: Suspicious 'volatile' field usage: compound operation is not atomic. 'Interlocked' class can be used instead

Label Label Label

Bad Example
volatile int counter; counter++; // Non-atomic operation on volatile field
Good Example
Interlocked.Increment(ref counter); // Ensures atomic increment

Non Parsable Element

Description: Part of the code cannot be parsed

Label Label Label

Bad Example
int x = ; // Missing value or syntax error
Good Example
int x = 5; // Properly assigned value

Non Public Method with Test Attribute

Description: NUnit. Non-public test method.

Label Label Label

Bad Example
[Test] private void PrivateTestMethod() { /* ... */ }
Good Example
[Test] public void PublicTestMethod() { /* ... */ }

Non Readonly Member in GetHashCode

Description: Non-readonly type member referenced in 'GetHashCode()'

Label Label Label

Bad Example
private int nonReadonlyField; public override int GetHashCode() { return nonReadonlyField.GetHashCode(); }
Good Example
private readonly int readonlyField; public override int GetHashCode() { return readonlyField.GetHashCode(); }

Non-Exhaustive Switch Expression

Description: The switch expression does not handle all possible inputs (it is not exhaustive).

Label Label Label

Bad Example
var result = status switch { Status.Active => "Active" };
Good Example
var result = status switch { Status.Active => "Active", _ => "Unknown" };

Non-Exhaustive Switch Expression for Enum Values

Description: The switch expression does not handle some values of its input type (it is not exhaustive) involving an unnamed enum value.

Label Label Label

Bad Example
var result = color switch { Color.Red => "Red" };
Good Example
var result = color switch { Color.Red => "Red", Color.Green => "Green", _ => "Unknown" };

Non-Exhaustive Switch Expression with 'when' Clause

Description: The switch expression does not handle all possible values of its input type (it is not exhaustive). However, a pattern with a 'when' clause might successfully match this value.

Label Label Label

Bad Example
var result = status switch { Status.Active => "Active" };
Good Example
var result = status switch { Status.Active => "Active", Status.Inactive when condition => "Inactive", _ => "Unknown" };

Non-nullable Member Uninitialized

Description: Non-nullable member is uninitialized.

Label Label Label

Bad Example
public string Name; // Not initialized
Good Example
public string Name = "Default"; // Initialized

Non-Nullable Return Due to [NotNullIfNotNull]

Description: Return value must be non-null because parameter mentioned in [NotNullIfNotNull] annotation is non-null.

Label Label Label

Bad Example
[return: NotNullIfNotNull("input")] public string? GetData(string? input) { return null; }
Good Example
[return: NotNullIfNotNull("input")] public string? GetData(string? input) { return input ?? "default"; }

Non-Private Accessibility

Description: Virtual (overridable) member is never overridden (non-private accessibility)

Label Label Label

Bad Example
public virtual void Method() { }
Good Example
// Make 'Method' non-virtual if no subclasses override it

Not Accessed Field. Compiler

Description: Non-accessed field

Label Label Label

Bad Example
private int unusedField;
Good Example
private int usedField; public int GetField() => usedField;

Not Accessed Global Field

Description: Non-accessed field (non-private accessibility)

Label Label Label

Bad Example
public int unusedField; // Field not accessed
Good Example
private int usedField; // Fields should be private if not accessed externally

Not Accessed Local Field

Description: Non-accessed field (private accessibility)

Label Label Label

Bad Example
private int unusedField; // Field not accessed
Good Example
public void Method() { int usedField = 10; } // Variable used locally

Not Accessed Positional Global Property

Description: Non-accessed positional property (non-private accessibility)

Label Label Label

Bad Example
public int Property { get; init; } // Property not accessed
Good Example
private int AccessedProperty { get; init; } = 10; // Private or used properties only

Not Accessed Positional Local Property

Description: Non-accessed positional property (private accessibility)

Label Label Label

Bad Example
private int Property { get; init; } // Property is declared but not used
Good Example
private int Property { get; init; } = 10; // Property is initialized and used

Not Accessed Variable

Description: Non-accessed local variable

Label Label Label

Bad Example
int unusedVariable = 5;
Good Example
// Remove the variable if it is not accessed

Not Accessed Variable. Compiler

Description: Non-accessed local variable

Label Label Label

Bad Example
int unusedVariable = 0;
Good Example
int usedVariable = 10; Console.WriteLine(usedVariable);

Not annotated Async-iterator

Description: Async-iterator has one or more parameters of type 'CancellationToken' but none of them is annotated with the 'EnumeratorCancellation' attribute.

Label Label Label

Bad Example
async IAsyncEnumerable<int> Generate(CancellationToken token) { yield return 1; }
Good Example
async IAsyncEnumerable<int> Generate([EnumeratorCancellation] CancellationToken token) { yield return 1; }

Not Null Member not Initialized

Description: Non-nullable member is not initialized at constructor exit

Label Label Label

Bad Example
public class MyClass { public string NotNullMember; }
Good Example
public class MyClass { public string NotNullMember; public MyClass() { NotNullMember = "Initialized"; } }

Not Observable Annotation Redundancy

Description: Nullability attribute used with declaration that cannot be directly referenced from other code

Label Label Label

Bad Example
[NotNull] private string internalData;
Good Example
private string internalData;

Not Resolved in Text

Description: Cannot resolve symbol in text argument

Label Label Label

Bad Example
Console.WriteLine("Value: " + unresolvedSymbol);
Good Example
int resolvedSymbol = 5; Console.WriteLine("Value: " + resolvedSymbol);

Null Check Assignment

Description: Join null check with assignment.

Label Label Label

Bad Example
if (x == null) { x = new Object(); }
Good Example
x ??= new Object();

Null Check Assignment

Description: Join null check with assignment (when possible).

Label Label Label

Bad Example
if (x == null) { x = new Object(); }
Good Example
x ??= new Object();

Nullability Mismatch in Base Type Interface

Description: Nullability of reference types in interface implemented by the base type doesn't match.

Label Label Label

Bad Example
public string? DerivedMethod() => "Value"; // Overrides non-nullable base method
Good Example
public string DerivedMethod() => "Value"; // Matches non-nullable base method

Nullability Mismatch in Constraints

Description: Nullability mismatch in constraints for type parameter.

Label Label Label

Bad Example
public void Process(T? item) where T : notnull { }
Good Example
public void Process(T item) where T : class { }

Nullability Mismatch in Interface Specifier

Description: Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type.

Label Label Label

Bad Example
public string? Method() => "Text"; // Implementing non-nullable interface
Good Example
public string Method() => "Text"; // Matches non-nullable interface

Nullable Annotation in Auto-Generated Code

Description: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.

Label Label Label

Bad Example
public string? nullableData;
Good Example
#nullable enable public string? nullableData; #nullable disable

Nullable Annotation Outside '#nullable' Context

Description: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Label Label Label

Bad Example
public string? data;
Good Example
#nullable enable public string? data; #nullable disable

Nullable Attributes

Description: Multiple nullable attributes usage

Label Label Label

Bad Example
[AllowNull][MaybeNull] public string? Name; // Redundant nullable attributes
Good Example
[MaybeNull] public string? Name; // Simplified with a single nullable attribute

Nullable Value Type May Be Null

Description: Nullable value type may be null.

Label Label Label

Bad Example
int? nullableInt = null; int nonNullableInt = nullableInt.Value; // May throw if null
Good Example
int? nullableInt = null; int nonNullableInt = nullableInt ?? 0; // Provides default

Nullable Warning Expression Operator

Description: Nullable warning suppression operator might be confused with inverted 'is' expression

Label Label Label

Bad Example
if (x is not null!) { } // Confusing use of nullable suppression operator
Good Example
if (x != null) { } // Clear and direct check for null

Nullable Warning Suppression

Description: A suppressed nullable warning might hide an underlying problem.

Label Label Label

Bad Example
var value = possiblyNull!;
Good Example
if (possiblyNull != null) { var value = possiblyNull; /* ... */ }

Object Creation as Statement

Description: Possible unassigned object created by 'new' expression

Label Label Label

Bad Example
new MyClass(); // Object created but not assigned or used
Good Example
var instance = new MyClass(); instance.DoSomething(); // Object is created and used

Object Creation Evident Type

Description: Use preferred style of 'new' expression when created type is evident

Label Label Label

Bad Example
List<int> numbers = new List<int>();
Good Example
List<int> numbers = new();

Object Creation Not Evident Type

Description: Use preferred style of 'new' expression when created type is not evident

Label Label Label

Bad Example
var numbers = new List<int>();
Good Example
List<int> numbers = new List<int>();

Obsolete Attribute to ‘member1’

Description: Member overrides obsolete member

Label Label Label

Bad Example
public override void ObsoleteMethod() { /* Obsolete method logic */ }
Good Example
[Obsolete] public override void ObsoleteMethod() { /* Method logic */ }

One Way Operation Return

Description: One way operations must not return values

Label Label Label

Bad Example
[OperationContract(IsOneWay = true)] public int GetData() { return 42; } // One-way operation with return type
Good Example
[OperationContract(IsOneWay = true)] public void SendData() { /* No return */ } // Proper one-way operation

Operation Contract without Service Contract

Description: Method is marked as OperationContract but containing type isn't marked as ServiceContract

Label Label Label

Bad Example
[OperationContract] public void MyMethod() { } // No [ServiceContract] on class
Good Example
[ServiceContract] public class MyService { [OperationContract] public void MyMethod() { } } // Correct usage

Operator Used

Description: Operator 'is'/'Type Of ... Is ...' can be used

Label Label Label

Bad Example
if (typeof(obj) == typeof(string)) { }
Good Example
if (obj is string) { } // Clearer usage of 'is' operator

Optional Parameter Hierarchy Mismatch

Description: Mismatch of optional parameter value in overridden method

Label Label Label

Bad Example
public virtual void Print(int x = 5) { } public override void Print(int x = 10) { } // Different defaults
Good Example
public virtual void Print(int x = 5) { } public override void Print(int x) { } // Consistent parameters

Optional Parameter Method Overload

Description: Method with optional or 'params' parameter is hidden by overload

Label Label Label

Bad Example
public void DoSomething(int x, int y = 0) { } public void DoSomething(int x) { } // Ambiguity
Good Example
public void DoSomething(int x) { } public void DoSomething(int x, int y) { } // Clear parameter usage

Optional Parameter Ref Out

Description: 'ref' or 'out' parameter with [Optional] attribute

Label Label Label

Bad Example
public void Method([Optional] ref int x) { } // Invalid use of Optional attribute with ref parameter
Good Example
public void Method(ref int x) { } // Avoids Optional attribute on ref parameter

Parameter After Interpolated String Handler

Description: Parameter occurs after interpolated string handler parameter in the parameter list.

Label Label Label

Bad Example
void Log(InterpolatedStringHandler handler, string message) { }
Good Example
void Log(string message, InterpolatedStringHandler handler) { }

Parameter Conditionally Must Be Non-Null

Description: Parameter must conditionally have a non-null value when exiting a function.

Label Label Label

Bad Example
void Process(string? data) { if (data == null) return; /* process data */ }
Good Example
void Process(string? data) { if (data == null) throw new ArgumentNullException(nameof(data)); /* process data */ }

Parameter Hides Member

Description: Parameter hides member

Label Label Label

Bad Example
public int count; public void SetCount(int count) { this.count = count; } // Parameter hides member
Good Example
public int count; public void SetCount(int value) { count = value; } // Clear parameter naming

Parameter Must Be Non-Null

Description: Parameter must have a non-null value when exiting.

Label Label Label

Bad Example
void Save(string? data) { /* some logic */ }
Good Example
void Save(string data) { /* some logic */ } // Ensure parameter is non-null before using

Parameter Must Be Non-Null Due to [NotNullIfNotNull]

Description: Parameter must have a non-null value when exiting because parameter mentioned in [NotNullIfNotNull] annotation is non-null.

Label Label Label

Bad Example
public string? GetData(string? input) { return input?.ToUpper(); }
Good Example
[return: NotNullIfNotNull("input")] public string? GetData(string? input) { return input?.ToUpper(); }

Parameter Nullability Mismatch with Delegate

Description: Nullability of reference types in type of a parameter doesn't match the target delegate (possibly because of nullability attributes).

Label Label Label

Bad Example
Action<string?> action = (input) => Console.WriteLine(input); // Expected non-nullable
Good Example
Action<string> action = (input) => Console.WriteLine(input); // Matches non-nullable

Parameter Nullability Mismatch with Implemented Member

Description: Nullability of reference types in type of parameter doesn't match implemented member.

Label Label Label

Bad Example
public void SetName(string? name) {} // Expected non-nullable
Good Example
public void SetName(string name) {} // Matches non-nullable

Parameter Nullability Mismatch with Implicitly Implemented Member

Description: Nullability of reference types in type of parameter doesn't match implicitly implemented member.

Label Label Label

Bad Example
public void Display(string? text) {} // Expected non-nullable
Good Example
public void Display(string text) {} // Matches non-nullable

Parameter Nullability Mismatch with Overridden Member

Description: Nullability of reference types in type of parameter doesn't match overridden member.

Label Label Label

Bad Example
public override void Process(string? data) {} // Expected non-nullable
Good Example
public override void Process(string data) {} // Matches non-nullable

Parameter Nullability Mismatch with Partial Method

Description: Nullability of reference types in type of parameter doesn't match partial method declaration.

Label Label Label

Bad Example
public partial void LoadData(string? data); // Expected non-nullable
Good Example
public partial void LoadData(string data); // Matches non-nullable

Parameter Type not Compatible

Description: NUnit. Specified values are not compatible with the test parameter type.

Label Label Label

Bad Example
[TestCase("string")] public void Method(int x) { /* ... */ }
Good Example
[TestCase(1)] public void Method(int x) { /* ... */ }

Parameter Type Nullability Mismatch with Implemented Member

Description: Nullability of type of parameter doesn't match implemented member (possibly because of nullability attributes).

Label Label Label

Bad Example
public void SetData(string? data) {} // Expected non-nullable parameter
Good Example
public void SetData(string data) {} // Matches non-nullable parameter type

Parameter Type Nullability Mismatch with Implicitly Implemented Member

Description: Nullability of type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).

Label Label Label

Bad Example
public void Process(string? input) {} // Expected non-nullable parameter
Good Example
public void Process(string input) {} // Matches non-nullable parameter type

Parameter Type Nullability Mismatch with Overridden Member

Description: Nullability of type of parameter doesn't match overridden member (possibly because of nullability attributes).

Label Label Label

Bad Example
public override void Display(string? message) {} // Expected non-nullable parameter
Good Example
public override void Display(string message) {} // Matches non-nullable parameter type

Partial Method

Description: Redundant 'partial' modifier on method declaration

Label Label Label

Bad Example
partial void Log(); // Only one part
Good Example
// Remove 'partial' modifier if the method has a single part

Partial Method Parameter Name Mismatch

Description: Parameter name differs in partial method declaration

Label Label Label

Bad Example
partial void Print(string message); partial void Print(string text) { } // Mismatched parameter names
Good Example
partial void Print(string message); partial void Print(string message) { } // Consistent parameter naming

Partial Type

Description: Redundant 'partial' modifier on type declaration

Label Label Label

Bad Example
public partial class SinglePartClass { }
Good Example
// Remove 'partial' modifier if the class is not split across files

Partially Unused Member in Super Non-Private Accessibility

Description: Type member is never accessed via base type (non-private accessibility)

Label Label Label

Bad Example
public override void Method() { } // Method never accessed via base
Good Example
// Remove or use the method in a way that utilizes the base type

Partially Unused Member in Super Private Accessibility

Description: Type member is never accessed via base type (private accessibility)

Label Label Label

Bad Example
private override void InternalMethod() { } // Never accessed via base
Good Example
// Consider removing the override if the base type is not used

Partially Unused Member Non-Private Accessibility

Description: Type member is only used in overrides (non-private accessibility)

Label Label Label

Bad Example
public void Method() { OverrideMethod(); }
Good Example
// Remove 'Method' if it is only used for override

Partially Unused Member Private Accessibility

Description: Type member is only used in overrides (private accessibility)

Label Label Label

Bad Example
private void InternalMethod() { OverrideInternalMethod(); }
Good Example
// Remove 'InternalMethod' if only used by overrides

Partially Unused Parameter Non-Private Accessibility

Description: Parameter is only used for precondition check (non-private accessibility)

Label Label Label

Bad Example
public void DoSomething(int x) { if (x < 0) throw new ArgumentException(); }
Good Example
// Consider refactoring if the parameter is only used for validation

Partially Unused Parameter Private Accessibility

Description: Parameter is only used for precondition check (private accessibility)

Label Label Label

Bad Example
private void Helper(int y) { if (y > 10) throw new ArgumentException(); }
Good Example
// Adjust the method or consider removing the parameter if it is only used for validation

Pass String Interpolation

Description: Pass string interpolation expression

Label Label Label

Bad Example
string result = string.Format("Hello, {0}", name);
Good Example
string result = $"Hello, {name}";

Pattern Always Matches

Description: The source expression always matches the provided pattern

Label Label Label

Bad Example
switch (obj) { case string s: break; } // Pattern always matches
Good Example
switch (obj) { case string s when s.Length > 0: break; } // Pattern conditionally matches

Pattern Matching

Description: Convert 'as' expression type check and the following null check into pattern matching.

Label Label Label

Bad Example
var obj = value as SomeType; if (obj != null) { /* ... */ }
Good Example
if (value is SomeType obj) { /* ... */ }

Pattern Never Matches

Description: The source expression never matches the provided pattern

Label Label Label

Bad Example
switch (obj) { case int i: break; } // Pattern will never match
Good Example
// Ensure patterns are meaningful for the expected types

Pattern Same Value

Description: Pattern is always 'true' or always 'false'

Label Label Label

Bad Example
if (x is int) { ... } // Always true for int type variable
Good Example
if (x is not null) { ... } // Pattern with meaningful check

Polymorphic Field-Like Event

Description: Invocation of polymorphic field-like event

Label Label Label

Bad Example
fieldLikeEvent?.Invoke(this, EventArgs.Empty);
Good Example
OnEventTriggered(); // Method wrapper around event invocation

Positional Deconstruction Pattern

Description: Move to existing positional deconstruction pattern

Label Label Label

Bad Example
if (point.X == 0 && point.Y == 0) { /* ... */ }
Good Example
if (point is (0, 0)) { /* ... */ }

Possible Empty Statement

Description: Possible mistaken empty statement

Label Label Label

Bad Example
if (condition); // Empty statement
Good Example
if (condition) { /* do something */ }

Possible Infinite Inheritance

Description: Possible infinite inheritance

Label Label Label

Bad Example
class A : A { }
Good Example
class A : B { }

Possible Intended Rethrow

Description: Exception rethrow possibly intended

Label Label Label

Bad Example
catch (Exception ex) { throw ex; }
Good Example
catch (Exception) { throw; } // Maintain stack trace

Possible Interface Member Ambiguity

Description: Possible ambiguity while accessing member by interface

Label Label Label

Bad Example
interface IA { void Display(); } interface IB { void Display(); } class C : IA, IB { public void Display() { } } // Ambiguous call
Good Example
class C : IA, IB { void IA.Display() { } void IB.Display() { } } // Explicit interface implementation

Possible Invalid Cast Exception

Description: Possible 'System.InvalidCastException'

Label Label Label

Bad Example
object obj = "string"; int number = (int)obj;
Good Example
object obj = "string"; if (obj is int number) { /* logic */ }

Possible Invalid Cast Exception in Foreach Loop

Description: Possible 'System.InvalidCastException' in foreach loop

Label Label Label

Bad Example
foreach (int number in objectList) { /* logic */ }
Good Example
foreach (var obj in objectList) { if (obj is int number) { /* logic */ } }

Possible Invalid Operation Exception

Description: Possible 'System.InvalidOperationException'

Label Label Label

Bad Example
var firstItem = list.First(item => item.Property == null);
Good Example
var firstItem = list.FirstOrDefault(item => item.Property == null); if (firstItem != null) { /* logic */ }

Possible IQueryable as IEnumerable

Description: IQueryable is possibly unintentionally used as IEnumerable

Label Label Label

Bad Example
var results = queryableCollection.ToList().Where(x => x > 10);
Good Example
var results = queryableCollection.Where(x => x > 10).ToList();

Possible Loss of Fraction

Description: Possible loss of fraction

Label Label Label

Bad Example
int result = 5 / 2; // result is 2
Good Example
double result = 5.0 / 2.0; // result is 2.5

Possible Mistaken Argument

Description: Possible mistaken argument

Label Label Label

Bad Example
public void SetDimensions(int width, int height) { }
...
SetDimensions(height, width);
Good Example
public void SetDimensions(int width, int height) { }
...
SetDimensions(width, height);

Possible Modification of Non-Variable Struct

Description: Value assigned to a property of non-variable qualifier expression can be lost

Label Label Label

Bad Example
GetStruct().Value = 5; // Modifying property of a non-variable expression
Good Example
var myStruct = GetStruct(); myStruct.Value = 5; // Assigned to a variable before modification

Possible Multiple Enumeration

Description: Possible multiple enumeration

Label Label Label

Bad Example
foreach (var item in collection) { if (collection.Contains(item)) { /* logic */ } }
Good Example
var cachedList = collection.ToList(); foreach (var item in cachedList) { /* logic */ }

Possible Multiple Write Access

Description: Possible incorrect implementation of Double-Check Locking pattern. Possible multiple write access to checked field

Label Label Label

Bad Example
if (_instance == null) { lock(_lock) { if (_instance == null) _instance = new Singleton(); } }
Good Example
private static readonly object _lock = new object(); if (_instance == null) { lock(_lock) { if (_instance == null) _instance = new Singleton(); } }

Possible Null Argument

Description: Possible null reference argument for a parameter.

Label Label Label

Bad Example
ProcessData(nullableData);
Good Example
ProcessData(nullableData ?? "Default");

Possible Null Assignment

Description: Possible null reference assignment.

Label Label Label

Bad Example
string? nullableStr = null; string nonNullableStr = nullableStr;
Good Example
string? nullableStr = null; string nonNullableStr = nullableStr ?? "Default";

Possible Null Reference Exception

Description: Possible 'System.NullReferenceException'

Label Label Label

Bad Example
string text = null; Console.WriteLine(text.Length); // Throws NullReferenceException
Good Example
string text = null; if (text != null) { Console.WriteLine(text.Length); } // Null check prevents exception

Possible Null Return

Description: Possible null reference return.

Label Label Label

Bad Example
public string? GetName() { return null; }
Good Example
public string GetName() { return "Default Name"; }

Possible Unintended Linear Search in Set

Description: Possibly unintended linear search in set

Label Label Label

Bad Example
myList.Contains(item); // Potential linear search in a list
Good Example
myHashSet.Contains(item); // Set-based collection avoids linear search

Possible Unintended Reference Comparison

Description: Possible unintended reference comparison

Label Label Label

Bad Example
if (string1 == string2) { /* Reference comparison instead of value */ }
Good Example
if (string1.Equals(string2)) { /* Value comparison */ }

Possible Unintended Reference Comparison

Description: Possible unintended reference comparison

Label Label Label

Bad Example
if (string1 == string2) { } // May lead to unintended reference comparison
Good Example
if (string1.Equals(string2)) { } // Proper value comparison for strings

Possibly Impure Method Call on Readonly Variable

Description: Possibly impure struct method is called on readonly variable: struct value always copied before invocation

Label Label Label

Bad Example
readonly MyStruct instance; instance.Modify(); // Causes struct copy
Good Example
MyStruct instance; instance.Modify(); // Struct is not readonly, so no copy is made

Possibly Missing Indexer Initializer Comma

Description: Possibly missing comma before indexer initializer

Label Label Label

Bad Example
var dict = new Dictionary<int, string> { [1] = "One" [2] = "Two" }; // Missing comma
Good Example
var dict = new Dictionary<int, string> { [1] = "One", [2] = "Two" }; // Correct comma placement

Possibly Mistaken Use of Interpolated String Insert

Description: Possibly unintended string interpolation instead of format string template.

Label Label Label

Bad Example
Console.WriteLine($"{0}, {1}"); // Likely intended as a format string
Good Example
Console.WriteLine("{0}, {1}", arg0, arg1); // Correctly formatted string template

Possibly Mistaken Use of Params

Description: Method with 'params' is invoked while more specific method is available

Label Label Label

Bad Example
public void Log(string message, params object[] args) { } // Call Log("Error", "Detail")
Good Example
public void Log(string message, string detail) { } // Better match for Log("Error", "Detail")

Prefer Auto Property

Description: Convert property to auto-property.

Label Label Label

Bad Example
private int _value; public int Value { get { return _value; } set { _value = value; } }
Good Example
public int Value { get; set; }

Prefer Auto Property

Description: Convert property to auto-property (when possible).

Label Label Label

Bad Example
private int _value; public int Value { get { return _value; } set { _value = value; } }
Good Example
public int Value { get; set; }

Prefer Auto Property with Private Setter

Description: Convert property to auto-property with private setter.

Label Label Label

Bad Example
private int _value; public int Value { get { return _value; } private set { _value = value; } }
Good Example
public int Value { get; private set; }

Prefer Computed Property Auto Property

Description: Replace auto-property with computed property

Label Label Label

Bad Example
public int Age { get; set; }
Good Example
public int Age => DateTime.Now.Year - birthYear;

Prefer Conditional Ternary Expression

Description: 'if' statement can be re-written as '?:' expression

Label Label Label

Bad Example
if (isActive) { result = "Active"; } else { result = "Inactive"; }
Good Example
result = isActive ? "Active" : "Inactive";

Prefer Conditional Ternary Expression

Description: Replace ternary expression with 'switch' expression.

Label Label Label

Bad Example
result = condition ? 'A' : 'B';
Good Example
result = condition switch { true => 'A', false => 'B' };

Prefer is Operator

Description: Use 'is' operator

Label Label Label

Bad Example
if (obj is MyType) { var myObj = (MyType)obj; ... }
Good Example
if (obj is MyType myObj) { ... }

Prefer is Operator

Description: Use 'is' operator

Label Label Label

Bad Example
if (obj is MyType) { var myObj = (MyType)obj; ... }
Good Example
if (obj is MyType myObj) { ... }

Prefer Local Function

Description: Convert delegate variable to local function.

Label Label Label

Bad Example
Func<int, int> Square = x => x * x;
Good Example
int Square(int x) => x * x;

Prefer Method Any

Description: Use method Any()

Label Label Label

Bad Example
if (list.Count > 0) { ... }
Good Example
if (list.Any()) { ... }

Prefer Method Any

Description: Use method Any()

Label Label Label

Bad Example
if (collection.Count() != 0) { ... }
Good Example
if (collection.Any()) { ... }

Prefer Method Any

Description: Use method Any()

Label Label Label

Bad Example
if (items.Where(x => x.IsActive).Count() > 0) { ... }
Good Example
if (items.Any(x => x.IsActive)) { ... }

Prefer Method Any

Description: Use method Any()

Label Label Label

Bad Example
if (elements.FindAll(x => x.IsReady).Count > 0) { ... }
Good Example
if (elements.Any(x => x.IsReady)) { ... }

Prefer Method Any

Description: Use method Any()

Label Label Label

Bad Example
if (data.Where(y => y.Valid).Count() > 0) { ... }
Good Example
if (data.Any(y => y.Valid)) { ... }

Prefer Method IsInstanceOfType

Description: Use method IsInstanceOfType(..)

Label Label Label

Bad Example
if (typeof(MyType).IsAssignableFrom(obj.GetType())) { ... }
Good Example
if (obj.GetType().IsInstanceOfType(typeof(MyType))) { ... }

Prefer Null Check

Description: Use null check pattern instead of a type check succeeding on any not-null value.

Label Label Label

Bad Example
if (obj is object) { ... } // Type check succeeds for any not-null value
Good Example
if (obj != null) { ... } // Uses null check directly

Prefer Null Check Pattern

Description: Use null check instead of a type check succeeding on any not-null value.

Label Label Label

Bad Example
if (obj is object) { ... } // Type check only succeeds if not null
Good Example
if (obj != null) { ... } // Uses direct null check

Prefer Null Coalescing Assignment

Description: 'if' statement can be re-written as '??=' assignment

Label Label Label

Bad Example
if (value == null) { value = defaultValue; }
Good Example
value ??= defaultValue;

Prefer Null Coalescing Expression

Description: 'if' statement can be re-written as '??' expression

Label Label Label

Bad Example
if (value == null) { value = defaultValue; }
Good Example
value ??= defaultValue;

Prefer Null Propagation

Description: Replace if statement with null-propagating code.

Label Label Label

Bad Example
if (obj != null) { result = obj.Property; }
Good Example
result = obj?.Property;

Prefer Null Propagation If

Description: Replace if statement with null-propagating code (when possible).

Label Label Label

Bad Example
if (obj != null) { result = obj.Property; }
Good Example
result = obj?.Property;

Prefer Nullable Annotation

Description: Use nullable annotation instead of an attribute.

Label Label Label

Bad Example
[Nullable] public string Name; // Nullable attribute
Good Example
public string? Name; // Nullable annotation

Prefer Or Expression

Description: Convert 'if' to '||'

Label Label Label

Bad Example
if (a) { } else if (b) { }
Good Example
if (a || b) { }

Prefer Primary Constructor

Description: Convert record constructor to primary constructor

Label Label Label

Bad Example
public record Person { public string Name { get; } public Person(string name) { Name = name; } }
Good Example
public record Person(string Name);

Prefer Range Indexer Slice

Description: Replace 'Slice' with range indexer.

Label Label Label

Bad Example
array.Slice(1, 3);
Good Example
array[1..4];

Prefer Range Indexer Substring

Description: Replace 'Substring' with range indexer.

Label Label Label

Bad Example
str.Substring(1, 3);
Good Example
str[1..4];

Prefer Return Statement

Description: 'if-return' statement can be re-written as 'return' statement

Label Label Label

Bad Example
if (condition) { return true; } return false;
Good Example
return condition;

Prefer Short Form

Description: Convert 'Nullable' to 'T?'.

Label Label Label

Bad Example
Nullable<int> number = 5;
Good Example
int? number = 5;

Prefer String IsNullOrEmpty

Description: Use 'String.IsNullOrEmpty'

Label Label Label

Bad Example
if (str == null || str == "") { ... }
Good Example
if (String.IsNullOrEmpty(str)) { ... }

Prefer Switch Expression

Description: Convert 'if' statement to 'switch' expression.

Label Label Label

Bad Example
if (x == 1) { return "One"; } else if (x == 2) { return "Two"; }
Good Example
return x switch { 1 => "One", 2 => "Two", _ => "Other" };

Prefer Switch Statement

Description: Convert 'if' statement to 'switch' statement.

Label Label Label

Bad Example
if (x == 1) { /* ... */ } else if (x == 2) { /* ... */ }
Good Example
switch (x) { case 1: /* ... */ break; case 2: /* ... */ break; }

Prefer Switch Statement

Description: Replace 'switch' statement with 'switch' expression.

Label Label Label

Bad Example
switch (value) { case 1: result = 'A'; break; }
Good Example
result = value switch { 1 => 'A', _ => 'B' };

Prefer to Compound Assignment

Description: Use compound assignment.

Label Label Label

Bad Example
x = x + 1;
Good Example
x += 1;

Prefer Var Pattern

Description: Replace object pattern not performing any additional checks with 'var' pattern.

Label Label Label

Bad Example
if (obj is MyClass myClass) { /* ... */ }
Good Example
if (obj is var myClass) { /* ... */ }

Prefer While Expression

Description: Convert 'if do while' to 'while

Label Label Label

Bad Example
if (condition) { do { /* Code */ } while (condition); } // Redundant if statement before do-while loop
Good Example
while (condition) { /* Code */ } // Simpler while loop without redundant if statement

Prefer With Expression

Description: 'with' expression is used instead of object initializer

Label Label Label

Bad Example
var newObj = oldObj with { Property = value };
Good Example
var newObj = new MyClass { Property = value }; // Use object initializer

Preferred Namespace Body

Description: Use preferred namespace body style

Label Label Label

Bad Example
namespace MyNamespace { class MyClass {} }
Good Example
namespace MyNamespace
{
class MyClass {}
}

Previous Level Indent

Description: Incorrect indent (line indent should be restored to the previous level elsewhere)

Label Label Label

Bad Example
if (condition)
{
if (anotherCondition)
{
doSomething();
}
}
Good Example
if (condition)
{
if (anotherCondition)
{
doSomething();
}
}

Private Accessibility

Description: Virtual (overridable) member is never overridden (private accessibility)

Label Label Label

Bad Example
protected virtual void Helper() { }
Good Example
// Remove 'virtual' modifier if 'Helper' is not overridden

Private Field to Local Variable

Description: Private field can be converted to local variable

Label Label Label

Bad Example
private int temp = Calculate(); // Field used only locally
Good Example
int temp = Calculate(); // Converted to local variable

Property not Resolved

Description: Cannot resolve property

Label Label Label

Bad Example
Console.WriteLine(nonExistentProperty);
Good Example
Console.WriteLine(existingProperty);

Public Constructor In Abstract Class

Description: Make constructor in abstract class protected

Label Label Label

Bad Example
public abstract class Example {
public Example() { }
}
Good Example
public abstract class Example {
protected Example() { }
}

Pure Attribute on Void Method

Description: 'void' method is annotated by [Pure] attribute

Label Label Label

Bad Example
[Pure] public void DoSomething() { /* code */ }
Good Example
public void DoSomething() { /* code */ } // Remove [Pure] as it has no effect on void methods

Range Step Sign Mismatch

Description: NUnit. Mismatch of the range step sign

Label Label Label

Bad Example
[Range(1, 10, -1)] public void Test(int value) { /* ... */ }
Good Example
[Range(1, 10, 1)] public void Test(int value) { /* ... */ }

Range Step Value Zero

Description: NUnit. Range 'step' parameter value must be non-zero.

Label Label Label

Bad Example
[TestCase(1, 10, 0)] public void TestMethod(int start, int end, int step) { /* ... */ }
Good Example
[TestCase(1, 10, 2)] public void TestMethod(int start, int end, int step) { /* ... */ }

Range Value not Reachable

Description: NUnit. The maximum range value is not reachable with the step value.

Label Label Label

Bad Example
[TestCase(1, 10, 5)] public void Method(int start, int end, int step) { /* ... */ }
Good Example
[TestCase(1, 10, 2)] public void Method(int start, int end, int step) { /* ... */ }

Razor Layout Not Resolved

Description: Unknown Razor layout

Label Label Label

Bad Example
@{ Layout = "UnknownLayout.cshtml"; }
Good Example
@{ Layout = "_Layout.cshtml"; // Ensure layout file exists }

Razor Section Not Resolved

Description: Unknown Razor section

Label Label Label

Bad Example
@RenderSection("unknownSection")
Good Example
@RenderSection("Scripts", required: false) // Verify section existence

Read Access in Double Check Locking

Description: Possible incorrect implementation of Double-Check Locking pattern. Read access to checked field

Label Label Label

Bad Example
if (_instance == null) { lock(_lock) { if (_instance == null) _instance = new Singleton(); } }
Good Example
private static readonly object _lock = new object(); if (_instance == null) { lock(_lock) { if (_instance == null) _instance = new Singleton(); } }

Real Shift Count Zero

Description: Actual shift count equals zero.

Label Label Label

Bad Example
int result = value << 0;
Good Example
int result = value;

Redundant Abstract Modifier

Description: Redundant 'abstract' modifier

Label Label Label

Bad Example
public abstract abstract class Shape { ... } // Double abstract modifier
Good Example
public abstract class Shape { ... } // Only one abstract modifier

Redundant Anonymous Type

Description: Redundant anonymous type property explicit name

Label Label Label

Bad Example
var person = new { Name = name, Age = age };
Good Example
var person = new { name, age }; // Remove explicit property names if variable names match

Redundant Argument Default Value

Description: Redundant argument with default value

Label Label Label

Bad Example
MyMethod(true); // true is default value
Good Example
MyMethod(); // Omit argument if it's the default value

Redundant Argument in InlineAutoData Attribute

Description: NUnit.AutoFixture. Redundant argument in InlineAutoData attribute

Label Label Label

Bad Example
[InlineAutoData(42, "Redundant")] public void Test(int value) { /* ... */ }
Good Example
[InlineAutoData] public void Test(int value) { /* ... */ }

Redundant Array Creation

Description: Array creation can be replaced with array initializer

Label Label Label

Bad Example
int[] numbers = new int[] { 1, 2, 3 };
Good Example
int[] numbers = { 1, 2, 3 }; // Use array initializer

Redundant Assignment

Description: Assignment is not used

Label Label Label

Bad Example
int value = 10; // value is assigned but never used
Good Example
// Remove unused assignment if value is not used

Redundant Attribute Parentheses

Description: Parentheses are redundant if attribute has no arguments

Label Label Label

Bad Example
[Obsolete()] public void OldMethod() { ... } // Redundant parentheses
Good Example
[Obsolete] public void OldMethod() { ... } // Removed unnecessary parentheses

Redundant Attribute Usage Property

Description: Redundant [AttributeUsage] attribute property assignment

Label Label Label

Bad Example
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] // Default value
Good Example
[AttributeUsage(AttributeTargets.Class)] // Removed redundant property

Redundant Base Qualifier

Description: Redundant 'base.' qualifier

Label Label Label

Bad Example
base.SomeMethod();
Good Example
SomeMethod(); // Remove base qualifier when not required

Redundant Blank Lines

Description: Incorrect blank lines (blank lines are redundant elsewhere).

Label Label Label

Bad Example
public class Example
{


void Method() {}


}
Good Example
public class Example
{

void Method() {}

}

Redundant Bool Compare

Description: Redundant boolean comparison

Label Label Label

Bad Example
if (isTrue == true) { /* code */ }
Good Example
if (isTrue) { /* code */ } // Simplify boolean comparison

Redundant Braces

Description: Use preferred braces style (remove redundant braces)

Label Label Label

Bad Example
if (condition) { DoSomething(); }
Good Example
if (condition) DoSomething();

Redundant Case Label

Description: Redundant 'case' label

Label Label Label

Bad Example
case SomeEnum.Value: /* code */; break; default: /* code */;
Good Example
default: /* code */; // Remove redundant case label if handled in default

Redundant Cast

Description: Redundant cast

Label Label Label

Bad Example
int value = (int)myNumber;
Good Example
int value = myNumber; // Remove redundant cast if unnecessary

Redundant Catch

Description: Redundant catch clause

Label Label Label

Bad Example
try { /* code */ } catch (Exception ex) { throw; }
Good Example
try { /* code */ } // Remove redundant catch clause if rethrowing

Redundant Check

Description: Redundant condition check before assignments

Label Label Label

Bad Example
if (x != 5) x = 5; // Unnecessary condition before assignment
Good Example
x = 5; // Direct assignment without condition check

Redundant Collection Braces

Description: Redundant braces in collection initializer

Label Label Label

Bad Example
var list = new List<int> { { 1 }, { 2 }, { 3 } };
Good Example
var list = new List<int> { 1, 2, 3 }; // Remove unnecessary braces

Redundant Configure Await

Description: Redundant 'ConfigureAwait(true)'

Label Label Label

Bad Example
await someTask.ConfigureAwait(true); // 'true' is redundant
Good Example
await someTask; // Removed unnecessary ConfigureAwait

Redundant Constructor Call

Description: Redundant base constructor call

Label Label Label

Bad Example
public Child() : base() { }
Good Example
// Remove the base constructor call if it's redundant

Redundant Declaration Semicolon

Description: Redundant semicolon after type or namespace declaration

Label Label Label

Bad Example
namespace MyNamespace {};
Good Example
namespace MyNamespace {} // Remove unnecessary semicolon

Redundant Delegate Creation

Description: Explicit delegate creation expression is redundant

Label Label Label

Bad Example
var action = new Action(() => DoSomething()); // Redundant delegate creation
Good Example
Action action = DoSomething; // Simplified without explicit creation

Redundant Discard

Description: Redundant discard designation

Label Label Label

Bad Example
var (_, y) = GetTuple(); // Discard is redundant
Good Example
var y = GetTuple().Item2; // Removed unnecessary discard

Redundant Empty Finally Block

Description: Redundant empty finally block

Label Label Label

Bad Example
try { ... } finally { } // Empty finally block
Good Example
try { ... } // Removed unnecessary finally block

Redundant Empty Object

Description: Redundant empty object or collection initializer

Label Label Label

Bad Example
var list = new List<int>() { }; // Empty initializer is redundant
Good Example
var list = new List<int>(); // Removed unnecessary initializer

Redundant Empty Object Creation Argument List

Description: Redundant empty argument list on object creation expression

Label Label Label

Bad Example
var obj = new MyClass(); // Empty argument list is redundant
Good Example
var obj = new MyClass; // Simplified object creation

Redundant Empty Switch

Description: Redundant empty switch section

Label Label Label

Bad Example
switch (value) { case 1: break; } // Empty switch section
Good Example
switch (value) { case 1: DoSomething(); break; }

Redundant Enum Case Label

Description: Redundant 'case' label before default section

Label Label Label

Bad Example
case MyEnum.Option1: /* code */; break; default: /* code */;
Good Example
default: /* code */; // Remove case if redundant with default

Redundant Enumerable Cast Call

Description: Redundant 'IEnumerable.Cast' or 'IEnumerable.OfType' call

Label Label Label

Bad Example
var numbers = collection.Cast<int>();
Good Example
var numbers = collection; // Remove redundant Cast or OfType if not needed

Redundant Explicit Array Creation

Description: Redundant explicit type in array creation

Label Label Label

Bad Example
int[] numbers = new int[] { 1, 2, 3 };
Good Example
var numbers = new[] { 1, 2, 3 }; // Use implicit typing if possible

Redundant Explicit Array Size

Description: Redundant explicit size specification in array creation

Label Label Label

Bad Example
int[] numbers = new int[3] { 1, 2, 3 };
Good Example
int[] numbers = new int[] { 1, 2, 3 }; // Remove explicit size specification

Redundant Explicit Positional

Description: Redundant explicit positional property declaration

Label Label Label

Bad Example
record Person(string Name, string Name) { }
Good Example
record Person(string Name) { } // Remove redundant explicit positional declaration

Redundant Explicit Tuple Name

Description: Redundant explicit tuple component name

Label Label Label

Bad Example
var tuple = (Name: "John", Age: 30);
Good Example
var tuple = ("John", 30); // Remove explicit component names if unnecessary

Redundant False Statement

Description: Remove redundant statement

Label Label Label

Bad Example
if (isActive || false) { /* Redundant false OR condition */ }
Good Example
if (isActive) { /* Clean condition without redundant OR */ }

Redundant Fixed Pointer Declaration

Description: Redundant fixed pointer declaration

Label Label Label

Bad Example
fixed (int* ptr = &array[0]) { /* code */ }
Good Example
/* code */ // Remove fixed pointer declaration if unnecessary

Redundant Global Using Directive

Description: Redundant global using directive

Label Label Label

Bad Example
global using System;
Good Example
// Remove redundant global using directive if unused in the project

Redundant If Else Block

Description: Redundant 'else' keyword

Label Label Label

Bad Example
if (condition) { ... } else { return; } // Redundant else
Good Example
if (condition) { ... } return; // Removed unnecessary else

Redundant Immediate Delegate Invocation

Description: Immediate delegate invocation

Label Label Label

Bad Example
((Action)delegate { Console.WriteLine("Hello"); })(); // Immediate delegate invocation
Good Example
Console.WriteLine("Hello"); // Directly execute the code

Redundant Is

Description: Redundant 'is' before relational pattern

Label Label Label

Bad Example
if (x is >= 10) { /* Condition with redundant 'is' */ }
Good Example
if (x >= 10) { /* Clean condition without redundant 'is' */ }

Redundant Jump

Description: Redundant control flow jump statement

Label Label Label

Bad Example
return; // Return statement without purpose
Good Example
Console.WriteLine("Complete"); // Removed unnecessary return

Redundant Lambda Parameter Type

Description: Redundant lambda expression parameter type specification

Label Label Label

Bad Example
Func<int, int> square = (int x) => x * x;
Good Example
Func<int, int> square = x => x * x; // Remove redundant type specification

Redundant Lambda Parentheses

Description: Redundant lambda signature parentheses

Label Label Label

Bad Example
Func<int, int> square = (x) => x * x;
Good Example
Func<int, int> square = x => x * x; // Remove redundant parentheses for single parameter

Redundant Line Break

Description: Incorrect line breaks (line break is redundant elsewhere).

Label Label Label

Bad Example
public void Method() {

int x = 5;

}
Good Example
public void Method() {
int x = 5;
}

Redundant List Entry

Description: Redundant class or interface specification in base types list

Label Label Label

Bad Example
class Derived : Base, Base { }
Good Example
// Remove duplicate or redundant base type declarations

Redundant Match Subpattern

Description: Redundant always match subpattern

Label Label Label

Bad Example
if (x is int _) { ... } // Redundant subpattern match
Good Example
if (x is int) { ... } // Removed unnecessary subpattern

Redundant Math Abs Method

Description: Math.Abs() argument is always non-negative

Label Label Label

Bad Example
int x = Math.Abs(positiveValue); // Argument is already non-negative
Good Example
int x = positiveValue; // Removed redundant Math.Abs() call

Redundant Member Initializer

Description: Redundant default member initializer

Label Label Label

Bad Example
private int value = 0; // '0' is default for int
Good Example
private int value; // Default initialization

Redundant Name Qualifier

Description: Redundant name qualifier

Label Label Label

Bad Example
System.Console.WriteLine("Hello"); // Redundant System qualifier
Good Example
Console.WriteLine("Hello"); // Removed redundant qualifier

Redundant Not Null Constraint

Description: Redundant 'notnull' constraint on type parameter constrained by non-nullable base type.

Label Label Label

Bad Example
where T : SomeClass, notnull // Redundant 'notnull' constraint
Good Example
where T : SomeClass // Simplified without 'notnull'

Redundant Nullable Annotation Non Nullable Type

Description: Redundant nullable annotation on base type constraint of type parameter having non-nullable type kind.

Label Label Label

Bad Example
where T : struct? // Redundant nullable annotation
Good Example
where T : struct // Removed unnecessary nullable annotation

Redundant Nullable Annotation Nullable Base Type

Description: Redundant nullable annotation on base type constraint of type parameter constrained by another non-nullable base type.

Label Label Label

Bad Example
where T : SomeClass? // Nullable annotation is redundant
Good Example
where T : SomeClass // Removed unnecessary nullable annotation

Redundant Nullable Annotation Reference Type

Description: Redundant nullable annotation on 'class?' constraint of type parameter constrained by non-nullable base type.

Label Label Label

Bad Example
where T : class? // Nullable annotation is redundant
Good Example
where T : class // Removed unnecessary nullable annotation

Redundant Nullable Creation

Description: Redundant explicit nullable type creation

Label Label Label

Bad Example
Nullable<int> x = new Nullable<int>(5); // Explicit nullable creation is redundant
Good Example
int? x = 5; // Simplified nullable assignment

Redundant Nullable Flow Attribute

Description: Redundant nullable attribute.

Label Label Label

Bad Example
[AllowNull] public string? Name { get; set; } // Redundant nullable attribute
Good Example
public string? Name { get; set; } // Removed unnecessary nullable attribute

Redundant Nullable Type Check

Description: Type check for nullable type is equal to underlying type check

Label Label Label

Bad Example
if (obj is int?) { ... } // Redundant nullable check
Good Example
if (obj is int) { ... } // Simplified without nullable mark

Redundant Nullness Attribute Nullable Reference Types

Description: [NotNull] or [CanBeNull] attribute is applied to a type that already has the same annotation from nullable reference types.

Label Label Label

Bad Example
[NotNull] public string Name { get; set; }
Good Example
public string Name { get; set; } // Remove redundant [NotNull] if nullable annotations are used

Redundant Operand

Description: Redundant operand in logical conditional expression

Label Label Label

Bad Example
if (isTrue && true) { ... } // Redundant '&& true'
Good Example
if (isTrue) { ... } // Removed redundant operand

Redundant Output Non-Private Accessibility

Description: Parameter output value is always discarded (non-private accessibility)

Label Label Label

Bad Example
public void ProcessData(out int result) { result = 5; } // result is never used
Good Example
// Refactor to remove the out parameter if the result is not needed

Redundant Output Private Accessibility

Description: Parameter output value is always discarded (private accessibility)

Label Label Label

Bad Example
private void Calculate(out int total) { total = 0; } // total is ignored
Good Example
// Remove the out parameter or use it if necessary

Redundant Overflow Checking

Description: Redundant arithmetic overflow checking context

Label Label Label

Bad Example
checked { int result = a + b; } // when overflow checking is enabled globally
Good Example
int result = a + b; // Remove checked if unnecessary

Redundant Overload Non-Private Accessibility

Description: Redundant method overload (non-private accessibility)

Label Label Label

Bad Example
public void Process(int x) {} public void Process(int x, int y = 0) {}
Good Example
// Use a single method with optional parameters if overloads are redundant

Redundant Overload Private Accessibility

Description: Redundant method overload (private accessibility)

Label Label Label

Bad Example
private void Calculate(int x) {} private void Calculate(int x, int y = 0) {}
Good Example
// Simplify to one method with optional parameters

Redundant Overridden Member

Description: Redundant member override

Label Label Label

Bad Example
public override void Method() { base.Method(); }
Good Example
// Remove the redundant override if it only calls base implementation

Redundant Params

Description: 'params' modifier is always ignored on overrides

Label Label Label

Bad Example
public override void Method(params int[] values) { }
Good Example
// Remove the 'params' modifier from the override

Redundant Params Array Creation

Description: Redundant explicit array creation in argument of 'params' parameter

Label Label Label

Bad Example
Method(new int[] { 1, 2, 3 }); // Explicit array creation is redundant
Good Example
Method(1, 2, 3); // Simplified without explicit array creation

Redundant Parentheses

Description: Remove redundant parentheses

Label Label Label

Bad Example
int result = (a + b);
Good Example
int result = a + b;

Redundant Pattern Parentheses

Description: Remove redundant pattern-matching parentheses

Label Label Label

Bad Example
if ((obj is int value)) { ... } // Redundant parentheses
Good Example
if (obj is int value) { ... } // Removed unnecessary parentheses

Redundant Property Pattern Clause

Description: Redundant property pattern clause

Label Label Label

Bad Example
case { Name: "" }: // Redundant pattern clause
Good Example
case { }: // Removed unnecessary clause

Redundant Query Order

Description: Redundant 'orderby' clause 'ascending' keyword

Label Label Label

Bad Example
var sorted = items.OrderBy(x => x, ascending); // 'ascending' is redundant
Good Example
var sorted = items.OrderBy(x => x); // Simplified without 'ascending'

Redundant Range Bound

Description: Redundant range bound

Label Label Label

Bad Example
var range = 0..^0; // Redundant range bound
Good Example
var range = 0..; // Removed unnecessary bound

Redundant Readonly Modifier

Description: Redundant 'readonly' modifier

Label Label Label

Bad Example
readonly int x; // Redundant 'readonly' modifier
Good Example
int x; // Removed unnecessary 'readonly' modifier

Redundant Record Body

Description: Redundant 'record' type declaration body

Label Label Label

Bad Example
record Person { }
Good Example
record Person; // Use record declaration without body if no additional members are defined

Redundant Record Class Keyword

Description: Redundant 'class' keyword in record declaration

Label Label Label

Bad Example
public record class Person(string Name); // 'class' keyword is redundant
Good Example
public record Person(string Name); // Simplified without 'class' keyword

Redundant Space

Description: Incorrect spacing (space is redundant elsewhere).

Label Label Label

Bad Example
int  x = 5;
Good Example
int x = 5;

Redundant String Format

Description: Redundant 'string.Format()' call

Label Label Label

Bad Example
var message = string.Format("Hello {0}", "world");
Good Example
var message = "Hello world"; // Use a simple string instead of string.Format when no formatting is required

Redundant String Interpolation

Description: Redundant string interpolation

Label Label Label

Bad Example
var message = $"Hello";
Good Example
var message = "Hello"; // Use a plain string if no interpolation is needed

Redundant String Prefix

Description: Redundant verbatim string prefix

Label Label Label

Bad Example
var path = @"C:\folder"; // Verbatim prefix '@' is redundant
Good Example
var path = "C:\folder"; // Removed redundant '@'

Redundant String To Char

Description: Redundant 'string.ToCharArray()' call

Label Label Label

Bad Example
var chars = "hello".ToCharArray();
Good Example
var chars = "hello"; // Remove redundant ToCharArray() if the string can be used directly

Redundant Suppress Warning

Description: Redundant suppress nullable warnings expression.

Label Label Label

Bad Example
string? name = null!;
Good Example
string? name = null; // Remove unnecessary suppression

Redundant Ternary Expression

Description: Redundant conditional ternary expression usage

Label Label Label

Bad Example
int result = isTrue ? 1 : 1; // Same value for both cases
Good Example
int result = 1; // Removed redundant ternary expression

Redundant To String Call

Description: Redundant 'object.ToString()' call

Label Label Label

Bad Example
var text = myString.ToString(); // 'ToString()' call is redundant
Good Example
var text = myString; // Simplified by removing 'ToString()'

Redundant To String Call Value Types

Description: Redundant 'object.ToString()' call for value types

Label Label Label

Bad Example
int number = 42; var text = number.ToString(); // Redundant 'ToString()'
Good Example
int number = 42; var text = "" + number; // Alternative without 'ToString()'

Redundant True Statement

Description: Remove redundant statement

Label Label Label

Bad Example
if (isComplete || true) { /* Redundant true OR condition */ }
Good Example
if (true) { /* Clean condition with only true */ }

Redundant Type Arguments

Description: Redundant type arguments of method

Label Label Label

Bad Example
var result = DoSomething<int>();
Good Example
var result = DoSomething(); // Remove redundant type argument if it can be inferred

Redundant Type Check

Description: Redundant type check in a pattern

Label Label Label

Bad Example
if (x is int i) { }
Good Example
if (x is int) { } // Simplify type pattern if variable is not used

Redundant Unsafe Context

Description: Unsafe context declaration is redundant

Label Label Label

Bad Example
unsafe { int* p = &value; } // Redundant unsafe context
Good Example
int* p = &value; // Removed unnecessary 'unsafe' block

Redundant Using Directive

Description: Redundant using directive

Label Label Label

Bad Example
using System.Text; // Unused directive
Good Example
// Remove unused using directives

Redundant Verbatim Prefix

Description: Redundant verbatim prefix

Label Label Label

Bad Example
var path = @"C:\Users\Name";
Good Example
var path = "C:\Users\Name"; // Remove verbatim prefix if it is unnecessary

Redundant with Expression

Description: Empty 'with' expression is redundant

Label Label Label

Bad Example
var personClone = person with { }; // Redundant
Good Example
var personClone = person; // Simply assign the object

Reference Equals with Value Type

Description: 'Object.ReferenceEquals' is always false because it is called with value type

Label Label Label

Bad Example
Object.ReferenceEquals(5, 5); // Always false for value types
Good Example
int x = 5; int y = 5; Console.WriteLine(x == y); // Proper equality check for value types

Reference to Non-Volatile Volatile Field

Description: Reference to a volatile field will not be treated as volatile

Label Label Label

Bad Example
int temp = myVolatileField;
Good Example
int temp = Volatile.Read(ref myVolatileField);

Remove ToList

Description: Remove ToList()

Label Label Label

Bad Example
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList(); // Unnecessary ToList()
Good Example
var evenNumbers = numbers.Where(n => n % 2 == 0); // Removed ToList() to defer execution

Remove ToList

Description: Remove ToList()

Label Label Label

Bad Example
var squares = numbers.Select(n => n * n).ToList(); // Unnecessary ToList() call
Good Example
var squares = numbers.Select(n => n * n); // Deferred execution by removing ToList()

Replace Virtual to Helper Function

Description: Access to a member through 'base' keyword from anonymous method, lambda expression, query expression or iterator results in unverifiable code

Label Label Label

Bad Example
base.SomeMethod();
Good Example
CallBaseMethod(); // Helper method to avoid using 'base' in lambda

Replace with FirstOrDefault

Description: Replace with FirstOrDefault($args$)

Label Label Label

Bad Example
var result = items.Where(x => x.IsActive).First();
Good Example
var result = items.FirstOrDefault(x => x.IsActive);

Replace with FirstOrDefault

Description: Replace with FirstOrDefault($args$)

Label Label Label

Bad Example
var result = items.Where(x => x.Age > 18).First();
Good Example
var result = items.FirstOrDefault(x => x.Age > 18);

Replace with FirstOrDefault

Description: Replace with FirstOrDefault($args$)

Label Label Label

Bad Example
var user = users.Where(u => u.Name == "John").First();
Good Example
var user = users.FirstOrDefault(u => u.Name == "John");

Replace with FirstOrDefault

Description: Replace with FirstOrDefault($args$)

Label Label Label

Bad Example
var item = data.Where(d => d.Status == "Active").First();
Good Example
var item = data.FirstOrDefault(d => d.Status == "Active");

Replace with LastOrDefault

Description: Replace with LastOrDefault($args$)

Label Label Label

Bad Example
var result = items.Where(x => x.IsActive).Last();
Good Example
var result = items.LastOrDefault(x => x.IsActive);

Replace with LastOrDefault

Description: Replace with LastOrDefault($args$)

Label Label Label

Bad Example
var lastMatch = items.Where(x => x.Category == "A").Last();
Good Example
var lastMatch = items.LastOrDefault(x => x.Category == "A");

Replace with LastOrDefault

Description: Replace with LastOrDefault($args$)

Label Label Label

Bad Example
var item = collection.Where(c => c.Price > 100).Last();
Good Example
var item = collection.LastOrDefault(c => c.Price > 100);

Replace with LastOrDefault

Description: Replace with LastOrDefault($args$)

Label Label Label

Bad Example
var element = elements.Where(e => e.IsEnabled).Last();
Good Example
var element = elements.LastOrDefault(e => e.IsEnabled);

Replace with ofType

Description: Replace with OfType()

Label Label Label

Bad Example
var stringItems = items.Where(item => item is string).Cast<string>();
Good Example
var stringItems = items.OfType<string>();

Replace with ofType

Description: Replace with OfType()

Label Label Label

Bad Example
var intItems = items.Where(item => item is int).Cast<int>();
Good Example
var intItems = items.OfType<int>();

Replace with ofType

Description: Replace with OfType().Where() (replace with OfType().Where(..))

Label Label Label

Bad Example
var matches = items.Where(x => x is MyType && x.IsAvailable).Cast<MyType>();
Good Example
var matches = items.OfType<MyType>().Where(x => x.IsAvailable);

Replace with OfType

Description: Replace with OfType()

Label Label Label

Bad Example
var strings = items.Where(x => x is string).Cast<string>();
Good Example
var strings = items.OfType<string>();

Replace with ofType Any

Description: Replace with OfType().Any()

Label Label Label

Bad Example
var hasStrings = items.Where(item => item is string).Any();
Good Example
var hasStrings = items.OfType<string>().Any();

Replace with ofType Any

Description: Replace with OfType().Any()

Label Label Label

Bad Example
var hasInts = items.Where(item => item is int).Any();
Good Example
var hasInts = items.OfType<int>().Any();

Replace with ofType Count

Description: Replace with OfType().Count()

Label Label Label

Bad Example
var stringCount = items.Where(item => item is string).Count();
Good Example
var stringCount = items.OfType<string>().Count();

Replace with ofType Count

Description: Replace with OfType().Count()

Label Label Label

Bad Example
var intCount = items.Where(item => item is int).Count();
Good Example
var intCount = items.OfType<int>().Count();

Replace with ofType First

Description: Replace with OfType().First()

Label Label Label

Bad Example
var firstString = items.Where(item => item is string).Cast<string>().First();
Good Example
var firstString = items.OfType<string>().First();

Replace with ofType First

Description: Replace with OfType().First()

Label Label Label

Bad Example
var firstInt = items.Where(item => item is int).Cast<int>().First();
Good Example
var firstInt = items.OfType<int>().First();

Replace with ofType FirstOrDefault

Description: Replace with OfType().FirstOrDefault()

Label Label Label

Bad Example
var firstString = items.Where(item => item is string).Cast<string>().FirstOrDefault();
Good Example
var firstString = items.OfType<string>().FirstOrDefault();

Replace with ofType FirstOrDefault

Description: Replace with OfType().FirstOrDefault()

Label Label Label

Bad Example
var firstInt = items.Where(item => item is int).Cast<int>().FirstOrDefault();
Good Example
var firstInt = items.OfType<int>().FirstOrDefault();

Replace with ofType Last

Description: Replace with OfType().Last()

Label Label Label

Bad Example
var lastItem = items.Where(x => x is MyType).Cast<MyType>().Last();
Good Example
var lastItem = items.OfType<MyType>().Last();

Replace with ofType Last

Description: Replace with OfType().Last() (replace with OfType().Last(..))

Label Label Label

Bad Example
var lastMatch = list.Where(x => x is MyType && x.IsActive).Cast<MyType>().Last();
Good Example
var lastMatch = list.OfType<MyType>().Last(x => x.IsActive);

Replace with ofType LastOrDefault

Description: Replace with OfType().LastOrDefault()

Label Label Label

Bad Example
var lastOrDefault = collection.Where(x => x is MyType).Cast<MyType>().LastOrDefault();
Good Example
var lastOrDefault = collection.OfType<MyType>().LastOrDefault();

Replace with ofType LastOrDefault

Description: Replace with OfType().LastOrDefault() (replace with OfType().LastOrDefault(..))

Label Label Label

Bad Example
var lastItem = items.Where(x => x is MyType && x.IsAvailable).Cast<MyType>().LastOrDefault();
Good Example
var lastItem = items.OfType<MyType>().LastOrDefault(x => x.IsAvailable);

Replace with ofType Long Count

Description: Replace with OfType().LongCount()

Label Label Label

Bad Example
var count = items.Where(x => x is MyType).Cast<MyType>().LongCount();
Good Example
var count = items.OfType<MyType>().LongCount();

Replace with ofType Single

Description: Replace with OfType().Single()

Label Label Label

Bad Example
var singleItem = collection.Where(x => x is MyType).Cast<MyType>().Single();
Good Example
var singleItem = collection.OfType<MyType>().Single();

Replace with ofType Single

Description: Replace with OfType().Single() (replace with OfType().Single(..))

Label Label Label

Bad Example
var singleItem = items.Where(x => x is MyType && x.IsUnique).Cast<MyType>().Single();
Good Example
var singleItem = items.OfType<MyType>().Single(x => x.IsUnique);

Replace with ofType SingleOrDefault

Description: Replace with OfType().SingleOrDefault()

Label Label Label

Bad Example
var singleOrDefault = collection.Where(x => x is MyType).Cast<MyType>().SingleOrDefault();
Good Example
var singleOrDefault = collection.OfType<MyType>().SingleOrDefault();

Replace with ofType SingleOrDefault

Description: Replace with OfType().SingleOrDefault() (replace with OfType().SingleOrDefault(..))

Label Label Label

Bad Example
var item = items.Where(x => x is MyType && x.IsActive).Cast<MyType>().SingleOrDefault();
Good Example
var item = items.OfType<MyType>().SingleOrDefault(x => x.IsActive);

Replace with Simple False Assignment

Description: Replace with simple assignment

Label Label Label

Bad Example
bool isAvailable = isAvailable == false ? false : isAvailable;
Good Example
bool isAvailable = false;

Replace with Simple True Assignment

Description: Replace with simple assignment

Label Label Label

Bad Example
if (condition) { flag = true; } else { flag = false; }
Good Example
flag = condition;

Replace with Single Call to Any

Description: Replace with single call to Any(..)

Label Label Label

Bad Example
var hasItems = collection.Count() > 0;
Good Example
var hasItems = collection.Any();

Replace with Single Call to Count

Description: Replace with single call to Count(..)

Label Label Label

Bad Example
var count = collection.Where(item => item.IsActive).Count();
Good Example
var count = collection.Count(item => item.IsActive);

Replace with Single Call to First

Description: Replace with single call to First(..)

Label Label Label

Bad Example
var firstActive = collection.Where(item => item.IsActive).First();
Good Example
var firstActive = collection.First(item => item.IsActive);

Replace with Single Call to FirstOrDefault

Description: Replace with single call to FirstOrDefault(..)

Label Label Label

Bad Example
var firstInactive = collection.Where(item => !item.IsActive).FirstOrDefault();
Good Example
var firstInactive = collection.FirstOrDefault(item => !item.IsActive);

Replace with Single Call to Last

Description: Replace with single call to Last(..)

Label Label Label

Bad Example
var lastItem = collection.Where(item => item.IsActive).Last();
Good Example
var lastItem = collection.Last(item => item.IsActive);

Replace with Single Call to LastOrDefault

Description: Replace with single call to LastOrDefault(..)

Label Label Label

Bad Example
var lastInactive = collection.Where(item => !item.IsActive).LastOrDefault();
Good Example
var lastInactive = collection.LastOrDefault(item => !item.IsActive);

Replace with Single Call to Single

Description: Replace with single call to Single(..)

Label Label Label

Bad Example
var singleItem = items.Where(x => x.IsMatch).Single();
Good Example
var singleItem = items.Single(x => x.IsMatch);

Replace with Single Call to Single or Default

Description: Replace with single call to SingleOrDefault(..)

Label Label Label

Bad Example
var singleOrDefaultItem = items.Where(x => x.IsMatch).SingleOrDefault();
Good Example
var singleOrDefaultItem = items.SingleOrDefault(x => x.IsMatch);

Replace with Single False Assignment

Description: Replace with single assignment

Label Label Label

Bad Example
isAvailable = isAvailable == false;
Good Example
isAvailable = false;

Replace with Single or Default

Description: Replace with SingleOrDefault($args$)

Label Label Label

Bad Example
var result = items.Where(x => x == condition).SingleOrDefault();
Good Example
var result = items.SingleOrDefault(x => x == condition);

Replace with Single or Default

Description: Replace with SingleOrDefault($args$)

Label Label Label

Bad Example
var result = items.Where(x => x == condition).SingleOrDefault();
Good Example
var result = items.SingleOrDefault(x => x == condition);

Replace with Single or Default

Description: Replace with SingleOrDefault($args$)

Label Label Label

Bad Example
var result = items.Where(x => x == condition).SingleOrDefault();
Good Example
var result = items.SingleOrDefault(x => x == condition);

Replace with Single or Default

Description: Replace with SingleOrDefault($args$)

Label Label Label

Bad Example
var result = items.Where(x => x == condition).SingleOrDefault();
Good Example
var result = items.SingleOrDefault(x => x == condition);

Replace with Single True Assignment

Description: Replace with single assignment

Label Label Label

Bad Example
isEnabled = isEnabled == true;
Good Example
isEnabled = true;

Required Base Types Conflict

Description: Required base type conflicting another type.

Label Label Label

Bad Example
class Example : BaseType, AnotherBaseType { }
Good Example
class Example : BaseType { }

Required Base Types Direct Conflict

Description: Type specified in '[BaseTypeRequired]' attribute conflicts another type.

Label Label Label

Bad Example
[BaseTypeRequired(typeof(BaseType))]
class Example : AnotherBaseType { }
Good Example
[BaseTypeRequired(typeof(BaseType))]
class Example : BaseType { }

Required Base Types not Inherited

Description: Base type is required

Label Label Label

Bad Example
public class DerivedClass {}
Good Example
public class DerivedClass : RequiredBaseClass {}

Resource Item not Resolved

Description: Cannot resolve resource item

Label Label Label

Bad Example
var item = Resources.MyResource.NonExistentItem;
Good Example
var item = Resources.MyResource.ExistingItem;

Resource not Resolved

Description: Cannot resolve resource

Label Label Label

Bad Example
var text = Resources.NonExistentResource;
Good Example
var text = Resources.ExistingResource;

Return Type not Nullable

Description: Return type of a function can be non-nullable

Label Label Label

Bad Example
public string? GetString() { return "Hello"; } // Return type could be non-nullable
Good Example
public string GetString() { return "Hello"; } // Return type explicitly non-nullable

Return Type Nullability Mismatch in Implementation

Description: Nullability of reference types in return type doesn't match implemented member.

Label Label Label

Bad Example
public string? ImplementedMethod() => "Text"; // Expected non-nullable return
Good Example
public string ImplementedMethod() => "Text"; // Matches non-nullable return

Return Type Nullability Mismatch in Implicit Implementation

Description: Nullability of reference types in return type doesn't match implicitly implemented member.

Label Label Label

Bad Example
public string? ImplicitMethod() => "Text"; // Expected non-nullable return
Good Example
public string ImplicitMethod() => "Text"; // Matches non-nullable return

Return Type Nullability Mismatch in Override

Description: Nullability of reference types in return type doesn't match overridden member.

Label Label Label

Bad Example
public override string? OverriddenMethod() => "Text"; // Expected non-nullable return
Good Example
public override string OverriddenMethod() => "Text"; // Matches non-nullable return

Return Type Nullability Mismatch in Partial Method

Description: Nullability of reference types in return type doesn't match partial method declaration.

Label Label Label

Bad Example
public partial string? PartialMethod(); // Expected non-nullable return
Good Example
public partial string PartialMethod(); // Matches non-nullable return

Return Type Nullability Mismatch with Delegate

Description: Nullability of reference types in return type doesn't match the target delegate (possibly because of nullability attributes).

Label Label Label

Bad Example
Func<string?> func = () => "Text"; // Expected non-nullable return
Good Example
Func<string> func = () => "Text"; // Matches non-nullable return

Return Type Nullability Mismatch with Implemented Member

Description: Nullability of return type doesn't match implemented member (possibly because of nullability attributes).

Label Label Label

Bad Example
public string? GetDetails() => "Details"; // Expected non-nullable
Good Example
public string GetDetails() => "Details"; // Matches non-nullable return

Return Type Nullability Mismatch with Implicitly Implemented Member

Description: Nullability of return type doesn't match implicitly implemented member (possibly because of nullability attributes).

Label Label Label

Bad Example
public string? GetData() => "Data"; // Expected non-nullable
Good Example
public string GetData() => "Data"; // Matches non-nullable return type

Return Type Nullability Mismatch with Overridden Member

Description: Nullability of return type doesn't match overridden member (possibly because of nullability attributes).

Label Label Label

Bad Example
public override string? GetDetails() => "Details"; // Expected non-nullable
Good Example
public override string GetDetails() => "Details"; // Matches non-nullable return type

Return Value of Pure Method not Used

Description: Return value of pure method is not used

Label Label Label

Bad Example
CalculateSum(5, 10); // Result ignored
Good Example
var result = CalculateSum(5, 10); // use result

Safe Cast for Type Check

Description: Try cast and check for null can be replaced with a type check

Label Label Label

Bad Example
var str = obj as string; if (str != null) { } // Safe cast used for type check
Good Example
if (obj is string str) { } // Direct type check

Sealed Member

Description: Sealed member in sealed class

Label Label Label

Bad Example
public sealed class MyClass { public sealed void Method() {} }
Good Example
// Remove 'sealed' modifier on member if the class itself is sealed

Service Contract without Operations

Description: Interfaces marked as ServiceContract should declare at least one OperationContract

Label Label Label

Bad Example
[ServiceContract] public interface IMyService { }
Good Example
[ServiceContract] public interface IMyService { [OperationContract] void MyOperation(); }

Shift Expression Result Equals Zero

Description: Constant shift expression with non-zero operands results in zero value.

Label Label Label

Bad Example
int result = 4 >> 5;
Good Example
int result = 4 << 1;

Shift Expression Zero Left Operand

Description: Shift expression with zero left operand equals zero.

Label Label Label

Bad Example
int result = 0 << 2;
Good Example
int value = 4; int result = value << 2;

Similar Anonymous Type Nearby

Description: Similar anonymous type detected nearby

Label Label Label

Bad Example
var person1 = new { Name = "John", Age = 30 }; var person2 = new { Name = "John", Age = 30 };
Good Example
var person = new { Name = "John", Age = 30 };

Simplify String Interpolation

Description: Use format specifier in interpolated strings

Label Label Label

Bad Example
string result = $"Value: {value}";
Good Example
string result = $"Value: {value:F2}"; // Use format specifier for precision

Source Type Nullability Mismatch

Description: Nullability of reference types in source type doesn't match target type.

Label Label Label

Bad Example
string? nullableString = nonNullableString; // Non-nullable expected
Good Example
string nonNullableString = nullableString ?? "default"; // Ensures non-nullable value

Spin Lock Read Only Field

Description: Do not store SpinLock in readonly field

Label Label Label

Bad Example
private readonly SpinLock _spinLock = new SpinLock();
Good Example
private SpinLock _spinLock = new SpinLock(); // Not readonly to avoid issues

Stack Alloc Inside Loop

Description: Using stackalloc inside loop

Label Label Label

Bad Example
for (int i = 0; i < 10; i++) { int* buffer = stackalloc int[10]; } // stackalloc in loop
Good Example
int* buffer = stackalloc int[10]; for (int i = 0; i < 10; i++) { ... } // Allocated once outside loop

Static Member in Generic Type

Description: Static field or auto-property in generic type

Label Label Label

Bad Example
class Container { public static int Count; }
Good Example
class Container { public int InstanceCount; }

Static Member Initializer

Description: Static member initializer refers to static member below or in other part

Label Label Label

Bad Example
class Example { static int A = B; static int B = 5; }
Good Example
class Example { static int B = 5; static int A = B; }

Static Member Qualifier

Description: Add/remove qualifier for static members

Label Label Label

Bad Example
Console.WriteLine("Hello");
Good Example
System.Console.WriteLine("Hello");

Static Problem in Text

Description: Cannot access static symbol in text argument

Label Label Label

Bad Example
var text = "Static value: " + MyClass.StaticValue;
Good Example
var text = string.Format("Static value: {0}", MyClass.StaticValue);

Static Test Case Source

Description: NUnit. Test case source must be static.

Label Label Label

Bad Example
[TestCaseSource(nameof(InstanceSource))] public void Method() { /* ... */ }
Good Example
[TestCaseSource(nameof(StaticSource))] public void Method() { /* ... */ }

Static Type in 'is' or 'as' Operator

Description: Static type in 'is' or 'as' operator.

Label Label Label

Bad Example
if (obj is typeof(MyClass)) { /* do something */ }
Good Example
if (obj is MyClass) { /* do something */ }

String Compare Culture Specific

Description: String.Compare is culture-specific (string.Compare(string, int, string, int) is culture-specific)

Label Label Label

Bad Example
int result = String.Compare(str1, 0, str2, 0, str2.Length);
Good Example
int result = String.Compare(str1, 0, str2, 0, str2.Length, StringComparison.Ordinal);

String Compare Culture Specific

Description: String.Compare is culture-specific (string.Compare(string, int, string, int, bool) is culture-specific)

Label Label Label

Bad Example
int result = String.Compare(str1, 0, str2, 0, str2.Length, ignoreCase);
Good Example
int result = String.Compare(str1, 0, str2, 0, str2.Length, ignoreCase, StringComparison.Ordinal);

String Compare Culture Specific

Description: String.Compare is culture-specific (string.Compare(string, int, string, int, bool) is culture-specific)

Label Label Label

Bad Example
int result = String.Compare(str1, 0, str2, 0, str2.Length, ignoreCase);
Good Example
int result = String.Compare(str1, 0, str2, 0, str2.Length, ignoreCase, StringComparison.Ordinal);

String Compare Culture Specific

Description: String.Compare is culture-specific (string.Compare(string, string) is culture-specific)

Label Label Label

Bad Example
int result = String.Compare(str1, str2);
Good Example
int result = String.Compare(str1, str2, StringComparison.Ordinal);

String Compare Culture Specific

Description: String.Compare is culture-specific (string.Compare(string, string, bool) is culture-specific)

Label Label Label

Bad Example
int result = String.Compare(str1, str2, ignoreCase);
Good Example
int result = String.Compare(str1, str2, ignoreCase, StringComparison.Ordinal);

String Compare Culture Specific

Description: String.Compare is culture-specific (string.Compare(string, string, bool) is culture-specific)

Label Label Label

Bad Example
int result = String.Compare(str1, str2, ignoreCase);
Good Example
int result = String.Compare(str1, str2, ignoreCase, StringComparison.Ordinal);

String CompareTo Culture Specific

Description: String.CompareTo is culture-specific

Label Label Label

Bad Example
int result = str1.CompareTo(str2);
Good Example
int result = String.Compare(str1, str2, StringComparison.Ordinal);

String Comparison

Description: Specify string comparison explicitly

Label Label Label

Bad Example
if (name.Equals("John")) { ... }
Good Example
if (name.Equals("John", StringComparison.Ordinal)) { ... }

String Comparison

Description: Specify string comparison explicitly

Label Label Label

Bad Example
if (name.Equals("John")) { ... }
Good Example
if (name.Equals("John", StringComparison.Ordinal)) { ... }

String Conversion Culture

Description: Specify string culture explicitly

Label Label Label

Bad Example
var lowerCaseName = name.ToLower();
Good Example
var lowerCaseName = name.ToLower(CultureInfo.InvariantCulture);

String Conversion Culture

Description: Specify string culture explicitly

Label Label Label

Bad Example
var lowerCaseName = name.ToLower();
Good Example
var lowerCaseName = name.ToLower(CultureInfo.InvariantCulture);

String EndsWith Culture Specific

Description: String.EndsWith is culture-specific (string.EndsWith(string) is culture-specific)

Label Label Label

Bad Example
bool result = str1.EndsWith(suffix);
Good Example
bool result = str1.EndsWith(suffix, StringComparison.Ordinal);

String IndexOf Culture Specific

Description: String.IndexOf is culture-specific (string.IndexOf(string) is culture-specific)

Label Label Label

Bad Example
int index = str1.IndexOf(substring);
Good Example
int index = str1.IndexOf(substring, StringComparison.Ordinal);

String IndexOf Culture Specific

Description: String.IndexOf is culture-specific (string.IndexOf(string, int) is culture-specific)

Label Label Label

Bad Example
int index = myString.IndexOf("text");
Good Example
int index = myString.IndexOf("text", StringComparison.Ordinal);

String IndexOf Culture Specific

Description: String.IndexOf is culture-specific (string.IndexOf(string, int) is culture-specific)

Label Label Label

Bad Example
int index = myString.IndexOf("text", 5);
Good Example
int index = myString.IndexOf("text", 5, StringComparison.Ordinal);

String LastIndexOf Culture Specific

Description: String.LastIndexOf is culture-specific (string.LastIndexOf(string) is culture-specific)

Label Label Label

Bad Example
int index = myString.LastIndexOf("text");
Good Example
int index = myString.LastIndexOf("text", StringComparison.Ordinal);

String LastIndexOf Culture Specific

Description: String.LastIndexOf is culture-specific (string.LastIndexOf(string, int) is culture-specific)

Label Label Label

Bad Example
int index = myString.LastIndexOf("text", 5);
Good Example
int index = myString.LastIndexOf("text", 5, StringComparison.Ordinal);

String LastIndexOf Culture Specific

Description: String.LastIndexOf is culture-specific (string.LastIndexOf(string, int) is culture-specific)

Label Label Label

Bad Example
int index = myString.LastIndexOf("text", 5, 3);
Good Example
int index = myString.LastIndexOf("text", 5, 3, StringComparison.Ordinal);

String Literal as Interpolation Argument

Description: String literal can be inlined

Label Label Label

Bad Example
var message = $"Hello {"John"}";
Good Example
var message = "Hello John";

String Literal as Interpolation Argument

Description: String literal can be inlined

Label Label Label

Bad Example
var message = $"Hello {"John"}";
Good Example
var message = "Hello John";

String Literal Typo

Description: Typo in string literal

Label Label Label

Bad Example
Console.WriteLine("Ths is a typo.");
Good Example
Console.WriteLine("This is correct.");

String StartsWith Culture Specific

Description: String.StartsWith is culture-specific (string.StartsWith(string) is culture-specific)

Label Label Label

Bad Example
if (myString.StartsWith("prefix")) { /* ... */ }
Good Example
if (myString.StartsWith("prefix", StringComparison.Ordinal)) { /* ... */ }

Struct Member Read Only

Description: Struct member can be made readonly

Label Label Label

Bad Example
public struct Rectangle { public int Width; public int Height; }
Good Example
public struct Rectangle { public readonly int Width; public readonly int Height; }

Struct Read Only

Description: Struct can be made readonly

Label Label Label

Bad Example
public struct Point { public int X; public int Y; }
Good Example
public readonly struct Point { public int X; public int Y; }

Structured Message Template

Description: Structured message template problems

Label Label Label

Bad Example
logger.LogInformation("User {0} logged in", userId); // Positional parameter may cause issues
Good Example
logger.LogInformation("User {userId} logged in", userId); // Structured template with named argument

Style String Literal

Description: Use preferred argument style for string literal values

Label Label Label

Bad Example
Console.WriteLine( "Hello" );
Good Example
Console.WriteLine("Hello");

Suspicious Lock Over

Description: Suspicious locking over synchronization primitive

Label Label Label

Bad Example
lock(Semaphore) { // Using synchronization primitive directly for locking
Good Example
lock(syncObject) { // Uses dedicated sync object instead of primitive

Suspicious Math Sign Method

Description: Math.Sign() method always gives the same result

Label Label Label

Bad Example
int sign = Math.Sign(positiveValue); // Always returns 1
Good Example
int sign = 1; // Replaced with a constant

Suspicious Parameter Name

Description: Suspicious parameter name in ArgumentNullException

Label Label Label

Bad Example
throw new ArgumentNullException("wrongParamName"); // Mismatched parameter name
Good Example
throw new ArgumentNullException(nameof(correctParamName)); // Uses correct parameter name

Suspicious Shift Count

Description: Suspicious shift count for this type of left operand.

Label Label Label

Bad Example
int shiftedValue = 1 << 35; // Shift count exceeds int size
Good Example
int shiftedValue = 1 << 5; // Valid shift within integer size

Suspicious Type Conversion

Description: Suspicious type conversion or check

Label Label Label

Bad Example
var number = (int)(object)"text"; // Suspicious and unsafe cast
Good Example
if (obj is int number) { ... } // Safe type check before conversion

Swap via Deconstruction

Description: Use deconstruction to swap variables.

Label Label Label

Bad Example
int temp = x; x = y; y = temp;
Good Example
(x, y) = (y, x);

Switch Case Pattern

Description: Type pattern and casts can be merged

Label Label Label

Bad Example
switch (obj) { case MyClass _: MyClass myObj = (MyClass)obj; break; }
Good Example
switch (obj) { case MyClass myObj: /* use myObj directly */ break; }

Switch Expression Enum Values Exception

Description: Some values of the enum are not processed inside 'switch' expression and are handled via exception in default arm

Label Label Label

Bad Example
Color color = GetColor(); switch (color) { case Color.Red: /* logic */ default: throw new ArgumentOutOfRangeException(); }
Good Example
switch (color) { case Color.Red: /* logic */ case Color.Blue: /* logic */ default: throw new ArgumentOutOfRangeException(); }

Switch Expression Lacks Null Handling

Description: The switch expression does not handle some null inputs (it is not exhaustive).

Label Label Label

Bad Example
var result = input switch { "A" => 1 };
Good Example
var result = input switch { "A" => 1, null => 0, _ => -1 };

Switch Expression Non-Exhaustive for Null with 'when' Clause

Description: The switch expression does not handle some null inputs (it is not exhaustive). However, a pattern with a 'when' clause might successfully match this value.

Label Label Label

Bad Example
var result = input switch { "A" => 1 };
Good Example
var result = input switch { "A" => 1, null when condition => 0, _ => -1 };

Switch Statement Enum Value

Description: Some values of the enum are not processed inside 'switch' statement and are handled via default section

Label Label Label

Bad Example
switch (status) { case Status.Active: /* logic */ default: /* handle all else */ }
Good Example
switch (status) { case Status.Active: /* logic */ case Status.Inactive: /* logic */ default: /* handle unknown */ }

Switch Statement Missing Enum Cases

Description: Some values of the enum are not processed inside 'switch' statement

Label Label Label

Bad Example
switch (status) { case Status.Active: /* logic */ }
Good Example
switch (status) { case Status.Active: /* logic */ case Status.Inactive: /* logic */ case Status.Pending: /* logic */ }

Symbol Reference Warning

Description: Symbol from module that might be missing at runtime

Label Label Label

Bad Example
using MissingAssembly; // Assembly might not be present at runtime
Good Example
// Ensure assembly is copied locally or loaded dynamically

Syntax Error in XML Comment

Description: Syntax error in XML comment

Label Label Label

Bad Example
/// <summary Process data </summary> public void ProcessData() {}
Good Example
/// <summary>Process data</summary> public void ProcessData() {}

Tabs and Spaces Mismatch

Description: Incorrect indent (tabs/spaces mismatch)

Label Label Label

Bad Example
if (condition)
{
doSomething();
}
Good Example
if (condition)
{
doSomething();
}

Tabs Outside Indent

Description: Incorrect spacing (tabs are prohibited here).

Label Label Label

Bad Example
int x	= 5;
Good Example
int x = 5;

Tail Recursive Call

Description: Tail recursive call can be replaced with loop

Label Label Label

Bad Example
int Factorial(int n) => n == 0 ? 1 : n * Factorial(n - 1); // Recursive call
Good Example
int Factorial(int n) { int result = 1; for (int i = 1; i <= n; i++) result *= i; return result; } // Loop replaces recursion

Taking Address of Marshal-By-Reference Field

Description: Taking address of marshal-by-reference class field

Label Label Label

Bad Example
ref var refField = ref myMarshalByReference.field;
Good Example
var fieldValue = myMarshalByReference.field;

Test Case Attribute Requires Expected Result

Description: NUnit. Missing expected result for non-void test method.

Label Label Label

Bad Example
[TestCase(1)] public int AddOne(int value) { return value + 1; }
Good Example
[TestCase(1, ExpectedResult = 2)] public int AddOne(int value) { return value + 1; }

Test Case Expected Result

Description: NUnit. Test case Result property duplicates ExpectedResult.

Label Label Label

Bad Example
[TestCase(ExpectedResult = 1, Result = 1)] public int Method() { return 1; }
Good Example
[TestCase(ExpectedResult = 1)] public int Method() { return 1; }

Test Case Result Obsolete

Description: NUnit. Test case Result property is obsolete.

Label Label Label

Bad Example
[TestCase(Result = 1)] public int Method() { return 1; }
Good Example
[TestCase(ExpectedResult = 1)] public int Method() { return 1; }

Test Case Source Cannot Be Resolved

Description: NUnit. Cannot resolve symbol in TestCaseSource or ValueSource attribute

Label Label Label

Bad Example
[TestCaseSource("NonExistentSource")] public void Test() { /* ... */ }
Good Example
[TestCaseSource(nameof(ExistingSource))] public void Test() { /* ... */ }

This Qualifier

Description: Add/remove 'this.' qualifier

Label Label Label

Bad Example
name = "John";
Good Example
this.name = "John";

Thread Static at Instance Field

Description: [ThreadStatic] doesn't work with instance fields

Label Label Label

Bad Example
[ThreadStatic] private int instanceField;
Good Example
private static int instanceField;

Thread Static Field Initializer

Description: Thread static field has initializer

Label Label Label

Bad Example
[ThreadStatic] public static int counter = 0; // Thread-static with initializer
Good Example
[ThreadStatic] public static int counter; // Initialize in method as needed

Too Wide Local Variable Scope

Description: Local variable has too wide declaration scope

Label Label Label

Bad Example
int result = 0;
for (int i = 0; i < 10; i++) {
result += i;
}
return result;
Good Example
int result = 0;
for (int i = 0; i < 10; i++) {
result += i;
}
return result;

Trailing Comma in Multi Line Lists

Description: Use preferred style for trailing comma before new line in multiline lists

Label Label Label

Bad Example
var list = new[]
{
"apple",
"badana"
};
Good Example
var list = new[]
{
"apple",
"badana",
};

Trailing Comma in Single Line Lists

Description: Use preferred style for trailing comma when the last element is not followed by a new line

Label Label Label

Bad Example
var items = new[] { "apple", "badana", };
Good Example
var items = new[] { "apple", "badana" };

Try Cast Always Succeeds

Description: Safe cast expression always succeeds

Label Label Label

Bad Example
var item = obj as MyClass; if (item != null) { /* always true */ }
Good Example
var item = obj as MyClass; if (item != null) { /* logic */ } // Cast with possible null

Try Statements Merged

Description: try-catch and try-finally statements can be merged

Label Label Label

Bad Example
try { /* ... */ } catch (Exception) { /* ... */ } finally { /* ... */ }
Good Example
try { /* ... */ } catch (Exception) { /* ... */ }

Tuple Element Name Ignored

Description: The tuple element name is ignored because a different name or no name is specified by the target type.

Label Label Label

Bad Example
(string name, int age) person = ("Alice", 30);
Good Example
(string Name, int Age) person = ("Alice", 30);

Type Argument Nullability Mismatch with 'class' Constraint

Description: Nullability of type argument doesn't match 'class' constraint.

Label Label Label

Bad Example
List<string?> nullableList; // 'class' constraint expects non-nullable type
Good Example
List<string> nonNullableList; // Matches 'class' constraint with non-nullable type

Type Argument Nullability Mismatch with 'notnull' Constraint

Description: Nullability of type argument doesn't match 'notnull' constraint.

Label Label Label

Bad Example
class Example where T : struct? {} // 'notnull' constraint expects non-nullable
Good Example
class Example where T : struct {} // Matches 'notnull' constraint

Type Argument Nullability Mismatch with Constraint Type

Description: Nullability of type argument doesn't match constraint type.

Label Label Label

Bad Example
class Example where T : MyClass? {} // Constraint expects non-nullable MyClass
Good Example
class Example where T : MyClass {} // Matches constraint with non-nullable type

Type Member Modifiers

Description: Use explicit or implicit modifier definition for type members

Label Label Label

Bad Example
static int myVar;
Good Example
public static int myVar;

Type Modifiers

Description: Use explicit or implicit modifier definition for types

Label Label Label

Bad Example
class MyClass {}
Good Example
public class MyClass {}

Type Nullability Mismatch with Implemented Member

Description: Nullability of reference types in type doesn't match implemented member.

Label Label Label

Bad Example
public string? Name { get; set; } // Expected non-nullable
Good Example
public string Name { get; set; } = "Default"; // Matches non-nullable type

Type Nullability Mismatch with Implicitly Implemented Member

Description: Nullability of reference types in type doesn't match implicitly implemented member.

Label Label Label

Bad Example
public string? GetName() => "Text"; // Expected non-nullable return
Good Example
public string GetName() => "Text"; // Matches non-nullable return

Type Nullability Mismatch with Overridden Member

Description: Nullability of reference types in type doesn't match overridden member.

Label Label Label

Bad Example
public override string? GetDetails() => "Details"; // Expected non-nullable return
Good Example
public override string GetDetails() => "Details"; // Matches non-nullable return

Type Parameter Variant

Description: Type parameter could be declared as covariant or contravariant

Label Label Label

Bad Example
public interface IRepository { /* ... */ }
Good Example
public interface IRepository<out T> { /* ... */ }

Type Reference Style

Description: Replace built-in type reference with a CLR type name or a keyword

Label Label Label

Bad Example
Int32 number = 42;
Good Example
int number = 42;

Type Reference Style for Member Access

Description: Replace built-in type reference with a CLR type name or a keyword in static member access expressions

Label Label Label

Bad Example
Int32.Parse("123");
Good Example
int.Parse("123");

Unassigned Field. Compiler

Description: Unassigned field.

Label Label Label

Bad Example
public class Example { public int value; }
Good Example
public class Example { public int value = 0; }

Unassigned Get Only Auto Property

Description: Get-only auto-property is never assigned

Label Label Label

Bad Example
public int Id { get; } // Property is never assigned
Good Example
public int Id { get; } = 1; // Property is initialized with a value

Unassigned Global Field

Description: Unassigned field (non-private accessibility)

Label Label Label

Bad Example
public int count;
Good Example
public int count = 0; // Initialize to a default value

Unassigned Local Field

Description: Unassigned field (private accessibility)

Label Label Label

Bad Example
private int count;
Good Example
private int count = 0; // Initialize to a default value

Unassigned Readonly Field

Description: Unassigned readonly field

Label Label Label

Bad Example
readonly int count;
Good Example
readonly int count = 0; // Assign during declaration

Unassigned Readonly Field. Compiler

Description: Unassigned readonly field.

Label Label Label

Bad Example
readonly int value;
Good Example
readonly int value = 42;

Unnecessary Whitespace

Description: Unnecessary whitespace at the end of line

Label Label Label

Bad Example
int value = 42;   
Good Example
int value = 42;

Unreachable Catch Condition

Description: A previous catch clause already catches all exceptions

Label Label Label

Bad Example
try { ... } catch (Exception) { ... } catch (InvalidOperationException) { ... }
Good Example
try { ... } catch (InvalidOperationException) { ... } catch (Exception) { ... }

Unreachable Code

Description: Code is unreachable

Label Label Label

Bad Example
return; Console.WriteLine("This is unreachable.");
Good Example
Console.WriteLine("This is reachable."); return;

Unreachable Code

Description: Heuristically unreachable code

Label Label Label

Bad Example
return; Console.WriteLine("Unreachable"); // Code after return is unreachable
Good Example
Console.WriteLine("Reached"); return; // Removed unreachable code

Unreachable Switch Arm

Description: Heuristically unreachable switch arm due to integer analysis.

Label Label Label

Bad Example
switch (num) { case 0: break; case 1000: break; } // num is never 1000
Good Example
switch (num) { case 0: break; default: Console.WriteLine("Other case"); break; }

Unreachable Switch Case

Description: Heuristically unreachable case due to integer analysis.

Label Label Label

Bad Example
switch (num) { case 5: break; case 15: break; } // num cannot be 15
Good Example
switch (num) { case 5: break; default: Console.WriteLine("Other case"); break; }

Unsupported Required Base Type

Description: BaseTypeRequired attribute supports only classes and interfaces

Label Label Label

Bad Example
[BaseTypeRequired] struct MyStruct {}
Good Example
[BaseTypeRequired] class MyClass {}

Unused Anonymous Method

Description: Anonymous method signature is not necessary

Label Label Label

Bad Example
Func<int, int> square = delegate(int x) { return x * x; };
Good Example
Func<int, int> square = x => x * x; // Simplify by removing unnecessary signature

Unused Field

Description: Field is never used

Label Label Label

Bad Example
private int unusedField;
Good Example
private int usedField; // Use this field somewhere in code

Unused Global Property

Description: Auto-property accessor is never used (non-private accessibility)

Label Label Label

Bad Example
public int Value { get; set; } // 'set' is never used
Good Example
public int Value { get; private set; } // Adjusted access level

Unused Label

Description: Unused label

Label Label Label

Bad Example
label: Console.WriteLine("Hello");
Good Example
// Remove unused 'label' if it's not referenced in code

Unused Local Function

Description: Local function is never used

Label Label Label

Bad Example
void UnusedFunction() { } // Local function is never called
Good Example
// Removed unused local function

Unused Local Function Return Value

Description: Local function return value is never used

Label Label Label

Bad Example
int UnusedFunction() { return 42; }
Good Example
// Use the return value or remove the function

Unused Local Property

Description: Auto-property accessor is never used (private accessibility)

Label Label Label

Bad Example
private int Value { get; set; } // 'set' is never used
Good Example
private readonly int _value; public int Value => _value; // Converted to readonly field

Unused Local Variable

Description: Unused local variable

Label Label Label

Bad Example
int unusedValue = 10;
Good Example
// Remove 'unusedValue' if not used in the code

Unused Member in Super Non-Private Accessibility

Description: Type is never used (non-private accessibility)

Label Label Label

Bad Example
public class UnusedClass {}
Good Example
// Remove or use the type in code if necessary

Unused Member in Super Private Accessibility

Description: Type is never used (private accessibility)

Label Label Label

Bad Example
private class UnusedHelperClass {}
Good Example
// Remove the class if it is not used within the code

Unused Member Non-Private Accessibility

Description: Type member is never used (non-private accessibility)

Label Label Label

Bad Example
public int unusedField;
Good Example
// Remove or utilize the field in code if necessary

Unused Member Private Accessibility

Description: Type member is never used (private accessibility)

Label Label Label

Bad Example
private string unusedString;
Good Example
// Remove or use the member if necessary within the code

Unused Method Return Value Non-Private Accessibility

Description: Method return value is never used (non-private accessibility)

Label Label Label

Bad Example
public int Calculate() { return 42; }
Good Example
// Ensure the return value is used or adjust the method as needed

Unused Method Return Value Private Accessibility

Description: Method return value is never used (private accessibility)

Label Label Label

Bad Example
private int Helper() { return 10; }
Good Example
// Use the return value or modify the method to void if unused

Unused Parameter In Partial Method

Description: Unused parameter in partial method

Label Label Label

Bad Example
partial void OnEvent(int unusedParam);
Good Example
// Remove 'unusedParam' if unnecessary in 'OnEvent'

Unused Parameter Non-Private Accessibility

Description: Unused parameter (non-private accessibility)

Label Label Label

Bad Example
public void DoSomething(int unusedParam) { }
Good Example
// Remove 'unusedParam' if not used in method body

Unused Parameter Private Accessibility

Description: Unused parameter (private accessibility)

Label Label Label

Bad Example
private void Helper(int unusedParam) { }
Good Example
// Remove 'unusedParam' if not needed in 'Helper'

Unused Positional Parameter

Description: Unused positional parameter

Label Label Label

Bad Example
Func<int, string> func = (unusedParam) => "Hello";
Good Example
// Remove 'unusedParam' if not used in lambda body

Unused Tuple Component in Return Value

Description: Component of the tuple is never used

Label Label Label

Bad Example
return (value, unused); // 'unused' component is never accessed
Good Example
return (value); // Removed unused tuple component

Unused Type Parameter

Description: Unused type parameter

Label Label Label

Bad Example
public class Example { }
Good Example
// Remove 'T' if the class does not use it

Unused Variable. Compiler

Description: Unused local variable.

Label Label Label

Bad Example
int unusedVariable = 5;
Good Example
// Variable is used somewhere meaningful in code.

Use Array Creation Expression

Description: Use array creation expression

Label Label Label

Bad Example
int[] numbers = new int[] {1, 2, 3};
Good Example
int[] numbers = {1, 2, 3};

Use Array Creation Expression

Description: Use array creation expression

Label Label Label

Bad Example
string[] names = new string[] {"Alice", "Bob"};
Good Example
string[] names = {"Alice", "Bob"};

Use Array Empty Method

Description: Use 'Array.Empty()'

Label Label Label

Bad Example
int[] emptyArray = new int[0];
Good Example
int[] emptyArray = Array.Empty<int>();

Use Await Using

Description: Convert to 'await using' statement or declaration

Label Label Label

Bad Example
using (var resource = await GetResourceAsync()) { /* ... */ }
Good Example
await using var resource = await GetResourceAsync();

Use Cancellation Token

Description: Use cancellation token for async enumerable

Label Label Label

Bad Example
await foreach (var item in GetDataAsync()) { ... }
Good Example
await foreach (var item in GetDataAsync(cancellationToken)) { ... }

Use Compound Assignment

Description: Convert to null coalescing compound assignment.

Label Label Label

Bad Example
if (x == null) { x = new Object(); }
Good Example
x ??= new Object();

Use Configure Await

Description: Missing '.ConfigureAwait(false)' in library code

Label Label Label

Bad Example
await Task.Delay(1000); // Missing ConfigureAwait(false)
Good Example
await Task.Delay(1000).ConfigureAwait(false); // Correct usage for library code

Use Configure Await for Async Disposable

Description: Missing '.ConfigureAwait(false)' for async disposable in library code

Label Label Label

Bad Example
await asyncDisposable.DisposeAsync(); // Missing ConfigureAwait(false)
Good Example
await asyncDisposable.DisposeAsync().ConfigureAwait(false); // Adds ConfigureAwait(false)

Use Deconstruction

Description: Use deconstruction.

Label Label Label

Bad Example
var x = tuple.Item1; var y = tuple.Item2;
Good Example
var (x, y) = tuple;

Use EmptyTypes Field

Description: Use 'Type.EmptyTypes'

Label Label Label

Bad Example
var types = new Type[0];
Good Example
var types = Type.EmptyTypes;

Use Event Args Empty Field

Description: Use 'EventArgs.Empty'

Label Label Label

Bad Example
OnEvent(new EventArgs());
Good Example
OnEvent(EventArgs.Empty);

Use Index from End Expression

Description: Use index from end expression.

Label Label Label

Bad Example
var last = array[array.Length - 1];
Good Example
var last = array[^1];

Use Indexed Property

Description: Use indexed property

Label Label Label

Bad Example
var value = dictionary.ContainsKey(key) ? dictionary[key] : default;
Good Example
var value = dictionary[key];

Use Name Of Expression

Description: Use 'nameof' expression to reference name.

Label Label Label

Bad Example
throw new ArgumentException("parameterName");
Good Example
throw new ArgumentException(nameof(parameterName));

Use Name Of Expression for Part of The String

Description: Use 'nameof' expression to reference name in part of the string literal.

Label Label Label

Bad Example
Log("Error in parameterName");
Good Example
Log($"Error in {nameof(parameterName)}");

Use Name Of Instead of Type Of

Description: Use 'nameof' expression to reference type's name.

Label Label Label

Bad Example
Console.WriteLine(typeof(MyClass).Name);
Good Example
Console.WriteLine(nameof(MyClass));

Use Nullable Attributes

Description: Use compiler-supported nullable attributes

Label Label Label

Bad Example
[NotNullWhen(true)] public bool TryGetValue(out string value) { ... }
Good Example
[NotNullWhen(true), MaybeNull] public bool TryGetValue(out string value) { ... }

Use Nullable Reference Types Annotation Syntax

Description: Use type annotation syntax

Label Label Label

Bad Example
public string Name { get; set; }
Good Example
public string? Name { get; set; }

Use Object or Collection Initializer

Description: Use object or collection initializer when possible

Label Label Label

Bad Example
var list = new List<int>(); list.Add(1); list.Add(2);
Good Example
var list = new List<int> { 1, 2 };

Use Parameter Deconstruction

Description: Use deconstruction (on parameter declaration).

Label Label Label

Bad Example
void Foo((int, int) tuple) { var x = tuple.Item1; var y = tuple.Item2; }
Good Example
void Foo((int x, int y) tuple) { /* ... */ }

Use Positional Deconstruction Pattern

Description: Use positional deconstruction pattern

Label Label Label

Bad Example
var point = GetPoint(); var x = point.X; var y = point.Y;
Good Example
var (x, y) = GetPoint();

Use String Interpolation

Description: Use string interpolation expression

Label Label Label

Bad Example
string result = string.Format("Hello, {0}", name);
Good Example
string result = $"Hello, {name}";

Use Throw if Null Method

Description: Use 'ArgumentNullException.ThrowIfNull'

Label Label Label

Bad Example
if (param == null) throw new ArgumentNullException(nameof(param));
Good Example
ArgumentNullException.ThrowIfNull(param);

Useless Binary Operation

Description: Useless binary operation.

Label Label Label

Bad Example
int result = x * 1; // Multiplication by 1 is redundant
Good Example
int result = x; // Simplified without useless operation

Useless Comparison to Integral

Description: Comparison to integral constant is useless.

Label Label Label

Bad Example
if (x == 10 || x != 10) { /* code */ }
Good Example
// Remove or refactor condition if the comparison is unnecessary

Useless Comparison to Integral Constant

Description: Comparison to integral constant is useless; the constant is outside the range of type 'type'.

Label Label Label

Bad Example
if (myByte == 300) { /* This comparison is invalid */ }
Good Example
if (myByte == 255) { /* Valid comparison within byte range */ }

Useless Global Event

Description: Event is never subscribed to (non-private accessibility)

Label Label Label

Bad Example
public event EventHandler MyEvent; // Never subscribed to
Good Example
// Remove unused event or add subscriptions as needed

Useless Local Event

Description: Event is never subscribed to (private accessibility)

Label Label Label

Bad Example
private event EventHandler MyEvent; // Never subscribed to
Good Example
// Remove or use event with proper subscriptions

Using Statement Braces

Description: Use preferred braces style (enforce braces in 'using' statement)

Label Label Label

Bad Example
using (var resource = GetResource()) DoSomething(resource);
Good Example
using (var resource = GetResource()) { DoSomething(resource); }

Value Parameter Not Used

Description: 'value' parameter is not used

Label Label Label

Bad Example
set { int result = 5; } // 'value' parameter is not used
Good Example
set { field = value; } // Proper use of 'value' parameter

Value Range Attribute Violation

Description: Possible violation of 'ValueRange'/'NonNegativeValue' attribute

Label Label Label

Bad Example
[ValueRange(0, 100)] public int Value = -5;
Good Example
[ValueRange(0, 100)] public int Value = 50;

Var Keywords in Deconstructing Declaration

Description: Join or separate 'var' in deconstruction declarations

Label Label Label

Bad Example
(int x, var y) = (1, 2);
Good Example
(var x, var y) = (1, 2);

Variable Not Nullable

Description: Variable can be declared as non-nullable

Label Label Label

Bad Example
string? name = "John"; // Nullable but always assigned a non-null value
Good Example
string name = "John"; // Declared as non-nullable

Variable Overwritten

Description: Variable in local function hides variable from outer scope

Label Label Label

Bad Example
int value = 5; void LocalFunc() { int value = 10; } // Hides outer variable
Good Example
int value = 5; void LocalFunc() { int innerValue = 10; } // Unique variable name

Variables Var Declaration Built-in

Description: Use preferred 'var' style (for built-in types)

Label Label Label

Bad Example
int age = 25;
Good Example
var age = 25;

Variables Var Declaration Deconstruction

Description: Use preferred 'var' style (in deconstruction declarations)

Label Label Label

Bad Example
(string name, int age) = person;
Good Example
var (name, age) = person;

Variables Var Declaration Elsewhere

Description: Use preferred 'var' style (elsewhere)

Label Label Label

Bad Example
List<string> names = new List<string>();
Good Example
var names = new List<string>();

Variables Var Declaration Simple Types

Description: Use preferred 'var' style (when type is simple)

Label Label Label

Bad Example
string name = "John";
Good Example
var name = "John";

Verbatim String

Description: Literal's length can be reduced by using verbatim string

Label Label Label

Bad Example
string path = "C:\\folder\\file.txt"; // Escapes increase length
Good Example
string path = @"C:\folder\file.txt"; // Verbatim string reduces length

Virtual Member Call in Constructor

Description: Virtual member call in constructor

Label Label Label

Bad Example
public MyClass() { VirtualMethod(); } // Calls virtual method in constructor
Good Example
public MyClass() { Initialize(); } protected virtual void Initialize() { ... } // Avoids calling virtual method directly in constructor

Virtual Members not Inherited Non-Private Accessibility

Description: Class with virtual (overridable) members never inherited (non-private accessibility)

Label Label Label

Bad Example
public class MyClass { public virtual void MyMethod() { } } // Virtual not inherited
Good Example
public class MyClass { public void MyMethod() { } } // Removed 'virtual' modifier

Virtual Members not Inherited Private Accessibility

Description: Class with virtual (overridable) members never inherited (private accessibility)

Label Label Label

Bad Example
private class MyClass { public virtual void MyMethod() { } } // Virtual not inherited
Good Example
private class MyClass { public void MyMethod() { } } // Removed 'virtual' modifier

Void Method Must Use Return Value

Description: 'void' method is annotated by [MustUseReturnValue] attribute

Label Label Label

Bad Example
[MustUseReturnValue] public void DoSomething() { ... } // Void method marked with MustUseReturnValue
Good Example
public void DoSomething() { ... } // Void method without MustUseReturnValue or returns a meaningful result

While Statement Braces

Description: Use preferred braces style (enforce braces in 'while' statement)

Label Label Label

Bad Example
while (condition) DoSomething();
Good Example
while (condition) { DoSomething(); }

Wrong Indent Size

Description: Incorrect indent (incorrect indent size)

Label Label Label

Bad Example
if (condition)
{
doSomething();
}
Good Example
if (condition)
{
doSomething();
}

XML Comment Ambiguous Reference

Description: Ambiguous reference in XML comment

Label Label Label

Bad Example
/// See <see cref="MyMethod"/> for more information.
Good Example
/// See <see cref="Namespace.MyClass.MyMethod"/> for more information.

XML Comment Duplicate Typeparam

Description: Duplicate typeparam tag in XML comment

Label Label Label

Bad Example
/// <typeparam name="T">Type parameter</typeparam> /// <typeparam name="T">Duplicate parameter</typeparam>
Good Example
/// <typeparam name="T">Type parameter</typeparam>

XML Comment Param Tag

Description: Duplicate param tag in XML comment

Label Label Label

Bad Example
/// <param name="x">First parameter</param> /// <param name="x">Duplicate parameter</param>
Good Example
/// <param name="x">First parameter</param>

XML in Included Comments File

Description: Badly formed XML in included comments file

Label Label Label

Bad Example
/// <summary>Badly formed XML
Good Example
/// <summary>Well-formed XML</summary>

Xunit Console Output

Description: Console output in Xunit tests

Label Label Label

Bad Example
Console.WriteLine("Test output");
Good Example
_output.WriteLine("Test output"); // Use Xunit's output helper

Secure your DevOps


8, Chalkis Street, Pylaia, Thessaloniki, Greece, Tel: +30 2310 471 030
Copyright © 2025 Cyclopt