Skip to main content

C# Coding Violations


Common Practices and Code Improvements

Access to Static Member via Derived Type

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

Label Label Label

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

Auto Local Property Get Only

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

Label Label Label

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

Empty Statement

Description: Empty statement is redundant

Label Label Label

Bad Example
;
Good Example
// Removed unnecessary statement

Join Declaration and Initializer

Description: Join local variable declaration and assignment

Label Label Label

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

Linq Expression Use All

Description: Simplify LINQ expression (use 'All')

Label Label Label

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

Method Async Overload

Description: Method has async overload

Label Label Label

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

More Specific Foreach

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

Label Label Label

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

Negative Equality Expression

Description: Simplify negative equality expression

Label Label Label

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

Nested String Interpolation

Description: Nested string interpolation can be inlined

Label Label Label

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

Prefer String IsNullOrEmpty

Description: Use 'String.IsNullOrEmpty'

Label Label Label

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

Public Constructor In Abstract Class

Description: Make constructor in abstract class protected

Label Label Label

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

Replace with Single Call to Any

Description: Replace with single call to Any(..)

Label Label Label

Bad Example
var hasItems = collection.Count() > 0;
Good Example
var hasItems = collection.Any();

Replace with Single Call to Count

Description: Replace with single call to Count(..)

Label Label Label

Bad Example
var count = collection.Where(item => item.IsActive).Count();
Good Example
var count = collection.Count(item => item.IsActive);

Replace with Single Call to First

Description: Replace with single call to First(..)

Label Label Label

Bad Example
var firstActive = collection.Where(item => item.IsActive).First();
Good Example
var firstActive = collection.First(item => item.IsActive);

Replace with Single Call to FirstOrDefault

Description: Replace with single call to FirstOrDefault(..)

Label Label Label

Bad Example
var firstInactive = collection.Where(item => !item.IsActive).FirstOrDefault();
Good Example
var firstInactive = collection.FirstOrDefault(item => !item.IsActive);

Replace with Single Call to Single

Description: Replace with single call to Single(..)

Label Label Label

Bad Example
var singleItem = items.Where(x => x.IsMatch).Single();
Good Example
var singleItem = items.Single(x => x.IsMatch);

Replace with Single Call to Single or Default

Description: Replace with single call to SingleOrDefault(..)

Label Label Label

Bad Example
var singleOrDefaultItem = items.Where(x => x.IsMatch).SingleOrDefault();
Good Example
var singleOrDefaultItem = items.SingleOrDefault(x => x.IsMatch);

Replace with Single False Assignment

Description: Replace with single assignment

Label Label Label

Bad Example
isAvailable = isAvailable == false;
Good Example
isAvailable = false;

Replace with Single True Assignment

Description: Replace with single assignment

Label Label Label

Bad Example
isEnabled = isEnabled == true;
Good Example
isEnabled = true;

String Literal as Interpolation Argument

Description: String literal can be inlined

Label Label Label

Bad Example
var message = $"Hello {"John"}";
Good Example
var message = "Hello John";

Too Wide Local Variable Scope

Description: Local variable has too wide declaration scope

Label Label Label

Bad Example
int result = 0;
for (int i = 0; i < 10; i++) {
result += i;
}
return result;
Good Example
int result = 0;
for (int i = 0; i < 10; i++) {
result += i;
}
return result;

Type Parameter Variant

Description: Type parameter could be declared as covariant or contravariant

Label Label Label

Bad Example
public interface IRepository { /* ... */ }
Good Example
public interface IRepository<out T> { /* ... */ }

Unassigned Get Only Auto Property

Description: Get-only auto-property is never assigned

Label Label Label

Bad Example
public int Id { get; } // Property is never assigned
Good Example
public int Id { get; } = 1; // Property is initialized with a value

Use Array Empty Method

Description: Use 'Array.Empty<T>()'

Label Label Label

Bad Example
int[] emptyArray = new int[0];
Good Example
int[] emptyArray = Array.Empty<int>();

Compiler Warnings

Async Function without Await

Description: Async function without await expression

Label Label Label

Bad Example
async Task Foo() { Console.WriteLine("no await"); }
Good Example
Task Foo() { Console.WriteLine("no await"); return Task.CompletedTask; }

Async without Await

Description: Async method invocation without await expression

Label Label Label

Bad Example
async Task<int> Foo() { return 42; }
Good Example
Task<int> Foo() { return Task.FromResult(42); }

