C# Coding Violations
'l' Suffix Easily Confused with '1'
Description: The 'l' suffix is easily confused with the digit '1'
long value = 1000000l;
long value = 1000000L;
Access in Text
Description: Cannot access symbol in text argument
var message = "Value is " + myInstance.PrivateField;
var message = $"Value is {myInstance.GetPrivateField()}"; // Use a getter method
Access to Disposed Closure
Description: Access to disposed captured variable
using (var resource = new Resource()) { Task.Run(() => resource.Use()); }
var localResource = new Resource(); Task.Run(() => { localResource.Use(); localResource.Dispose(); });
Access to For Each Variable
Description: Access to foreach variable in closure
foreach (var item in items) { tasks.Add(() => Console.WriteLine(item)); }
foreach (var item in items) { var localItem = item; tasks.Add(() => Console.WriteLine(localItem)); }
Access to Modified Closure
Description: Access to modified captured variable
int count = 0; tasks.Add(() => Console.WriteLine(count++));
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
class Base { public static void Log() {} } class Derived : Base {} Derived.Log(); // Accessed via derived type
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)
public int MyProperty { get { return _value; } }
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
MarshalByRefObject obj = new MyRemoteObject(); Task.Run(() => obj.DoSomething());
var localObj = new MyRemoteObject(); Task.Run(() => localObj.DoSomething());
Annotate not Null Parameter
Description: Declaration nullability inferred (parameter is inferred to be not null)
public void DoSomething(string value) { }
public void DoSomething([NotNull] string value) { }
Annotate not Null Type Member
Description: Declaration nullability inferred (type member is inferred to be not null)
public string Name { get; set; }
[NotNull] public string Name { get; set; }
Annotate Null Parameter
Description: Declaration nullability inferred (parameter is inferred to be nullable)
public void DoSomething(string? value) { }
public void DoSomething([CanBeNull] string? value) { }
Annotate Null Type Member
Description: Declaration nullability inferred (type member is inferred to be nullable)
public string? Name { get; set; }
[CanBeNull] public string? Name { get; set; }
Annotation Conflict in Hierarchy
Description: Annotation conflict in hierarchy
class BaseClass { public virtual string? Name { get; } } class DerivedClass : BaseClass { public override string Name { get; } }
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
[AllowNull] public int Age; // Nullable attribute on a value type is redundant
public int Age; // Removed nullable attribute on value type
Annotation Redundancy in Hierarchy
Description: Annotation duplicate in hierarchy
[Obsolete] class Base {} [Obsolete] class Derived : Base {} // Duplicate annotation
[Obsolete] class Base {} class Derived : Base {} // Avoid duplicate annotation
Argument In Test Case Attribute
Description: NUnit. Redundant argument in TestCase attribute.
[TestCase(1, ExpectedResult = 1)] public int Method(int x) { return x; }
[TestCase(ExpectedResult = 1)] public int Method() { return 1; }
Argument Instead of Expected Result
Description: NUnit. Redundant argument instead of ExpectedResult.
[TestCase(1)] public int Method(int x) { return x; }
[TestCase(ExpectedResult = 1)] public int Method() { return 1; }
Arguments Style Anonymous Function
Description: Use preferred argument style for anonymous functions
(x) => { return x * x; };
x => x * x;
Arguments Style Literal
Description: Use preferred argument style for literal values
MethodCall( 42 );
MethodCall(42);
Arguments Style Named Expression
Description: Use preferred argument style for named expressions
MethodCall(argument: 42);
MethodCall(42);
Arguments Style Other
Description: Use preferred argument style
MethodCall( a ,b );
MethodCall(a, b);
Assign Null to not Null Attribute
Description: Possible 'null' assignment to non-nullable entity
public string NotNullProperty { get; set; } = null;
public string NotNullProperty { get; set; } = "Default Value";
Assignment Fully Discarded
Description: Assignment results are fully discarded
value = 10; // Assignment result is never used
// Remove or refactor assignment if not used
Assignment in Conditional Expression
Description: Operator = used instead of ==
if (a = b) { Console.WriteLine("Equal"); }
if (a == b) { Console.WriteLine("Equal"); }
Assignment in Conditional Expression
Description: Assignment in conditional expression
if ((value = GetValue()) != null) { /* ... */ }
value = GetValue(); if (value != null) { /* ... */ }
Assignment to Same Variable
Description: Assignment made to same variable
int x = 5; x = x;
int x = 5; x = y;
Async Function without Await
Description: Async function without await expression
async Task ExampleAsync() { Console.WriteLine("Hello"); }
async Task ExampleAsync() { await Task.Delay(1000); Console.WriteLine("Hello"); }
Async Invocation without Await Foreach
Description: Async iterator invocation without 'await foreach'
var items = GetAsyncItems(); foreach (var item in items) { /* ... */ }
var items = GetAsyncItems(); await foreach (var item in items) { /* ... */ }
Async Method Task
Description: NUnit. Async test method must return Task or Task
public async void TestMethodAsync() { /* ... */ }
public async Task TestMethodAsync() { /* ... */ }
Async Void Lambda
Description: Avoid using 'async' lambda when delegate type returns 'void'
Action action = async () => await Task.Delay(1000);
Func<Task> action = async () => await Task.Delay(1000);
Async Void Method
Description: Avoid using 'async' methods with the 'void' return type
public async void Method() { await Task.Delay(1000); }
public async Task Method() { await Task.Delay(1000); }
Async without Await
Description: Async method invocation without await expression
MethodAsync();
await MethodAsync();
Attribute Bounds out of Range
Description: NUnit. Values in range do not fit the type of the test parameter.
[Range(int.MinValue, int.MaxValue + 1)] public void Method(int x) { /* ... */ }
[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
[module: Obsolete] class MyClass { }
[Obsolete] class MyClass { }
Attribute Produces too Many Tests
Description: NUnit. Specified attribute values produce too many tests.
[Values(1, 2, 3, ... ,10000)] public void Method(int x) { /* ... */ }
[Values(1, 2, 3)] public void Method(int x) { /* ... */ }
Attributes in Section
Description: Join or separate attributes in section
[Serializable][Obsolete] class Sample {}
[Serializable, Obsolete] class Sample {}
Auto Global Property Get Only
Description: Auto-property can be made get-only (non-private accessibility)
public int Value { get; set; } // Setter is unnecessary
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)
private int Value { get; set; } // Setter is unnecessary
private int Value { get; } // Get-only property as no setter needed
Bad Attribute Brackets Spaces
Description: Incorrect spacing (around attributes).
[ Obsolete ] public void Method() {}
[Obsolete] public void Method() {}
Bad Braces Spaces
Description: Incorrect spacing (around braces).
public void Method() { int x = 5; }
public void Method() {
int x = 5;
}
Bad Child Statement Indent
Description: Incorrect indent (around child statement).
if (condition) {
int x = 5;
}
if (condition) {
int x = 5;
}
Bad Colon Spaces
Description: Incorrect spacing (around colon).
case 1 : Console.WriteLine("One");
case 1: Console.WriteLine("One");
Bad Comma Spaces
Description: Incorrect spacing (around comma)
var items = new[] {1,2, 3};
var items = new[] { 1, 2, 3 };
Bad Control Braces Indent
Description: Incorrect indent (around statement braces)
if (condition)
{
doSomething();
}
if (condition)
{
doSomething();
}
Bad Control Braces Line Breaks
Description: Incorrect line breaks (around statement braces).
if (condition) { action(); }
if (condition)
{
action();
}
Bad Declaration Braces Indent
Description: Incorrect indent (around declaration braces).
public class Example {
int x = 5;
}
public class Example {
int x = 5;
}
Bad Declaration Braces Line Breaks
Description: Incorrect line breaks (around declaration braces)
public class MyClass
{
public void MyMethod() { doSomething(); }
}
public class MyClass
{
public void MyMethod()
{
doSomething();
}
}
Bad Empty Braces Line Breaks
Description: Incorrect line breaks (around empty braces).
public class Example {
}
public class Example {
}
Bad Expression Braces Indent
Description: Incorrect indent (around expression braces).
var result = (x + y);
if (result > 0) { x = 1; }
var result = (x + y);
if (result > 0) {
x = 1;
}
Bad Expression Braces Line Breaks
Description: Incorrect line breaks (around expression braces).
var result = (x + y);
var result = (
x + y
);
Bad Generic Brackets Spaces
Description: Incorrect spacing (around generic brackets)
List <int> numbers = new List <int>();
List<int> numbers = new List<int>();
Bad Indent
Description: Incorrect indent (line indent should not be changed relative to the previous line elsewhere)
int a = 10;
int b = 20;
int c = 30;
int a = 10;
int b = 20;
int c = 30;
Bad Linq Line Breaks
Description: Incorrect line breaks (around LINQ queries).
var results = items.Where(x => x > 5).Select(x => x * 2);
var results = items
.Where(x => x > 5)
.Select(x => x * 2);
Bad List Line Breaks
Description: Incorrect line breaks (around comma in lists)
var list = new List<int> {
1,
2, 3
};
var list = new List<int> {
1,
2,
3
};
Bad Member Access Spaces
Description: Incorrect spacing (around member access symbols)
myObject . MyMethod ();
myObject.MyMethod();
Bad Namespace Braces Indent
Description: Incorrect indent (around namespace braces).
namespace Example {
class MyClass {}
}
namespace Example {
class MyClass {}
}
Bad Parens Line Breaks
Description: Incorrect line breaks (around parenthesis).
var result = Method(param1, param2, param3);
var result = Method(
param1,
param2,
param3
);
Bad Parens Spaces
Description: Incorrect spacing (around parenthesis)
Console.WriteLine ( "Hello" );
Console.WriteLine("Hello");
Bad Preprocessor Indent
Description: Incorrect indent (around preprocessor directive).
#if DEBUG
Console.WriteLine("Debug mode");
#endif
#if DEBUG
Console.WriteLine("Debug mode");
#endif
Bad Semicolon Spaces
Description: Incorrect spacing (around semicolon)
int a = 5 ;
int a = 5;
Bad Spaces After Keyword
Description: Incorrect spacing (between keyword and parenthesis)
if( condition )
if (condition)
Bad Square Brackets Spaces
Description: Incorrect spacing (around square brackets within a statement)
var item = array [ i ];
var item = array[i];
Bad Switch Braces Indent
Description: Incorrect indent (around switch statement)
switch (value)
{
case 1:
doSomething();
break;
}
switch (value)
{
case 1:
doSomething();
break;
}
Bad Symbol Spaces
Description: Incorrect spacing (around operator symbols)
int result = a + b *c;
int result = a + b * c;
Base Member Params
Description: Base member has 'params' parameter, but overrider hasn't
class Base { public virtual void DoSomething(params int[] values) {} } class Derived : Base { public override void DoSomething(int[] values) {} } // 'params' missing
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
base.Method(); // Implicit use of default parameter values
base.Method(defaultValue); // Explicitly specify default values
Base Object Equals
Description: Call to 'base.Equals(...)' is reference equality
base.Equals(obj); // Compares reference equality
object.Equals(this, obj); // Explicitly call equality method
Base Object Get Hash Code Call
Description: Overridden GetHashCode calls base 'Object.GetHashCode()'
public override int GetHashCode() { return base.GetHashCode(); }
public override int GetHashCode() { return field1.GetHashCode() ^ field2.GetHashCode(); }
Base Type for Parameter
Description: Parameter can be declared with base type
public void ProcessData(List<int> data) { }
public void ProcessData(IEnumerable<int> data) { }
Base Type Parameter
Description: Parameter can be declared with base type
public ExampleClass(List<int> data) { }
public ExampleClass(IEnumerable<int> data) { }
Bitwise Operator Without Flags
Description: Bitwise operation on enum which is not marked by [Flags] attribute
MyEnum result = MyEnum.Option1 | MyEnum.Option2;
[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'
volatile int field = 0; Task.Run(() => { var value = field; });
int localField = field; Task.Run(() => { var value = localField; });
C Sharp Warnings:: C S0108, C S0114
Description: Keyword 'new' is required
public int Property { get; set; } // Hides base class member without 'new'
public new int Property { get; set; }
C Sharp Warnings:: C S0675
Description: Bitwise-or operator used on a sign-extended operand.
int result = value | 0xFF;
int result = value & 0xFF;
C Sharp Warnings:: C S1030
Description: '#warning' directive
#warning This code needs revision
// 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
/// <param name="nonexistentParam">This parameter does not exist</param>
/// <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
/// <see cref="NonExistentMethod"/>
/// <see cref="ExistingMethod"/>
C Sharp Warnings:: C S1587
Description: XML comment is not placed on a valid language element
/// This is an invalid XML comment
/// <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
/// <typeparam name="NonexistentType">This type does not exist</typeparam>
/// <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
/// <see cref="T" />
/// <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.
Console.WriteLine("{0,10000}", value);
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].
void Process([NotNull] string data) { Console.WriteLine(data.Length); }
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.
void Example(string nonNullable) { AcceptNullable(null); }
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.
void UpdateValue([NotNull] out string? result) { result = null; }
void UpdateValue([NotNull] out string result) { result = string.Empty; }
C Sharp Warnings:: C S8625
Description: Cannot convert null literal to non-nullable reference type.
string nonNullableString = null;
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'
readonly void ReadonlyMethod() { NonReadonlyMethod(); }
void ReadonlyMethod() { /* Access only readonly members here */ }
C Sharp Warnings:: C S8763
Description: A method marked [DoesNotReturn] should not return.
[DoesNotReturn] void Terminate() { return; }
[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.
Func<string, bool> func = ([InterpolatedStringHandlerArgument] string input) => true;
Func<string, bool> func = (string input) => true;
C Sharp Warnings:: CS0612
Description: Use of obsolete symbol (without message).
[Obsolete] public int OldProperty { get; set; }
public int NewProperty { get; set; }
C Sharp Warnings:: CS0618
Description: Use of obsolete symbol.
[Obsolete] public void OldMethod() {}
public void NewMethod() {}
C Sharp Warnings:: CS0693
Description: Type parameter has the same name as a type parameter from the outer type.
class Outer { class Inner {} }
class Outer { class Inner<U> {} }
C Sharp Warnings:: CS1589
Description: Unable to include XML fragment.
/// <include file='NonExistent.xml' />
/// <include file='ValidFile.xml' />
C Sharp Warnings:: CS1712
Description: Type parameter has no matching typeparam tag in the XML comment.
/// <summary>Example method</summary>
void Method() {}
/// <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.
if (obj is dynamic) {}
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.
(int first, int second) == (int one, int two);
(int first, int second) == (int first, int second);
C Sharp Warnings:: CS8597
Description: Thrown value may be null.
throw null;
throw new InvalidOperationException("Error message");
C Sharp Warnings:: CS8605
Description: Unboxing a possibly null value.
int value = (int)nullableObject;
int? value = nullableObject as int?;
C Sharp Warnings:: CS8645
Description: Type is already listed in the interface list with different nullability of reference types.
interface IExample<T, T?> {}
interface IExample {}
C Sharp Warnings:: CS8860
Description: Types and aliases should not be named 'record'.
class record {}
class RecordExample {}
Call to GetType
Description: Possible mistaken call to GetType()
if (obj.GetType() == typeof(string)) { }
if (obj is string) { }
Call to GetType
Description: Possible mistaken call to GetType()
if (this.GetType() == typeof(MyClass)) { }
if (this is MyClass) { }
CallerArgumentExpression Invalid Parameter Name
Description: The CallerArgumentExpressionAttribute is applied with an invalid parameter name.
public void Log(string message, [CallerArgumentExpression("invalidParam")] string paramName = "") {}
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.
public void Validate(string value, [CallerArgumentExpression("value")] string? message = null) {}
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
public void Log([CallerArgumentExpression("message")] string filePath = "") {}
public void Log(string message, string filePath = "") {}
CallerArgumentExpression Overridden by CallerLineNumberAttribute
Description: The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerLineNumberAttribute
public void Log([CallerArgumentExpression("message")] string lineNumber = "") {}
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
public void Log([CallerArgumentExpression("message")] string callerName = "") {}
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
public void LogMessage([CallerArgumentExpression("message")] string paramName) {}
public void LogMessage(string message, [CallerArgumentExpression("message")] string paramName = "") {}
Cannot Apply Equality Operator
Description: Compare with '==' types marked by 'CannotApplyEqualityOperatorAttribute'
if (customType1 == customType2) {}
if (customType1.Equals(customType2)) {}
Cast to non Nullable
Description: Converting null literal or possible null value to non-nullable type.
string nonNullableString = (string)null;
string? nullableString = null; /* Or handle possible null */
Check for Reference Equality
Description: Check for reference equality instead
if (str1 == str2) { // Risky, checks for value equality rather than reference equality }
if (ReferenceEquals(str1, str2)) { // Checks for reference equality }
Check for Reference Equality
Description: Check for reference equality instead
if (object1 == object2) { // Value equality check, not reference }
if (ReferenceEquals(object1, object2)) { // Proper reference equality check }
Check for Reference Equality
Description: Check for reference equality instead
if (item1 == item2) { // Value equality check instead of reference }
if (ReferenceEquals(item1, item2)) { // Proper reference equality check }
Check for Reference Equality
Description: Check for reference equality instead
if (objA == objB) { // Checks value equality instead of reference }
if (ReferenceEquals(objA, objB)) { // Uses reference equality as preferred }
Check Namespace
Description: Namespace does not correspond to file location
namespace IncorrectNamespace {}
namespace CorrectNamespace {}
Class Instantiation
Description: Class cannot be instantiated.
var obj = new AbstractClass();
// Use a derived class instead
var obj = new ConcreteClass();
Co-variant Array Conversion
Description: Co-variant array conversion
object[] array = new string[10];
string[] array = new string[10];
Collection Count Property
Description: Use collection's count property
if (list.Length > 0) { /* do something */ }
if (list.Count > 0) { /* do something */ }
Comment Typo
Description: Typo in comment
// This is a cmment with a typo.
// This is a comment with correct spelling.
Compare non Constrained Generic with Null
Description: Possible comparison of value type with 'null'
public bool IsNull(T value) { return value == null; } // Comparisons with null on value types
public bool IsNull(T? value) where T : struct { return value == null; } // Nullable constraint
Compiler Unused Local Function
Description: Compiler: local function is never used
void UnusedFunction() { /* some code */ }
// Remove or use the local function if necessary
Conditional Ternary Equal Branch
Description: '?:' expression has identical true and false branches
var result = condition ? value : value;
var result = value;
Conditional Ternary Expression
Description: Simplify conditional ternary expression
var result = condition ? true : false;
var result = condition;
Confusing Char as Integer
Description: Char is possibly unintentionally used as integer
var number = new MyClass('A');
var number = new MyClass((int)'A');
Constant Conditional Access Qualifier
Description: Conditional access qualifier expression is known to be null or not null
var length = obj?.Length; // if obj is guaranteed non-null
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
string result = value ?? "default"; // if value is always non-null
string result = value; // Remove null coalescing if unnecessary
Constructor Initializer Loop
Description: Possible cyclic constructor call
public ClassA() : this(0) { } public ClassA(int x) : this() { } // Recursive call causes stack overflow
public ClassA() : this(0) { } public ClassA(int x) { } // Avoid recursive constructor calls
Constructor Invocation
Description: Remove constructor invocation
var date = new DateTime(); // Redundant constructor invocation
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)
public MyClass() { /* constructor code */ }
public MyClass() => /* constructor code */;
Container Annotation Redundancy
Description: Container nullability attribute usage with declaration of non-container type
[NotNull] int number; // Non-container type annotated with container nullability
int number; // Container nullability attribute removed from non-container type
Contract Annotation not Parsed
Description: Problem in contract annotation definition
[ContractAnnotation("null=>null;")]
[ContractAnnotation("=>null; notnull=>notnull")]
Control Transfer Statement
Description: Separate control transfer statement with blank line
return;continue;
return;
continue;
Convert Closure to Method Group
Description: Convert lambda expression to method group.
Action action = () => Method();
Action action = Method;
Convert Global to Constant
Description: Convert local variable or field to constant (non-private accessibility)
public int exampleValue = 10;
public const int ExampleValue = 10;
Convert Local to Constant
Description: Convert local variable or field to constant (private accessibility)
private int exampleValue = 10;
private const int ExampleValue = 10;
Convert to Lambda Expression
Description: Convert to lambda expression
Func<int, int> square = delegate(int x) { return x * x; };
Func<int, int> square = x => x * x;
Convert to Lambda Expression
Description: Convert to lambda expression (when possible)
Action action = delegate { Console.WriteLine("Hello"); };
Action action = () => Console.WriteLine("Hello");
Convert to Static Class
Description: Convert to static class
public class Helper { public static void DoWork() { } }
public static class Helper { public static void DoWork() { } }
Convert to Using Declaration
Description: Convert to 'using' declaration
using (var reader = new StreamReader(path)) { /* ... */ }
using var reader = new StreamReader(path);
Default Namespace
Description: Namespace should be default namespace of this project
namespace AnotherNamespace { }
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
void Method(int x = 5) { }
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
public void Method([DefaultValue(5)] int param = 0) { } // Misleading use of DefaultValueAttribute
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
int number = default(int);
int number = 0;
Default Value Not Evident Type
Description: Use preferred style of default value expression when type is not evident
var items = new List<int> { default(int) };
var items = new List<int> { 0 };
Disallowed Tabs
Description: Usage of tabulation character for indentation is prohibited
int value = 42;
int value = 42;
Discard Declaration Var Style
Description: Use preferred style for discard declaration
var _ = GetValue();
_ = GetValue();
Division by Zero
Description: Division by zero in at least one execution path.
int result = value / divisor; // Potential division by zero
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)
do Console.WriteLine("Hello"); while(condition);
do { Console.WriteLine("Hello"); } while(condition);
Double Negation in Pattern
Description: Simplify negated pattern
if (!!isActive) { ... }
if (isActive) { ... }
Double Negation in Pattern
Description: Simplify negated pattern
if (!!isActive) { ... }
if (isActive) { ... }
Double Negation Operator
Description: Double negation operator
bool result = !!isTrue; // Double negation
bool result = isTrue; // Removes unnecessary negation
Duplicate Values
Description: NUnit. Duplicate values
[TestCase(1)] [TestCase(1)] public void Test(int value) { /* ... */ }
[TestCase(1)] [TestCase(2)] public void Test(int value) { /* ... */ }
Dynamic Shift Right
Description: Right operand of dynamic shift operation should be convertible to 'int'
dynamic shiftAmount = 2.5; int value = 1 << shiftAmount;
int shiftAmount = 2; int value = 1 << shiftAmount;
Empty Catch Clause
Description: Empty general catch clause
try { /* code */ } catch { /* Empty catch block */ }
try { /* code */ } catch (Exception ex) { Console.WriteLine(ex.Message); }
Empty Constructor
Description: Empty constructor
public MyClass() { } // Constructor is empty
// Removed empty constructor
Empty Destructor
Description: Empty destructor
~MyClass() { } // Destructor is empty
// Removed empty destructor
Empty Embedded Statement
Description: Empty control statement body
if (condition) ;
if (condition) { DoSomething(); }
Empty For Statement
Description: Empty 'for' loop is redundant
for (int i = 0; i < 10; i++); // Empty for loop
for (int i = 0; i < 10; i++) { /* meaningful work */ }
Empty Namespace
Description: Empty namespace declaration
namespace MyNamespace { } // Namespace is empty
// Removed empty namespace declaration
Empty Statement
Description: Empty statement is redundant
;
// Removed unnecessary statement
Empty Switch Block
Description: A switch block must have one or more case or default statements.
switch (value) { }
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)
public class MyEntity { } // Only declared to capture its name
// Removed unused entity declaration
Entity Name Private Accessibility
Description: Entity is only used to capture its name (private accessibility)
private class MyEntity { } // Only declared to capture its name
// Removed unused entity declaration
Enum Underlying Type
Description: Underlying type of enum is 'int'
enum Status : int { Active, Inactive }
enum Status { Active, Inactive } // int is default underlying type
Enumerable Sum Unchecked Context
Description: 'Enumerable.Sum' invocation in explicit unchecked context
unchecked { var sum = numbers.Sum(); }
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'.
[EnumeratorCancellation] int count;
public async IAsyncEnumerable<int> GenerateAsync([EnumeratorCancellation] CancellationToken cancellationToken) {}
Equal Expression Comparison
Description: Similar expressions comparison
if (a == a) { /* always true */ }
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
public class MyClass { public static bool operator ==(MyClass a, MyClass b) => a.Equals(b); }
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
public event EventHandler MyEvent; // Declared but never invoked
public event EventHandler MyEvent; protected void OnMyEvent() { MyEvent?.Invoke(this, EventArgs.Empty); }
Event Unsubscription
Description: Event unsubscription via anonymous delegate
eventHandler -= (s, e) => { /* anonymous delegate */ };
EventHandler handler = (s, e) => { /* named handler */ }; eventHandler -= handler;
Expected Result in Test Case Attribute
Description: NUnit. Redundant expected result for void test method.
[TestCase(ExpectedResult = 2)] public void Method() { /* ... */ }
[TestCase] public void Method() { /* ... */ }
Explicit Caller Info Argument
Description: Explicit argument passed to parameter with caller info attribute
LogMessage("Log", "explicitFileName.cs");
LogMessage("Log"); // Caller info auto-populated
Expression Always False
Description: The given expression of 'is' operator is never of the provided type
if (obj is int) { } // obj is never an int in this context
// Avoid redundant type checks in code
Expression Always Matches Constant
Description: The given expression always matches the provided constant.
if (value == 5 && value == 5) { /* code */ }
if (value == 5) { /* code */ }
Expression Always Null
Description: Expression is always 'null'
if (obj == null) { obj.ToString(); } // Expression is always null
if (obj != null) { obj.ToString(); } // Proper null check
Expression Always of Provided Type
Description: Given expression is always of the provided type
if (myString is string) { /* Always true */ }
if (myString != null) { /* Check for non-null string */ }
Expression Always True
Description: The given expression of 'is' operator is always of the provided type
if (obj is string) { } // 'obj' is always a string in this context
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.
bool result = (value & mask) == mask;
bool result = value == mask;
Expression Matching Pattern
Description: Given expression always matches the provided pattern
if (obj is object) { /* Always true */ }
if (obj != null) { /* Null check */ }
Expression Never Matches Pattern
Description: The given expression never matches the provided pattern.
if (value is string s && value is int) { /* code */ }
if (value is int v) { /* code */ }
Expression not of Provided Type
Description: Given expression is never of the provided type
if (myInt is string) { /* Always false */ }
if (myObj is string str) { /* Only execute if myObj is a string */ }
Expression Same Value
Description: Expression is always 'true' or always 'false'
if (5 > 3) { ... } // Condition always true
if (x > 3) { ... } // Condition depends on variable value
Field Property Default Implementation
Description: Field hides property with default implementation in interface
public class MyClass : IMyInterface { public int MyProperty; }
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.
[TestCaseSource("nonFieldPropertyOrMethod")] public void Method() { /* ... */ }
[TestCaseSource("DataSource")] public void Method() { /* ... */ }
Filter Expression Constant
Description: Filter expression is a constant, consider removing the filter
catch (Exception) when (true) { /* This filter is redundant */ }
catch (Exception ex) when (ex is SomeSpecificException) { /* Valid conditional handling */ }
Finalize Method Interfere
Description: Introducing a 'Finalize' method can interfere with destructor invocation
public void Finalize() { /* Interferes with destructor */ }
~MyClass() { /* Use destructor instead */ }
Fixed Statement Braces
Description: Use preferred braces style (enforce braces in 'fixed' statement)
fixed (int* p = arr) Console.WriteLine(*p);
fixed (int* p = arr) { Console.WriteLine(*p); }
Float Comparison
Description: Equality comparison of floating point numbers
if (a == b) { /* risky float comparison */ }
if (Math.Abs(a - b) < 0.0001) { /* safer float comparison */ }
For Converted to Foreach
Description: For-loop can be converted into foreach-loop
for (int i = 0; i < items.Length; i++) { Console.WriteLine(items[i]); }
foreach (var item in items) { Console.WriteLine(item); }
For Statement Braces
Description: Use preferred braces style (enforce braces in 'for' statement)
for (int i = 0; i < 10; i++) Console.WriteLine(i);
for (int i = 0; i < 10; i++) { Console.WriteLine(i); }
For Statement Condition Always True
Description: 'true' is redundant as 'for'-statement condition
for (; true;) { ... } // Condition 'true' is redundant
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
foreach (var item in collection) { if (item.IsValid) result.Add(item); }
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
foreach (var item in collection) { if (item.IsActive) result.Add(item); }
result.AddRange(collection.Where(item => item.IsActive));
Foreach Statement Braces
Description: Use preferred braces style (enforce braces in 'foreach' statement)
foreach (var item in collection) Console.WriteLine(item);
foreach (var item in collection) { Console.WriteLine(item); }
Format Specifier in Format String
Description: Use format specifier in format strings
string result = string.Format("Value: {0}", value);
string result = string.Format("Value: {0:F2}", value); // Use format specifier
Format String Problem
Description: String formatting method problems
string message = string.Format("Value: {0}");
string message = string.Format("Value: {0}", value);
Function Complexity Overflow
Description: Function body is too complex to analyze
public void ComplexFunction() { /* Highly nested logic */ }
public void ComplexFunction() { /* Refactored into smaller methods */ }
Function never Returns
Description: Function never returns
int InfiniteLoop() { while (true) { } }
int FiniteLoop(int limit) { int i = 0; while (i < limit) { i++; } return i; }
Function Recursive Paths
Description: Function is recursive on all execution paths
int RecursiveFunction(int n) { return RecursiveFunction(n - 1); }
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
GC.SuppressFinalize(this);
public class MyClass { ~MyClass() { } public void Dispose() { GC.SuppressFinalize(this); } }
Generic Enumerator not Disposed
Description: Instance of IEnumerator is never disposed
IEnumerator enumerator = collection.GetEnumerator(); while (enumerator.MoveNext()) { /* ... */ }
using (IEnumerator enumerator = collection.GetEnumerator()) { while (enumerator.MoveNext()) { /* ... */ } }
GetCurrentMethod Declared to Return a Null Value
Description: Dereference of a possibly null reference.
int length = nullableString.Length;
if (nullableString != null) { int length = nullableString.Length; }
GetHashCode No Override
Description: Class overrides Object.Equals(object o) but not Object.GetHashCode()
public override bool Equals(object obj) { /* Equality logic */ }
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)
public class UnusedClass { /* class implementation */ }
public class UsedClass { /* class implementation */ } new UsedClass();
Global Class Sealed
Description: Class can be made sealed (non-inheritable) (non-private accessibility)
public class MyClass { /* Implementation */ } // Can be inherited, even though inheritance is unnecessary
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)
public List<int> numbers = new List<int> { 1, 2, 3 };
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)
public List<int> numbers = new List<int>();
public List<int> numbers = new List<int> { 1, 2, 3 };
Global Event Never Invoked
Description: Abstract or virtual (overridable) event is never invoked
public virtual event EventHandler MyEvent;
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)
public int Value = 10; // Field can be modified outside constructor
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)
public int exampleValue = 10;
private int exampleValue = 10;
Global Member Protected
Description: Member can be made protected (non-private accessibility)
public int exampleValue = 10;
protected int exampleValue = 10;
Global Member Static
Description: Member can be made static (shared) (non-private accessibility)
public int exampleValue = 10;
public static int ExampleValue = 10;
Global Parameter Type
Description: Parameter type can be IEnumerable (non-private accessibility)
public void PrintData(List<string> data) { }
public void PrintData(IEnumerable<string> data) { }
Global Property Init Only
Description: Property can be made init-only (non-private accessibility)
public string Name { get; set; } // Allows modification after initialization
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)
public List<int> GetValues() { return new List<int>(); }
public IEnumerable<int> GetValues() { return new List<int>(); }
GoTo Value not Convertible
Description: 'goto case' value is not implicitly convertible to required type
switch (value) { case 1: goto case 2.0; }
switch (value) { case 1: /* handle */ break; case 2: /* handle */ break; }
Hidden Static Member
Description: Member hides static member from outer class
public class Outer { public static int value; class Inner { int value; } } // Hides static 'value'
public class Outer { public static int value; class Inner { int innerValue; } } // Clear variable naming
Identifier Typo
Description: Typo in identifier
int mispelledVariable = 10;
int misspelledVariable = 10;
IEnumerable Test Case Source
Description: NUnit. Test case source must be non-abstract and implement IEnumerable.
[TestCaseSource(typeof(NonEnumerableSource))] public void Method() { /* ... */ }
[TestCaseSource(typeof(EnumerableSource))] public void Method() { /* ... */ }
If Statement Braces
Description: Use preferred braces style (enforce braces in 'if' statement)
if (condition) Console.WriteLine("Hello");
if (condition) { Console.WriteLine("Hello"); }
Ignored Parameter Attribute
Description: NUnit. Ignored parameter attribute
[TestCase(Ignore="Reason")] public void Test() { /* ... */ }
[Ignore("Reason")] public void Test() { /* ... */ }
Implicit Dereference of Possibly Null Member
Description: Object or collection initializer implicitly dereferences possibly null member.
var obj = new MyClass { Name = nullableName }; // nullableName may be null
var obj = new MyClass { Name = nullableName ?? "Default" }; // Provides default if null
Implicit Unspecified Null Values
Description: NUnit. Implicitly unspecified null values
[TestCase(null)] public void Test(string value) { /* ... */ }
[TestCase((string?)null)] public void Test(string? value) { /* ... */ }
Inconsistent Naming
Description: Inconsistent Naming
public int myVariable;
public int MyVariable;
Inconsistent Nullability in Partial Method Declaration
Description: Partial method declarations have inconsistent nullability for type parameter.
partial void ProcessData(T? data); partial void ProcessData(T data);
partial void ProcessData(T data); partial void ProcessData(T data);
Inconsistent Order of Locks
Description: Inconsistent order of taken locks
lock (lock1) { lock (lock2) { /* Code */ } } // Reversed order elsewhere
lock (lock2) { lock (lock1) { /* Code */ } } // Consistent locking order
Inconsistently Synchronized Field
Description: Inconsistent synchronization on field
lock (lockObject) { field++; } // Field accessed without lock elsewhere
lock (lockObject) { field++; } // Always accessed within lock
Incorrect Argument Type
Description: NUnit. Incompatible argument type or incorrect argument value
[TestCase(1.5)] public void Test(int value) { /* ... */ }
[TestCase(1)] public void Test(int value) { /* ... */ }
Incorrect Argument Type
Description: NUnit.AutoFixture. Incompatible argument type or incorrect argument value.
[AutoData] public void Method(string x) { /* ... */ }
[AutoData] public void Method(int x) { /* ... */ }
Incorrect Blank Lines Near Braces
Description: Incorrect blank lines (incorrect number of blank lines near braces).
public class Example {
void Method() {
}
public class Example {
void Method() {
}
}
Incorrect Expected Result Type
Description: NUnit. Incompatible expected result type or incorrect value
[TestCase(5, ExpectedResult="5")] public int Test(int value) { return value; }
[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'
[Range(10, 5, 1)] public void Test(int value) { /* ... */ }
[Range(5, 10, 1)] public void Test(int value) { /* ... */ }
Incorrect signature in XML comment
Description: Invalid Type for 'parameter number' in XML comment
/// <param name="str">String parameter</param> void Method(int number) { }
/// <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
var substring = text.Substring(5, 2); // when text.Length < 7
if (text.Length >= 7) { var substring = text.Substring(5, 2); }
Inheritdoc Consider Usage
Description: Use
/// <summary>Does something.</summary>
<inheritdoc /> // Use to inherit documentation when available
Inheritdoc Invalid Usage
Description: Usage of
<inheritdoc /> // in a non-root element
<inheritdoc /> // in a root-level element inheriting from a base class or interface
Initializer Value Ignored
Description: Member initialized value ignored
public int Value { get; set; } = 10; // Later set to a different value, ignoring initializer
public int Value { get; set; } = 10; // Initial value honored in logic
Inline out Variable Declaration
Description: Inline 'out' variable declaration
int result; bool success = int.TryParse(input, out result);
bool success = int.TryParse(input, out int result);
Inline Temporary Variable
Description: Inline temporary variable
int temp = GetResult(); return temp;
return GetResult();
Int Variable Overflow
Description: Possible overflow.
int overflow = int.MaxValue + 1;
int max = int.MaxValue; /* handle overflow scenario */
Int Variable Overflow in Checked Context
Description: Possible overflow in checked context.
checked { int max = int.MaxValue + 1; }
checked { int max = int.MaxValue; /* handle overflow */ }
Int Variable Overflow in Unchecked Context
Description: Possible overflow in unchecked context.
unchecked { int max = int.MaxValue + 1; }
unchecked { int max = int.MaxValue; /* handle overflow */ }
Interpolated String Expression Not IFormattable
Description: Formatting is specified, but interpolated string expression is not IFormattable
Console.WriteLine($"Value: {myObject:F2}");
Console.WriteLine($"Value: {((IFormattable)myObject).ToString("F2", null)}");
Introduce Optional Global Parameters
Description: Introduce optional parameters (non-private accessibility).
public void Method(int x) { /* ... */ }
public void Method(int x = 0) { /* ... */ }
Introduce Optional Local Parameters
Description: Introduce optional parameters (private accessibility).
private void Method(int x) { /* ... */ }
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
[method: Obsolete] void Example() { }
[Obsolete] void Example() { }
Invalid Module Name
Description: Module with this name does not exist
PublicDependencyModuleNames.Add("NonExistentModule");
PublicDependencyModuleNames.Add("ValidModule");
Invalid Xml Comment
Description: Invalid XML documentation comment
/// Summary with unmatched < tags
/// <summary>Valid XML documentation comment</summary>
Invalid XML in XML comment
Description: XML Comment on 'construct' badly formed XML
/// <summary> This is an <unclosed> tag </summary>
/// <summary> This is a properly closed tag </summary>
Invalid XML Include Element
Description: Invalid XML include element
/// <include file='NonExistentFile.xml' />
/// <include file='ValidFile.xml' path='Docs/Member[@name="M:Method"]' />
Invert Condition
Description: Invert condition
if (!isAvailable) { /* Action if unavailable */ } else { /* Action if available */ }
if (isAvailable) { /* Action if available */ } else { /* Action if unavailable */ } // Inverted condition for readability
Invert if
Description: Invert 'if' statement to reduce nesting.
if (condition) { /* nested code */ } else { return; }
if (!condition) { return; } /* flattened code */
Invocation Skipped
Description: Method invocation is skipped
int x = 5; x; // x is evaluated, but the result is not used, effectively skipping any invocation
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
StringExtensions.DoSomething(myString);
myString.DoSomething();
Iterator Method Result Ignored
Description: Return value of iterator is not used
GetItems(); // Result ignored
foreach (var item in GetItems()) { /* process item */ }
Iterator Never Returns
Description: Iterator never returns
IEnumerable<int> EndlessIterator() { while (true) { yield return 1; } }
IEnumerable<int> LimitedIterator() { for (int i = 0; i < 10; i++) { yield return i; } }
Join Declaration and Initializer
Description: Join local variable declaration and assignment
int count; count = 10; // Declaration and assignment are separate
int count = 10; // Declaration and assignment are joined
Lambda Expression Made Static
Description: Lambda expression/anonymous method can be made 'static'.
Func<int, int> square = x => x * x;
static int Square(int x) => x * x;
Lambda Expression Static
Description: Lambda expression/anonymous method must be 'static' to avoid allocations.
Func<int, int> square = x => x * x;
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.
int a = 5; Func<int> getA = () => a;
int GetA(int a) => a;
Linq Expression Use All
Description: Simplify LINQ expression (use 'All')
var allActive = !collection.Any(item => !item.IsActive);
var allActive = collection.All(item => item.IsActive);
Linq Expression Use All
Description: Simplify LINQ expression (use 'All')
var allActive = !collection.Any(item => !item.IsActive);
var allActive = collection.All(item => item.IsActive);
Linq Expression Use Any
Description: Simplify LINQ expression (use 'Any')
var hasActiveItems = collection.Count(item => item.IsActive) > 0;
var hasActiveItems = collection.Any(item => item.IsActive);
Linq Expression Use Any
Description: Simplify LINQ expression (use 'Any')
var hasActiveItems = collection.Count(item => item.IsActive) > 0;
var hasActiveItems = collection.Any(item => item.IsActive);
Local Class Never Instantiated
Description: Class is never instantiated (private accessibility)
private class UnusedClass { /* class implementation */ }
private class UsedClass { /* class implementation */ } new UsedClass();
Local Class Sealed
Description: Class can be made sealed (non-inheritable) (private accessibility)
internal class InternalClass { /* Implementation */ } // Can be inherited within assembly
internal sealed class InternalClass { /* Implementation */ } // Sealed to prevent unintended inheritance
Local Collection Never Queried
Description: Collection's content is never queried (private accessibility)
private List<int> numbers = new List<int> { 1, 2, 3 };
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)
private List<int> numbers = new List<int>();
private List<int> numbers = new List<int> { 1, 2, 3 };
Local Field Read Only
Description: Field can be made readonly (private accessibility)
private int _counter = 0; // Field can be modified in other methods
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)
void LocalFunction() { Console.WriteLine("Hello"); }
void LocalFunction() => Console.WriteLine("Hello");
Local Function Hides Method
Description: Local function hides method
void MyMethod() { void MyMethod() { /* Local function */ } }
void MyMethod() { void LocalHelper() { /* Local function */ } }
Local Function Static
Description: Local function can be made static
void ProcessData() { /* Function does not access instance members */ }
static void ProcessData() { /* Marked as static to clarify no access to instance members */ }
Local Member Private
Description: Member can be made private (private accessibility)
public int exampleValue = 10;
private int exampleValue = 10;
Local Member Protected
Description: Member can be made protected (private accessibility)
public int exampleValue = 10;
protected int exampleValue = 10;
Local Member Static
Description: Member can be made static (shared) (private accessibility)
private int exampleValue = 10;
private static int ExampleValue = 10;
Local Parameter Type
Description: Parameter type can be IEnumerable (private accessibility)
private void PrintData(List<string> data) { }
private void PrintData(IEnumerable<string> data) { }
Local Property Init Only
Description: Property can be made init-only (private accessibility)
private string Name { get; set; } // Allows modification after initialization
private string Name { get; init; } // Init-only, settable only during object initialization
Local Return Type IEnumerable
Description: Return type can be IEnumerable (private accessibility)
private List<string> GetItems() { return new List<string>(); }
private IEnumerable<string> GetItems() { return new List<string>(); }
Local Variable Hides Member
Description: Local variable hides member
public int value; void SetValue() { int value = 10; /* Local variable hides member */ }
public int value; void SetValue() { int localValue = 10; value = localValue; }
Localizable Element
Description: Element is localizable
Console.WriteLine("Hello, World!");
Console.WriteLine(Resources.GreetingMessage); // Use resource for localization
Lock Statement Braces
Description: Use preferred braces style (enforce braces in 'lock' statement)
lock (myLock) DoSomething();
lock (myLock) { DoSomething(); }
Loop Converted to Query
Description: Loop can be converted into LINQ-expression.
foreach (var item in items) { if (item.IsActive) activeItems.Add(item); }
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
for (int i = 0; i < list.Count; i++) { if (list[i] > 0) positiveItems.Add(list[i]); }
positiveItems.AddRange(list.Where(item => item > 0));
Loop Variable Never Changes
Description: Loop control variable is never changed inside loop
for (int i = 0; i < 10; ) { Console.WriteLine(i); } // 'i' is not incremented inside loop
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.
public static void Main() { Console.WriteLine("Hello"); }
// Top-level statement Console.WriteLine("Hello");
Math Clamp Invalid Values
Description: Inconsistent arguments passed to 'Math.Clamp()' method.
var result = Math.Clamp(value, 10, 5);
var result = Math.Clamp(value, 5, 10);
Meaningless Default Parameter Value
Description: 'DefaultParameterValueAttribute' should be used in conjunction with 'OptionalAttribute'
[DefaultParameterValue(5)] public void MyMethod(int value) { } // Lacks 'OptionalAttribute'
[DefaultParameterValue(5), Optional] public void MyMethod(int value) { } // Added 'OptionalAttribute'
Member 'name' Overriding 'method'
Description: Multiple override candidates at run-time
public override void Method(int x) { } public override void Method(object x) { }
public override void Method(int x) { } public void AnotherMethod(object x) { }
Member Internal
Description: Member or type can be made internal(friend)
public class Example { }
internal class Example { }
Member non Null Value when Exiting
Description: Member must have a non-null value when exiting.
public void Initialize() { /* myObject might still be null */ }
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.
if (condition) { return; }
if (condition) { myObject = new Object(); } return;
Member not Documented
Description: Missing XML comment for private or internal type or member
internal class DataProcessor { /* No XML documentation */ }
/// <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.
[MyAttribute(Name)]
[MyAttribute("ValidValue")]
Member with Default Implementation
Description: Non-public member in implementation class hides default implementation in interface
public interface ITest { void Display() { Console.WriteLine("Interface"); } } class Test : ITest { private void Display() { } }
public interface ITest { void Display() { Console.WriteLine("Interface"); } } class Test : ITest { public void Display() { Console.WriteLine("Test"); } }
Merge and Pattern
Description: Merge 'and' pattern.
if (x is >= 1 && x is <= 10) { /* ... */ }
if (x is >= 1 and <= 10) { /* ... */ }
Merge Cast with Type Check
Description: Type check and casts can be merged
if (obj is MyClass) { MyClass myObj = (MyClass)obj; }
if (obj is MyClass myObj) { /* use myObj directly */ }
Merge Conditional Expression
Description: Merge conditional ?: expression into conditional access.
var result = obj != null ? obj.Property : null;
var result = obj?.Property;
Merge Conditional Expression
Description: Merge conditional ?: expression into conditional access (when possible)
var result = condition ? obj.Property : null;
var result = obj?.Property;
Merge Into Logical Pattern
Description: Merge null/pattern/value checks into 'or'/'and' patterns
if (value is null || value == 0) { /* ... */ }
if (value is null or 0) { /* ... */ }
Merge into Negated Pattern
Description: Merge negated null/pattern checks into complex pattern
if (!(value is null || value == "")) { /* ... */ }
if (value is not null and not "") { /* ... */ }
Merge into Pattern
Description: Merge null/pattern checks into complex pattern
if (value != null && value is int) { /* ... */ }
if (value is not null and int) { /* ... */ }
Merge Nested Property Patterns
Description: Merge nested property patterns
if (person is { Address: { City: { Name: "New York" } } }) { /* ... */ }
if (person is { Address.City.Name: "New York" }) { /* ... */ }
Merge Sequential Checks
Description: Merge sequential checks into single conditional access check
if (obj != null && obj.Property != null) { /* ... */ }
if (obj?.Property != null) { /* ... */ }
Merge Sequential Checks
Description: Merge sequential checks into single conditional access check (when possible)
if (list != null && list.Count > 0) { /* ... */ }
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.
public static async Task Main() { await Task.Delay(1000); }
public static void Main() { Task.Run(async () => await Task.Delay(1000)).Wait(); }
Method Async Overload
Description: Method has async overload
public void SaveData() { /* Synchronous implementation */ }
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
public async Task SaveDataAsync() { /* Async without cancellation support */ }
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)
public int Add(int a, int b) { return a + b; }
public int Add(int a, int b) => a + b;
Method Supports Cancellation
Description: Method supports cancellation
public async Task ProcessDataAsync() { /* Lacks cancellation handling */ }
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.
[Test] public void TestMethod(int x) { /* ... */ }
[TestCase(1)] public void TestMethod(int x) { /* ... */ }
Missed Test Attribute
Description: NUnit.AutoFixture. Missed Test or TestFixture attribute
public void TestMethod() { /* ... */ }
[Test] public void TestMethod() { /* ... */ }
Missing Arguments in Test Case Attribute
Description: NUnit. Missing arguments in TestCase attribute
[TestCase] public void Test(string value) { /* ... */ }
[TestCase("example")] public void Test(string value) { /* ... */ }
Missing Blank Lines
Description: Incorrect blank lines (blank lines are missing elsewhere).
public class Example
{
void Method() {}
}
public class Example
{
void Method() {}
}
Missing DoesNotReturn Annotation
Description: Method lacks '[DoesNotReturn]' annotation in order to match implemented or overridden member.
public void Terminate() { throw new Exception(); }
[DoesNotReturn] public void Terminate() { throw new Exception(); }
Missing GetHashCode in Record
Description: Record defined 'Equals' but not 'GetHashCode'
public record MyRecord { public bool Equals(MyRecord other) { /* custom equality logic */ } }
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)
if (condition)
doSomething();
if (condition)
doSomething();
Missing Linebreak
Description: Incorrect line breaks (line break is missing elsewhere).
public void Method() { int x = 5; int y = 10; }
public void Method() {
int x = 5;
int y = 10;
}
Missing Parentheses
Description: Add parentheses to avoid non-obvious precedence
int result = a + b * c;
int result = a + (b * c);
Missing Plugin Dependency
Description: Dependency for plugin is missing in project file
// Plugin dependency is missing from .uproject file
"Plugins": [ { "Name": "MyPlugin", "Enabled": true } ]
Missing Space
Description: Incorrect spacing (space is missing elsewhere)
int a=10;
int a = 10;
Missing XML Comment
Description: Missing XML comment for publicly visible type or member
public class MyClass { public void Method() { } }
/// <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
/// <summary>Processes data.</summary> public void ProcessData(string data) {}
/// <summary>Processes data.</summary> /// <param name="data">The data to process.</param> public void ProcessData(string data) {}
Modifiers Order
Description: Adjust modifiers declaration order
static public int Count;
public static int Count;
More Specific Foreach
Description: Iteration variable can be declared with a more specific type
foreach (object item in list) { /* Use item as a specific type */ }
foreach (string item in list) { /* Use item as a specific type */ } // Declared with a more specific type
Multiple OrderBy
Description: Multiple sequential 'OrderBy' invocation
items.OrderBy(x => x.Name).OrderBy(x => x.Age); // Multiple OrderBy causes issues
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
Console.WriteLine("Value: " + ambiguousSymbol);
Console.WriteLine("Value: " + resolvedSymbol);
Multiple Spaces
Description: Incorrect spacing (multiple spaces are prohibited)
int count = 10;
int count = 10;
Multiple Statements on One Line
Description: Incorrect line breaks (multiple statements on one line).
int x = 5; int y = 10;
int x = 5;
int y = 10;
Multiple Type Members
Description: Incorrect line breaks (multiple type members on one line).
public int X { get; set; } public int Y { get; set; }
public int X { get; set; }
public int Y { get; set; }
Must Use Return Value
Description: Return value of [MustUseReturnValue] annotated method is not used
CalculateValue(); // Ignoring return value of a method marked with MustUseReturnValue
var result = CalculateValue(); // Correctly uses the return value
Negated Pattern in is Expression
Description: Convert negated 'is' expression to 'is' expression with negated pattern.
if (!(value is SomeType)) { /* ... */ }
if (value is not SomeType) { /* ... */ }
Negated Pattern Matching
Description: Convert 'as' expression type check and the following null check into negated pattern matching.
if (!(obj is SomeType)) { /* ... */ }
if (obj is not SomeType) { /* ... */ }
Negation of Relational Pattern
Description: Simplify negated relational pattern
if (!(value > 10)) { ... }
if (value <= 10) { ... }
Negation of Relational Pattern
Description: Simplify negated relational pattern
if (!(value > 10)) { ... }
if (value <= 10) { ... }
Negative Equality Expression
Description: Simplify negative equality expression
if (!(status == Status.Active)) { ... }
if (status != Status.Active) { ... }
Negative Equality Expression
Description: Simplify negative equality expression
if (!(status == Status.Active)) { ... }
if (status != Status.Active) { ... }
Negative Index
Description: Possible 'System.ArgumentOutOfRangeException'. Index must be a non-negative integer
var value = array[-1];
var value = array[0];
Nested String Interpolation
Description: Nested string interpolation can be inlined
string name = $"{GetFirstName()} {GetLastName()}"; // Nested interpolation
string name = $"{GetFullName()}"; // Inlined interpolation by combining into a single method
New Keyword not Required
Description: Keyword 'new' is redundant
public new int Property { get; set; }
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
sealed class MyClass { protected void MyMethod() { } }
sealed class MyClass { private void MyMethod() { } }
No Values Provided
Description: NUnit. No values provided in the attributes.
[TestCase] public void TestMethod(int value) { /* ... */ }
[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
volatile int counter; counter++; // Non-atomic operation on volatile field
Interlocked.Increment(ref counter); // Ensures atomic increment
Non Parsable Element
Description: Part of the code cannot be parsed
int x = ; // Missing value or syntax error
int x = 5; // Properly assigned value
Non Public Method with Test Attribute
Description: NUnit. Non-public test method.
[Test] private void PrivateTestMethod() { /* ... */ }
[Test] public void PublicTestMethod() { /* ... */ }
Non Readonly Member in GetHashCode
Description: Non-readonly type member referenced in 'GetHashCode()'
private int nonReadonlyField; public override int GetHashCode() { return nonReadonlyField.GetHashCode(); }
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).
var result = status switch { Status.Active => "Active" };
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.
var result = color switch { Color.Red => "Red" };
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.
var result = status switch { Status.Active => "Active" };
var result = status switch { Status.Active => "Active", Status.Inactive when condition => "Inactive", _ => "Unknown" };
Non-nullable Member Uninitialized
Description: Non-nullable member is uninitialized.
public string Name; // Not initialized
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.
[return: NotNullIfNotNull("input")] public string? GetData(string? input) { return null; }
[return: NotNullIfNotNull("input")] public string? GetData(string? input) { return input ?? "default"; }
Non-Private Accessibility
Description: Virtual (overridable) member is never overridden (non-private accessibility)
public virtual void Method() { }
// Make 'Method' non-virtual if no subclasses override it
Not Accessed Field. Compiler
Description: Non-accessed field
private int unusedField;
private int usedField; public int GetField() => usedField;
Not Accessed Global Field
Description: Non-accessed field (non-private accessibility)
public int unusedField; // Field not accessed
private int usedField; // Fields should be private if not accessed externally
Not Accessed Local Field
Description: Non-accessed field (private accessibility)
private int unusedField; // Field not accessed
public void Method() { int usedField = 10; } // Variable used locally
Not Accessed Positional Global Property
Description: Non-accessed positional property (non-private accessibility)
public int Property { get; init; } // Property not accessed
private int AccessedProperty { get; init; } = 10; // Private or used properties only
Not Accessed Positional Local Property
Description: Non-accessed positional property (private accessibility)
private int Property { get; init; } // Property is declared but not used
private int Property { get; init; } = 10; // Property is initialized and used
Not Accessed Variable
Description: Non-accessed local variable
int unusedVariable = 5;
// Remove the variable if it is not accessed
Not Accessed Variable. Compiler
Description: Non-accessed local variable
int unusedVariable = 0;
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.
async IAsyncEnumerable<int> Generate(CancellationToken token) { yield return 1; }
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
public class MyClass { public string NotNullMember; }
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
[NotNull] private string internalData;
private string internalData;
Not Resolved in Text
Description: Cannot resolve symbol in text argument
Console.WriteLine("Value: " + unresolvedSymbol);
int resolvedSymbol = 5; Console.WriteLine("Value: " + resolvedSymbol);
Null Check Assignment
Description: Join null check with assignment.
if (x == null) { x = new Object(); }
x ??= new Object();
Null Check Assignment
Description: Join null check with assignment (when possible).
if (x == null) { x = new Object(); }
x ??= new Object();
Nullability Mismatch in Base Type Interface
Description: Nullability of reference types in interface implemented by the base type doesn't match.
public string? DerivedMethod() => "Value"; // Overrides non-nullable base method
public string DerivedMethod() => "Value"; // Matches non-nullable base method
Nullability Mismatch in Constraints
Description: Nullability mismatch in constraints for type parameter.
public void Process(T? item) where T : notnull { }
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.
public string? Method() => "Text"; // Implementing non-nullable interface
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.
public string? nullableData;
#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.
public string? data;
#nullable enable public string? data; #nullable disable
Nullable Attributes
Description: Multiple nullable attributes usage
[AllowNull][MaybeNull] public string? Name; // Redundant nullable attributes
[MaybeNull] public string? Name; // Simplified with a single nullable attribute
Nullable Value Type May Be Null
Description: Nullable value type may be null.
int? nullableInt = null; int nonNullableInt = nullableInt.Value; // May throw if null
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
if (x is not null!) { } // Confusing use of nullable suppression operator
if (x != null) { } // Clear and direct check for null
Nullable Warning Suppression
Description: A suppressed nullable warning might hide an underlying problem.
var value = possiblyNull!;
if (possiblyNull != null) { var value = possiblyNull; /* ... */ }
Object Creation as Statement
Description: Possible unassigned object created by 'new' expression
new MyClass(); // Object created but not assigned or used
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
List<int> numbers = new List<int>();
List<int> numbers = new();
Object Creation Not Evident Type
Description: Use preferred style of 'new' expression when created type is not evident
var numbers = new List<int>();
List<int> numbers = new List<int>();
Obsolete Attribute to ‘member1’
Description: Member overrides obsolete member
public override void ObsoleteMethod() { /* Obsolete method logic */ }
[Obsolete] public override void ObsoleteMethod() { /* Method logic */ }
One Way Operation Return
Description: One way operations must not return values
[OperationContract(IsOneWay = true)] public int GetData() { return 42; } // One-way operation with return type
[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
[OperationContract] public void MyMethod() { } // No [ServiceContract] on class
[ServiceContract] public class MyService { [OperationContract] public void MyMethod() { } } // Correct usage
Operator Used
Description: Operator 'is'/'Type Of ... Is ...' can be used
if (typeof(obj) == typeof(string)) { }
if (obj is string) { } // Clearer usage of 'is' operator
Optional Parameter Hierarchy Mismatch
Description: Mismatch of optional parameter value in overridden method
public virtual void Print(int x = 5) { } public override void Print(int x = 10) { } // Different defaults
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
public void DoSomething(int x, int y = 0) { } public void DoSomething(int x) { } // Ambiguity
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
public void Method([Optional] ref int x) { } // Invalid use of Optional attribute with ref parameter
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.
void Log(InterpolatedStringHandler handler, string message) { }
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.
void Process(string? data) { if (data == null) return; /* process data */ }
void Process(string? data) { if (data == null) throw new ArgumentNullException(nameof(data)); /* process data */ }
Parameter Hides Member
Description: Parameter hides member
public int count; public void SetCount(int count) { this.count = count; } // Parameter hides member
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.
void Save(string? data) { /* some logic */ }
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.
public string? GetData(string? input) { return input?.ToUpper(); }
[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).
Action<string?> action = (input) => Console.WriteLine(input); // Expected non-nullable
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.
public void SetName(string? name) {} // Expected non-nullable
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.
public void Display(string? text) {} // Expected non-nullable
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.
public override void Process(string? data) {} // Expected non-nullable
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.
public partial void LoadData(string? data); // Expected non-nullable
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.
[TestCase("string")] public void Method(int x) { /* ... */ }
[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).
public void SetData(string? data) {} // Expected non-nullable parameter
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).
public void Process(string? input) {} // Expected non-nullable parameter
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).
public override void Display(string? message) {} // Expected non-nullable parameter
public override void Display(string message) {} // Matches non-nullable parameter type
Partial Method
Description: Redundant 'partial' modifier on method declaration
partial void Log(); // Only one part
// Remove 'partial' modifier if the method has a single part
Partial Method Parameter Name Mismatch
Description: Parameter name differs in partial method declaration
partial void Print(string message); partial void Print(string text) { } // Mismatched parameter names
partial void Print(string message); partial void Print(string message) { } // Consistent parameter naming
Partial Type
Description: Redundant 'partial' modifier on type declaration
public partial class SinglePartClass { }
// 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)
public override void Method() { } // Method never accessed via base
// 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)
private override void InternalMethod() { } // Never accessed via base
// 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)
public void Method() { OverrideMethod(); }
// Remove 'Method' if it is only used for override
Partially Unused Member Private Accessibility
Description: Type member is only used in overrides (private accessibility)
private void InternalMethod() { OverrideInternalMethod(); }
// Remove 'InternalMethod' if only used by overrides
Partially Unused Parameter Non-Private Accessibility
Description: Parameter is only used for precondition check (non-private accessibility)
public void DoSomething(int x) { if (x < 0) throw new ArgumentException(); }
// 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)
private void Helper(int y) { if (y > 10) throw new ArgumentException(); }
// Adjust the method or consider removing the parameter if it is only used for validation
Pass String Interpolation
Description: Pass string interpolation expression
string result = string.Format("Hello, {0}", name);
string result = $"Hello, {name}";
Pattern Always Matches
Description: The source expression always matches the provided pattern
switch (obj) { case string s: break; } // Pattern always matches
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.
var obj = value as SomeType; if (obj != null) { /* ... */ }
if (value is SomeType obj) { /* ... */ }
Pattern Never Matches
Description: The source expression never matches the provided pattern
switch (obj) { case int i: break; } // Pattern will never match
// Ensure patterns are meaningful for the expected types
Pattern Same Value
Description: Pattern is always 'true' or always 'false'
if (x is int) { ... } // Always true for int type variable
if (x is not null) { ... } // Pattern with meaningful check
Polymorphic Field-Like Event
Description: Invocation of polymorphic field-like event
fieldLikeEvent?.Invoke(this, EventArgs.Empty);
OnEventTriggered(); // Method wrapper around event invocation
Positional Deconstruction Pattern
Description: Move to existing positional deconstruction pattern
if (point.X == 0 && point.Y == 0) { /* ... */ }
if (point is (0, 0)) { /* ... */ }
Possible Empty Statement
Description: Possible mistaken empty statement
if (condition); // Empty statement
if (condition) { /* do something */ }
Possible Infinite Inheritance
Description: Possible infinite inheritance
class A : A { }
class A : B { }
Possible Intended Rethrow
Description: Exception rethrow possibly intended
catch (Exception ex) { throw ex; }
catch (Exception) { throw; } // Maintain stack trace
Possible Interface Member Ambiguity
Description: Possible ambiguity while accessing member by interface
interface IA { void Display(); } interface IB { void Display(); } class C : IA, IB { public void Display() { } } // Ambiguous call
class C : IA, IB { void IA.Display() { } void IB.Display() { } } // Explicit interface implementation
Possible Invalid Cast Exception
Description: Possible 'System.InvalidCastException'
object obj = "string"; int number = (int)obj;
object obj = "string"; if (obj is int number) { /* logic */ }
Possible Invalid Cast Exception in Foreach Loop
Description: Possible 'System.InvalidCastException' in foreach loop
foreach (int number in objectList) { /* logic */ }
foreach (var obj in objectList) { if (obj is int number) { /* logic */ } }
Possible Invalid Operation Exception
Description: Possible 'System.InvalidOperationException'
var firstItem = list.First(item => item.Property == null);
var firstItem = list.FirstOrDefault(item => item.Property == null); if (firstItem != null) { /* logic */ }
Possible IQueryable as IEnumerable
Description: IQueryable is possibly unintentionally used as IEnumerable
var results = queryableCollection.ToList().Where(x => x > 10);
var results = queryableCollection.Where(x => x > 10).ToList();
Possible Loss of Fraction
Description: Possible loss of fraction
int result = 5 / 2; // result is 2
double result = 5.0 / 2.0; // result is 2.5
Possible Mistaken Argument
Description: Possible mistaken argument
public void SetDimensions(int width, int height) { }
...
SetDimensions(height, width);
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
GetStruct().Value = 5; // Modifying property of a non-variable expression
var myStruct = GetStruct(); myStruct.Value = 5; // Assigned to a variable before modification
Possible Multiple Enumeration
Description: Possible multiple enumeration
foreach (var item in collection) { if (collection.Contains(item)) { /* logic */ } }
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
if (_instance == null) { lock(_lock) { if (_instance == null) _instance = new Singleton(); } }
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.
ProcessData(nullableData);
ProcessData(nullableData ?? "Default");
Possible Null Assignment
Description: Possible null reference assignment.
string? nullableStr = null; string nonNullableStr = nullableStr;
string? nullableStr = null; string nonNullableStr = nullableStr ?? "Default";
Possible Null Reference Exception
Description: Possible 'System.NullReferenceException'
string text = null; Console.WriteLine(text.Length); // Throws NullReferenceException
string text = null; if (text != null) { Console.WriteLine(text.Length); } // Null check prevents exception
Possible Null Return
Description: Possible null reference return.
public string? GetName() { return null; }
public string GetName() { return "Default Name"; }
Possible Unintended Linear Search in Set
Description: Possibly unintended linear search in set
myList.Contains(item); // Potential linear search in a list
myHashSet.Contains(item); // Set-based collection avoids linear search
Possible Unintended Reference Comparison
Description: Possible unintended reference comparison
if (string1 == string2) { /* Reference comparison instead of value */ }
if (string1.Equals(string2)) { /* Value comparison */ }
Possible Unintended Reference Comparison
Description: Possible unintended reference comparison
if (string1 == string2) { } // May lead to unintended reference comparison
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
readonly MyStruct instance; instance.Modify(); // Causes struct copy
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
var dict = new Dictionary<int, string> { [1] = "One" [2] = "Two" }; // Missing comma
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.
Console.WriteLine($"{0}, {1}"); // Likely intended as a format string
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
public void Log(string message, params object[] args) { } // Call Log("Error", "Detail")
public void Log(string message, string detail) { } // Better match for Log("Error", "Detail")
Prefer Auto Property
Description: Convert property to auto-property.
private int _value; public int Value { get { return _value; } set { _value = value; } }
public int Value { get; set; }
Prefer Auto Property
Description: Convert property to auto-property (when possible).
private int _value; public int Value { get { return _value; } set { _value = value; } }
public int Value { get; set; }
Prefer Auto Property with Private Setter
Description: Convert property to auto-property with private setter.
private int _value; public int Value { get { return _value; } private set { _value = value; } }
public int Value { get; private set; }
Prefer Computed Property Auto Property
Description: Replace auto-property with computed property
public int Age { get; set; }
public int Age => DateTime.Now.Year - birthYear;
Prefer Conditional Ternary Expression
Description: 'if' statement can be re-written as '?:' expression
if (isActive) { result = "Active"; } else { result = "Inactive"; }
result = isActive ? "Active" : "Inactive";
Prefer Conditional Ternary Expression
Description: Replace ternary expression with 'switch' expression.
result = condition ? 'A' : 'B';
result = condition switch { true => 'A', false => 'B' };
Prefer is Operator
Description: Use 'is' operator
if (obj is MyType) { var myObj = (MyType)obj; ... }
if (obj is MyType myObj) { ... }
Prefer is Operator
Description: Use 'is' operator
if (obj is MyType) { var myObj = (MyType)obj; ... }
if (obj is MyType myObj) { ... }
Prefer Local Function
Description: Convert delegate variable to local function.
Func<int, int> Square = x => x * x;
int Square(int x) => x * x;
Prefer Method Any
Description: Use method Any()
if (list.Count > 0) { ... }
if (list.Any()) { ... }
Prefer Method Any
Description: Use method Any()
if (collection.Count() != 0) { ... }
if (collection.Any()) { ... }
Prefer Method Any
Description: Use method Any()
if (items.Where(x => x.IsActive).Count() > 0) { ... }
if (items.Any(x => x.IsActive)) { ... }
Prefer Method Any
Description: Use method Any()
if (elements.FindAll(x => x.IsReady).Count > 0) { ... }
if (elements.Any(x => x.IsReady)) { ... }
Prefer Method Any
Description: Use method Any()
if (data.Where(y => y.Valid).Count() > 0) { ... }
if (data.Any(y => y.Valid)) { ... }
Prefer Method IsInstanceOfType
Description: Use method IsInstanceOfType(..)
if (typeof(MyType).IsAssignableFrom(obj.GetType())) { ... }
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.
if (obj is object) { ... } // Type check succeeds for any not-null value
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.
if (obj is object) { ... } // Type check only succeeds if not null
if (obj != null) { ... } // Uses direct null check
Prefer Null Coalescing Assignment
Description: 'if' statement can be re-written as '??=' assignment
if (value == null) { value = defaultValue; }
value ??= defaultValue;
Prefer Null Coalescing Expression
Description: 'if' statement can be re-written as '??' expression
if (value == null) { value = defaultValue; }
value ??= defaultValue;
Prefer Null Propagation
Description: Replace if statement with null-propagating code.
if (obj != null) { result = obj.Property; }
result = obj?.Property;
Prefer Null Propagation If
Description: Replace if statement with null-propagating code (when possible).
if (obj != null) { result = obj.Property; }
result = obj?.Property;
Prefer Nullable Annotation
Description: Use nullable annotation instead of an attribute.
[Nullable] public string Name; // Nullable attribute
public string? Name; // Nullable annotation
Prefer Or Expression
Description: Convert 'if' to '||'
if (a) { } else if (b) { }
if (a || b) { }
Prefer Primary Constructor
Description: Convert record constructor to primary constructor
public record Person { public string Name { get; } public Person(string name) { Name = name; } }
public record Person(string Name);
Prefer Range Indexer Slice
Description: Replace 'Slice' with range indexer.
array.Slice(1, 3);
array[1..4];
Prefer Range Indexer Substring
Description: Replace 'Substring' with range indexer.
str.Substring(1, 3);
str[1..4];
Prefer Return Statement
Description: 'if-return' statement can be re-written as 'return' statement
if (condition) { return true; } return false;
return condition;
Prefer Short Form
Description: Convert 'Nullable' to 'T?'.
Nullable<int> number = 5;
int? number = 5;
Prefer String IsNullOrEmpty
Description: Use 'String.IsNullOrEmpty'
if (str == null || str == "") { ... }
if (String.IsNullOrEmpty(str)) { ... }
Prefer Switch Expression
Description: Convert 'if' statement to 'switch' expression.
if (x == 1) { return "One"; } else if (x == 2) { return "Two"; }
return x switch { 1 => "One", 2 => "Two", _ => "Other" };
Prefer Switch Statement
Description: Convert 'if' statement to 'switch' statement.
if (x == 1) { /* ... */ } else if (x == 2) { /* ... */ }
switch (x) { case 1: /* ... */ break; case 2: /* ... */ break; }
Prefer Switch Statement
Description: Replace 'switch' statement with 'switch' expression.
switch (value) { case 1: result = 'A'; break; }
result = value switch { 1 => 'A', _ => 'B' };
Prefer to Compound Assignment
Description: Use compound assignment.
x = x + 1;
x += 1;
Prefer Var Pattern
Description: Replace object pattern not performing any additional checks with 'var' pattern.
if (obj is MyClass myClass) { /* ... */ }
if (obj is var myClass) { /* ... */ }
Prefer While Expression
Description: Convert 'if do while' to 'while
if (condition) { do { /* Code */ } while (condition); } // Redundant if statement before do-while loop
while (condition) { /* Code */ } // Simpler while loop without redundant if statement
Prefer With Expression
Description: 'with' expression is used instead of object initializer
var newObj = oldObj with { Property = value };
var newObj = new MyClass { Property = value }; // Use object initializer
Preferred Namespace Body
Description: Use preferred namespace body style
namespace MyNamespace { class MyClass {} }
namespace MyNamespace
{
class MyClass {}
}
Previous Level Indent
Description: Incorrect indent (line indent should be restored to the previous level elsewhere)
if (condition)
{
if (anotherCondition)
{
doSomething();
}
}
if (condition)
{
if (anotherCondition)
{
doSomething();
}
}
Private Accessibility
Description: Virtual (overridable) member is never overridden (private accessibility)
protected virtual void Helper() { }
// Remove 'virtual' modifier if 'Helper' is not overridden
Private Field to Local Variable
Description: Private field can be converted to local variable
private int temp = Calculate(); // Field used only locally
int temp = Calculate(); // Converted to local variable
Property not Resolved
Description: Cannot resolve property
Console.WriteLine(nonExistentProperty);
Console.WriteLine(existingProperty);
Public Constructor In Abstract Class
Description: Make constructor in abstract class protected
public abstract class Example {
public Example() { }
}
public abstract class Example {
protected Example() { }
}
Pure Attribute on Void Method
Description: 'void' method is annotated by [Pure] attribute
[Pure] public void DoSomething() { /* code */ }
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
[Range(1, 10, -1)] public void Test(int value) { /* ... */ }
[Range(1, 10, 1)] public void Test(int value) { /* ... */ }
Range Step Value Zero
Description: NUnit. Range 'step' parameter value must be non-zero.
[TestCase(1, 10, 0)] public void TestMethod(int start, int end, int step) { /* ... */ }
[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.
[TestCase(1, 10, 5)] public void Method(int start, int end, int step) { /* ... */ }
[TestCase(1, 10, 2)] public void Method(int start, int end, int step) { /* ... */ }
Razor Layout Not Resolved
Description: Unknown Razor layout
@{ Layout = "UnknownLayout.cshtml"; }
@{ Layout = "_Layout.cshtml"; // Ensure layout file exists }
Razor Section Not Resolved
Description: Unknown Razor section
@RenderSection("unknownSection")
@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
if (_instance == null) { lock(_lock) { if (_instance == null) _instance = new Singleton(); } }
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.
int result = value << 0;
int result = value;
Redundant Abstract Modifier
Description: Redundant 'abstract' modifier
public abstract abstract class Shape { ... } // Double abstract modifier
public abstract class Shape { ... } // Only one abstract modifier
Redundant Anonymous Type
Description: Redundant anonymous type property explicit name
var person = new { Name = name, Age = age };
var person = new { name, age }; // Remove explicit property names if variable names match
Redundant Argument Default Value
Description: Redundant argument with default value
MyMethod(true); // true is default value
MyMethod(); // Omit argument if it's the default value
Redundant Argument in InlineAutoData Attribute
Description: NUnit.AutoFixture. Redundant argument in InlineAutoData attribute
[InlineAutoData(42, "Redundant")] public void Test(int value) { /* ... */ }
[InlineAutoData] public void Test(int value) { /* ... */ }
Redundant Array Creation
Description: Array creation can be replaced with array initializer
int[] numbers = new int[] { 1, 2, 3 };
int[] numbers = { 1, 2, 3 }; // Use array initializer
Redundant Assignment
Description: Assignment is not used
int value = 10; // value is assigned but never used
// Remove unused assignment if value is not used
Redundant Attribute Parentheses
Description: Parentheses are redundant if attribute has no arguments
[Obsolete()] public void OldMethod() { ... } // Redundant parentheses
[Obsolete] public void OldMethod() { ... } // Removed unnecessary parentheses
Redundant Attribute Usage Property
Description: Redundant [AttributeUsage] attribute property assignment
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] // Default value
[AttributeUsage(AttributeTargets.Class)] // Removed redundant property
Redundant Base Qualifier
Description: Redundant 'base.' qualifier
base.SomeMethod();
SomeMethod(); // Remove base qualifier when not required
Redundant Blank Lines
Description: Incorrect blank lines (blank lines are redundant elsewhere).
public class Example
{
void Method() {}
}
public class Example
{
void Method() {}
}
Redundant Bool Compare
Description: Redundant boolean comparison
if (isTrue == true) { /* code */ }
if (isTrue) { /* code */ } // Simplify boolean comparison
Redundant Braces
Description: Use preferred braces style (remove redundant braces)
if (condition) { DoSomething(); }
if (condition) DoSomething();
Redundant Case Label
Description: Redundant 'case' label
case SomeEnum.Value: /* code */; break; default: /* code */;
default: /* code */; // Remove redundant case label if handled in default
Redundant Cast
Description: Redundant cast
int value = (int)myNumber;
int value = myNumber; // Remove redundant cast if unnecessary
Redundant Catch
Description: Redundant catch clause
try { /* code */ } catch (Exception ex) { throw; }
try { /* code */ } // Remove redundant catch clause if rethrowing
Redundant Check
Description: Redundant condition check before assignments
if (x != 5) x = 5; // Unnecessary condition before assignment
x = 5; // Direct assignment without condition check
Redundant Collection Braces
Description: Redundant braces in collection initializer
var list = new List<int> { { 1 }, { 2 }, { 3 } };
var list = new List<int> { 1, 2, 3 }; // Remove unnecessary braces
Redundant Configure Await
Description: Redundant 'ConfigureAwait(true)'
await someTask.ConfigureAwait(true); // 'true' is redundant
await someTask; // Removed unnecessary ConfigureAwait
Redundant Constructor Call
Description: Redundant base constructor call
public Child() : base() { }
// Remove the base constructor call if it's redundant
Redundant Declaration Semicolon
Description: Redundant semicolon after type or namespace declaration
namespace MyNamespace {};
namespace MyNamespace {} // Remove unnecessary semicolon
Redundant Delegate Creation
Description: Explicit delegate creation expression is redundant
var action = new Action(() => DoSomething()); // Redundant delegate creation
Action action = DoSomething; // Simplified without explicit creation
Redundant Discard
Description: Redundant discard designation
var (_, y) = GetTuple(); // Discard is redundant
var y = GetTuple().Item2; // Removed unnecessary discard
Redundant Empty Finally Block
Description: Redundant empty finally block
try { ... } finally { } // Empty finally block
try { ... } // Removed unnecessary finally block
Redundant Empty Object
Description: Redundant empty object or collection initializer
var list = new List<int>() { }; // Empty initializer is redundant
var list = new List<int>(); // Removed unnecessary initializer
Redundant Empty Object Creation Argument List
Description: Redundant empty argument list on object creation expression
var obj = new MyClass(); // Empty argument list is redundant
var obj = new MyClass; // Simplified object creation
Redundant Empty Switch
Description: Redundant empty switch section
switch (value) { case 1: break; } // Empty switch section
switch (value) { case 1: DoSomething(); break; }
Redundant Enum Case Label
Description: Redundant 'case' label before default section
case MyEnum.Option1: /* code */; break; default: /* code */;
default: /* code */; // Remove case if redundant with default
Redundant Enumerable Cast Call
Description: Redundant 'IEnumerable.Cast' or 'IEnumerable.OfType' call
var numbers = collection.Cast<int>();
var numbers = collection; // Remove redundant Cast or OfType if not needed
Redundant Explicit Array Creation
Description: Redundant explicit type in array creation
int[] numbers = new int[] { 1, 2, 3 };
var numbers = new[] { 1, 2, 3 }; // Use implicit typing if possible
Redundant Explicit Array Size
Description: Redundant explicit size specification in array creation
int[] numbers = new int[3] { 1, 2, 3 };
int[] numbers = new int[] { 1, 2, 3 }; // Remove explicit size specification
Redundant Explicit Positional
Description: Redundant explicit positional property declaration
record Person(string Name, string Name) { }
record Person(string Name) { } // Remove redundant explicit positional declaration
Redundant Explicit Tuple Name
Description: Redundant explicit tuple component name
var tuple = (Name: "John", Age: 30);
var tuple = ("John", 30); // Remove explicit component names if unnecessary
Redundant False Statement
Description: Remove redundant statement
if (isActive || false) { /* Redundant false OR condition */ }
if (isActive) { /* Clean condition without redundant OR */ }
Redundant Fixed Pointer Declaration
Description: Redundant fixed pointer declaration
fixed (int* ptr = &array[0]) { /* code */ }
/* code */ // Remove fixed pointer declaration if unnecessary
Redundant Global Using Directive
Description: Redundant global using directive
global using System;
// Remove redundant global using directive if unused in the project
Redundant If Else Block
Description: Redundant 'else' keyword
if (condition) { ... } else { return; } // Redundant else
if (condition) { ... } return; // Removed unnecessary else
Redundant Immediate Delegate Invocation
Description: Immediate delegate invocation
((Action)delegate { Console.WriteLine("Hello"); })(); // Immediate delegate invocation
Console.WriteLine("Hello"); // Directly execute the code
Redundant Is
Description: Redundant 'is' before relational pattern
if (x is >= 10) { /* Condition with redundant 'is' */ }
if (x >= 10) { /* Clean condition without redundant 'is' */ }
Redundant Jump
Description: Redundant control flow jump statement
return; // Return statement without purpose
Console.WriteLine("Complete"); // Removed unnecessary return
Redundant Lambda Parameter Type
Description: Redundant lambda expression parameter type specification
Func<int, int> square = (int x) => x * x;
Func<int, int> square = x => x * x; // Remove redundant type specification
Redundant Lambda Parentheses
Description: Redundant lambda signature parentheses
Func<int, int> square = (x) => x * x;
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).
public void Method() {
int x = 5;
}
public void Method() {
int x = 5;
}
Redundant List Entry
Description: Redundant class or interface specification in base types list
class Derived : Base, Base { }
// Remove duplicate or redundant base type declarations
Redundant Match Subpattern
Description: Redundant always match subpattern
if (x is int _) { ... } // Redundant subpattern match
if (x is int) { ... } // Removed unnecessary subpattern
Redundant Math Abs Method
Description: Math.Abs() argument is always non-negative
int x = Math.Abs(positiveValue); // Argument is already non-negative
int x = positiveValue; // Removed redundant Math.Abs() call
Redundant Member Initializer
Description: Redundant default member initializer
private int value = 0; // '0' is default for int
private int value; // Default initialization
Redundant Name Qualifier
Description: Redundant name qualifier
System.Console.WriteLine("Hello"); // Redundant System qualifier
Console.WriteLine("Hello"); // Removed redundant qualifier
Redundant Not Null Constraint
Description: Redundant 'notnull' constraint on type parameter constrained by non-nullable base type.
where T : SomeClass, notnull // Redundant 'notnull' constraint
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.
where T : struct? // Redundant nullable annotation
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.
where T : SomeClass? // Nullable annotation is redundant
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.
where T : class? // Nullable annotation is redundant
where T : class // Removed unnecessary nullable annotation
Redundant Nullable Creation
Description: Redundant explicit nullable type creation
Nullable<int> x = new Nullable<int>(5); // Explicit nullable creation is redundant
int? x = 5; // Simplified nullable assignment
Redundant Nullable Flow Attribute
Description: Redundant nullable attribute.
[AllowNull] public string? Name { get; set; } // Redundant nullable attribute
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
if (obj is int?) { ... } // Redundant nullable check
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.
[NotNull] public string Name { get; set; }
public string Name { get; set; } // Remove redundant [NotNull] if nullable annotations are used
Redundant Operand
Description: Redundant operand in logical conditional expression
if (isTrue && true) { ... } // Redundant '&& true'
if (isTrue) { ... } // Removed redundant operand
Redundant Output Non-Private Accessibility
Description: Parameter output value is always discarded (non-private accessibility)
public void ProcessData(out int result) { result = 5; } // result is never used
// 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)
private void Calculate(out int total) { total = 0; } // total is ignored
// Remove the out parameter or use it if necessary
Redundant Overflow Checking
Description: Redundant arithmetic overflow checking context
checked { int result = a + b; } // when overflow checking is enabled globally
int result = a + b; // Remove checked if unnecessary
Redundant Overload Non-Private Accessibility
Description: Redundant method overload (non-private accessibility)
public void Process(int x) {} public void Process(int x, int y = 0) {}
// Use a single method with optional parameters if overloads are redundant
Redundant Overload Private Accessibility
Description: Redundant method overload (private accessibility)
private void Calculate(int x) {} private void Calculate(int x, int y = 0) {}
// Simplify to one method with optional parameters
Redundant Overridden Member
Description: Redundant member override
public override void Method() { base.Method(); }
// Remove the redundant override if it only calls base implementation
Redundant Params
Description: 'params' modifier is always ignored on overrides
public override void Method(params int[] values) { }
// Remove the 'params' modifier from the override
Redundant Params Array Creation
Description: Redundant explicit array creation in argument of 'params' parameter
Method(new int[] { 1, 2, 3 }); // Explicit array creation is redundant
Method(1, 2, 3); // Simplified without explicit array creation
Redundant Parentheses
Description: Remove redundant parentheses
int result = (a + b);
int result = a + b;
Redundant Pattern Parentheses
Description: Remove redundant pattern-matching parentheses
if ((obj is int value)) { ... } // Redundant parentheses
if (obj is int value) { ... } // Removed unnecessary parentheses
Redundant Property Pattern Clause
Description: Redundant property pattern clause
case { Name: "" }: // Redundant pattern clause
case { }: // Removed unnecessary clause
Redundant Query Order
Description: Redundant 'orderby' clause 'ascending' keyword
var sorted = items.OrderBy(x => x, ascending); // 'ascending' is redundant
var sorted = items.OrderBy(x => x); // Simplified without 'ascending'
Redundant Range Bound
Description: Redundant range bound
var range = 0..^0; // Redundant range bound
var range = 0..; // Removed unnecessary bound
Redundant Readonly Modifier
Description: Redundant 'readonly' modifier
readonly int x; // Redundant 'readonly' modifier
int x; // Removed unnecessary 'readonly' modifier
Redundant Record Body
Description: Redundant 'record' type declaration body
record Person { }
record Person; // Use record declaration without body if no additional members are defined
Redundant Record Class Keyword
Description: Redundant 'class' keyword in record declaration
public record class Person(string Name); // 'class' keyword is redundant
public record Person(string Name); // Simplified without 'class' keyword
Redundant Space
Description: Incorrect spacing (space is redundant elsewhere).
int x = 5;
int x = 5;
Redundant String Format
Description: Redundant 'string.Format()' call
var message = string.Format("Hello {0}", "world");
var message = "Hello world"; // Use a simple string instead of string.Format when no formatting is required
Redundant String Interpolation
Description: Redundant string interpolation
var message = $"Hello";
var message = "Hello"; // Use a plain string if no interpolation is needed
Redundant String Prefix
Description: Redundant verbatim string prefix
var path = @"C:\folder"; // Verbatim prefix '@' is redundant
var path = "C:\folder"; // Removed redundant '@'
Redundant String To Char
Description: Redundant 'string.ToCharArray()' call
var chars = "hello".ToCharArray();
var chars = "hello"; // Remove redundant ToCharArray() if the string can be used directly
Redundant Suppress Warning
Description: Redundant suppress nullable warnings expression.
string? name = null!;
string? name = null; // Remove unnecessary suppression
Redundant Ternary Expression
Description: Redundant conditional ternary expression usage
int result = isTrue ? 1 : 1; // Same value for both cases
int result = 1; // Removed redundant ternary expression
Redundant To String Call
Description: Redundant 'object.ToString()' call
var text = myString.ToString(); // 'ToString()' call is redundant
var text = myString; // Simplified by removing 'ToString()'
Redundant To String Call Value Types
Description: Redundant 'object.ToString()' call for value types
int number = 42; var text = number.ToString(); // Redundant 'ToString()'
int number = 42; var text = "" + number; // Alternative without 'ToString()'
Redundant True Statement
Description: Remove redundant statement
if (isComplete || true) { /* Redundant true OR condition */ }
if (true) { /* Clean condition with only true */ }
Redundant Type Arguments
Description: Redundant type arguments of method
var result = DoSomething<int>();
var result = DoSomething(); // Remove redundant type argument if it can be inferred
Redundant Type Check
Description: Redundant type check in a pattern
if (x is int i) { }
if (x is int) { } // Simplify type pattern if variable is not used
Redundant Unsafe Context
Description: Unsafe context declaration is redundant
unsafe { int* p = &value; } // Redundant unsafe context
int* p = &value; // Removed unnecessary 'unsafe' block
Redundant Using Directive
Description: Redundant using directive
using System.Text; // Unused directive
// Remove unused using directives
Redundant Verbatim Prefix
Description: Redundant verbatim prefix
var path = @"C:\Users\Name";
var path = "C:\Users\Name"; // Remove verbatim prefix if it is unnecessary
Redundant with Expression
Description: Empty 'with' expression is redundant
var personClone = person with { }; // Redundant
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
Object.ReferenceEquals(5, 5); // Always false for value types
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
int temp = myVolatileField;
int temp = Volatile.Read(ref myVolatileField);
Remove ToList
Description: Remove ToList()
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList(); // Unnecessary ToList()
var evenNumbers = numbers.Where(n => n % 2 == 0); // Removed ToList() to defer execution
Remove ToList
Description: Remove ToList()
var squares = numbers.Select(n => n * n).ToList(); // Unnecessary ToList() call
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
base.SomeMethod();
CallBaseMethod(); // Helper method to avoid using 'base' in lambda
Replace with FirstOrDefault
Description: Replace with FirstOrDefault($args$)
var result = items.Where(x => x.IsActive).First();
var result = items.FirstOrDefault(x => x.IsActive);
Replace with FirstOrDefault
Description: Replace with FirstOrDefault($args$)
var result = items.Where(x => x.Age > 18).First();
var result = items.FirstOrDefault(x => x.Age > 18);
Replace with FirstOrDefault
Description: Replace with FirstOrDefault($args$)
var user = users.Where(u => u.Name == "John").First();
var user = users.FirstOrDefault(u => u.Name == "John");
Replace with FirstOrDefault
Description: Replace with FirstOrDefault($args$)
var item = data.Where(d => d.Status == "Active").First();
var item = data.FirstOrDefault(d => d.Status == "Active");
Replace with LastOrDefault
Description: Replace with LastOrDefault($args$)
var result = items.Where(x => x.IsActive).Last();
var result = items.LastOrDefault(x => x.IsActive);
Replace with LastOrDefault
Description: Replace with LastOrDefault($args$)
var lastMatch = items.Where(x => x.Category == "A").Last();
var lastMatch = items.LastOrDefault(x => x.Category == "A");
Replace with LastOrDefault
Description: Replace with LastOrDefault($args$)
var item = collection.Where(c => c.Price > 100).Last();
var item = collection.LastOrDefault(c => c.Price > 100);
Replace with LastOrDefault
Description: Replace with LastOrDefault($args$)
var element = elements.Where(e => e.IsEnabled).Last();
var element = elements.LastOrDefault(e => e.IsEnabled);
Replace with ofType
Description: Replace with OfType()
var stringItems = items.Where(item => item is string).Cast<string>();
var stringItems = items.OfType<string>();
Replace with ofType
Description: Replace with OfType()
var intItems = items.Where(item => item is int).Cast<int>();
var intItems = items.OfType<int>();
Replace with ofType
Description: Replace with OfType().Where() (replace with OfType().Where(..))
var matches = items.Where(x => x is MyType && x.IsAvailable).Cast<MyType>();
var matches = items.OfType<MyType>().Where(x => x.IsAvailable);
Replace with OfType
Description: Replace with OfType()
var strings = items.Where(x => x is string).Cast<string>();
var strings = items.OfType<string>();
Replace with ofType Any
Description: Replace with OfType().Any()
var hasStrings = items.Where(item => item is string).Any();
var hasStrings = items.OfType<string>().Any();
Replace with ofType Any
Description: Replace with OfType().Any()
var hasInts = items.Where(item => item is int).Any();
var hasInts = items.OfType<int>().Any();
Replace with ofType Count
Description: Replace with OfType().Count()
var stringCount = items.Where(item => item is string).Count();
var stringCount = items.OfType<string>().Count();
Replace with ofType Count
Description: Replace with OfType().Count()
var intCount = items.Where(item => item is int).Count();
var intCount = items.OfType<int>().Count();
Replace with ofType First
Description: Replace with OfType().First()
var firstString = items.Where(item => item is string).Cast<string>().First();
var firstString = items.OfType<string>().First();
Replace with ofType First
Description: Replace with OfType().First()
var firstInt = items.Where(item => item is int).Cast<int>().First();
var firstInt = items.OfType<int>().First();
Replace with ofType FirstOrDefault
Description: Replace with OfType().FirstOrDefault()
var firstString = items.Where(item => item is string).Cast<string>().FirstOrDefault();
var firstString = items.OfType<string>().FirstOrDefault();
Replace with ofType FirstOrDefault
Description: Replace with OfType().FirstOrDefault()
var firstInt = items.Where(item => item is int).Cast<int>().FirstOrDefault();
var firstInt = items.OfType<int>().FirstOrDefault();
Replace with ofType Last
Description: Replace with OfType().Last()
var lastItem = items.Where(x => x is MyType).Cast<MyType>().Last();
var lastItem = items.OfType<MyType>().Last();
Replace with ofType Last
Description: Replace with OfType().Last() (replace with OfType().Last(..))
var lastMatch = list.Where(x => x is MyType && x.IsActive).Cast<MyType>().Last();
var lastMatch = list.OfType<MyType>().Last(x => x.IsActive);
Replace with ofType LastOrDefault
Description: Replace with OfType().LastOrDefault()
var lastOrDefault = collection.Where(x => x is MyType).Cast<MyType>().LastOrDefault();
var lastOrDefault = collection.OfType<MyType>().LastOrDefault();
Replace with ofType LastOrDefault
Description: Replace with OfType().LastOrDefault() (replace with OfType().LastOrDefault(..))
var lastItem = items.Where(x => x is MyType && x.IsAvailable).Cast<MyType>().LastOrDefault();
var lastItem = items.OfType<MyType>().LastOrDefault(x => x.IsAvailable);
Replace with ofType Long Count
Description: Replace with OfType().LongCount()
var count = items.Where(x => x is MyType).Cast<MyType>().LongCount();
var count = items.OfType<MyType>().LongCount();
Replace with ofType Single
Description: Replace with OfType().Single()
var singleItem = collection.Where(x => x is MyType).Cast<MyType>().Single();
var singleItem = collection.OfType<MyType>().Single();
Replace with ofType Single
Description: Replace with OfType().Single() (replace with OfType().Single(..))
var singleItem = items.Where(x => x is MyType && x.IsUnique).Cast<MyType>().Single();
var singleItem = items.OfType<MyType>().Single(x => x.IsUnique);
Replace with ofType SingleOrDefault
Description: Replace with OfType().SingleOrDefault()
var singleOrDefault = collection.Where(x => x is MyType).Cast<MyType>().SingleOrDefault();
var singleOrDefault = collection.OfType<MyType>().SingleOrDefault();
Replace with ofType SingleOrDefault
Description: Replace with OfType().SingleOrDefault() (replace with OfType().SingleOrDefault(..))
var item = items.Where(x => x is MyType && x.IsActive).Cast<MyType>().SingleOrDefault();
var item = items.OfType<MyType>().SingleOrDefault(x => x.IsActive);
Replace with Simple False Assignment
Description: Replace with simple assignment
bool isAvailable = isAvailable == false ? false : isAvailable;
bool isAvailable = false;
Replace with Simple True Assignment
Description: Replace with simple assignment
if (condition) { flag = true; } else { flag = false; }
flag = condition;
Replace with Single Call to Any
Description: Replace with single call to Any(..)
var hasItems = collection.Count() > 0;
var hasItems = collection.Any();
Replace with Single Call to Count
Description: Replace with single call to Count(..)
var count = collection.Where(item => item.IsActive).Count();
var count = collection.Count(item => item.IsActive);
Replace with Single Call to First
Description: Replace with single call to First(..)
var firstActive = collection.Where(item => item.IsActive).First();
var firstActive = collection.First(item => item.IsActive);
Replace with Single Call to FirstOrDefault
Description: Replace with single call to FirstOrDefault(..)
var firstInactive = collection.Where(item => !item.IsActive).FirstOrDefault();
var firstInactive = collection.FirstOrDefault(item => !item.IsActive);
Replace with Single Call to Last
Description: Replace with single call to Last(..)
var lastItem = collection.Where(item => item.IsActive).Last();
var lastItem = collection.Last(item => item.IsActive);
Replace with Single Call to LastOrDefault
Description: Replace with single call to LastOrDefault(..)
var lastInactive = collection.Where(item => !item.IsActive).LastOrDefault();
var lastInactive = collection.LastOrDefault(item => !item.IsActive);
Replace with Single Call to Single
Description: Replace with single call to Single(..)
var singleItem = items.Where(x => x.IsMatch).Single();
var singleItem = items.Single(x => x.IsMatch);
Replace with Single Call to Single or Default
Description: Replace with single call to SingleOrDefault(..)
var singleOrDefaultItem = items.Where(x => x.IsMatch).SingleOrDefault();
var singleOrDefaultItem = items.SingleOrDefault(x => x.IsMatch);
Replace with Single False Assignment
Description: Replace with single assignment
isAvailable = isAvailable == false;
isAvailable = false;
Replace with Single or Default
Description: Replace with SingleOrDefault($args$)
var result = items.Where(x => x == condition).SingleOrDefault();
var result = items.SingleOrDefault(x => x == condition);
Replace with Single or Default
Description: Replace with SingleOrDefault($args$)
var result = items.Where(x => x == condition).SingleOrDefault();
var result = items.SingleOrDefault(x => x == condition);
Replace with Single or Default
Description: Replace with SingleOrDefault($args$)
var result = items.Where(x => x == condition).SingleOrDefault();
var result = items.SingleOrDefault(x => x == condition);
Replace with Single or Default
Description: Replace with SingleOrDefault($args$)
var result = items.Where(x => x == condition).SingleOrDefault();
var result = items.SingleOrDefault(x => x == condition);
Replace with Single True Assignment
Description: Replace with single assignment
isEnabled = isEnabled == true;
isEnabled = true;
Required Base Types Conflict
Description: Required base type conflicting another type.
class Example : BaseType, AnotherBaseType { }
class Example : BaseType { }
Required Base Types Direct Conflict
Description: Type specified in '[BaseTypeRequired]' attribute conflicts another type.
[BaseTypeRequired(typeof(BaseType))]
class Example : AnotherBaseType { }
[BaseTypeRequired(typeof(BaseType))]
class Example : BaseType { }
Required Base Types not Inherited
Description: Base type is required
public class DerivedClass {}
public class DerivedClass : RequiredBaseClass {}
Resource Item not Resolved
Description: Cannot resolve resource item
var item = Resources.MyResource.NonExistentItem;
var item = Resources.MyResource.ExistingItem;
Resource not Resolved
Description: Cannot resolve resource
var text = Resources.NonExistentResource;
var text = Resources.ExistingResource;
Return Type not Nullable
Description: Return type of a function can be non-nullable
public string? GetString() { return "Hello"; } // Return type could be non-nullable
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.
public string? ImplementedMethod() => "Text"; // Expected non-nullable return
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.
public string? ImplicitMethod() => "Text"; // Expected non-nullable return
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.
public override string? OverriddenMethod() => "Text"; // Expected non-nullable return
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.
public partial string? PartialMethod(); // Expected non-nullable return
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).
Func<string?> func = () => "Text"; // Expected non-nullable return
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).
public string? GetDetails() => "Details"; // Expected non-nullable
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).
public string? GetData() => "Data"; // Expected non-nullable
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).
public override string? GetDetails() => "Details"; // Expected non-nullable
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
CalculateSum(5, 10); // Result ignored
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
var str = obj as string; if (str != null) { } // Safe cast used for type check
if (obj is string str) { } // Direct type check
Sealed Member
Description: Sealed member in sealed class
public sealed class MyClass { public sealed void Method() {} }
// 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
[ServiceContract] public interface IMyService { }
[ServiceContract] public interface IMyService { [OperationContract] void MyOperation(); }
Shift Expression Result Equals Zero
Description: Constant shift expression with non-zero operands results in zero value.
int result = 4 >> 5;
int result = 4 << 1;
Shift Expression Zero Left Operand
Description: Shift expression with zero left operand equals zero.
int result = 0 << 2;
int value = 4; int result = value << 2;
Similar Anonymous Type Nearby
Description: Similar anonymous type detected nearby
var person1 = new { Name = "John", Age = 30 }; var person2 = new { Name = "John", Age = 30 };
var person = new { Name = "John", Age = 30 };
Simplify String Interpolation
Description: Use format specifier in interpolated strings
string result = $"Value: {value}";
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.
string? nullableString = nonNullableString; // Non-nullable expected
string nonNullableString = nullableString ?? "default"; // Ensures non-nullable value
Spin Lock Read Only Field
Description: Do not store SpinLock in readonly field
private readonly SpinLock _spinLock = new SpinLock();
private SpinLock _spinLock = new SpinLock(); // Not readonly to avoid issues
Stack Alloc Inside Loop
Description: Using stackalloc inside loop
for (int i = 0; i < 10; i++) { int* buffer = stackalloc int[10]; } // stackalloc in loop
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
class Container { public static int Count; }
class Container { public int InstanceCount; }
Static Member Initializer
Description: Static member initializer refers to static member below or in other part
class Example { static int A = B; static int B = 5; }
class Example { static int B = 5; static int A = B; }
Static Member Qualifier
Description: Add/remove qualifier for static members
Console.WriteLine("Hello");
System.Console.WriteLine("Hello");
Static Problem in Text
Description: Cannot access static symbol in text argument
var text = "Static value: " + MyClass.StaticValue;
var text = string.Format("Static value: {0}", MyClass.StaticValue);
Static Test Case Source
Description: NUnit. Test case source must be static.
[TestCaseSource(nameof(InstanceSource))] public void Method() { /* ... */ }
[TestCaseSource(nameof(StaticSource))] public void Method() { /* ... */ }
Static Type in 'is' or 'as' Operator
Description: Static type in 'is' or 'as' operator.
if (obj is typeof(MyClass)) { /* do something */ }
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)
int result = String.Compare(str1, 0, str2, 0, str2.Length);
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)
int result = String.Compare(str1, 0, str2, 0, str2.Length, ignoreCase);
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)
int result = String.Compare(str1, 0, str2, 0, str2.Length, ignoreCase);
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)
int result = String.Compare(str1, str2);
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)
int result = String.Compare(str1, str2, ignoreCase);
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)
int result = String.Compare(str1, str2, ignoreCase);
int result = String.Compare(str1, str2, ignoreCase, StringComparison.Ordinal);
String CompareTo Culture Specific
Description: String.CompareTo is culture-specific
int result = str1.CompareTo(str2);
int result = String.Compare(str1, str2, StringComparison.Ordinal);
String Comparison
Description: Specify string comparison explicitly
if (name.Equals("John")) { ... }
if (name.Equals("John", StringComparison.Ordinal)) { ... }
String Comparison
Description: Specify string comparison explicitly
if (name.Equals("John")) { ... }
if (name.Equals("John", StringComparison.Ordinal)) { ... }
String Conversion Culture
Description: Specify string culture explicitly
var lowerCaseName = name.ToLower();
var lowerCaseName = name.ToLower(CultureInfo.InvariantCulture);
String Conversion Culture
Description: Specify string culture explicitly
var lowerCaseName = name.ToLower();
var lowerCaseName = name.ToLower(CultureInfo.InvariantCulture);
String EndsWith Culture Specific
Description: String.EndsWith is culture-specific (string.EndsWith(string) is culture-specific)
bool result = str1.EndsWith(suffix);
bool result = str1.EndsWith(suffix, StringComparison.Ordinal);
String IndexOf Culture Specific
Description: String.IndexOf is culture-specific (string.IndexOf(string) is culture-specific)
int index = str1.IndexOf(substring);
int index = str1.IndexOf(substring, StringComparison.Ordinal);
String IndexOf Culture Specific
Description: String.IndexOf is culture-specific (string.IndexOf(string, int) is culture-specific)
int index = myString.IndexOf("text");
int index = myString.IndexOf("text", StringComparison.Ordinal);
String IndexOf Culture Specific
Description: String.IndexOf is culture-specific (string.IndexOf(string, int) is culture-specific)
int index = myString.IndexOf("text", 5);
int index = myString.IndexOf("text", 5, StringComparison.Ordinal);
String LastIndexOf Culture Specific
Description: String.LastIndexOf is culture-specific (string.LastIndexOf(string) is culture-specific)
int index = myString.LastIndexOf("text");
int index = myString.LastIndexOf("text", StringComparison.Ordinal);
String LastIndexOf Culture Specific
Description: String.LastIndexOf is culture-specific (string.LastIndexOf(string, int) is culture-specific)
int index = myString.LastIndexOf("text", 5);
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)
int index = myString.LastIndexOf("text", 5, 3);
int index = myString.LastIndexOf("text", 5, 3, StringComparison.Ordinal);
String Literal as Interpolation Argument
Description: String literal can be inlined
var message = $"Hello {"John"}";
var message = "Hello John";
String Literal as Interpolation Argument
Description: String literal can be inlined
var message = $"Hello {"John"}";
var message = "Hello John";
String Literal Typo
Description: Typo in string literal
Console.WriteLine("Ths is a typo.");
Console.WriteLine("This is correct.");
String StartsWith Culture Specific
Description: String.StartsWith is culture-specific (string.StartsWith(string) is culture-specific)
if (myString.StartsWith("prefix")) { /* ... */ }
if (myString.StartsWith("prefix", StringComparison.Ordinal)) { /* ... */ }
Struct Member Read Only
Description: Struct member can be made readonly
public struct Rectangle { public int Width; public int Height; }
public struct Rectangle { public readonly int Width; public readonly int Height; }
Struct Read Only
Description: Struct can be made readonly
public struct Point { public int X; public int Y; }
public readonly struct Point { public int X; public int Y; }
Structured Message Template
Description: Structured message template problems
logger.LogInformation("User {0} logged in", userId); // Positional parameter may cause issues
logger.LogInformation("User {userId} logged in", userId); // Structured template with named argument
Style String Literal
Description: Use preferred argument style for string literal values
Console.WriteLine( "Hello" );
Console.WriteLine("Hello");
Suspicious Lock Over
Description: Suspicious locking over synchronization primitive
lock(Semaphore) { // Using synchronization primitive directly for locking
lock(syncObject) { // Uses dedicated sync object instead of primitive
Suspicious Math Sign Method
Description: Math.Sign() method always gives the same result
int sign = Math.Sign(positiveValue); // Always returns 1
int sign = 1; // Replaced with a constant
Suspicious Parameter Name
Description: Suspicious parameter name in ArgumentNullException
throw new ArgumentNullException("wrongParamName"); // Mismatched parameter name
throw new ArgumentNullException(nameof(correctParamName)); // Uses correct parameter name
Suspicious Shift Count
Description: Suspicious shift count for this type of left operand.
int shiftedValue = 1 << 35; // Shift count exceeds int size
int shiftedValue = 1 << 5; // Valid shift within integer size
Suspicious Type Conversion
Description: Suspicious type conversion or check
var number = (int)(object)"text"; // Suspicious and unsafe cast
if (obj is int number) { ... } // Safe type check before conversion
Swap via Deconstruction
Description: Use deconstruction to swap variables.
int temp = x; x = y; y = temp;
(x, y) = (y, x);
Switch Case Pattern
Description: Type pattern and casts can be merged
switch (obj) { case MyClass _: MyClass myObj = (MyClass)obj; break; }
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
Color color = GetColor(); switch (color) { case Color.Red: /* logic */ default: throw new ArgumentOutOfRangeException(); }
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).
var result = input switch { "A" => 1 };
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.
var result = input switch { "A" => 1 };
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
switch (status) { case Status.Active: /* logic */ default: /* handle all else */ }
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
switch (status) { case Status.Active: /* logic */ }
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
using MissingAssembly; // Assembly might not be present at runtime
// Ensure assembly is copied locally or loaded dynamically
Syntax Error in XML Comment
Description: Syntax error in XML comment
/// <summary Process data </summary> public void ProcessData() {}
/// <summary>Process data</summary> public void ProcessData() {}
Tabs and Spaces Mismatch
Description: Incorrect indent (tabs/spaces mismatch)
if (condition)
{
doSomething();
}
if (condition)
{
doSomething();
}
Tabs Outside Indent
Description: Incorrect spacing (tabs are prohibited here).
int x = 5;
int x = 5;
Tail Recursive Call
Description: Tail recursive call can be replaced with loop
int Factorial(int n) => n == 0 ? 1 : n * Factorial(n - 1); // Recursive call
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
ref var refField = ref myMarshalByReference.field;
var fieldValue = myMarshalByReference.field;
Test Case Attribute Requires Expected Result
Description: NUnit. Missing expected result for non-void test method.
[TestCase(1)] public int AddOne(int value) { return value + 1; }
[TestCase(1, ExpectedResult = 2)] public int AddOne(int value) { return value + 1; }
Test Case Expected Result
Description: NUnit. Test case Result property duplicates ExpectedResult.
[TestCase(ExpectedResult = 1, Result = 1)] public int Method() { return 1; }
[TestCase(ExpectedResult = 1)] public int Method() { return 1; }
Test Case Result Obsolete
Description: NUnit. Test case Result property is obsolete.
[TestCase(Result = 1)] public int Method() { return 1; }
[TestCase(ExpectedResult = 1)] public int Method() { return 1; }
Test Case Source Cannot Be Resolved
Description: NUnit. Cannot resolve symbol in TestCaseSource or ValueSource attribute
[TestCaseSource("NonExistentSource")] public void Test() { /* ... */ }
[TestCaseSource(nameof(ExistingSource))] public void Test() { /* ... */ }
This Qualifier
Description: Add/remove 'this.' qualifier
name = "John";
this.name = "John";
Thread Static at Instance Field
Description: [ThreadStatic] doesn't work with instance fields
[ThreadStatic] private int instanceField;
private static int instanceField;
Thread Static Field Initializer
Description: Thread static field has initializer
[ThreadStatic] public static int counter = 0; // Thread-static with initializer
[ThreadStatic] public static int counter; // Initialize in method as needed
Too Wide Local Variable Scope
Description: Local variable has too wide declaration scope
int result = 0;
for (int i = 0; i < 10; i++) {
result += i;
}
return result;
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
var list = new[]
{
"apple",
"badana"
};
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
var items = new[] { "apple", "badana", };
var items = new[] { "apple", "badana" };
Try Cast Always Succeeds
Description: Safe cast expression always succeeds
var item = obj as MyClass; if (item != null) { /* always true */ }
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
try { /* ... */ } catch (Exception) { /* ... */ } finally { /* ... */ }
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.
(string name, int age) person = ("Alice", 30);
(string Name, int Age) person = ("Alice", 30);
Type Argument Nullability Mismatch with 'class' Constraint
Description: Nullability of type argument doesn't match 'class' constraint.
List<string?> nullableList; // 'class' constraint expects non-nullable type
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.
class Example where T : struct? {} // 'notnull' constraint expects non-nullable
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.
class Example where T : MyClass? {} // Constraint expects non-nullable MyClass
class Example where T : MyClass {} // Matches constraint with non-nullable type
Type Member Modifiers
Description: Use explicit or implicit modifier definition for type members
static int myVar;
public static int myVar;
Type Modifiers
Description: Use explicit or implicit modifier definition for types
class MyClass {}
public class MyClass {}
Type Nullability Mismatch with Implemented Member
Description: Nullability of reference types in type doesn't match implemented member.
public string? Name { get; set; } // Expected non-nullable
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.
public string? GetName() => "Text"; // Expected non-nullable return
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.
public override string? GetDetails() => "Details"; // Expected non-nullable return
public override string GetDetails() => "Details"; // Matches non-nullable return
Type Parameter Variant
Description: Type parameter could be declared as covariant or contravariant
public interface IRepository { /* ... */ }
public interface IRepository<out T> { /* ... */ }
Type Reference Style
Description: Replace built-in type reference with a CLR type name or a keyword
Int32 number = 42;
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
Int32.Parse("123");
int.Parse("123");
Unassigned Field. Compiler
Description: Unassigned field.
public class Example { public int value; }
public class Example { public int value = 0; }
Unassigned Get Only Auto Property
Description: Get-only auto-property is never assigned
public int Id { get; } // Property is never assigned
public int Id { get; } = 1; // Property is initialized with a value
Unassigned Global Field
Description: Unassigned field (non-private accessibility)
public int count;
public int count = 0; // Initialize to a default value
Unassigned Local Field
Description: Unassigned field (private accessibility)
private int count;
private int count = 0; // Initialize to a default value
Unassigned Readonly Field
Description: Unassigned readonly field
readonly int count;
readonly int count = 0; // Assign during declaration
Unassigned Readonly Field. Compiler
Description: Unassigned readonly field.
readonly int value;
readonly int value = 42;
Unnecessary Whitespace
Description: Unnecessary whitespace at the end of line
int value = 42;
int value = 42;
Unreachable Catch Condition
Description: A previous catch clause already catches all exceptions
try { ... } catch (Exception) { ... } catch (InvalidOperationException) { ... }
try { ... } catch (InvalidOperationException) { ... } catch (Exception) { ... }
Unreachable Code
Description: Code is unreachable
return; Console.WriteLine("This is unreachable.");
Console.WriteLine("This is reachable."); return;
Unreachable Code
Description: Heuristically unreachable code
return; Console.WriteLine("Unreachable"); // Code after return is unreachable
Console.WriteLine("Reached"); return; // Removed unreachable code
Unreachable Switch Arm
Description: Heuristically unreachable switch arm due to integer analysis.
switch (num) { case 0: break; case 1000: break; } // num is never 1000
switch (num) { case 0: break; default: Console.WriteLine("Other case"); break; }
Unreachable Switch Case
Description: Heuristically unreachable case due to integer analysis.
switch (num) { case 5: break; case 15: break; } // num cannot be 15
switch (num) { case 5: break; default: Console.WriteLine("Other case"); break; }
Unsupported Required Base Type
Description: BaseTypeRequired attribute supports only classes and interfaces
[BaseTypeRequired] struct MyStruct {}
[BaseTypeRequired] class MyClass {}
Unused Anonymous Method
Description: Anonymous method signature is not necessary
Func<int, int> square = delegate(int x) { return x * x; };
Func<int, int> square = x => x * x; // Simplify by removing unnecessary signature
Unused Field
Description: Field is never used
private int unusedField;
private int usedField; // Use this field somewhere in code
Unused Global Property
Description: Auto-property accessor is never used (non-private accessibility)
public int Value { get; set; } // 'set' is never used
public int Value { get; private set; } // Adjusted access level
Unused Label
Description: Unused label
label: Console.WriteLine("Hello");
// Remove unused 'label' if it's not referenced in code
Unused Local Function
Description: Local function is never used
void UnusedFunction() { } // Local function is never called
// Removed unused local function
Unused Local Function Return Value
Description: Local function return value is never used
int UnusedFunction() { return 42; }
// Use the return value or remove the function
Unused Local Property
Description: Auto-property accessor is never used (private accessibility)
private int Value { get; set; } // 'set' is never used
private readonly int _value; public int Value => _value; // Converted to readonly field
Unused Local Variable
Description: Unused local variable
int unusedValue = 10;
// Remove 'unusedValue' if not used in the code
Unused Member in Super Non-Private Accessibility
Description: Type is never used (non-private accessibility)
public class UnusedClass {}
// Remove or use the type in code if necessary
Unused Member in Super Private Accessibility
Description: Type is never used (private accessibility)
private class UnusedHelperClass {}
// 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)
public int unusedField;
// Remove or utilize the field in code if necessary
Unused Member Private Accessibility
Description: Type member is never used (private accessibility)
private string unusedString;
// 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)
public int Calculate() { return 42; }
// 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)
private int Helper() { return 10; }
// Use the return value or modify the method to void if unused
Unused Parameter In Partial Method
Description: Unused parameter in partial method
partial void OnEvent(int unusedParam);
// Remove 'unusedParam' if unnecessary in 'OnEvent'
Unused Parameter Non-Private Accessibility
Description: Unused parameter (non-private accessibility)
public void DoSomething(int unusedParam) { }
// Remove 'unusedParam' if not used in method body
Unused Parameter Private Accessibility
Description: Unused parameter (private accessibility)
private void Helper(int unusedParam) { }
// Remove 'unusedParam' if not needed in 'Helper'
Unused Positional Parameter
Description: Unused positional parameter
Func<int, string> func = (unusedParam) => "Hello";
// Remove 'unusedParam' if not used in lambda body
Unused Tuple Component in Return Value
Description: Component of the tuple is never used
return (value, unused); // 'unused' component is never accessed
return (value); // Removed unused tuple component
Unused Type Parameter
Description: Unused type parameter
public class Example { }
// Remove 'T' if the class does not use it
Unused Variable. Compiler
Description: Unused local variable.
int unusedVariable = 5;
// Variable is used somewhere meaningful in code.
Use Array Creation Expression
Description: Use array creation expression
int[] numbers = new int[] {1, 2, 3};
int[] numbers = {1, 2, 3};
Use Array Creation Expression
Description: Use array creation expression
string[] names = new string[] {"Alice", "Bob"};
string[] names = {"Alice", "Bob"};
Use Array Empty Method
Description: Use 'Array.Empty()'
int[] emptyArray = new int[0];
int[] emptyArray = Array.Empty<int>();
Use Await Using
Description: Convert to 'await using' statement or declaration
using (var resource = await GetResourceAsync()) { /* ... */ }
await using var resource = await GetResourceAsync();
Use Cancellation Token
Description: Use cancellation token for async enumerable
await foreach (var item in GetDataAsync()) { ... }
await foreach (var item in GetDataAsync(cancellationToken)) { ... }
Use Compound Assignment
Description: Convert to null coalescing compound assignment.
if (x == null) { x = new Object(); }
x ??= new Object();
Use Configure Await
Description: Missing '.ConfigureAwait(false)' in library code
await Task.Delay(1000); // Missing ConfigureAwait(false)
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
await asyncDisposable.DisposeAsync(); // Missing ConfigureAwait(false)
await asyncDisposable.DisposeAsync().ConfigureAwait(false); // Adds ConfigureAwait(false)
Use Deconstruction
Description: Use deconstruction.
var x = tuple.Item1; var y = tuple.Item2;
var (x, y) = tuple;
Use EmptyTypes Field
Description: Use 'Type.EmptyTypes'
var types = new Type[0];
var types = Type.EmptyTypes;
Use Event Args Empty Field
Description: Use 'EventArgs.Empty'
OnEvent(new EventArgs());
OnEvent(EventArgs.Empty);
Use Index from End Expression
Description: Use index from end expression.
var last = array[array.Length - 1];
var last = array[^1];
Use Indexed Property
Description: Use indexed property
var value = dictionary.ContainsKey(key) ? dictionary[key] : default;
var value = dictionary[key];
Use Name Of Expression
Description: Use 'nameof' expression to reference name.
throw new ArgumentException("parameterName");
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.
Log("Error in parameterName");
Log($"Error in {nameof(parameterName)}");
Use Name Of Instead of Type Of
Description: Use 'nameof' expression to reference type's name.
Console.WriteLine(typeof(MyClass).Name);
Console.WriteLine(nameof(MyClass));
Use Nullable Attributes
Description: Use compiler-supported nullable attributes
[NotNullWhen(true)] public bool TryGetValue(out string value) { ... }
[NotNullWhen(true), MaybeNull] public bool TryGetValue(out string value) { ... }
Use Nullable Reference Types Annotation Syntax
Description: Use type annotation syntax
public string Name { get; set; }
public string? Name { get; set; }
Use Object or Collection Initializer
Description: Use object or collection initializer when possible
var list = new List<int>(); list.Add(1); list.Add(2);
var list = new List<int> { 1, 2 };
Use Parameter Deconstruction
Description: Use deconstruction (on parameter declaration).
void Foo((int, int) tuple) { var x = tuple.Item1; var y = tuple.Item2; }
void Foo((int x, int y) tuple) { /* ... */ }
Use Positional Deconstruction Pattern
Description: Use positional deconstruction pattern
var point = GetPoint(); var x = point.X; var y = point.Y;
var (x, y) = GetPoint();
Use String Interpolation
Description: Use string interpolation expression
string result = string.Format("Hello, {0}", name);
string result = $"Hello, {name}";
Use Throw if Null Method
Description: Use 'ArgumentNullException.ThrowIfNull'
if (param == null) throw new ArgumentNullException(nameof(param));
ArgumentNullException.ThrowIfNull(param);
Useless Binary Operation
Description: Useless binary operation.
int result = x * 1; // Multiplication by 1 is redundant
int result = x; // Simplified without useless operation
Useless Comparison to Integral
Description: Comparison to integral constant is useless.
if (x == 10 || x != 10) { /* code */ }
// 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'.
if (myByte == 300) { /* This comparison is invalid */ }
if (myByte == 255) { /* Valid comparison within byte range */ }
Useless Global Event
Description: Event is never subscribed to (non-private accessibility)
public event EventHandler MyEvent; // Never subscribed to
// Remove unused event or add subscriptions as needed
Useless Local Event
Description: Event is never subscribed to (private accessibility)
private event EventHandler MyEvent; // Never subscribed to
// Remove or use event with proper subscriptions
Using Statement Braces
Description: Use preferred braces style (enforce braces in 'using' statement)
using (var resource = GetResource()) DoSomething(resource);
using (var resource = GetResource()) { DoSomething(resource); }
Value Parameter Not Used
Description: 'value' parameter is not used
set { int result = 5; } // 'value' parameter is not used
set { field = value; } // Proper use of 'value' parameter
Value Range Attribute Violation
Description: Possible violation of 'ValueRange'/'NonNegativeValue' attribute
[ValueRange(0, 100)] public int Value = -5;
[ValueRange(0, 100)] public int Value = 50;
Var Keywords in Deconstructing Declaration
Description: Join or separate 'var' in deconstruction declarations
(int x, var y) = (1, 2);
(var x, var y) = (1, 2);
Variable Not Nullable
Description: Variable can be declared as non-nullable
string? name = "John"; // Nullable but always assigned a non-null value
string name = "John"; // Declared as non-nullable
Variable Overwritten
Description: Variable in local function hides variable from outer scope
int value = 5; void LocalFunc() { int value = 10; } // Hides outer variable
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)
int age = 25;
var age = 25;
Variables Var Declaration Deconstruction
Description: Use preferred 'var' style (in deconstruction declarations)
(string name, int age) = person;
var (name, age) = person;
Variables Var Declaration Elsewhere
Description: Use preferred 'var' style (elsewhere)
List<string> names = new List<string>();
var names = new List<string>();
Variables Var Declaration Simple Types
Description: Use preferred 'var' style (when type is simple)
string name = "John";
var name = "John";
Verbatim String
Description: Literal's length can be reduced by using verbatim string
string path = "C:\\folder\\file.txt"; // Escapes increase length
string path = @"C:\folder\file.txt"; // Verbatim string reduces length
Virtual Member Call in Constructor
Description: Virtual member call in constructor
public MyClass() { VirtualMethod(); } // Calls virtual method in constructor
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)
public class MyClass { public virtual void MyMethod() { } } // Virtual not inherited
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)
private class MyClass { public virtual void MyMethod() { } } // Virtual not inherited
private class MyClass { public void MyMethod() { } } // Removed 'virtual' modifier
Void Method Must Use Return Value
Description: 'void' method is annotated by [MustUseReturnValue] attribute
[MustUseReturnValue] public void DoSomething() { ... } // Void method marked with MustUseReturnValue
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)
while (condition) DoSomething();
while (condition) { DoSomething(); }
Wrong Indent Size
Description: Incorrect indent (incorrect indent size)
if (condition)
{
doSomething();
}
if (condition)
{
doSomething();
}
XML Comment Ambiguous Reference
Description: Ambiguous reference in XML comment
/// See <see cref="MyMethod"/> for more information.
/// See <see cref="Namespace.MyClass.MyMethod"/> for more information.
XML Comment Duplicate Typeparam
Description: Duplicate typeparam tag in XML comment
/// <typeparam name="T">Type parameter</typeparam> /// <typeparam name="T">Duplicate parameter</typeparam>
/// <typeparam name="T">Type parameter</typeparam>
XML Comment Param Tag
Description: Duplicate param tag in XML comment
/// <param name="x">First parameter</param> /// <param name="x">Duplicate parameter</param>
/// <param name="x">First parameter</param>
XML in Included Comments File
Description: Badly formed XML in included comments file
/// <summary>Badly formed XML
/// <summary>Well-formed XML</summary>
Xunit Console Output
Description: Console output in Xunit tests
Console.WriteLine("Test output");
_output.WriteLine("Test output"); // Use Xunit's output helper