Rule Description Example KPI
AbstractClassShouldNotHavePublicConstructors Abstract class should not have public constructors // Cause:
//Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type,
//and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed.

 

 

 

 

 

 

//Example For Issue Occurrence:

public abstract class Book
{
public Book()
{
}
}

//CODE FIX:

public abstract class Book
{
protected Book()
{
}
}

//To fix a violation of this rule, either make the constructor protected or do not declare the type as abstract.

Understandability
AccessModifierMustBeDeclared The access modifier for a C# element has not been explicitly defined // Cause:
//The access modifier for a C# element has not been explicitly defined.

 

 

 

 

 

 

//C# allows elements to be defined without an access modifier. Depending upon the type of element, C# will automatically
//assign an access level to the element in this case. This rule requires an access modifier to be explicitly defined for
//every element.This removes the need for the reader to make assumptions about the code, improving the readability of the code.

Understandability
CallExtensionMethodAsExtension Consider simplifying a call to some static methods by using their Extension method implementation. //Example For Issue Occurrence:

 

 

 

 

 

 

public void DoThis()
{
var source = new int[] { 100, 102, 104 };
Enumerable.Any(source, x => x > 100);
}

//CODE FIX:

public void DoThis()
{
var source = new int[] { 100, 102, 104 };
source.Any(x => x > 100);
}

Understandability
ChangeForExpressionValue Change an expression for its value if the expression is made of literal values //Example For Issue Occurrence:

 

 

 

 

 

 

var minutes = 24 * 60;

//CODE FIX:

var minutes = 1440;

//If the expression is made up of literal values an additional computation cycle is introduced to calculate the final value hence it is better to use the //final value directly thereby reducing the computational cost of the given expression.

Understandability
CodeMustNotContainSpaceAfterNewKeywordInImplicitlyTypedArrayAllocation An implicitly typed new array allocation within a C# code file is not spaced correctly // Cause:
//A violation of this rule occurs whenever the code contains an implicitly typed new array allocation which is not
//spaced correctly. Within an implicitly typed new array allocation, there should not be any space between the new
//keyword and the opening array bracket.

 

 

 

 

 

 

//Example For Issue Occurrence:

var test = new[] { 1, 2, 3, 4};

//To fix a violation of this rule, remove any whitespace between the new keyword and the opening array bracket.

Understandability
ComplexFieldsMustBeReadonly Consider making this field readonly // Cause:
//Fields of reference type objects should be made readonly.
//Example For Issue Occurrence:

 

 

 

 

 

 

private System.DateTime d = new System.DateTime(1);

//CODE FIX:

private readonly System.DateTime d = new System.DateTime(1);

Robustness
IncorrectStringFormatUsage The format argument in String.Format determines the number of other arguments that need to be passed into the method based on the number of curly braces used. Consider checking the arguments are being passed.   Accuracy
InterfaceNamesMustBeginWithI The name of an interface must begin with the capital letter I // Cause:
//A violation of this rule occurs when the name of an interface does not begin with the capital letter I.
//Interface names should always begin with I.For example, ICustomer.

 

 

 

 

 

 

//To fix a violation of this rule, add the capital letter I to the front of the interface name.