C Sharp Warnings:: C S1711

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

Label Label Label

Bad Example
// CS1711: XML comment has typeparam tag but no type parameter
Good Example
/// <typeparam name=\"T\">The type.</typeparam>
void M<T>() { }

Cast to non Nullable

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

Label Label Label

Bad Example
int? x = null; int y = (int)x;
Good Example
int? x = null; if (x.HasValue) { int y = x.Value; }

Expression not of Provided Type

Description: Given expression is never of the provided type

Label Label Label

Bad Example
object o = "hello"; if (o is int) { }
Good Example
object o = "hello"; if (o is string) { }

New Protected Member Sealed Class

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

Label Label Label

Bad Example
sealed class C { protected void M() { } }
Good Example
sealed class C { private void M() { } }

Not Accessed Variable. Compiler

Description: Non-accessed local variable

Label Label Label

Bad Example
int x = 1; Console.WriteLine("test");
Good Example
Console.WriteLine("test");

Unused Field

Description: Field is never used

Label Label Label

Bad Example
class C { public int _unused; public void M() { } }
Good Example
class C { public void M() { } }

Constraints Violations

Check Namespace

Description: Namespace does not correspond to file location

Label Label Label

Bad Example
using System; using System.IO; class C { }
Good Example
using System.IO; class C { }

Formatting

Bad Child Statement Indent

Description: Incorrect indent (around child statement)

Label Label Label

Bad Example
if (x > 0) {
int y = 1;
}
Good Example
if (x > 0)
{
int y = 1;
}

Bad Control Braces Indent

Description: Incorrect indent (around statement braces)

Label Label Label

Bad Example
if (x > 0) {
return;
}
Good Example
if (x > 0)
{
return;
}

Language Usage Opportunities

Convert to Using Declaration

Description: Convert to 'using' declaration

Label Label Label

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

For Converted to Foreach

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

Label Label Label

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

Inline out Variable Declaration

Description: Inline 'out' variable declaration

Label Label Label

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

Invoke as Extension Method

Description: Convert static method invocation to extension method call

Label Label Label

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

Merge and Pattern

Description: Merge 'and' pattern

Label Label Label

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

Merge Conditional Expression

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

Label Label Label

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

Merge into Pattern

Description: Merge null/pattern checks into complex pattern

Label Label Label

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

Pattern Matching

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

Label Label Label

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

Prefer Conditional Ternary Expression

Description: Replace ternary expression with 'switch' expression

Label Label Label

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

Prefer Null Coalescing Expression

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

Label Label Label

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

Prefer Short Form

Description: Convert 'Nullable<T>' to 'T?'

Label Label Label

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

Use Await Using

Description: Convert to 'await using' statement or declaration

Label Label Label

Bad Example
using (var resource = await GetResourceAsync()) { /* ... */ }
Good Example
await using var resource = await GetResourceAsync();

Use Index from End Expression

Description: Use index from end expression

Label Label Label

Bad Example
var last = array[array.Length - 1];
Good Example
var last = array[^1];

Use Name Of Expression

Description: Use 'nameof' expression to reference name

Label Label Label

Bad Example
throw new ArgumentException("parameterName");
Good Example
throw new ArgumentException(nameof(parameterName));

Use Object or Collection Initializer

Description: Use object or collection initializer when possible

Label Label Label

Bad Example
var list = new List<int>(); list.Add(1); list.Add(2);
Good Example
var list = new List<int> { 1, 2 };

Use String Interpolation

Description: Use string interpolation expression

Label Label Label

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

Potential Code Quality Issues

Access to Modified Closure

Description: Access to modified captured variable

Label Label Label

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

Assignment in Conditional Expression

Description: Assignment in conditional expression

Label Label Label

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

Async Void Lambda

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

Label Label Label

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

Async Void Method

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

Label Label Label

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

Base Method Call With Default Parameter

Description: Call to base member with implicit default parameters

Label Label Label

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

Bitwise Operator Without Flags

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

Label Label Label

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

Collection Count Property

Description: Use collection's count property

Label Label Label

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

Conditional Ternary Equal Branch

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

Label Label Label

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

Empty Catch Clause

Description: Empty general catch clause

Label Label Label

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

Equal Expression Comparison

Description: Similar expressions comparison

Label Label Label

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

Event Never Invoked

Description: Event never invoked

Label Label Label

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

