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
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
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
Empty Statement
Description: Empty statement is redundant
;
// Removed unnecessary statement
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
Linq Expression Use All
Description: Simplify LINQ expression (use 'All')
var allActive = !collection.Any(item => !item.IsActive);
var allActive = collection.All(item => item.IsActive);
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
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
Negative Equality Expression
Description: Simplify negative equality expression
if (!(status == Status.Active)) { ... }
if (status != Status.Active) { ... }
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
Prefer String IsNullOrEmpty
Description: Use 'String.IsNullOrEmpty'
if (str == null || str == "") { ... }
if (String.IsNullOrEmpty(str)) { ... }
Public Constructor In Abstract Class
Description: Make constructor in abstract class protected
public abstract class Example {
public Example() { }
}
public abstract class Example {
protected Example() { }
}
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 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 True Assignment
Description: Replace with single assignment
isEnabled = isEnabled == true;
isEnabled = true;
String Literal as Interpolation Argument
Description: String literal can be inlined
var message = $"Hello {"John"}";
var message = "Hello John";
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;
Type Parameter Variant
Description: Type parameter could be declared as covariant or contravariant
public interface IRepository { /* ... */ }
public interface IRepository<out T> { /* ... */ }
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
Use Array Empty Method
Description: Use 'Array.Empty<T>()'
int[] emptyArray = new int[0];
int[] emptyArray = Array.Empty<int>();
Compiler Warnings
Async Function without Await
Description: Async function without await expression
async Task Foo() { Console.WriteLine("no await"); }
Task Foo() { Console.WriteLine("no await"); return Task.CompletedTask; }
Async without Await
Description: Async method invocation without await expression
async Task<int> Foo() { return 42; }
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
// CS1711: XML comment has typeparam tag but no type parameter
/// <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.
int? x = null; int y = (int)x;
int? x = null; if (x.HasValue) { int y = x.Value; }
Expression not of Provided Type
Description: Given expression is never of the provided type
object o = "hello"; if (o is int) { }
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
sealed class C { protected void M() { } }
sealed class C { private void M() { } }
Not Accessed Variable. Compiler
Description: Non-accessed local variable
int x = 1; Console.WriteLine("test");
Console.WriteLine("test");
Unused Field
Description: Field is never used
class C { public int _unused; public void M() { } }
class C { public void M() { } }
Constraints Violations
Check Namespace
Description: Namespace does not correspond to file location
using System; using System.IO; class C { }
using System.IO; class C { }
Formatting
Bad Child Statement Indent
Description: Incorrect indent (around child statement)
if (x > 0) {
int y = 1;
}
if (x > 0)
{
int y = 1;
}
Bad Control Braces Indent
Description: Incorrect indent (around statement braces)
if (x > 0) {
return;
}
if (x > 0)
{
return;
}
Language Usage Opportunities
Convert to Using Declaration
Description: Convert to 'using' declaration
using (var reader = new StreamReader(path)) { /* ... */ }
using var reader = new StreamReader(path);
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); }
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);
Invoke as Extension Method
Description: Convert static method invocation to extension method call
StringExtensions.DoSomething(myString);
myString.DoSomething();
Merge and Pattern
Description: Merge 'and' pattern
if (x is >= 1 && x is <= 10) { /* ... */ }
if (x is >= 1 and <= 10) { /* ... */ }
Merge Conditional Expression
Description: Merge conditional ?: expression into conditional access (when possible)
var result = condition ? obj.Property : null;
var result = obj?.Property;
Merge into Pattern
Description: Merge null/pattern checks into complex pattern
if (value != null && value is int) { /* ... */ }
if (value is not null and int) { /* ... */ }
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) { /* ... */ }
Prefer Conditional Ternary Expression
Description: Replace ternary expression with 'switch' expression
result = condition ? 'A' : 'B';
result = condition switch { true => 'A', false => 'B' };
Prefer Null Coalescing Expression
Description: 'if' statement can be re-written as '??' expression
if (value == null) { value = defaultValue; }
value ??= defaultValue;
Prefer Short Form
Description: Convert 'Nullable<T>' to 'T?'
Nullable<int> number = 5;
int? number = 5;
Use Await Using
Description: Convert to 'await using' statement or declaration
using (var resource = await GetResourceAsync()) { /* ... */ }
await using var resource = await GetResourceAsync();
Use Index from End Expression
Description: Use index from end expression
var last = array[array.Length - 1];
var last = array[^1];
Use Name Of Expression
Description: Use 'nameof' expression to reference name
throw new ArgumentException("parameterName");
throw new ArgumentException(nameof(parameterName));
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 String Interpolation
Description: Use string interpolation expression
string result = string.Format("Hello, {0}", name);
string result = $"Hello, {name}";
Potential Code Quality Issues
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));
Assignment in Conditional Expression
Description: Assignment in conditional expression
if ((value = GetValue()) != null) { /* ... */ }
value = GetValue(); if (value != null) { /* ... */ }
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); }
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
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;
Collection Count Property
Description: Use collection's count property
if (list.Length > 0) { /* do something */ }
if (list.Count > 0) { /* do something */ }
Conditional Ternary Equal Branch
Description: '?:' expression has identical true and false branches
var result = condition ? value : value;
var result = value;
Empty Catch Clause
Description: Empty general catch clause
try { /* code */ } catch { /* Empty catch block */ }
try { /* code */ } catch (Exception ex) { Console.WriteLine(ex.Message); }
Equal Expression Comparison
Description: Similar expressions comparison
if (a == a) { /* always true */ }
if (a == b) { /* logic */ }
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); }
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 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; }
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()) { /* ... */ } }
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
Inconsistently Synchronized Field
Description: Inconsistent synchronization on field
lock (lockObject) { field++; } // Field accessed without lock elsewhere
lock (lockObject) { field++; } // Always accessed within lock
Inheritdoc Invalid Usage
Description: Usage of <inheritdoc /> is invalid.
<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
Iterator Method Result Ignored
Description: Return value of iterator is not used
GetItems(); // Result ignored
foreach (var item in GetItems()) { /* process item */ }
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 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; }
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 */ }
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(); }
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
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
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
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
Possible Intended Rethrow
Description: Exception rethrow possibly intended
catch (Exception ex) { throw ex; }
catch (Exception) { throw; } // Maintain stack trace
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 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 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 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 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
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
Property not Resolved
Description: Cannot resolve property
Console.WriteLine(nonExistentProperty);
Console.WriteLine(existingProperty);
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
Simplify String Interpolation
Description: Use format specifier in interpolated strings
string result = $"Value: {value}";
string result = $"Value: {value:F2}"; // Use format specifier for precision
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; }
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
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
Useless Binary Operation
Description: Useless binary operation.
int result = x * 1; // Multiplication by 1 is redundant
int result = x; // Simplified without useless operation
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
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
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
Redundancies in Code
Assignment Fully Discarded
Description: Assignment results are fully discarded
value = 10; // Assignment result is never used
// Remove or refactor assignment if not used
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
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 Bool Compare
Description: Redundant boolean comparison
if (isTrue == true) { /* code */ }
if (isTrue) { /* code */ } // Simplify boolean comparison
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 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 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 Enumerable Cast Call
Description: Redundant 'IEnumerable.Cast<T>' or 'IEnumerable.OfType<T>' 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 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 Match Subpattern
Description: Redundant always match subpattern
if (x is int _) { ... } // Redundant subpattern match
if (x is int) { ... } // Removed unnecessary subpattern
Redundant Name Qualifier
Description: Redundant name qualifier
System.Console.WriteLine("Hello"); // Redundant System qualifier
Console.WriteLine("Hello"); // Removed redundant qualifier
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 Record Body
Description: Redundant 'record' type declaration body
record Person { }
record Person; // Use record declaration without body if no additional members are defined
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 x = "hello";
var x = "hello"; // This is already the default
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 Unsafe Context
Description: Unsafe context declaration is redundant
unsafe { int* p = &value; } // Redundant unsafe context
int* p = &value; // Removed unnecessary 'unsafe' block
Redundancies in Symbol Declarations
Compiler Unused Local Function
Description: Compiler: local function is never used
void UnusedFunction() { /* some code */ }
// Remove or use the local function if necessary
Empty Constructor
Description: Empty constructor
public MyClass() { } // Constructor is empty
// Removed empty constructor
Empty Namespace
Description: Empty namespace declaration
namespace MyNamespace { } // Namespace is empty
// Removed empty namespace 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
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
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
Redundant Constructor Call
Description: Redundant base constructor call
public Child() : base() { }
// Remove the base constructor call if it's redundant
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 Member Initializer
Description: Redundant default member initializer
private int value = 0; // '0' is default for int
private int value; // Default initialization
Redundant Overridden Member
Description: Redundant member override
public override void Method() { base.Method(); }
// Remove the redundant override if it only calls base implementation
Unused Local Function
Description: Local function is never used
void UnusedFunction() { } // Local function is never called
// Removed unused local function
Unused Local Variable
Description: Unused local variable
int unusedValue = 10;
// Remove 'unusedValue' if not used in the code
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 Private Accessibility
Description: Type member is never used (private accessibility)
private string unusedString;
// Remove or use the member if necessary within the code
Unused Parameter Private Accessibility
Description: Unused parameter (private accessibility)
private void Helper(int unusedParam) { }
// Remove 'unusedParam' if not needed in 'Helper'
Unused Type Parameter
Description: Unused type parameter
public class 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)
public int X { get { return _x; } }
public int X { get => _x; }
Modifiers Order
Description: Adjust modifiers declaration order
static public void M() { }
public static void M() { }
Object Creation Evident Type
Description: Use preferred style of 'new' expression when created type is evident
MyClass obj = new MyClass();
MyClass obj = new();
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);
Uncategorized / Custom
Assign To Not Null Attribute
Description: Source file: assign-null-to-not-null-attribute.js
[NotNull] string value = null;
[NotNull] string value = "hello";
Attribute Modifier Invalid Location
Description: Source file: attribute-modifier-invalid-location.js
[Obsolete] int x;
[field: Obsolete] int x;
Class Never Instantiated
Description: Source file: class-never-instantiated.js
class MyClass { public void M() { } }
// Remove unused class or add instantiation logic
Class With Virtual Members Never Inherited
Description: Source file: class-with-virtual-members-never-inherited.global.js
sealed class C { public virtual void M() { } }
sealed class C { public void M() { } }
Collection Never Queried
Description: Source file: collection-never-queried.global.js
var list = new List<int> { 1, 2, 3 };
list.Add(4);
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
var list = new List<int> { 1, 2, 3 };
foreach (var item in list) { Console.WriteLine(item); }
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
string s = MaybeNull(); if (s != null) { Console.WriteLine(s.Length); }
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
string s = "hello"; int? len = s?.Length;
string s = "hello"; int len = s.Length;
Convert Auto Property When Possible
Description: Source file: convert-auto-property-when-possible.js
private int _x;
public int X { get { return _x; } set { _x = value; } }
public int X { get; set; }
Convert If To Null Coalescing Assignment
Description: Source file: convert-if-statement-to-null-coalescing-assignment.js
if (x == null) { x = y; }
x ??= y;
Covariant Array Conversion
Description: Source file: covariant-array-conversion.js
string[] strings = { "a" };
object[] objs = strings;
objs[0] = 5; // runtime error
string[] strings = { "a" };
// Use List<object> instead
Csharp Warnings Cs1717
Description: Source file: assign-to-the-same-variable.js
int x; x = x; // assigned to itself
int x = GetValue();
Cyclomatic Complexity
Description: Source file: cyclomatic-complexity.js
if (a) { if (b) { if (c) { if (d) { } } } }
// Refactor into smaller methods to reduce complexity
Default Value Evident Type
Description: Source file: default-value-evident-type.js
int x = 0; bool b = false;
int x; bool b;
Event Never Subscribed To
Description: Source file: event-never-subscribed-to.global.js
public event EventHandler MyEvent;
public void Raise() { MyEvent?.Invoke(this, EventArgs.Empty); }
// Remove unused event or ensure subscribers are attached
Field Can Be Made Readonly
Description: Source file: field-can-be-made-read-only.local.js
class C { private int _x;
public C() { _x = 5; }
public int X => _x; }
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
int _x; void Init() { _x = 5; }
readonly int _x; void Init() { _x = 5; }
Guid.Empty
Description: Source file: unassigned-field.global.js
if (id == new Guid()) { }
if (id == Guid.Empty) { }
Introduce Optional Parameters
Description: Source file: introduce-optional-parameters.js
void M(int x) { }
void Caller() { M(42); }
void M(int x = 42) { }
void Caller() { M(); }
Invalid Attribute Modifier Specified
Description: Source file: invalid-attribute-modifier-specified.js
[Obsolete]
public string Name { get; set; }
[Obsolete("Use NewName instead")]
public string Name { get; set; }
Linq Expression Use Any
Description: Source file: linq-expression-use-any.js
if (list.Count() > 0) { }
if (list.Any()) { }
Loop Variable Never Changes
Description: Source file: loop-variable-never-changes.js
for (int i = 0; i < 10; i++) { if (i == 5) { i = 0; } }
for (int i = 0; i < 10; i++) { }
Member Can Be Private
Description: Source file: member-can-be-private.local.js
class C { public int X; }
class C { private int X; }
Member Can Be Protected
Description: Source file: member-can-be-protected.global.js
class C { public void M() { } }
class C { protected void M() { } }
Not Accessed Positional Property
Description: Source file: not-accessed-positional-library.global.js
var (x, _) = GetValues();
var (x, y) = GetValues(); Console.WriteLine(y);
Null Check Assignment
Description: Source file: null-check-assignment.js
if (x == null) { x = new Foo(); }
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
string s = GetNonNull(); string r = s ?? "default";
string s = GetNonNull(); string r = s;
Operator Used
Description: Source file: operator-used.js
if (x != null && x.Value > 0) { }
if (x?.Value > 0) { }
Parameter Type Can Be Enumerable
Description: Source file: parameter-type-can-be-enumerable.js
void M(List<int> items) { foreach (var i in items) { } }
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
struct Point { public int X; }
GetPoint().X = 5;
var p = GetPoint(); p.X = 5;
Prefer While Expression
Description: Source file: prefer-while-expression.js
while (true) { if (cond) { break; } body; }
while (cond) { body; }
Property Can Be Made Init Only
Description: Source file: property-can-be-made-init-only.js
public int X { get; set; }
public int X { get; init; }
Redundant Anonymous Property Name
Description: Source file: redundant-anonymous-property-name.js
new { Name = Name, Age = Age }
new { Name, Age }
Redundant Discard
Description: Source file: redundant-discard.js
_ = SomeMethod();
SomeMethod();
Redundant Explicit Tuple Name
Description: Source file: redundant-explicit-tuple-name.js
(int x, int y) = (1, 2); // explicit names
(int, int) = (1, 2);
Redundant Private Accessibility
Description: Source file: redundant-private-accesibility.js
class C { private int _x; }
class C { int _x; }
Redundant Suppress Nullable Warning
Description: Source file: redundant-suppress-nullable-warning-expression.js
string s = null!;
string? s = null;
Redundant Tostring Call
Description: Source file: redundant-to-string-call.js
$"Hello {name.ToString()}"
$"Hello {name}"
Safe Cast For Type Check
Description: Source file: safe-cast-for-type-check.js
if (o is MyType) { var m = (MyType)o; }
if (o is MyType m) { }
Sealed Member
Description: Source file: sealed-member.js
class C { public virtual void M() { } }
class C { public void M() { } }
Simplify Conditional Ternary
Description: Source file: simplify-conditional-ternary-expression.js
var x = cond ? true : false;
var x = cond;
Specify Culture In String Conversion
Description: Source file: specify-a-culture-in-string-conversion-explicitly.js
int.Parse("42");
int.Parse("42", CultureInfo.InvariantCulture);
Static Member Initializer References Member Below
Description: Source file: static-member-initializer-referes-to-member-below.js
class C { public static int A = B; public static int B = 5; }
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
string.Compare(a, b);
string.Compare(a, b, StringComparison.Ordinal);
String Indexof Is Culture Specific 3
Description: Source file: string-index-of-is-culture-specific.js
str.IndexOf("test");
str.IndexOf("test", StringComparison.Ordinal);
String Last Index Of Is Culture Specific
Description: Source file: string-last-index-of-is-culture-specific.js
str.LastIndexOf("test");
str.LastIndexOf("test", StringComparison.Ordinal);
Structured Message Template
Description: Source file: structured-message-template.js
Log.Info("User " + name + " logged in");
Log.Info("User {Name} logged in", name);
Suspicious Parameter Name
Description: Source file: suspicious-parameter-name.js
void M(int value) { Console.WriteLine(count); }
void M(int value) { Console.WriteLine(value); }
Unreachable Switch Case
Description: Source file: unreachable-switch-case.js
switch (x) { case 1: return; case 2: break; case 1: return; }
switch (x) { case 1: return; case 2: break; }
Unused Member Hierarchy
Description: Source file: unused-member-hierarchy.global.js
class Base { public virtual void M() { } }
class Derived : Base { public override void M() { } }
class Base { public virtual void M() { } }
class Derived : Base { }
Unused Positional Parameter
Description: Source file: unused-positional-parameter.js
void M(int x, int y) { Console.WriteLine(x); }
void M(int x) { Console.WriteLine(x); }
Use Compound Assignment
Description: Source file: use-compound-assignment.js
x = x + 5;
x += 5;
Use Method Any
Description: Source file: use-method-any.js
if (list.Where(x => x > 0).Count() > 0) { }
if (list.Any(x => x > 0)) { }
Use Name Instead Of Type Of
Description: Source file: use-name-instead-of-type-of.js
nameof(C); // C is a type
nameof(C); // C is the type name, this is correct
Xml Comment Ambiguous Reference
Description: Source file: xml-comment-ambiguous-reference.js
/// <see cref=\"M\"/>
/// <see cref=\"M()\"/>