Understandability
InvalidArgumentName The argument passed to ArgumentException constructor must be the name of one of the method arguments. It can be either specified directly or using the nameof() operator (C#6 only) // Cause:
//The string passed as the ‘paramName’ argument of ArgumentException constructor must be the name of one of the
//method arguments. It can be either specified directly or using the nameof() operator (C#6 only)

 

 

 

 

 

 

//Example For Issue Occurrence:
public async Task DoThis(int x, int y)
{
throw new ArgumentException(“message”, “c”);
}

//CODE FIX:
public async Task DoThis(int x, int y)
{
throw new ArgumentException(“message”, “x”);
}

Maintainability
NameOfOperatorAnalyzer The nameof() operator should be used to specify the name of a program element instead of a string literal as it produces code that is easier to refactor //Example For Issue Occurrence:

 

 

 

 

 

 

void Class1(string example)
{
var test = “example”;
}

//CODE FIX:

void Class1(string example)
{
var test = nameof(example);
}

Maintainability
PartialElementsMustDeclareAccess The partial element does not have an access modifier defined. // Cause:
//A violation of this rule occurs when the partial class or a partial method does not have an access modifier defined.

 

 

 

 

 

 

//To fix an instance of this violation, specify an access modifier for the partial element.

Understandability
ProtectedMustComeBeforeInternal The keyword ‘protected’ is positioned after the keyword ‘internal’ within the declaration of a protected internal C# element to improve readability // Cause:
//The keyword protected is positioned after the keyword internal within the declaration of a protected internal C# element.

 

 

 

 

 

 

//To make the code easier to read and more consistent, standardizing the ordering of these keywords is helpful, so that a
//protected internal element will always be described as such, and never as internal protected. This can help to reduce
//confusion about whether these access levels are indeed the same.

Understandability
RemoveLambdaExprForMethodWithSameSignature The extra unnecessary layer of indirection induced by the lambda expression can be avoided by passing the method group instead. //Example For Issue Occurrence:

 

 

 

 

 

 

var test = a.Where(item => filter(item));

//CODE FIX:

var test = a.Where(filter);

//In the above example the method can be directly passed as the condition and thereby an unnecessary layer of introducing the simple lambda expression //can be avoided. This in turn will reduce the computational cost of the entire expression.

Efficiency
RemoveRedundantElse An empty else clause only adds complexity. You may safely remove it. // Cause:
//Certain if-else conditions can safely have their else clause removed. Only use an else segment if you want a mutually exclusive logical branch in the //program’s execution. There’s no need to use an explicit else, it just adds to the length of the code.

 

 

 

 

 

 

//Example For Issue Occurrence:

if (true)
{
//some statement (not a comment)
}
else
{
}

//CODE FIX:

if (true)
{
//some statement (not a comment)
}

Efficiency
RemoveTheWhereInvocationWhenItIsPossible Use linq operator that supports a predicate parameter instead of using ‘where’ followed by the operator // Cause:
//When a linq operator supports a predicate parameter, it should be used instead of using ‘Where’ followed by the operator

 

 

 

 

 

 

//Example For Issue Occurrence:

var a = new int[10];
var f = a.Where(item => item > 10).First();

//CODE FIX:

var a = new int[10];
var f = a.First(item => item > 10)

Efficiency
ReturnConditionDirectly Using an if/else statement to return a boolean can be avoided by directly returning a boolean. // Cause:
//Using an if/else to return true/false depending on the condition isn’t useful, as the condition is already
//a boolean it can be returned directly.

 

 

 

 

 

 

//Example For Issue Occurrence:

private bool CheckAll()
{
if ( ….)
{
return true;
}
return false;
}

//CODE FIX:

private bool CheckAll()
{
return (your_condition);
}

Maintainability
ReturnInterfacesToCollections Return an IEnumerable or ICollection instead of a concrete collection class. //Example For Issue Occurrence:

 

 

 

 

 

 

List M()
{
throw new NotImplementedException();
}

//CODE FIX:

ICollection M()
{
throw new NotImplementedException();
}

Robustness
SetPropertyShouldBePrivate Use private set for automatic properties // Cause:
//A property with a private set; can be set from everywhere inside that class.
Maintainability
ShouldDisposeObject When a disposable object is created it should be disposed as soon as possible. This warning will appear if you create a disposable object and don’t store, return or dispose it //Example For Issue Occurrence:

 

 

 

 

 

 

void Test()
{
var t = new MemoryStream();
//other statements
}

//CODE FIX:

void Test()
{
using (var t = new MemoryStream())
{
//other statements
}
}

Resource Utilization
SimplifyExpression This expression can be more simplified //Example For Issue Occurrence:

 

 

 

 

 

 

bool foo= true;
if(foo!=true)
{
//
}

//CODE FIX:

bool foo= true;
if(!foo)
{
//
}

Maintainability
TerminateAsyncMethodWithAsyncKeyword Asynchronous method name should end with ‘Async’ //Example For Issue Occurrence:

 

 

 

 

 

 

public static async Task Foo()
{
return await Task.FromResult(false);
}

//CODE FIX:

public static async Task FooAsync()
{
return await Task.FromResult(false);
}

Understandability
UnnecessaryParenthesis Statement must not use unnecessary parenthesis // Cause:
//There is no need to specify that the no-parameter constructor is used with an initializer as it is implicit

 

 

 

 

 

 

//Example For Issue Occurrence:

var t = new Test() { X = 1 };

//CODE FIX:

var t = new Test { X = 1 };

Understandability
UnnecessaryToStringCallInStringConcatenation The runtime automatically calls ‘ToString()’ for string concatenation when there is no parameter. Consider removing it. //Example For Issue Occurrence:

 

 

 

 

 

 

string x = s.ToString();

//CODE FIX:

string x = s;

Understandability
UnusedMethod Unused private methods can be safely removed as they are unnecessary // Cause:
//Removes a private method that is not in use.

 

 

 

 

 

 

//Example For Issue Occurrence:

public class MyClass
{
private int field;

public MyClass() { }

private void MyMethod()
{
field = 1;
}
}

//CODE FIX:

public class MyClass
{
private int field;

public MyClass() { }
}

Maintainability
UnusedParameters A method with an unused parameter creates unnecessary confusion and should be deleted. // Cause:
//When a method declares a parameter and does not use it might bring incorrect conclusions for anyone reading the
//code and also demands the parameter when the method is called, unnecessarily.

 

 

 

 

 

 

//Example For Issue Occurrence:

public static void Method1(string name)
{
}

//CODE FIX:

public static void Method1()
{
}

Understandability
UseExpressionBodiedMembersWheneverPossible Usage of an expression bodied members improves readability of the code //Example For Issue Occurrence:

 

 

 

 

 

 

public override string ToString()
{
return this.Name;
}

//CODE FIX:

public override string ToString() => this.Name;

Understandability
UseForeach for loop can be converted into foreach loop // Cause:
//Foreach loop should be used when iterating through a collection that implements IEnumerable.

 

 

 

 

 

 

//Example For Issue Occurrence:

int[] ints = new int[100000];
int j;
for (int i = 0; i < 100000; i++) { j = ints[i]; } //CODE FIX: int[] ints = new int[100000]; int j; foreach(int i in ints) { j = i; }

Understandability
UseLambdaSyntax Lambda expressions are more succinct and easier to read than anonymous methods so they should/are preferred whenever the two are functionally equivalent. //Example For Issue Occurrence:

 

 

 

 

 

 

var x = items.Select(delegate (object f)
{
return f.ToString();
});

//CODE FIX:

var x = items.Select((object f) =>
{
return f.ToString();
});

Understandability
UseObjectInitializer When possible an object initializer should be used to initialize the properties of an object instead of multiple assignments. //Example For Issue Occurrence:

 

 

 

 

 

 

Code c;
c = new Code();
c.Language = “CSharp”;
c.Loc = 1105;

//CODE FIX:

Code c;
c = new Code()
{
Language = “CSharp”,
Loc = 1105
};

Maintainability
UseReadableConditions When a comparison is made between a variable and a literal the variable should be placed on the left hand side to maximize readability. //Example For Issue Occurrence:

 

 

 

 

 

 

public void Method(string value)
{
if (null == value)
{
//some code
}
}

//CODE FIX:

public void Method(string value)
{
if (value == null)
{
//some code
}
}

Understandability
UseStringEmpty Consider using ‘String.Empty’ instead of “” // Cause:
//This will cause the compiler to embed an empty string into the compiled code. Rather than including
//a hard-coded empty string, use the static string.Empty property

 

 

 

 

 

 

//Example For Issue Occurrence:

string s = “”;

//CODE FIX:

string s = string.Empty;

Understandability
UseStringInterpolationInsteadOfStringFormat String interpolation allows for better reading of the resulting string when compared to String.Format. You should use String.Format only when another method is supplying the format string. //Example For Issue Occurrence:

 

 

 

 

 

 

decimal pricePerOunce = 17.36m;
string s = string.Format(“The current price is {0} per ounce.”,
pricePerOunce);

//CODE FIX:

decimal pricePerOunce = 17.36m;
string s = $”The current price is {pricePerOunce} per ounce.”;

Understandability
UseTernaryOperator Consider using ternary operator instead of if else when dealing with direct value comparisons and assignments // Cause:
//If-else statements can be changed to ternary operators.

 

 

 

 

 

 

//Example For Issue Occurrence:

var result = true;
if (result)
return 1;
else
return 2;

//CODE FIX:

var result = true;
return result? 1 : 2;

Understandability
VerbatimString Change to verbatim string // Cause:
//A regular string can be converted into a verbatim string. A verbatim means that special chars don’t need to be escaped and thereby it reduces the //overhead to explicitly escape the control characters in the sting.

 

 

 

 

 

 

//Example For Issue Occurrence:

var str = “c:TestFolder”;

//CODE FIX:

var str = @”c:TestFolder”;

Accuracy