Format Specifier in Format String

Description: Use format specifier in format strings

Label Label Label

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

Format String Problem

Description: String formatting method problems

Label Label Label

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

Function never Returns

Description: Function never returns

Label Label Label

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

Function Recursive Paths

Description: Function is recursive on all execution paths

Label Label Label

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

Generic Enumerator not Disposed

Description: Instance of IEnumerator is never disposed

Label Label Label

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

Hidden Static Member

Description: Member hides static member from outer class

Label Label Label

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

Inconsistently Synchronized Field

Description: Inconsistent synchronization on field

Label Label Label

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

Inheritdoc Invalid Usage

Description: Usage of <inheritdoc /> is invalid.

Label Label Label

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

Initializer Value Ignored

Description: Member initialized value ignored

Label Label Label

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

Iterator Method Result Ignored

Description: Return value of iterator is not used

Label Label Label

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

Local Collection Never Queried

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

Label Label Label

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

Local Collection Never Updated

Description: Collection is never updated (private accessibility)

Label Label Label

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

Local Variable Hides Member

Description: Local variable hides member

Label Label Label

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

Merge Cast with Type Check

Description: Type check and casts can be merged

Label Label Label

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

Non Readonly Member in GetHashCode

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

Label Label Label

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

Object Creation as Statement

Description: Possible unassigned object created by 'new' expression

Label Label Label

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

Optional Parameter Hierarchy Mismatch

Description: Mismatch of optional parameter value in overridden method

Label Label Label

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

Optional Parameter Method Overload

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

Label Label Label

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

Parameter Hides Member

Description: Parameter hides member

Label Label Label

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

Pattern Never Matches

Description: The source expression never matches the provided pattern

Label Label Label

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

Possible Intended Rethrow

Description: Exception rethrow possibly intended

Label Label Label

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

Possible Invalid Operation Exception

Description: Possible 'System.InvalidOperationException'

Label Label Label

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

Possible Loss of Fraction

Description: Possible loss of fraction

Label Label Label

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

Possible Multiple Enumeration

Description: Possible multiple enumeration

Label Label Label

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

Possible Unintended Reference Comparison

Description: Possible unintended reference comparison

Label Label Label

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

Possibly Mistaken Use of Interpolated String Insert

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

Label Label Label

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

Prefer Null Check Pattern

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

Label Label Label

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

Property not Resolved

Description: Cannot resolve property

Label Label Label

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

Return Type not Nullable

Description: Return type of a function can be non-nullable

Label Label Label

Bad Example
public string? GetString() { return "Hello"; } // Return type could be non-nullable
Good Example
public string GetString() { return "Hello"; } // Return type explicitly non-nullable

Simplify String Interpolation

Description: Use format specifier in interpolated strings

Label Label Label

Bad Example
string result = $"Value: {value}";
Good Example
string result = $"Value: {value:F2}"; // Use format specifier for precision

Static Member in Generic Type

Description: Static field or auto-property in generic type

Label Label Label

Bad Example
class Container { public static int Count; }
Good Example
class Container { public int InstanceCount; }

Suspicious Type Conversion

Description: Suspicious type conversion or check

Label Label Label

Bad Example
var number = (int)(object)"text"; // Suspicious and unsafe cast
Good Example
if (obj is int number) { ... } // Safe type check before conversion

Try Cast Always Succeeds

Description: Safe cast expression always succeeds

Label Label Label

Bad Example
var item = obj as MyClass; if (item != null) { /* always true */ }
Good Example
var item = obj as MyClass; if (item != null) { /* logic */ } // Cast with possible null

Useless Binary Operation

Description: Useless binary operation.

Label Label Label

Bad Example
int result = x * 1; // Multiplication by 1 is redundant
Good Example
int result = x; // Simplified without useless operation

Value Parameter Not Used

Description: 'value' parameter is not used

Label Label Label

Bad Example
set { int result = 5; } // 'value' parameter is not used
Good Example
set { field = value; } // Proper use of 'value' parameter

Variable Not Nullable

Description: Variable can be declared as non-nullable

Label Label Label

Bad Example
string? name = "John"; // Nullable but always assigned a non-null value
Good Example
string name = "John"; // Declared as non-nullable

Variable Overwritten

Description: Variable in local function hides variable from outer scope

Label Label Label

Bad Example
int value = 5; void LocalFunc() { int value = 10; } // Hides outer variable
Good Example
int value = 5; void LocalFunc() { int innerValue = 10; } // Unique variable name

Virtual Member Call in Constructor

Description: Virtual member call in constructor

Label Label Label

Bad Example
public MyClass() { VirtualMethod(); } // Calls virtual method in constructor
Good Example
public MyClass() { Initialize(); } protected virtual void Initialize() { ... } // Avoids calling virtual method directly in constructor

Redundancies in Code

Assignment Fully Discarded

Description: Assignment results are fully discarded

Label Label Label

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

Private Field to Local Variable

Description: Private field can be converted to local variable

Label Label Label

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

Redundant Attribute Usage Property

Description: Redundant [AttributeUsage] attribute property assignment

Label Label Label

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

Redundant Base Qualifier

Description: Redundant 'base.' qualifier

Label Label Label

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

Redundant Bool Compare

Description: Redundant boolean comparison

Label Label Label

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

Redundant Case Label

Description: Redundant 'case' label

Label Label Label

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

Redundant Cast

Description: Redundant cast

Label Label Label

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

Redundant Catch

Description: Redundant catch clause

Label Label Label

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

Redundant Delegate Creation

Description: Explicit delegate creation expression is redundant

Label Label Label

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

Redundant Empty Finally Block

Description: Redundant empty finally block

Label Label Label

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

Redundant Empty Object

Description: Redundant empty object or collection initializer

Label Label Label

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

Redundant Enumerable Cast Call

Description: Redundant 'IEnumerable.Cast<T>' or 'IEnumerable.OfType<T>' call

Label Label Label

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

Redundant Explicit Array Creation

Description: Redundant explicit type in array creation

Label Label Label

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

Redundant Lambda Parameter Type

Description: Redundant lambda expression parameter type specification

Label Label Label

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

Redundant Match Subpattern

Description: Redundant always match subpattern

Label Label Label

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

Redundant Name Qualifier

Description: Redundant name qualifier

Label Label Label

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

Redundant Params Array Creation

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

Label Label Label

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

Redundant Record Body

Description: Redundant 'record' type declaration body

Label Label Label

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

Redundant String Format

Description: Redundant 'string.Format()' call

Label Label Label

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

Redundant String Interpolation

Description: Redundant string interpolation

Label Label Label

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

Redundant String Prefix

Description: Redundant verbatim string prefix

Label Label Label

Bad Example
var x = "hello";
Good Example
var x = "hello"; // This is already the default

Redundant Ternary Expression

Description: Redundant conditional ternary expression usage

Label Label Label

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

Redundant Unsafe Context

Description: Unsafe context declaration is redundant

Label Label Label

Bad Example
unsafe { int* p = &value; } // Redundant unsafe context
Good Example
int* p = &value; // Removed unnecessary 'unsafe' block

Redundancies in Symbol Declarations

Compiler Unused Local Function

Description: Compiler: local function is never used

Label Label Label

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

Empty Constructor

Description: Empty constructor

Label Label Label

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

Empty Namespace

Description: Empty namespace declaration

Label Label Label

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

Enum Underlying Type

Description: Underlying type of enum is 'int'

Label Label Label

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

Partial Method

Description: Redundant 'partial' modifier on method declaration

Label Label Label

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

Partially Unused Parameter Private Accessibility

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

Label Label Label

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

Redundant Constructor Call

Description: Redundant base constructor call

Label Label Label

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

Redundant List Entry

Description: Redundant class or interface specification in base types list

Label Label Label

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

Redundant Member Initializer

Description: Redundant default member initializer

Label Label Label

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

Redundant Overridden Member

Description: Redundant member override

Label Label Label

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

Unused Local Function

Description: Local function is never used

Label Label Label

Bad Example
void UnusedFunction() { } // Local function is never called
Good Example
// Removed unused local function

Unused Local Variable

Description: Unused local variable

Label Label Label

Bad Example
int unusedValue = 10;
Good Example
// Remove 'unusedValue' if not used in the code

Unused Member in Super Private Accessibility

Description: Type is never used (private accessibility)

Label Label Label

Bad Example
private class UnusedHelperClass {}
Good Example
// Remove the class if it is not used within the code

Unused Member Private Accessibility

Description: Type member is never used (private accessibility)

Label Label Label

Bad Example
private string unusedString;
Good Example
// Remove or use the member if necessary within the code

Unused Parameter Private Accessibility

Description: Unused parameter (private accessibility)

Label Label Label

Bad Example
private void Helper(int unusedParam) { }
Good Example
// Remove 'unusedParam' if not needed in 'Helper'

Unused Type Parameter

Description: Unused type parameter

Label Label Label

Bad Example
public class Example { }
Good Example
// Remove 'T' if the class does not use it

Syntax Style

Accessor Owner Body

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

Label Label Label

Bad Example
public int X { get { return _x; } }
Good Example
public int X { get => _x; }

Modifiers Order

Description: Adjust modifiers declaration order

Label Label Label

Bad Example
static public void M() { }
Good Example
public static void M() { }

Object Creation Evident Type

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

Label Label Label

Bad Example
MyClass obj = new MyClass();
Good Example
MyClass obj = new();

Var Keywords in Deconstructing Declaration

Description: Join or separate 'var' in deconstruction declarations

Label Label Label

Bad Example
(int x, var y) = (1, 2);
Good Example
(var x, var y) = (1, 2);

Uncategorized / Custom

Assign To Not Null Attribute

Description: Source file: assign-null-to-not-null-attribute.js

Label Label Label

Bad Example
[NotNull] string value = null;
Good Example
[NotNull] string value = "hello";

Attribute Modifier Invalid Location

Description: Source file: attribute-modifier-invalid-location.js

Label Label Label

Bad Example
[Obsolete] int x;
Good Example
[field: Obsolete] int x;

Class Never Instantiated

Description: Source file: class-never-instantiated.js

Label Label Label

Bad Example
class MyClass { public void M() { } }
Good Example
// Remove unused class or add instantiation logic

Class With Virtual Members Never Inherited

Description: Source file: class-with-virtual-members-never-inherited.global.js

Label Label Label

Bad Example
sealed class C { public virtual void M() { } }
Good Example
sealed class C { public void M() { } }

Collection Never Queried

Description: Source file: collection-never-queried.global.js

Label Label Label

Bad Example
var list = new List<int> { 1, 2, 3 };
list.Add(4);
Good Example
var list = new List<int> { 1, 2, 3, 4 };
foreach (var item in list) { Console.WriteLine(item); }

Collection Never Updated

Description: Source file: collection-never-updated.js

Label Label Label

Bad Example
var list = new List<int> { 1, 2, 3 };
foreach (var item in list) { Console.WriteLine(item); }
Good Example
int[] arr = { 1, 2, 3 };
foreach (var item in arr) { Console.WriteLine(item); }

Condition Is Always True Or False According To Nullable API Contract

Description: Source file: condition-is-always-true-or-false-according-to-nullable-api-contract.js

Label Label Label

Bad Example
string s = MaybeNull(); if (s != null) { Console.WriteLine(s.Length); }
Good Example
string? s = MaybeNull(); if (s != null) { Console.WriteLine(s.Length); }

Conditional Access Qualifier Is Non Nullable According To API Contract

Description: Source file: conditional-access-qualifier-is-non-nullable-according-to-api-contract.js

Label Label Label

Bad Example
string s = "hello"; int? len = s?.Length;
Good Example
string s = "hello"; int len = s.Length;

Convert Auto Property When Possible

Description: Source file: convert-auto-property-when-possible.js

Label Label Label

Bad Example
private int _x;
public int X { get { return _x; } set { _x = value; } }
Good Example
public int X { get; set; }

Convert If To Null Coalescing Assignment

Description: Source file: convert-if-statement-to-null-coalescing-assignment.js

Label Label Label

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

Covariant Array Conversion

Description: Source file: covariant-array-conversion.js

Label Label Label

Bad Example
string[] strings = { "a" };
object[] objs = strings;
objs[0] = 5; // runtime error
Good Example
string[] strings = { "a" };
// Use List<object> instead

Csharp Warnings Cs1717

Description: Source file: assign-to-the-same-variable.js

Label Label Label

Bad Example
int x; x = x; // assigned to itself
Good Example
int x = GetValue();

Cyclomatic Complexity

Description: Source file: cyclomatic-complexity.js

Label Label Label

Bad Example
if (a) { if (b) { if (c) { if (d) { } } } }
Good Example
// Refactor into smaller methods to reduce complexity

Default Value Evident Type

Description: Source file: default-value-evident-type.js

Label Label Label

Bad Example
int x = 0; bool b = false;
Good Example
int x; bool b;

Event Never Subscribed To

Description: Source file: event-never-subscribed-to.global.js

Label Label Label

Bad Example
public event EventHandler MyEvent;
public void Raise() { MyEvent?.Invoke(this, EventArgs.Empty); }
Good Example
// Remove unused event or ensure subscribers are attached

Field Can Be Made Readonly

Description: Source file: field-can-be-made-read-only.local.js

Label Label Label

Bad Example
class C { private int _x;
public C() { _x = 5; }
public int X => _x; }
Good Example
class C { private readonly int _x;
public C() { _x = 5; }
public int X => _x; }

Field Can Be Made Readonly Global

Description: Source file: field-can-be-made-read-only.global.js

Label Label Label

Bad Example
int _x; void Init() { _x = 5; }
Good Example
readonly int _x; void Init() { _x = 5; }

Guid.Empty

Description: Source file: unassigned-field.global.js

Label Label Label

Bad Example
if (id == new Guid()) { }
Good Example
if (id == Guid.Empty) { }

Introduce Optional Parameters

Description: Source file: introduce-optional-parameters.js

Label Label Label

Bad Example
void M(int x) { }
void Caller() { M(42); }
Good Example
void M(int x = 42) { }
void Caller() { M(); }

Invalid Attribute Modifier Specified

Description: Source file: invalid-attribute-modifier-specified.js

Label Label Label

Bad Example
[Obsolete]
public string Name { get; set; }
Good Example
[Obsolete("Use NewName instead")]
public string Name { get; set; }

Linq Expression Use Any

Description: Source file: linq-expression-use-any.js

Label Label Label

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

Loop Variable Never Changes

Description: Source file: loop-variable-never-changes.js

Label Label Label

Bad Example
for (int i = 0; i < 10; i++) { if (i == 5) { i = 0; } }
Good Example
for (int i = 0; i < 10; i++) { }

Member Can Be Private

Description: Source file: member-can-be-private.local.js

Label Label Label

Bad Example
class C { public int X; }
Good Example
class C { private int X; }

Member Can Be Protected

Description: Source file: member-can-be-protected.global.js

Label Label Label

Bad Example
class C { public void M() { } }
Good Example
class C { protected void M() { } }

Not Accessed Positional Property

Description: Source file: not-accessed-positional-library.global.js

Label Label Label

Bad Example
var (x, _) = GetValues();
Good Example
var (x, y) = GetValues(); Console.WriteLine(y);

Null Check Assignment

Description: Source file: null-check-assignment.js

Label Label Label

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

Null Coalescing Condition Is Always Not Null According To API Contract

Description: Source file: null-coalescing-condition-is-always-not-null-according-to-api-contract.js

Label Label Label

Bad Example
string s = GetNonNull(); string r = s ?? "default";
Good Example
string s = GetNonNull(); string r = s;

Operator Used

Description: Source file: operator-used.js

Label Label Label

Bad Example
if (x != null && x.Value > 0) { }
Good Example
if (x?.Value > 0) { }

Parameter Type Can Be Enumerable

Description: Source file: parameter-type-can-be-enumerable.js

Label Label Label

Bad Example
void M(List<int> items) { foreach (var i in items) { } }
Good Example
void M(IEnumerable<int> items) { foreach (var i in items) { } }

Possible Struct Member Modification Of Non Variable

Description: Source file: possible-struct-member-modification-of-non-variable-struct.js

Label Label Label

Bad Example
struct Point { public int X; }
GetPoint().X = 5;
Good Example
var p = GetPoint(); p.X = 5;

Prefer While Expression

Description: Source file: prefer-while-expression.js

Label Label Label

Bad Example
while (true) { if (cond) { break; } body; }
Good Example
while (cond) { body; }

Property Can Be Made Init Only

Description: Source file: property-can-be-made-init-only.js

Label Label Label

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

Redundant Anonymous Property Name

Description: Source file: redundant-anonymous-property-name.js

Label Label Label

Bad Example
new { Name = Name, Age = Age }
Good Example
new { Name, Age }

Redundant Discard

Description: Source file: redundant-discard.js

Label Label Label

Bad Example
_ = SomeMethod();
Good Example
SomeMethod();

Redundant Explicit Tuple Name

Description: Source file: redundant-explicit-tuple-name.js

Label Label Label

Bad Example
(int x, int y) = (1, 2); // explicit names
Good Example
(int, int) = (1, 2);

Redundant Private Accessibility

Description: Source file: redundant-private-accesibility.js

Label Label Label

Bad Example
class C { private int _x; }
Good Example
class C { int _x; }

Redundant Suppress Nullable Warning

Description: Source file: redundant-suppress-nullable-warning-expression.js

Label Label Label

Bad Example
string s = null!;
Good Example
string? s = null;

Redundant Tostring Call

Description: Source file: redundant-to-string-call.js

Label Label Label

Bad Example
$"Hello {name.ToString()}"
Good Example
$"Hello {name}"

Safe Cast For Type Check

Description: Source file: safe-cast-for-type-check.js

Label Label Label

Bad Example
if (o is MyType) { var m = (MyType)o; }
Good Example
if (o is MyType m) { }

Sealed Member

Description: Source file: sealed-member.js

Label Label Label

Bad Example
class C { public virtual void M() { } }
Good Example
class C { public void M() { } }

Simplify Conditional Ternary

Description: Source file: simplify-conditional-ternary-expression.js

Label Label Label

Bad Example
var x = cond ? true : false;
Good Example
var x = cond;

Specify Culture In String Conversion

Description: Source file: specify-a-culture-in-string-conversion-explicitly.js

Label Label Label

Bad Example
int.Parse("42");
Good Example
int.Parse("42", CultureInfo.InvariantCulture);

Static Member Initializer References Member Below

Description: Source file: static-member-initializer-referes-to-member-below.js

Label Label Label

Bad Example
class C { public static int A = B; public static int B = 5; }
Good Example
class C { public static int B = 5; public static int A = B; }

String Compare Is Culture Specific

Description: Source file: string-comparels-culture-specific.js

Label Label Label

Bad Example
string.Compare(a, b);
Good Example
string.Compare(a, b, StringComparison.Ordinal);

String Indexof Is Culture Specific 3

Description: Source file: string-index-of-is-culture-specific.js

Label Label Label

Bad Example
str.IndexOf("test");
Good Example
str.IndexOf("test", StringComparison.Ordinal);

String Last Index Of Is Culture Specific

Description: Source file: string-last-index-of-is-culture-specific.js

Label Label Label

Bad Example
str.LastIndexOf("test");
Good Example
str.LastIndexOf("test", StringComparison.Ordinal);

Structured Message Template

Description: Source file: structured-message-template.js

Label Label Label

Bad Example
Log.Info("User " + name + " logged in");
Good Example
Log.Info("User {Name} logged in", name);

Suspicious Parameter Name

Description: Source file: suspicious-parameter-name.js

Label Label Label

Bad Example
void M(int value) { Console.WriteLine(count); }
Good Example
void M(int value) { Console.WriteLine(value); }

Unreachable Switch Case

Description: Source file: unreachable-switch-case.js

Label Label Label

Bad Example
switch (x) { case 1: return; case 2: break; case 1: return; }
Good Example
switch (x) { case 1: return; case 2: break; }

Unused Member Hierarchy

Description: Source file: unused-member-hierarchy.global.js

Label Label Label

Bad Example
class Base { public virtual void M() { } }
class Derived : Base { public override void M() { } }
Good Example
class Base { public virtual void M() { } }
class Derived : Base { }

Unused Positional Parameter

Description: Source file: unused-positional-parameter.js

Label Label Label

Bad Example
void M(int x, int y) { Console.WriteLine(x); }
Good Example
void M(int x) { Console.WriteLine(x); }

Use Compound Assignment

Description: Source file: use-compound-assignment.js

Label Label Label

Bad Example
x = x + 5;
Good Example
x += 5;

Use Method Any

Description: Source file: use-method-any.js

Label Label Label

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

Use Name Instead Of Type Of

Description: Source file: use-name-instead-of-type-of.js

Label Label Label

Bad Example
nameof(C); // C is a type
Good Example
nameof(C); // C is the type name, this is correct

Xml Comment Ambiguous Reference

Description: Source file: xml-comment-ambiguous-reference.js

Label Label Label

Bad Example
/// <see cref=\"M\"/>
Good Example
/// <see cref=\"M()\"/>

Ship Fast. Validate Smarter.Protect your reputation.

Cyclopt G2 profile

29A, Ptolemaion Street, Coho Building, Thessaloniki, Greece, Tel: +30 2310 471 030
Copyright © 2026 Cyclopt