> ## Documentation Index
> Fetch the complete documentation index at: https://docs.codeant.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# C #

<AccordionGroup>
  <Accordion title="Jump statements should not be redundant">
    <div class="paragraph">
      <p>Jump statements, such as <code>return, yield break, goto, and continue</code> let you change the default flow of program execution, but jump statements that direct the control flow to the original direction are just a waste of keystrokes.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      void Foo()
      {
      goto A; // Noncompliant
      A:
      while (condition1)
      {
      if (condition2)
      {
        continue; // Noncompliant
      }
      else
      {
        DoTheThing();
      }
      }
      return; // Noncompliant; this is a void method
      }
      ```

      ```csharp Fix theme={null}
      void Foo()
      {
      while (condition1)
      {
      if (!condition2)
      {
        DoTheThing();
      }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Invalid casts should be avoided">
    <div class="paragraph">
      <p>A cast is an <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions#explicit-conversions">explicit conversion</a>, which is a way to tell the compiler the intent to convert from one type to another.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      void Method(object value)
      {
      int i;
      i = (int)value;   // Casting (explicit conversion) from float to int
      }
      ```

      ```csharp Fix theme={null}
      public interface IMyInterface
      { /* ... */ }

      public class Implementer : IMyInterface
      { /* ... */ }

      public class AnotherClass
      { /* ... */ }

      public static class Program
      {
      public static void Main()
      {
      var another = new AnotherClass();
      var x = (IMyInterface)another;     // Noncompliant: InvalidCastException is being thrown
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Classes implementing IEquatable<T> should be sealed">
    <div class="paragraph">
      <p>When a class implements the IEquatable\<T> interface, it enters a contract that, in effect, states "I know how to compare two instances of type T or any type derived from T for equality.". However if that class is derived, it is very unlikely that the base class will know how to make a meaningful comparison. Therefore that implicit contract is now broken.</p>
    </div>

    <div class="paragraph">
      <p>Alternatively IEqualityComparer\<T> provides a safer interface and is used by collections or Equals could be made virtual.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when an unsealed, public or protected class implements IEquatable\<T> and the Equals is neither virtual nor abstract.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      namespace MyLibrary
      {
      public class Base : IEquatable<Base> // Noncompliant
      {
      public bool Equals(Base other) 
      {
        if (other == null) { return false; }
        // do comparison of base properties
        return true;
      }

      public override bool Equals(object other)  => Equals(other as Base);
      }

      class A : Base 
      {
      public bool Equals(A other) 
      {
        if (other == null) { return false; }
        // do comparison of A properties
        return base.Equals(other);
      }

      public override bool Equals(object other)  => Equals(other as A); 
      }

      class B : Base 
      {
      public bool Equals(B other) 
      {
        if (other == null) { return false; }
        // do comparison of B properties
        return base.Equals(other); 
      }

      public override bool Equals(object other)  => Equals(other as B);
      }

      internal class Program
      {
      static void Main(string[] args)
      {
          A a = new A();
          B b = new B();
           Console.WriteLine(a.Equals(b)); // This calls the WRONG equals. This causes Base.Equals(Base)
                                           // to be called which only compares the properties in Base and ignores the fact that 
                                           // a and b are different types. In the working example A.Equals(Object) would have been 
                                           // called and Equals would return false because it correctly recognizes that a and b are 
                                           // different types. If a and b have the same base properties they will be returned as equal. 
      }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;

      namespace MyLibrary
      {
      public sealed class Foo : IEquatable<Foo>
      {
          public bool Equals(Foo other) 
          {
              // Your code here        
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Caller information parameters should come at the end of the parameter list">
    <div class="paragraph">
      <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/caller-information">Caller information attributes</a> provide a way to get information about the caller of a method through <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments#optional-arguments">optional</a> parameters. But they only work right if their values aren’t provided explicitly. So if you define a method with caller info attributes in the middle of the parameter list, the caller is forced to use named arguments if they want to use the method properly.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when the following attributes are used on parameters before the end of the parameter list:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callerfilepathattribute">CallerFilePathAttribute</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callerlinenumberattribute">CallerLineNumberAttribute</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute">CallerMemberNameAttribute</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callerargumentexpressionattribute">CallerArgumentExpressionAttribute</a></p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      void TraceMessage([CallerMemberName] string memberName = "",
      [CallerFilePath] string filePath = "",
      [CallerLineNumber] int lineNumber = 0,
      string message = null)  // Noncompliant: decorated parameters appear before "message" parameter
      {
      /* ... */
      }
      ```

      ```csharp Fix theme={null}
      void TraceMessage(string message = null,
      [CallerMemberName] string memberName = "",
      [CallerFilePath] string filePath = "",
      [CallerLineNumber] int lineNumber = 0)
      {
      /* ... */
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="out and ref parameters should not be used">
    <div class="paragraph">
      <p>Passing a parameter by reference, which is what happens when you use the \`out or ref parameter modifiers, means that the method will receive a pointer to the argument, rather than the argument itself. If the argument was a value type, the method will be able to change the argument’s values. If it was a reference type, then the method receives a pointer to a pointer, which is usually not what was intended. Even when it is what was intended, this is the sort of thing that’s difficult to get right, and should be used with caution.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when out or ref is used on a non-Optional parameter in a public method. Optional\` parameters are covered by S3447.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public void GetReply(
           ref MyClass input, // Noncompliant
           out string reply)  // Noncompliant
      { ... }
      ```

      ```csharp Fix theme={null}
      public string GetReply(MyClass input)
      { ... }

      public bool TryGetReply(MyClass input, out string reply)
      { ... }

      public ReplyData GetReply(MyClass input)
      { ... }

      internal void GetReply(ref MyClass input, out string reply) 
      { ... }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Start index should be used instead of calling Substring">
    <div class="paragraph">
      <p>It is important to be careful when searching for characters within a substring. Let’s consider the following example:</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if (str.SubString(startIndex).IndexOf(char1) == -1) // Noncompliant: a new string is going to be created by "Substring"
      {
      // ...
      }
      ```

      ```csharp Fix theme={null}
      if (str.IndexOf(char1, startIndex) == -1)           // Compliant: no new instance of string is created
      {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="main should not throw anything">
    <div class="paragraph">
      <p>There’s no reason for a \`Main method to throw anything. After all, what’s going to catch it?</p>
    </div>

    <div class="paragraph">
      <p>Instead, the method should itself gracefully handle any exceptions that may bubble up to it, attach as much contextual information as possible, and perform whatever logging or user communication is necessary, and Exit\` with a non-zero (i.e. non-success) exit code if necessary.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public static void Main(string[] args) { // Noncompliant
      if (args.Length == 0)
      {
      throw new ArgumentException();
      }
      // do stuff
      }
      ```

      ```csharp Fix theme={null}
      private const int ERROR_INVALID_COMMAND_LINE = 0x667;
      public static void Main(string[] args) { // Noncompliant
      if (args.Length == 0)
      {
      Console.WriteLine("Should provide at least one argument");
      Environment.ExitCode = ERROR_INVALID_COMMAND_LINE;  
      }
      // do stuff
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Base class methods should not be hidden">
    <div class="paragraph">
      <p>When a method in a derived class has:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>the same name as a method in the base class</p>
        </li>

        <li>
          <p>but types of parameters that are ancestors (for example string in the base class and object in the derived class)</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>the result is that the base method becomes hidden.</p>
    </div>

    <div class="paragraph">
      <p>As shown in the following code snippet, when an instance of the derived class is used, invoking the method with an argument that matches the less derived parameter type will invoke the derived class method instead of the base class method:</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      class BaseClass
      {
      internal void MyMethod(string str) => Console.WriteLine("BaseClass: Method(string)");
      }

      class DerivedClass : BaseClass
      {
      internal void MyMethod(object str) => Console.WriteLine("DerivedClass: Method(object)"); // Noncompliant
      }

      // ...
      BaseClass baseObj = new BaseClass();
      baseObj.MyMethod("Hello"); // Output: BaseClass: Method(string)

      DerivedClass derivedObj = new DerivedClass();
      derivedObj.MyMethod("Hello"); // Output: DerivedClass: Method(object) - DerivedClass method is hiding the BaseClass method

      BaseClass derivedAsBase = new DerivedClass();
      derivedAsBase.MyMethod("Hello"); // Output: BaseClass: Method(string)
      ```

      ```csharp Fix theme={null}
      class BaseClass
      {
      internal void MyMethod(string str) => Console.WriteLine("BaseClass: Method(string)");
      }

      class DerivedClass : BaseClass
      {
      internal void MyOtherMethod(object str) => Console.WriteLine("DerivedClass: Method(object)"); // Compliant
      }

      // ...
      BaseClass baseObj = new BaseClass();
      baseObj.MyMethod("Hello"); // Output: BaseClass: Method(string)

      DerivedClass derivedObj = new DerivedClass();
      derivedObj.MyMethod("Hello"); // Output: BaseClass: Method(string)

      BaseClass derivedAsBase = new DerivedClass();
      derivedAsBase.MyMethod("Hello"); // Output: BaseClass: Method(string)
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="NaN should not be used in comparisons">
    <div class="paragraph">
      <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.double.nan">double.NaN</a> and <a href="https://learn.microsoft.com/en-us/dotnet/api/system.single.nan">float.NaN</a> are not equal to anything, not even themselves.</p>
    </div>

    <div class="paragraph">
      <p>When anything is compared with NaN using one of the <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/comparison-operators">comparison operators</a> >, >=, \<, ⇐ or the <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/equality-operators#equality-operator-">equality operator</a> ==, the result will always be false. In contrast, when anything is compared with NaN using the <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/equality-operators#inequality-operator-">inequality operator</a> !=, the result will always be true.</p>
    </div>

    <div class="paragraph">
      <p>Instead, the best way to see whether a variable is equal to NaN is to use the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.single.isnan">float.IsNaN</a> and <a href="https://learn.microsoft.com/en-us/dotnet/api/system.double.isnan">double.IsNaN</a> methods, which work as expected.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      var a = double.NaN;

      if (a == double.NaN) // Noncompliant: always false
      {
      Console.WriteLine("a is not a number");
      }
      if (a != double.NaN)  // Noncompliant: always true
      {
      Console.WriteLine("a is not NaN");
      }
      ```

      ```csharp Fix theme={null}
      var a = double.NaN;

      if (double.IsNaN(a)) 
      {
      Console.WriteLine("a is not a number");
      }
      if (!double.IsNaN(a)) 
      {
      Console.WriteLine("a is not NaN");
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="ThreadStatic fields should not be initialized">
    <div class="paragraph">
      <p>When an object has a field annotated with <code>ThreadStatic</code>, that field is shared within a given thread, but unique across threads. Since a class' static initializer is only invoked for the first thread created, it also means that only the first thread will have the expected initial values.</p>
    </div>

    <div class="paragraph">
      <p>Instead, allow such fields to be initialized to their default values or make the initialization lazy.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Foo
      {
      [ThreadStatic]
      public static object PerThreadObject = new object(); // Noncompliant. Will be null in all the threads except the first one.
      }
      ```

      ```csharp Fix theme={null}
      public class Foo
      {
      [ThreadStatic]
      public static object _perThreadObject;
      public static object PerThreadObject 
      {
      get 
      {
        if (_perThreadObject == null) 
        {
          _perThreadObject = new object();
        }
        return _perThreadObject;
      }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Method calls should not resolve ambiguously to overloads with params">
    <div class="paragraph">
      <p>The rules for method resolution are complex and perhaps not properly understood by all coders. The \`params keyword can make method declarations overlap in non-obvious ways, so that slight changes in the argument types of an invocation can resolve to different methods.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when an invocation resolves to a method declaration with params, but could also resolve to another non-params\` method too.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class MyClass
      {
      private void Format(string a, params object[] b) { }

      private void Format(object a, object b, object c) { }
      }

      // ...
      MyClass myClass = new MyClass();

      myClass.Format("", null, null); // Noncompliant, resolves to the first Format with params, but was that intended?
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Arrays should not be created for params parameters">
    <div class="paragraph">
      <p>There’s no point in creating an array solely for the purpose of passing it to a params parameter. Simply pass the elements directly. They will be consolidated into an array automatically.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public void Base() 
      {
      Method(new string[] { "s1", "s2" }); // Noncompliant: unnecessary
      Method(new string[] { });            // Noncompliant
      Method(new string[12]);              // Compliant
      }

      public void Method(params string[] args)
      {
      // ...
      }
      ```

      ```csharp Fix theme={null}
      public void Base()
      {
      Method("s1", "s2");
      Method();
      Method(new string[12]);
      }

      public void Method(params string[] args)
      {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Redundant constructors and desctructors should not be declared">
    <div class="paragraph">
      <p>When only a single <code>public parameterless constructor is defined in a class, then that constructor can be removed because the compiler would generate it automatically. Similarly, empty static</code> constructors and empty destructors are also wasted keystrokes.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      class Sample
      { 
      public Sample() { } // Noncompliant
      static Sample() { }  // Noncompliant
      ~Sample() { } // Noncompliant

      ...
      }
      ```

      ```csharp Fix theme={null}
      class Sample
      { 
      ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Generic.List instances should not be part of public APIs">
    <div class="paragraph">
      <p>\`System.Collections.Generic.List\<T> is a generic collection that is designed for performance and not inheritance. For example, it does not contain virtual members that make it easier to change the behavior of an inherited class. That means that future attempts to expand the behavior will be spoiled because the extension points simply aren’t there. Instead, one of the following generic collections should be used:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>System.Collections.Generic.IEnumerable\<T></p>
        </li>

        <li>
          <p>System.Collections.Generic.IReadOnlyCollection\<T></p>
        </li>

        <li>
          <p>System.Collections.Generic.ICollection\<TKey></p>
        </li>

        <li>
          <p>System.Collections.Generic.IReadOnlyList\<T></p>
        </li>

        <li>
          <p>System.Collections.Generic.IList\<TKey></p>
        </li>

        <li>
          <p>System.Collections.ObjectModel.Collection\<T></p>
        </li>

        <li>
          <p>System.Collections.ObjectModel.ReadOnlyCollection\<T></p>
        </li>

        <li>
          <p>System.Collections.ObjectModel.KeyedCollection\<TKey, Titem></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue every time a System.Collections.Generic.List\<T>\` is exposed:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>As an externally visible member.</p>
        </li>

        <li>
          <p>As the return type of an externally visible method.</p>
        </li>

        <li>
          <p>As a parameter type of an an externally visible method.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      namespace Foo
      {
      public class Bar
      {
        public List<T> Method1(T arg) // Noncompliant
        {
             //...
        }
      }
      }
      ```

      ```csharp Fix theme={null}
      namespace Foo
      {
      public class Bar
      {
        public Collection<T> Method1(T arg)
        {
             //...
        }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Short-circuit logic should be used in boolean contexts">
    <div class="paragraph">
      <p><a href="https://en.wikipedia.org/wiki/Short-circuit_evaluation">Short-circuit evaluation</a> is an evaluation strategy for <a href="https://en.wikipedia.org/wiki/Logical_connective">Boolean operators</a>, that doesn’t evaluates the second argument of the operator if it is not needed to determine the result of the operation.</p>
    </div>

    <div class="paragraph">
      <p>C# provides logical operators that implement short-circuit evaluation: && and ||, as well as non-short-circuit versions: & and |. Unlike short-circuit operators, non-short-circuit ones evaluate both operands and afterwards perform the logical operation.</p>
    </div>

    <div class="paragraph">
      <p>For example false && FunctionCall() always results in false, even when FunctionCall invocation would raise an exception. Instead, false & FunctionCall() also evaluates FunctionCall(), and results in an exception if FunctionCall() invocation raises an exception.</p>
    </div>

    <div class="paragraph">
      <p>Similarly, true || FunctionCall() always results in true, no matter what the return value of FunctionCall() would be.</p>
    </div>

    <div class="paragraph">
      <p>The use of non-short-circuit logic in a boolean context is likely a mistake - one that could cause serious program errors as conditions are evaluated under the wrong circumstances.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if (GetTrue() | GetFalse()) // Noncompliant: both sides evaluated
      {
      }
      ```

      ```csharp Fix theme={null}
      if (GetTrue() || GetFalse()) // Compliant: short-circuit logic used
      {
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="SQL keywords should be delimited by whitespace">
    <div class="paragraph">
      <p>When concatenating strings, it is very easy to forget a whitespace.</p>
    </div>

    <div class="paragraph">
      <p>In some scenarios this might cause runtime errors, one of which is while creating an SQL query via concatenation:</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      string select = "SELECT p.FirstName, p.LastName, p.PhoneNumber" +
          "FROM Person as p" +    // Noncompliant: concatenation results in "p.PhoneNumberFROM"
          "WHERE p.Id = @Id";     // Noncompliant: concatenation results in "pWHERE"
      ```

      ```csharp Fix theme={null}
      string select = "SELECT p.FirstName, p.LastName, p.PhoneNumber" +
          " FROM Person as p" +
          " WHERE p.Id = @Id";
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="string.Create should be used instead of FormattableString">
    <div class="paragraph">
      <p>In order to produce a formatted string, both string.Create and either FormattableString.Invariant or FormattableString.CurrentCulture can be used. However, string.Create rents array buffers from ArrayPool\<char> making it more performant, as well as preventing unnecessary allocations and future stress on the Garbage Collector.</p>
    </div>

    <div class="paragraph">
      <p>This applies to .NET versions after .NET 6, when these string.Create overloads were introduced.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      string Interpolate(string value) =>
      FormattableString.Invariant($"Value: {value}");
      ```

      ```csharp Fix theme={null}
      string Interpolate(string value) =>
      FormattableString.CurrentCulture($"Value: {value}");
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Equals(Object) and GetHashCode() should be overridden in pairs">
    <div class="paragraph">
      <p>Suppose you override <a href="https://learn.microsoft.com/en-us/dotnet/api/system.object.equals">Object.Equals</a> in a type, you must also override <a href="https://learn.microsoft.com/en-us/dotnet/api/system.object.gethashcode">Object.GetHashCode</a>. If two objects are equal according to the Equals method, then calling GetHashCode on each of them must yield the same integer. If this is not the case, many collections, such as a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.hashtable">Hashtable</a> or a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2">Dictionary</a> won’t handle class instances correctly.</p>
    </div>

    <div class="paragraph">
      <p>In order to not have unpredictable behavior, Equals and GetHashCode should be either both inherited, or both overridden.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      class MyClass   // Noncompliant: should also override GetHashCode
      {
      public override bool Equals(object obj)
      {
          // ...
      }
      }
      ```

      ```csharp Fix theme={null}
      class MyClass
      {
      public override bool Equals(object obj)
      {
          // ...
      }

      public override int GetHashCode()
      {
          // ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="LINQ expressions should be simplified">
    <div class="paragraph">
      <p>In the interests of readability, code that can be simplified should be simplified. To that end, there are several ways <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ienumerable-1">IEnumerable</a> language integrated queries (LINQ) can be simplified.
      This not only improves readabilty but can also lead to improved performance.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public void Foo(IEnumerable<Vehicle> seq, List<int> list)
      {
      var result1 = seq.Select(x => x as Car).Any(x => x != null);               // Noncompliant; use OfType
      var result2 = seq.Select(x => x as Car).Any(x => x != null && x.HasOwner); // Noncompliant; use OfType before calling Any
      var result3 = seq.Where(x => x is Car).Select(x => x as Car);              // Noncompliant; use OfType
      var result4 = seq.Where(x => x is Car).Select(x => (Car)x);                // Noncompliant; use OfType
      var result5 = seq.Where(x => x.HasOwner).Any();                            // Noncompliant; use Any([predicate])

      var num = list.Count();                                                    // Noncompliant; use the Count property
      var arr = seq.ToList().ToArray();                                          // Noncompliant; ToList is not needed
      var count = seq.ToList().Count(x => x.HasOwner);                           // Noncompliant; ToList is not needed
      }
      ```

      ```csharp Fix theme={null}
      public void Foo(IEnumerable<Vehicle> seq, List<int> list)
      {
      var result1 = seq.OfType<Car>().Any();
      var result2 = seq.OfType<Car>().Any(x => x.HasOwner);
      var result3 = seq.OfType<Car>();
      var result4 = seq.OfType<Car>();
      var result5 = seq.Any(x => x.HasOwner);

      var num = list.Count;
      var arr = seq.ToArray();
      var count = seq.Count(x => x.HasOwner);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="params should be used instead of varargs">
    <div class="paragraph">
      <p>A method using the \`VarArgs calling convention is not Common Language Specification (CLS) compliant and might not be accessible across programming languages, while the params keyword works the same way and is CLS compliant.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a public or protected type contains a public or protected method that uses the VarArgs\` calling convention.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      namespace MyLibrary
      {
      public class Foo 
      {
          public void Bar(__arglist) // Noncompliant
          { 
              ArgIterator argumentIterator = new ArgIterator(__arglist);
              for(int i = 0; i < argumentIterator.GetRemainingCount(); i++) 
              { 
                  Console.WriteLine(
                      __refvalue(argumentIterator.GetNextArg(), string));
              } 
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;

      [assembly: CLSCompliant(true)]
      namespace MyLibrary
      {
      public class Foo 
      {
          public void Bar(params string[] wordList)
          { 
              for(int i = 0; i < wordList.Length; i++) 
              { 
                  Console.WriteLine(wordList[i]);
              } 
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Collections should implement the generic interface">
    <div class="paragraph">
      <p>The NET Framework 2.0 introduced the generic interface \`System.Collections.Generic.IEnumerable\<T> and it should be preferred over the older, non generic, interfaces.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a public type implements System.Collections.IEnumerable\`.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;
      using System.Collections;

      public class MyData
      {
      public MyData()
      {
      }
      }

      public class MyList : CollectionBase // Noncompliant
      {
      public void Add(MyData data)
      {
      InnerList.Add(data);
      }

      // ...
      }
      ```

      ```csharp Fix theme={null}
      using System;
      using System.Collections.ObjectModel;

      public class MyData
      {
      public MyData()
      {
      }
      }

      public class MyList : Collection<MyData>
      {
      // Implementation...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Results of integer division should not be assigned to floating point variables">
    <div class="paragraph">
      <p>When division is performed on <code>ints, the result will always be an int. You can assign that result to a double, float or decimal with automatic type conversion, but having started as an int, the result will likely not be what you expect. If the result of int</code> division is assigned to a floating-point variable, precision will have been lost before the assignment. Instead, at least one operand should be cast or promoted to the final type before the operation takes place.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      static void Main()
      {
      decimal dec = 3/2; // Noncompliant
      Method(3/2); // Noncompliant
      }

      static void Method(float f) { }
      ```

      ```csharp Fix theme={null}
      static void Main()
      {
      decimal dec = (decimal)3/2;
      Method(3.0F/2);
      }

      static void Method(float f) { }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Method overloads with default parameter values should not overlap">
    <div class="paragraph">
      <p>The rules for method resolution can be complex and may not be fully understood by all developers.
      The situation becomes even more challenging when dealing with method overloads that have optional parameter values.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when an overload with default parameter values is hidden by another overload that does not have the optional parameters.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      MyClass.Print(1);  // which overload of Print will be called?

      public static class MyClass
      {
      public static void Print(int number) { } 
      public static void Print(int number, string delimiter = "\n") { } // Noncompliant, default parameter value is hidden by overload
      }
      ```

      ```csharp Fix theme={null}
      MyClass.Print(1);  // which overload of Print will be called?

      public static class MyClass
      {
      public static void Print(int number) { } 
      public static void Print(int number, string delimiter = "\n") { } // Noncompliant: default parameter value is hidden by overload
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Blocks should be synchronized on read-only fields">
    <div class="paragraph">
      <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/lock">Locking</a> on a class field synchronizes not on the field itself, but on the object assigned to it. Thus, there are some good practices to follow to avoid problems related to <a href="https://learn.microsoft.com/en-us/dotnet/standard/threading/threads-and-threading">thread</a> synchronization.</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Locking on a non-readonly field makes it possible for the field’s value to change while a thread is in the code block, locked on the old value. This allows another thread to lock on the new value and access the same block concurrently.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      private Color color = new Color("red");
      private void DoSomething()
      {
      // Synchronizing access via "color"
      lock (color) // Noncompliant: lock is actually on object instance "red" referred to by the "color" field
      {
      //...
      color = new Color("green"); // other threads now allowed into this block
      // ...
      }
      }
      ```

      ```csharp Fix theme={null}
      private void DoSomething()
      {
      lock (new object()) // Noncompliant: every thread locks on a different new instance
      {
      // ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="ToString() calls should not be redundant">
    <div class="paragraph">
      <p>Invoking a method designed to return a string representation of an object which is already a string is a waste of keystrokes. Similarly, explicitly invoking \`ToString() when the compiler would do it implicitly is also needless code-bloat.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when ToString() is invoked:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>on a string</p>
        </li>

        <li>
          <p>on a non-string operand to concatenation</p>
        </li>

        <li>
          <p>on an argument to string.Format\`</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      var s = "foo";
      var t = "fee fie foe " + s.ToString();  // Noncompliant
      var someObject = new object();
      var u = "" + someObject.ToString(); // Noncompliant
      var v = string.Format("{0}", someObject.ToString()); // Noncompliant
      ```

      ```csharp Fix theme={null}
      var s = "foo";
      var t = "fee fie foe " + s;
      var someObject = new object();
      var u = "" + someObject;
      var v = string.Format("{0}", someObject);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Loops should be simplified with LINQ expressions">
    <div class="paragraph">
      <p>When a loop is filtering, selecting or aggregating, those functions can be handled with a clearer, more concise LINQ expression instead.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      var result = new List<string>();
      foreach (var element in collection)  // Noncompliant
      {
      if (condition(element))
      {
      result.Add(element);
      }
      }

      foreach (var element in collection2) // Noncompliant
      {
      var someValue = element.Property;
      if (someValue != null)
      {
      result.Add(someValue);
      }
      }
      ```

      ```csharp Fix theme={null}
      var result = new List<string>();

      foreach (var element in collection.Where(x => condition(x)))
      {
      result.Add(element);
      }

      foreach (var someValue in collection2.Select(x => x.Property).Where(y => y != null))
      {
      result.Add(someValue);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="NullReferenceException should not be caught">
    <div class="paragraph">
      <p>Catching NullReferenceException is generally considered a bad practice because it can hide bugs in your code. Instead of catching this exception, you should aim to prevent it. This makes your code more robust and easier to understand.
      In addition, constantly catching and handling NullReferenceException can lead to performance issues. Exceptions are expensive in terms of system resources, so they should be used cautiously and only for exceptional conditions, not for regular control flow.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public int GetLengthPlusTwo(string str)
      {
      try
      {
          return str.Length + 2;
      }
      catch (NullReferenceException e)
      {
          return 2;
      }
      }
      ```

      ```csharp Fix theme={null}
      public int GetLengthPlusTwo(string str)
      {
      if (str is null)
      {
          return 2;
      }
      return str.Length + 2;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="sealed classes should not have protected members">
    <div class="paragraph">
      <p>The difference between <code>private and protected visibility is that child classes can see and use protected members, but they cannot see private ones. Since a sealed class cannot have children, marking its members protected</code> is confusingly pointless.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public sealed class MySealedClass 
      {
      protected string name = "Fred";  // Noncompliant
      protected void SetName(string name) // Noncompliant
      {
          // ...
      }
      }
      ```

      ```csharp Fix theme={null}
      public sealed class MySealedClass 
      {
      private string name = "Fred";
      public void SetName(string name)
      {
          // ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Mutable fields should not be public static">
    <div class="paragraph">
      <p>public static mutable fields of classes which are accessed directly should be protected to the degree possible. This can be done by reducing the accessibility of the field or by changing the return type to an immutable type.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises issues for public static fields with a type inheriting/implementing System.Array or System.Collections.Generic.ICollection\<T>.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class A 
      {
      public static string[] strings1 = {"first","second"};  // Noncompliant
      public static List<String> strings3 = new List<String>();  // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      public class A 
      {
      protected static string[] strings1 = {"first","second"};
      protected static List<String> strings3 = new List<String>();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Test methods should not be async void ">
    <div class="paragraph">
      <p>In general, <code>async void</code> test methods are not executed by test frameworks, therefore it’s better to avoid them altogether.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      [TestMethod]
      public async void MyIgnoredTestMethod()  // Noncompliant
      { /* ... */ }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="A Route attribute should be added to the controller when a route template is specified at the action level">
    <div class="paragraph">
      <p>In <a href="https://learn.microsoft.com/en-us/aspnet/core/mvc/overview">ASP.NET Core MVC</a>, the <a href="https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing">routing</a> middleware utilizes a series of rules and conventions to identify the appropriate controller and action method to handle a specific HTTP request. This process, known as <em>conventional routing</em>, is generally established using the <a href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.controllerendpointroutebuilderextensions.mapcontrollerroute">MapControllerRoute</a> method. This method is typically configured in one central location for all controllers during the application setup.</p>
    </div>

    <div class="paragraph">
      <p>Conversely, <em>attribute routing</em> allows routes to be defined at the controller or action method level. It is possible to <a href="https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing#mixed-routing-attribute-routing-vs-conventional-routing">mix both mechanisms</a>. Although it’s permissible to employ diverse routing strategies across multiple controllers, combining both mechanisms within one controller can result in confusion and increased complexity, as illustrated below.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      // Conventional mapping definition
      app.MapControllerRoute(
      name: "default",
      pattern: "{controller=Home}/{action=Index}/{id?}");

      public class PersonController
      {
      // Conventional routing:
      // Matches e.g. /Person/Index/123
      public IActionResult Index(int? id) => View();

      // Attribute routing:
      // Matches e.g. /Age/Ascending (and model binds "Age" to sortBy and "Ascending" to direction)
      // but does not match /Person/List/Age/Ascending
      [HttpGet(template: "{sortBy}/{direction}")]
      public IActionResult List(string sortBy, SortOrder direction) => View();
      }
      ```

      ```csharp Fix theme={null}
      public class PersonController : Controller
      {
      // Matches /Person/Index/123
      public IActionResult Index(int? id) => View();

      // Matches /Age/Ascending
      [HttpGet(template: "{sortBy}/{direction}")] // Noncompliant: The "Index" and the "List" actions are
                                                  // reachable via different routing mechanisms and routes
      public IActionResult List(string sortBy, SortOrder direction) => View();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="string.IsNullOrEmpty should be used">
    <div class="paragraph">
      <p>Using <code>string.Equals to determine if a string is empty is significantly slower than using string.IsNullOrEmpty() or checking for </code>++string.Length</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      "".Equals(name); // Noncompliant
      !name.Equals(""); // Noncompliant
      name.Equals(string.Empty); // Noncompliant
      ```

      ```csharp Fix theme={null}
      name != null && name.Length > 0 // Compliant but more error prone
      !string.IsNullOrEmpty(name)
      string.IsNullOrEmpty(name)
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="[JSInvokable] attribute should only be used on public methods">
    <div class="paragraph">
      <p>In Blazor, the <a href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.jsinterop.jsinvokableattribute">\[JSInvokable]</a> attribute is used to annotate a method, enabling it to be invoked from JavaScript code. The prerequisite for this functionality is that the method must be declared as public.
      Otherwise, a runtime error will be triggered when an attempt is made to call the method from JavaScript.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      @code {
      [JSInvokable]
      private static void MyStaticMethod() { } // Noncompliant

      [JSInvokable]
      internal void MyMethod() { } // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      @code {
      [JSInvokable]
      public static void MyStaticMethod() { } // Compliant

      [JSInvokable]
      public void MyMethod() { } // Compliant
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Loops with at most one iteration should be refactored">
    <div class="paragraph">
      <p>A <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/iteration-statements">loop statement</a> with at most one iteration is equivalent to an if statement; the following block is executed only once.</p>
    </div>

    <div class="paragraph">
      <p>If the initial intention was to conditionally execute the block only once, an if statement should be used instead. If that was not the initial intention, the block of the loop should be fixed so the block is executed multiple times.</p>
    </div>

    <div class="paragraph">
      <p>A loop statement with at most one iteration can happen when a statement unconditionally transfers control, such as a <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/jump-statements">jump statement</a> or a <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/exception-handling-statements#the-throw-statement">throw statement</a>, is misplaced inside the loop block.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises when the following statements are misplaced:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/jump-statements#the-break-statement">break</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/jump-statements#the-continue-statement">continue</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/jump-statements#the-return-statement">return</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/exception-handling-statements#the-throw-statement">throw</a></p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public object Method(IEnumerable<object> items)
      {
      for (int i = 0; i < 10; i++)
      {
          Console.WriteLine(i);
          break; // Noncompliant: loop only executes once
      }

      foreach (object item in items)
      {
          return item; // Noncompliant: loop only executes once
      }
      return null;
      }
      ```

      ```csharp Fix theme={null}
      public object Method(IEnumerable<object> items)
      {
      for (int i = 0; i < 10; i++)
      {
          Console.WriteLine(i);
      }

      var item = items.FirstOrDefault();
      if (item != null)
      {
          return item;
      }
      return null;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="interface instances should not be cast to concrete types">
    <div class="paragraph">
      <p>Needing to cast from an <code>interface to a concrete type indicates that something is wrong with the abstractions in use, likely that something is missing from the interface. Instead of casting to a discrete type, the missing functionality should be added to the interface</code>. Otherwise there is a risk of runtime exceptions.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public interface IMyInterface
      {
      void DoStuff();
      }

      public class MyClass1 : IMyInterface
      {
      public int Data { get { return new Random().Next(); } }

      public void DoStuff()
      {
      // TODO...
      }
      }

      public static class DowncastExampleProgram
      {
      static void EntryPoint(IMyInterface interfaceRef)
      {
      MyClass1 class1 = (MyClass1)interfaceRef;  // Noncompliant
      int privateData = class1.Data;

      class1 = interfaceRef as MyClass1;  // Noncompliant
      if (class1 != null)
      {
        // ...
      }
      }
      }
      ```

      ```csharp Fix theme={null}
      static void EntryPoint(IMyInterface interfaceRef)
      {
      var o = (object)interfaceRef;
      ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="An abstract class should have both abstract and concrete methods">
    <div class="paragraph">
      <p>The purpose of an abstract class is to provide some heritable behaviors while also defining methods which must be implemented by sub-classes.</p>
    </div>

    <div class="paragraph">
      <p>A \`class with no abstract methods that was made abstract purely to prevent instantiation should be converted to a concrete class (i.e. remove the abstract keyword) with a protected constructor.</p>
    </div>

    <div class="paragraph">
      <p>A class with only abstract methods and no inheritable behavior should be converted to an interface\`.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public abstract class Animal //Noncompliant; should be an interface
      {
      abstract void Move();
      abstract void Feed();
      }

      public abstract class Color //Noncompliant; should be concrete with a protected constructor
      {
      private int red = 0;
      private int green = 0;
      private int blue = 0;

      public int GetRed()
      {
      return red;
      }
      }
      ```

      ```csharp Fix theme={null}
      public interface Animal
      {
      void Move();
      void Feed();
      }

      public class Color
      {
      private int red = 0;
      private int green = 0;
      private int blue = 0;

      protected Color()
      {}

      public int GetRed()
      {
      return red;
      }
      }

      public abstract class Lamp
      {
      private bool switchLamp = false;

      public abstract void Glow();

      public void FlipSwitch()
      {
      switchLamp = !switchLamp;
      if (switchLamp)
      {
        Glow();
      }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Blazor query parameter type should be supported">
    <div class="paragraph">
      <p>The <a href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.supplyparameterfromqueryattribute">SupplyParameterFromQuery</a> attribute can be used to specify that a component parameter, of a routable component, comes from the query string.</p>
    </div>

    <div class="paragraph">
      <p>Component parameters supplied from the query string support the following types:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>bool, DateTime, decimal, double, float, Guid, int, long, string.</p>
        </li>

        <li>
          <p>Nullable variants of the preceding types.</p>
        </li>

        <li>
          <p>Arrays of the preceding types, whether they’re nullable or not nullable.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Query parameters should have one of the supported types. Otherwise, an unhandled exception will be raised at runtime.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      Unhandled exception rendering component: Querystring values cannot be parsed as type '<type>'.
      System.NotSupportedException: Querystring values cannot be parsed as type '<type>'
      ...
      ```

      ```csharp Fix theme={null}
      @page "/print"
      <p> Parameter value is: @Value </p>
      @code {
      [Parameter]
      [SupplyParameterFromQuery()]
      public TimeSpan Value { get; set; }     // Noncompliant
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Windows Forms entry points should be marked with STAThread">
    <div class="paragraph">
      <p>When an assembly uses Windows Forms (classes and interfaces from the \`System.Windows.Forms namespace) its entry point should be marked with the STAThreadAttribute to indicate that the threading model should be "Single-Threaded Apartment" (STA) which is the only one supported by Windows Forms.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when the entry point (static void Main\` method) of an assembly using Windows Forms is not marked as STA.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System; 
      using System.Windows.Forms;

      namespace MyLibrary
      {
      public class MyForm: Form
      {
          public MyForm()
          {
              this.Text = "Hello World!";
          }

          public static void Main()  // Noncompliant
          {
              var form = new MyForm();
              Application.Run(form);
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System; 
      using System.Windows.Forms;

      namespace MyLibrary
      {
      public class MyForm: Form
      {
          public MyForm()
          {
              this.Text = "Hello World!";
          }

          [STAThread]
          public static void Main()
          {
              var form = new MyForm();
              Application.Run(form);
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="The simplest possible condition syntax should be used">
    <div class="paragraph">
      <p>In the interests of keeping code clean, the simplest possible conditional syntax should be used. That means</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>using the \`??= operator for a self-assign-if-not-null operation,</p>
        </li>

        <li>
          <p>using the ?? operator for an assign-if-not-null operation, and</p>
        </li>

        <li>
          <p>using the ternary operator ?:\` for assignment to a single variable.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      object a = null, b = null, x;

      if (a != null) // Noncompliant; needlessly verbose
      {
      x = a;
      }
      else
      {
      x = b;
      }

      x = a != null ? a : b; // Noncompliant; better but could still be simplified

      x = (a == null) ? new object() : a; // Noncompliant

      if (condition) // Noncompliant
      {
      x = a;
      }
      else
      {
      x = b;
      }

      if (a == null)  // Noncompliant
      a = new object();

      var y = null ?? new object(); // Noncompliant

      a = a ?? new object();  // Noncompliant for C# 8
      ```

      ```csharp Fix theme={null}
      object x;

      x = a ?? b;
      x = a ?? b;
      x = a ?? new object();
      x = condition ? a : b;
      a ??= new object();
      var y = new object();
      a ??= new object();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Composite format strings should be used correctly">
    <div class="paragraph">
      <p>Because composite format strings are interpreted at runtime, rather than validated by the compiler, they can contain errors that lead to unexpected behaviors or runtime errors. This rule statically validates the good behavior of composite formats when calling the methods of</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>\`String.Format</p>
        </li>

        <li>
          <p>StringBuilder.AppendFormat</p>
        </li>

        <li>
          <p>Console.Write</p>
        </li>

        <li>
          <p>Console.WriteLine</p>
        </li>

        <li>
          <p>TextWriter.Write</p>
        </li>

        <li>
          <p>TextWriter.WriteLine</p>
        </li>

        <li>
          <p>Debug.WriteLine(String, Object\[])</p>
        </li>

        <li>
          <p>Trace.TraceError(String, Object\[])</p>
        </li>

        <li>
          <p>Trace.TraceInformation(String, Object\[])</p>
        </li>

        <li>
          <p>Trace.TraceWarning(String, Object\[])</p>
        </li>

        <li>
          <p>TraceSource.TraceInformation(String, Object\[])\`.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      s = string.Format("{0}", arg0, arg1); // Noncompliant, arg1 is declared but not used.
      s = string.Format("{0} {2}", arg0, arg1, arg2); // Noncompliant, the format item with index 1 is missing so arg1 will not be used.
      s = string.Format("value is " + value);  // Noncompliant; use an argument instead of concatenaion
      s = string.Format("no argument here");
      ```

      ```csharp Fix theme={null}
      s = string.Format("{0}", arg0);
      s = string.Format("{0} {1}", arg0, arg2);
      s = string.Format("value is {0}", value);
      s = no argument here";
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Serializable classes should provide a serialization constructor">
    <div class="paragraph">
      <p>Classes that declare an implementation of \`Serializable should provide a serializable constructor. Without such a constructor, you’ll be unable to deserialize the class.</p>
    </div>

    <div class="paragraph">
      <p>Serialization constructors should be private for sealed types and protected\` otherwise.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      [Serializable]
      public class Person : ISerializable {  // Noncompliant; missing serializable constructor
      public void GetObjectData (SerializationInfo info, StreamingContext context) {
      // ...
      }
      }
      ```

      ```csharp Fix theme={null}
      [Serializable]
      public class Person : ISerializable {  // Noncompliant; missing serializable constructor

      protected Person (SerializationInfo info, StreamingContext context) {
      // ...
      }

      public void GetObjectData (SerializationInfo info, StreamingContext context) {
      // ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Overloads with a StringComparison parameter should be used">
    <div class="paragraph">
      <p>Many string operations, the \`Compare and Equals methods in particular, provide an overload that accepts a StringComparison enumeration value as a parameter. Calling these overloads and explicitly providing this parameter makes your code clearer and easier to maintain.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a string comparison operation doesn’t use the overload that takes a StringComparison\` parameter.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      namespace MyLibrary
      {
      public class Foo
      {
      public bool HaveSameNames(string name1, string name2)
      {
        return string.Compare(name1, name2) == 0; // Noncompliant
      }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;

      namespace MyLibrary
      {
      public class Foo
      {
      public bool HaveSameNames(string name1, string name2)
      {
        return string.Compare(name1, name2, StringComparison.OrdinalIgnoreCase) == 0;
      }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="IEnumerables should only be iterated once">
    <div class="paragraph">
      <p>Because \`IEnumerables are lazy-evaluated, each iteration causes a re-retrieval of the values, which could involve considerable overhead. For instance, when the IEnumerable is backed by a database, each iteration requires an additional round of database interactions. For that reason, any time the set represented by an IEnumerable must be iterated multiple times, it should first be converted to a List, which will retrieve the values and store them in memory. From that point they can be iterated as often as needed without an additional performance hit.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue for each iteration of an IEnumerable\` after the first one.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      IEnumerable<int> numbers = GetNumbers();

      var count = numbers.Count(); // causes an iteration
      var last = numbers.Last(); // Noncompliant; causes an iteration

      foreach(var x in numbers)  // Noncompliant
      {
      // ...
      }
      ```

      ```csharp Fix theme={null}
      List<int> numbers = GetNumbers().ToList(); // iterable to your heart's content

      var count = numbers.Count();
      var last = numbers.[count -1];

      foreach(var x in numbers)
      {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Constructor and destructor declarations should not be redundant">
    <div class="paragraph">
      <p>Since the compiler will automatically invoke the base type’s no-argument constructor, there’s no need to specify its invocation explicitly. Also, when only a single <code>public parameterless constructor is defined in a class, then that constructor can be removed because the compiler would generate it automatically. Similarly, empty static</code> constructors and empty destructors are also wasted keystrokes.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      class X
      {
      public X() { } // Noncompliant
      static X() { }  // Noncompliant
      ~X() { } // Noncompliant

      ...
      }

      class Y : X
      {
      public Y(int parameter) : base() // Noncompliant
      {
      /* does something with the parameter */
      }
      }
      ```

      ```csharp Fix theme={null}
      class X
      {
      ...
      }

      class Y : X
      {
      public Y(int parameter)
      {
      /* does something with the parameter */
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="DebuggerDisplayAttribute strings should reference existing members">
    <div class="paragraph">
      <p>The DebuggerDisplayAttribute is used to determine how an object is displayed in the debugger window.</p>
    </div>

    <div class="paragraph">
      <p>The DebuggerDisplayAttribute constructor takes a single mandatory argument: the string to be displayed in the value column for instances of the type. Any text within curly braces is evaluated as the name of a field or property, or any complex expression containing method calls and operators.</p>
    </div>

    <div class="paragraph">
      <p>Naming a non-existent member between curly braces will result in a CS0103 error in the debug window when debugging objects. Although there is no impact on the production code, providing a wrong value can lead to difficulties when debugging the application.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when text specified between curly braces refers to members that don’t exist in the current context.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      [DebuggerDisplay("Name: {Name}")] // Noncompliant - Name doesn't exist in this context
      public class Person
      {
      public string FullName { get; private set; }
      }
      ```

      ```csharp Fix theme={null}
      [DebuggerDisplay("Name: {FullName}")]
      public class Person
      {
      public string FullName { get; private set; }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="GC.KeepAlive should be called when using native resources">
    <div class="paragraph">
      <p>Usually <code>IntPtr and UIntPtr fields are used to store pointers to unmanaged resources and the finalizer will free the unmanaged resource pointed to by the pointer fields. If the garbage collector finalises the object while the managed resources are still in use it could lead to serious, hard to diagnose bug. To prevent this from happening the object should be kept alive by calling GC.KeepAlive(this)</code> in methods calling unmanaged code on this pointers.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      namespace MyLibrary
      {
      class Foo
      {
        private IntPtr res;

        Foo()
        {
           GetRes (res);
        }

        ~Foo()
        {
           FreeRes (res);
        }

        void Bar()  // Noncompliant
        {
           UseRes(res); 
        }

        // Methods that would typically make calls to unmanaged code.
        void GetRes(IntPtr p)
        {
          // Allocate the resource ...
        }
        void FreeRes(IntPtr p)
        {
          // Free the resource and set the pointer to null ...
        }
        void UseRes(IntPtr p)
        {
          // Use the resource in unmanaged code ...
        }

      }
      }
      ```

      ```csharp Fix theme={null}
      using System;

      namespace MyLibrary
      {
      class Foo
      {
        private IntPtr res;

        Foo()
        {
           GetRes (res);
        }

        ~Foo()
        {
           FreeRes (res);
        }

        void Bar()
        {
           UseRes(res); 
           GC.KeepAlive(this);
        }

        // Methods that would typically make calls to unmanaged code.
        void GetRes(IntPtr p)
        {
          // Allocate the resource ...
        }
        void FreeRes(IntPtr p)
        {
          // Free the resource and set the pointer to null ...
        }
        void UseRes(IntPtr p)
        {
          // Use the resource in unmanaged code ...
        }

      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="The [Serializable] attribute should be used on ISerializable classes">
    <div class="paragraph">
      <p>The <code>ISerializable interface gives you control over <em>how</em> your class is serialized, but does not itself make the class serializable. Such classes must also have the \[Serializable]</code> attribute.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Person : ISerializable {  // Noncompliant; [Serializable] attribute missing
      // ...
      }
      ```

      ```csharp Fix theme={null}
      [Serializable]
      public class Person : ISerializable {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="== should not be used when Equals is overridden">
    <div class="paragraph">
      <p>Using the equality <code>== and inequality != operators to compare two objects generally works. The operators can be overloaded, and therefore the comparison can resolve to the appropriate method. However, when the operators are used on interface instances, then == resolves to reference equality, which may result in unexpected behavior if implementing classes override Equals. Similarly, when a class overrides Equals, but instances are compared with non-overloaded ==</code>, there is a high chance that value comparison was meant instead of the reference one.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public interface IMyInterface
      {
      }

      public class MyClass : IMyInterface
      {
      public override bool Equals(object obj)
      {
          //...
      }
      }

      public class Program
      {
      public static void Method(IMyInterface instance1, IMyInterface instance2)
      {
          if (instance1 == instance2) // Noncompliant, will do reference equality check, but was that intended? MyClass overrides Equals.
          {
              Console.WriteLine("Equal");
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      public interface IMyInterface
      {
      }

      public class MyClass : IMyInterface
      {
      public override bool Equals(object obj)
      {
          //...
      }
      }

      public class Program
      {
      public static void Method(IMyInterface instance1, IMyInterface instance2)
      {
          if (object.Equals(instance1, instance2)) // object.Equals checks for null and then calls the instance based Equals, so MyClass.Equals
          {
              Console.WriteLine("Equal");
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Static fields should not be used in generic types">
    <div class="paragraph">
      <p>A static field in a generic type is not shared among instances of different closed constructed types, thus <code>LengthLimitedSingletonCollection\<int>.instances and LengthLimitedSingletonCollection\<string>.instances will point to different objects, even though instances is seemingly shared among all LengthLimitedSingletonCollection\<></code> generic classes.</p>
    </div>

    <div class="paragraph">
      <p>If you need to have a static field shared among instances with different generic arguments, define a non-generic base class to store your static members, then set your generic type to inherit from the base class.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class LengthLimitedSingletonCollection<T> where T : new() 
      {
      protected const int MaxAllowedLength = 5;
      protected static Dictionary<Type, object> instances = new Dictionary<Type, object>(); // Noncompliant

      public static T GetInstance() 
      {
      object instance;

      if (!instances.TryGetValue(typeof(T), out instance)) 
      {
        if (instances.Count >= MaxAllowedLength) 
        {
          throw new Exception();
        }
        instance = new T();
        instances.Add(typeof(T), instance);
      }
      return (T)instance;
      }
      }
      ```

      ```csharp Fix theme={null}
      public class SingletonCollectionBase 
      {
      protected static Dictionary<Type, object> instances = new Dictionary<Type, object>(); 
      }

      public class LengthLimitedSingletonCollection<T> : SingletonCollectionBase where T : new()
      {
      protected const int MaxAllowedLength = 5;

      public static T GetInstance() 
      {
      object instance;

      if (!instances.TryGetValue(typeof(T), out instance)) 
      {
        if (instances.Count >= MaxAllowedLength) 
        {
          throw new Exception();
        }
        instance = new T();
        instances.Add(typeof(T), instance);
      }
      return (T)instance;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Nullable type comparison should not be redundant">
    <div class="paragraph">
      <p>Calling <a href="https://learn.microsoft.com/en-us/dotnet/api/system.object.gettype">GetType()</a> on a <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types">nullable value type</a> object returns the underlying value type. Therefore, comparing the returned <a href="https://learn.microsoft.com/en-us/dotnet/api/system.type">Type</a> object to typeof(Nullable\<SomeType>) will either throw an <a href="https://learn.microsoft.com/en-us/dotnet/api/system.nullreferenceexception">NullReferenceException</a> or the result will always be true or false and can be known at compile time.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      void DoChecks<T>(Nullable<T> value) where T : struct
      {
      bool areEqual = value.GetType() == typeof(Nullable<int>); // Noncompliant: always false
      bool areNotEqual = value.GetType() != typeof(Nullable<int>); // Noncompliant: always true

      Nullable<int> nullable = null;
      bool nullComparison = nullable.GetType() != typeof(Nullable<int>); // Noncompliant: throws NullReferenceException
      }
      ```

      ```csharp Fix theme={null}
      void DoChecks<T>(Nullable<T> value) where T : struct
      {
      bool areEqual = value.GetType() == typeof(int); // Compliant: can be true or false 
      bool areNotEqual = value.GetType() != typeof(int); // Compliant: can be true or false 

      Nullable<int> nullable = null;
      bool nullComparison = nullable is not null && nullable.GetType() == typeof(int); // Compliant: does not throw NullReferenceException
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Overflow checking should not be disabled for Enumerable.Sum">
    <div class="paragraph">
      <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sum">Enumerable.Sum()</a> always executes addition in a checked context, so an <a href="https://learn.microsoft.com/en-us/dotnet/api/system.overflowexception">OverflowException</a> will be thrown if the value exceeds MaxValue, even if an unchecked context was specified. Therefore, using this method inside an unchecked context will only make the code more confusing, since the behavior will still be checked.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when an unchecked context is specified for a Sum on integer types.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      void Add(List<int> list)
      {
      unchecked 
      {
      try 
      {
        int total = list.Sum();
      } 
      catch (System.OverflowException e) 
      {
        // Exception handling    
      }
      }
      }
      ```

      ```csharp Fix theme={null}
      void Add(List<int> list)
      {
      int total1 = unchecked(list.Sum());  // Noncompliant

      unchecked 
      {
      int total2 = list.Sum();  // Noncompliant
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Type should not be examined on System.Type instances">
    <div class="paragraph">
      <p>Calling GetType on a Type variable will always return the System.Type representation, which is equivalent to typeof(System.Type). This also applies to passing a Type argument to IsInstanceOfType which always returns false.</p>
    </div>

    <div class="paragraph">
      <p>In both cases, the results are entirely predictable and should be avoided.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      typeof(Type).GetType(); // Can be used by convention to get an instance of 'System.RuntimeType'
      ```

      ```csharp Fix theme={null}
      void ExamineSystemType(string str) 
      {
      Type stringType = str.GetType();
      Type runtimeType = stringType.GetType(); // Noncompliant

      if (stringType.IsInstanceOfType(typeof(string))) // Noncompliant; will always return false
      { /* ... */ }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Generic exceptions should not be ignored">
    <div class="paragraph">
      <p>When exceptions occur, it is usually a bad idea to simply ignore them. Instead, it is better to handle them properly, or at least to log them.</p>
    </div>

    <div class="paragraph">
      <p>This rule only reports on empty catch clauses that catch generic `Exception`s.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      string text = "";
      try 
      {
      text = File.ReadAllText(fileName);
      } 
      catch (Exception exc) // Noncompliant
      {  
      }
      ```

      ```csharp Fix theme={null}
      string text = "";
      try 
      {
      text = File.ReadAllText(fileName);
      } 
      catch (Exception exc) 
      {
      logger.Log(exc);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Strings or integral types should be used for indexers">
    <div class="paragraph">
      <p>Strings and integral types are typically used as indexers. When some other type is required, it typically indicates design problems, and potentially a situation where a method should be used instead.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public int this[MyCustomClass index]  // Noncompliant
      {  
      // get and set accessors  
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="nameof should be used">
    <div class="paragraph">
      <p>Because parameter names could be changed during refactoring, they should not be spelled out literally in strings. Instead, use \`nameof(), and the string that’s output will always be correct.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a string in the throw\` statement contains the name of one of the method parameters.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      void DoSomething(int someParameter, string anotherParam)
      {
      if (someParameter < 0) 
      {
          throw new ArgumentException("Bad argument", "someParameter");  // Noncompliant
      }
      if (anotherParam == null)
      {
          throw new Exception("anotherParam should not be null"); // Noncompliant
      }
      }
      ```

      ```csharp Fix theme={null}
      void DoSomething(int someParameter)
      {
      if (someParameter < 0)
      {
          throw new ArgumentException("Bad argument", nameof(someParameter));
      }
      if (anotherParam == null)
      {
          throw new Exception($"{nameof(anotherParam)} should not be null");
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Exception should not be caught">
    <div class="paragraph">
      <p>Catching System.Exception seems like an efficient way to handle multiple possible exceptions. Unfortunately, it traps all exception types, including the ones that were not intended to be caught. To prevent any misunderstandings, the exception filters should be used. Alternatively each exception type should be in a separate catch block.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      try
      {
      // do something that might throw a FileNotFoundException or IOException
      }
      catch (Exception e) // Noncompliant
      {
      // log exception ...
      }
      ```

      ```csharp Fix theme={null}
      try
      {
      // do something
      }
      catch (Exception e) when (e is FileNotFoundException || e is IOException)
      {
      // do something
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="ASP.NET HTTP request validation feature should not be disabled">
    <div class="paragraph">
      <p>ASP.Net has a feature to validate HTTP requests to prevent potentially dangerous content to perform a cross-site scripting (XSS) attack. There is no reason to disable this mechanism even if other checks to prevent XXS attacks are in place.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue if a method with parameters is marked with <code>System.Web.Mvc.HttpPostAttribute and not System.Web.Mvc.ValidateInputAttribute(true)</code>.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class FooBarController : Controller
      {
      [HttpPost] // Noncompliant
      [ValidateInput(false)] 
      public ActionResult Purchase(string input)
      {
          return Foo(input);
      }

      [HttpPost] // Noncompliant
      public ActionResult PurchaseSomethingElse(string input)
      {
          return Foo(input);
      }
      }
      ```

      ```csharp Fix theme={null}
      public class FooBarController : Controller
      {
      [HttpPost]
      [ValidateInput(true)] // Compliant
      public ActionResult Purchase(string input)
      {
          return Foo(input);
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Thread.Sleep should not be used in tests">
    <div class="paragraph">
      <p>Using Thread.Sleep in a test might introduce unpredictable and inconsistent results depending on the environment. Furthermore, it will block the <a href="https://en.wikipedia.org/wiki/Thread_(computing)">thread</a>, which means the system resources are not being fully used.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      [TestMethod]
      public void SomeTest()
      {
      Thread.Sleep(500); // Noncompliant
      // assertions...
      }
      ```

      ```csharp Fix theme={null}
      [TestMethod]
      public async Task SomeTest()
      {
      await Task.Delay(500);
      // assertions...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Monitor.Pulse should not be called when multiple locks are held">
    <div class="paragraph">
      <p>The <code>Monitor.Pulse</code> call releases the object on which it was called and wakes up the first thread waiting for the lock on that object. Significantly, it only releases <em>one</em> lock, and if multiple locks are held when it is called deadlocks could result.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public void doSomething(Object obj) 
      {  
      lock (this) //first lock
      {
      lock (obj) {  // second lock
        // ...
        Monitor.Pulse(obj); // Noncompliant; only the second lock is released
      }
      }
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Exceptions should not be created without being thrown">
    <div class="paragraph">
      <p>Creating a new <a href="https://learn.microsoft.com/en-us/dotnet/api/system.exception">Exception</a> without actually throwing does not achieve the intended purpose.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if (x < 0)
      {
      new ArgumentException("x must be nonnegative");
      }
      ```

      ```csharp Fix theme={null}
      if (x < 0)
      {
      throw new ArgumentException("x must be nonnegative");
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Generic type parameters should be co/contravariant when possible">
    <div class="paragraph">
      <p>In the interests of making code as usable as possible, interfaces and delegates with generic parameters should use the \`out and in modifiers when possible to make the interfaces and delegates covariant and contravariant, respectively.</p>
    </div>

    <div class="paragraph">
      <p>The out keyword can be used when the type parameter is used only as a return type in the interface or delegate. Doing so makes the parameter covariant, and allows interface and delegate instances created with a sub-type to be used as instances created with a base type. The most notable example of this is IEnumerable\<out T>, which allows the assignment of an IEnumerable\<string> instance to an IEnumerable\<object> variable, for instance.</p>
    </div>

    <div class="paragraph">
      <p>The in keyword can be used when the type parameter is used only as a method parameter in the interface or a parameter in the delegate. Doing so makes the parameter contravariant, and allows interface and delegate instances created with a base type to be used as instances created with a sub-type. I.e. this is the inversion of covariance. The most notable example of this is the Action\<in T> delegate, which allows the assignment of an Action\<object> instance to a Action\<string>\` variable, for instance.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      interface IConsumer<T>  // Noncompliant
      {
      bool Eat(T fruit);
      }
      ```

      ```csharp Fix theme={null}
      interface IConsumer<in T>
      {
      bool Eat(T fruit);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Value types should implement IEquatable<T>">
    <div class="paragraph">
      <p>If you’re using a struct, it is likely because you’re interested in performance. But by failing to implement IEquatable\<T> you’re loosing performance when comparisons are made because without IEquatable\<T>, boxing and reflection are used to make comparisons.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      struct MyStruct  // Noncompliant
      {
      public int Value { get; set; }
      }
      ```

      ```csharp Fix theme={null}
      struct MyStruct : IEquatable<MyStruct>
      {
      public int Value { get; set; }

      public bool Equals(MyStruct other)
      {
          // ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="params should not be introduced on overrides">
    <div class="paragraph">
      <p>Adding <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params">params</a> to a method override has no effect. The compiler accepts it, but the callers won’t be able to benefit from the added modifier.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      class Base
      {
      public virtual void Method(int[] numbers)
      {
      ...
      }
      }
      class Derived : Base
      {
      public override void Method(params int[] numbers) // Noncompliant, method can't be called with params syntax.
      {
      ...
      }
      }
      ```

      ```csharp Fix theme={null}
      class Base
      {
      public virtual void Method(int[] numbers)
      {
      ...
      }
      }
      class Derived : Base
      {
      public override void Method(int[] numbers)
      {
      ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Expressions used in Debug.Assert should not produce side effects">
    <div class="paragraph">
      <p>An assertion is a piece of code that’s used during development when the <a href="https://learn.microsoft.com/en-us/visualstudio/debugger/how-to-set-debug-and-release-configurations">compilation debug mode is activated</a>. It allows a program to check itself as it runs. When an assertion is true, that means everything is operating as expected.</p>
    </div>

    <div class="paragraph">
      <p>In non-debug mode, all <a href="https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.debug.assert">Debug.Assert</a> calls are automatically left out (via the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.conditionalattribute">Conditional("DEBUG")</a> mechanism). So, by contract, the boolean expressions that are evaluated by those assertions must not contain any <a href="https://en.wikipedia.org/wiki/Side_effect_(computer_science)">side effects</a>. Otherwise, when leaving the debug mode, the functional behavior of the application is not the same anymore.</p>
    </div>

    <div class="paragraph">
      <p>The rule will raise if the method name starts with any of the following remove, delete, add, pop, update, retain, insert, push, append, clear, dequeue, enqueue, dispose, put, or set, although SetEquals will be ignored.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      Debug.Assert(list.Remove("dog"));
      ```

      ```csharp Fix theme={null}
      bool result = list.Remove("dog");
      Debug.Assert(result);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Constructors should not be called recursively">
    <div class="paragraph">
      <p>Unfortunately, it is possible to make constructor calls recursive. When this happens, you get a class that cannot be instantiated.</p>
    </div>

    <div class="paragraph">
      <p>As a general rule, no constructor should make a call to another constructor in the same class that requires fewer arguments than the calling constructor received. I.e. the constructor that accepts the most arguments is the one that has the fullest picture of how the class should look. It should perform class initialization.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      class Foo
      {
      int start;

      Foo() : this(0)  { }
      Foo(int v) : this()   { }  // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      class Foo
      {
      int start;

      Foo() : this(0)  { }
      Foo(int v)
      {
      this.count = v;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Redundant modifiers should not be used">
    <div class="paragraph">
      <p>Unnecessary keywords simply clutter the code and should be removed. Specifically:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>\`partial on type declarations that are completely defined in one place</p>
        </li>

        <li>
          <p>sealed on members of sealed classes</p>
        </li>

        <li>
          <p>unsafe method or block inside construct already marked with unsafe, or when there are no unsafe constructs in the block</p>
        </li>

        <li>
          <p>checked and unchecked\` blocks with no integral-type arithmetic operations</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public partial class MyClass // Noncompliant
      {
      public virtual void Method()
      {
      }
      }

      public sealed class MyOtherClass : MyClass
      {
      public sealed override void Method() // Noncompliant
      {
      }
      }
      ```

      ```csharp Fix theme={null}
      public class MyClass
      {
      public virtual void Method()
      {
      }
      }

      public sealed class MyOtherClass : MyClass
      {
      public override void Method()
      {
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unnecessary bit operations should not be performed">
    <div class="paragraph">
      <p>Certain <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/bitwise-and-shift-operators">bitwise operations</a> are not needed and should not be performed because their results are predictable.</p>
    </div>

    <div class="paragraph">
      <p>Specifically, using & -1 with any value always results in the original value.</p>
    </div>

    <div class="paragraph">
      <p>That is because the binary representation of -1 on a <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types">integral numeric type</a> supporting negative numbers, such as int or long, is based on <a href="https://en.wikipedia.org/wiki/Two%27s_complement">two’s complement</a> and made of all 1s: 0b111…​111.</p>
    </div>

    <div class="paragraph">
      <p>Performing & between a value and 0b111…​111 means applying the & operator to each bit of the value and the bit 1, resulting in a value equal to the provided one, bit by bit.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      anyValue & -1 // Noncompliant
      anyValue      // Compliant
      ```

      ```csharp Fix theme={null}
      anyValue | 0  // Noncompliant
      anyValue      // Compliant
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unnecessary mathematical comparisons should not be made">
    <div class="paragraph">
      <p>Certain <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/comparison-operators">mathematical comparisons</a> will always return the same value, and should not be performed.</p>
    </div>

    <div class="paragraph">
      <p>Specifically, the following comparisons will return either always true or always false depending on the kind of comparison:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>comparing a char with a numeric constant that is outside of the range of char</p>
        </li>

        <li>
          <p>comparing a float with a numeric constant that is outside of the range of float</p>
        </li>

        <li>
          <p>comparing a long with a numeric constant that is outside of the range of long</p>
        </li>

        <li>
          <p>comparing a ulong with a numeric constant that is outside of the range of ulong</p>
        </li>

        <li>
          <p>etc.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      float f = 42.0f;
      if (f <= double.MaxValue) { } // Noncompliant: always true
      if (f > double.MaxValue) { }  // Noncompliant: always false
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="ToString() method should not return null">
    <div class="paragraph">
      <p>Calling <a href="https://learn.microsoft.com/en-us/dotnet/api/system.object.tostring">ToString()</a> on an object should always return a string. Thus, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method">overriding the ToString method</a> should never return null, as it breaks the method’s implicit contract, and as a result the consumer’s expectations.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public override string ToString ()
      {
      if (this.collection.Count == 0) 
      {
      return null; // Noncompliant
      } 
      else 
      {
      // ...
      }
      }
      ```

      ```csharp Fix theme={null}
      public override string ToString () 
      {
      if (this.collection.Count == 0) 
      {
      return string.Empty;
      } 
      else 
      {
      // ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="default clauses should be first or last">
    <div class="paragraph">
      <p>The <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/selection-statements#the-switch-statement">switch statement</a> is a conditional statement that executes a sequence of instructions based on patterns matching the provided value.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      switch (temperatureInCelsius)
      {
      case < 35.0:
          Console.WriteLine("Hypothermia");
          break;
      case >= 36.5 and <= 37.5:
          Console.WriteLine("Normal");
          break;
      case > 37.5 and <= 40.0:
          Console.WriteLine("Fever or hyperthermia");
          break;        
      case > 40.0:
          Console.WriteLine("Hyperpyrexia");
          break;
      }
      ```

      ```csharp Fix theme={null}
      switch (gradeLetter)
      {
      case "A+":
      case "A":
      case "A-":
          Console.WriteLine("Excellent");
          break;
      case "B+":
      case "B":
          Console.WriteLine("Very Good");
          break;
      case "B-":
      case "C+":    
          Console.WriteLine("Good");
          break;        
      case "C":
          Console.WriteLine("Pass");
          break;
      case "F":
          Console.WriteLine("Fail");
          break;
      default:
          Console.WriteLine("Invalid grade letter!");
          break;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Members should not have conflicting transparency annotations">
    <div class="paragraph">
      <p>Transparency attributes can be declared at several levels. If two different attributes are declared at two different levels, the attribute that prevails is the one in the highest level.
      For example, you can declare that a class is <code>SecuritySafeCritical and that a method of this class is SecurityCritical. In this case, the method will be SecuritySafeCritical and the SecurityCritical</code> attribute attached to it is ignored.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;
      using System.Security;

      namespace MyLibrary
      {
      [SecuritySafeCritical]
      public class Foo
      {
          [SecurityCritical] // Noncompliant
          public void Bar()
          {
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;
      using System.Security;

      namespace MyLibrary
      {
      public class Foo
      {
          [SecurityCritical]
          public void Bar()
          {
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="private methods called only by inner classes should be moved to those classes">
    <div class="paragraph">
      <p>When a <code>private static</code> method is only invoked by a nested class, there’s no reason not to move it into that class. It will still have the same access to the outer class' static members, but the outer class will be clearer and less cluttered.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Outer
      {
      private const int base = 42;

      private static void Print(int num)  // Noncompliant - static method is only used by the nested class, should be moved there
      {
          Console.WriteLine(num + base);
      }

      public class Nested
      {
          public void SomeMethod()
          {
              Outer.Print(1);
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      public class Outer
      {
      private const int base = 42;

      public class Nested
      {
          public void SomeMethod()
          {
              Print(1);
          }

          private static void Print(int num)
          {
              Console.WriteLine(num + base);
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Properties should be preferred">
    <div class="paragraph">
      <p>Properties are accessed like fields which makes them easier to use.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when the name of a <code>public or protected method starts with Get</code>, takes no parameter, and returns a value that is not an array.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      namespace MyLibrary
      {
      public class Foo
      {
          private string name;

          public string GetName()  // Noncompliant
          {
              return name;
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;

      namespace MyLibrary
      {
      public class Foo
      {
          private string name;

          public string Name
          {
              get
              {
                  return name;
              }
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="synchronized methods should not be called in loops">
    <div class="paragraph">
      <p>Synchronization can be expensive in terms of time when multiple threads need to pass through the same bottleneck (method with \`\[MethodImpl(MethodImplOptions.Synchronized)]).</p>
    </div>

    <div class="paragraph">
      <p>If you have a piece of code calling a method with \[MethodImpl(MethodImplOptions.Synchronized)] attribute once, then it only has to wait its turn to pass through the bottleneck once. But call it in a loop, and your code has to get back in line for the bottleneck over and over.</p>
    </div>

    <div class="paragraph">
      <p>Instead, it would be better to get into the bottleneck, and then do the looping. I.e. consider refactoring the code to perform the loop inside the method.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a method with \[MethodImpl(MethodImplOptions.Synchronized)]\` is called in a loop.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public void doSomething(int max) {
      for (int i = 0; i < max; i++) {
      doSynchronized(i);  // Noncompliant
      }
      }

      [MethodImpl(MethodImplOptions.Synchronized)]
      public void doSynchronized(int val) {
      // ...
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="ThreadStatic should not be used on non-static fields">
    <div class="paragraph">
      <p>When you annotate a field with the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threadstaticattribute">ThreadStatic attribute</a>, it is an indication that the value of this field is unique for each thread. But if you don’t mark the field as static,  then the ThreadStatic attribute is ignored.</p>
    </div>

    <div class="paragraph">
      <p>The ThreadStatic attribute should either be removed or replaced with the use of <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.threadlocal-1">ThreadLocal\<T></a> class, which gives a similar behavior for non-static fields.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class MyClass 
      {
      [ThreadStatic]  // Noncompliant
      private int count = 0;

      // ...
      }
      ```

      ```csharp Fix theme={null}
      public class MyClass 
      {
      private int count = 0;

      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Finalizers should not be empty">
    <div class="paragraph">
      <p>Finalizers come with a performance cost due to the overhead of tracking the life cycle of objects. An empty one is consequently costly with no benefit or justification.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Foo 
      {
      ~Foo() // Noncompliant
      { 
      }
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Property names should not match get methods">
    <div class="paragraph">
      <p>Properties and Get method should have names that makes them clearly distinguishable.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when the name of a public or protected member starts with 'Get' and otherwise matches the name of a public or protected property.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      namespace MyLibrary
      {
      public class Foo
      {
          public DateTime Date
          {
              get { return DateTime.Today; }
          }

          public string GetDate() // Noncompliant
          {
              return this.Date.ToString();
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;

      namespace MyLibrary
      {
      public class Foo
      {
          public DateTime Date
          {
              get { return DateTime.Today; }
          }

          public string GetDateAsString()
          {
              return this.Date.ToString();
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Delegates should not be subtracted">
    <div class="paragraph">
      <p>In C#, delegates can be added together to chain their execution, and subtracted to remove their execution from the chain.</p>
    </div>

    <div class="paragraph">
      <p>Subtracting a chain of delegates from another one might yield unexpected results as shown hereunder - and is likely to be a bug.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      MyDelegate first, second, third, fourth;
      first = () => Console.Write("1");
      second = () => Console.Write("2");
      third = () => Console.Write("3");
      fourth = () => Console.Write("4");

      MyDelegate chain1234 = first + second + third + fourth; // Compliant - chain sequence = "1234"
      MyDelegate chain12 = chain1234 - third - fourth; // Compliant - chain sequence = "12"


      MyDelegate chain14 = first + fourth; // creates a new MyDelegate instance which is a list under the covers
      MyDelegate chain23 = chain1234 - chain14; // Noncompliant; (first + fourth) doesn't exist in chain1234


      // The chain sequence of "chain23" will be "1234" instead of "23"!
      // Indeed, the sequence "1234" does not contain the subsequence "14", so nothing is subtracted
      // (but note that "1234" contains both the "1" and "4" subsequences)
      chain23 = chain1234 - (first + fourth); // Noncompliant

      chain23(); // will print "1234"!
      ```

      ```csharp Fix theme={null}
      MyDelegate chain23 = chain1234 - first - fourth; // Compliant - "1" is first removed, followed by "4"

      chain23(); // will print "23"
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Closures should not be modified">
    <div class="paragraph">
      <p>Once you modify a closure, any use of it could provide unexpected results.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      var x = 0;
      Func<int> f1 = () => x;  // Noncompliant
      x = 1;
      Console.WriteLine(f1());

      var input = new[] { 1, 2, 3 };
      var fs = new List<Func<int>>();
      for (var i = 0; i < input.Length; i++) {
      Func<int> f = () => input[i];  // Noncompliant
      fs.Add(f);
      }
      Console.WriteLine(fs[0]()); //Access to modified closure yields Exception
      ```

      ```csharp Fix theme={null}
      var x = 0;
      var xx = x;
      Func<int> f = () => xx;
      x = 1;
      Console.WriteLine(f());

      var input = new[] { 1, 2, 3 };
      var fs = new List<Func<int>>();
      for (var i = 0; i < input.Length; i++) {
      var ii = i;
      Func<int> f = () => input[ii];
      fs.Add(f);
      }
      Console.WriteLine(fs[0]());
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Overloads with a CultureInfo or an IFormatProvider parameter should be used">
    <div class="paragraph">
      <p>When a \`System.Globalization.CultureInfo or IFormatProvider object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales.</p>
    </div>

    <div class="paragraph">
      <p>You should supply culture-specific information according to the following guidelines:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>If the value will be displayed to the user, use the current culture. See CultureInfo.CurrentCulture.</p>
        </li>

        <li>
          <p>If the value will be stored and accessed by software (persisted to a file or database), use the invariant culture. See CultureInfo.InvariantCulture.</p>
        </li>

        <li>
          <p>If you do not know the destination of the value, have the data consumer or provider specify the culture.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a method or constructor calls one or more members that have overloads that accept a System.IFormatProvider parameter, and the method or constructor does not call the overload that takes the IFormatProvider parameter. This rule ignores calls to .NET Framework methods that are documented as ignoring the IFormatProvider parameter as well as the following methods:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Activator.CreateInstance</p>
        </li>

        <li>
          <p>ResourceManager.GetObject</p>
        </li>

        <li>
          <p>ResourceManager.GetString\`</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      namespace MyLibrary
      {
      public class Foo
      {
          public void Bar(String string1)
          {
              if(string.Compare(string1, string2, false) == 0) // Noncompliant
              {
                  Console.WriteLine(string3.ToLower()); // Noncompliant
              }
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;
      using System.Globalization;

      namespace MyLibrary
      {
      public class Foo
      {
          public void Bar(String string1, String string2, String string3)
          {
              if(string.Compare(string1, string2, false, 
                                CultureInfo.InvariantCulture) == 0)
              {
                  Console.WriteLine(string3.ToLower(CultureInfo.CurrentCulture));
              }
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Object.ReferenceEquals should not be used for value types">
    <div class="paragraph">
      <p>In C#, the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.object.referenceequals">Object.ReferenceEquals</a> method is used to compare two <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types">reference type</a> variables. If you use this method to compare two <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-types">value types</a>, such as int, float, or bool you will not get the expected results because value type variables contain an instance of the type and not a reference to it.</p>
    </div>

    <div class="paragraph">
      <p>Due to value type variables containing directly an instance of the type, they can’t have the same reference, and using Object.ReferenceEquals to compare them will always return false even if the compared variables have the same value.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      struct MyStruct
      {
      int valueA;
      int valueB;
      }

      static class MyClass
      {
      public static void Method(MyStruct struct1, MyStruct struct2)
      {
          if (Object.ReferenceEquals(struct1, struct2)) // Noncompliant: this will be always false
          {
              // ...
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;

      struct MyStruct : IEquatable<MyStruct>
      {
      int valueA;
      int valueB;

      public bool Equals(MyStruct other) => valueA == other.valueA && valueB == other.valueB;

      public override bool Equals(object obj) => obj is MyStruct other && Equals(other);

      public override int GetHashCode() => HashCode.Combine(valueA, valueB);

      public static bool operator ==(MyStruct lhs, MyStruct rhs) => lhs.Equals(rhs);

      public static bool operator !=(MyStruct lhs, MyStruct rhs) => !(lhs == rhs);
      }

      static class MyClass
      {
      public static void Method(MyStruct struct1, MyStruct struct2)
      {
          if (struct1.Equals(struct2)) // Compliant: value are compared
          {
              // ...
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="ConfigureAwait(false) should be used">
    <div class="paragraph">
      <p>After an \`awaited Task has executed, you can continue execution in the original, calling thread or any arbitrary thread. Unless the rest of the code needs the context from which the Task was spawned, Task.ConfigureAwait(false) should be used to keep execution in the Task thread to avoid the need for context switching and the possibility of deadlocks.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when code in a class library targeting .Net Framework awaits a Task and continues execution in the original calling thread.</p>
    </div>

    <div class="paragraph">
      <p>The rule does not raise for .Net Core libraries as there is no SynchronizationContext\` in .Net Core.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      var response = await httpClient.GetAsync(url);  // Noncompliant
      ```

      ```csharp Fix theme={null}
      var response = await httpClient.GetAsync(url).ConfigureAwait(false);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Locales should be set for data types">
    <div class="paragraph">
      <p>When you create a \`DataTable or DataSet, you should set the locale explicitly. By default, the locale for these types is the current culture. For data that is stored in a database or file and is shared globally, the locale should ordinarily be set to the invariant culture (CultureInfo.InvariantCulture).</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when System.Data.DataTable or System.Data.DataSet instances are created without explicitly setting the locale property (DataTable.Locale or DataSet.Locale\`).</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;
      using System.Data;

      namespace MyLibrary
      {
      public class Foo
      {
          public DataTable CreateTable()
          {
              DataTable table = new DataTable("Customers"); // Noncompliant table.Locale not set
              DataColumn key = table.Columns.Add("ID", typeof(Int32));

              key.AllowDBNull = false;
              key.Unique = true;
              table.Columns.Add("LastName", typeof(String));
              table.Columns.Add("FirstName", typeof(String));
              return table;
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;
      using System.Data;
      using System.Globalization;

      namespace MyLibrary
      {
      public class Foo
      {
          public DataTable CreateTable()
          {
              DataTable table = new DataTable("Customers");
              table.Locale = CultureInfo.InvariantCulture;
              DataColumn key = table.Columns.Add("ID", typeof(Int32));

              key.AllowDBNull = false;
              key.Unique = true;
              table.Columns.Add("LastName", typeof(String));
              table.Columns.Add("FirstName", typeof(String));
              return table;
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Duplicate casts should not be made">
    <div class="paragraph">
      <p>Because the <code>is operator performs a cast if the object is not null, using is to check type and then casting the same argument to that type, necessarily performs two casts. The same result can be achieved more efficiently with a single cast using as</code>, followed by a null-check.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      if (x is Fruit)  // Noncompliant
      {
      var f = (Fruit)x; // or x as Fruit
      // ...
      }
      ```

      ```csharp Fix theme={null}
      // C# 6
      var f = x as Fruit;
      if (f != null)
      {
      // ...
      }
      // C# 7
      if (x is Fruit fruit)
      {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Right operands of shift operators should be integers">
    <div class="paragraph">
      <p>Numbers can be shifted with the \<<a href="#/code> and <code">\[/code> and \<code]</a>> <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/bitwise-and-shift-operators#left-shift-operator-">operators</a>, but the right operand of the operation needs to be an int or a type that has an <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/conversions#102-implicit-conversions">implicit conversion</a> to int. However, when the left operand is <a href="https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/interop/using-type-dynamic">dynamic</a>, the compiler’s type checking is turned off, so you can pass anything to the right of a shift operator and have it compile. And if the argument can’t be implicitly converted to int at runtime, then a <a href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.csharp.runtimebinder.runtimebinderexception">RuntimeBinderException</a> will be raised.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      dynamic d = 5;
      var x = d >> 5.4;   // Noncompliant
      x = d << null;      // Noncompliant
      x <<= new object(); // Noncompliant
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Identical expressions should not be used on both sides of operators">
    <div class="paragraph">
      <p>Using the same value on both sides of certain operators is a code defect. In the case of logical operators, it is either a copy/paste error and, therefore, a bug, or it is simply duplicated code and should be simplified. For bitwise operators and most binary mathematical operators, having the same value on both sides of an operator yields predictable results and should be simplified as well to avoid further code defects.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises for the following operators.</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/equality-operators">Equality operators</a> (== and !=)</p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/comparison-operators">Comparison operators</a> (\< =, <a href="#/code>">\<code</a>, >=)</p>
        </li>

        <li>
          <p>The following <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators">Logical Operators</a>:</p>

          <div class="ulist">
            <ul>
              <li>
                <p>Logical OR (| )</p>
              </li>

              <li>
                <p>Conditional logical OR (||)</p>
              </li>

              <li>
                <p>Logical AND (&)</p>
              </li>

              <li>
                <p>Conditional logical AND (&&)</p>
              </li>

              <li>
                <p>Logical exclusive OR (^)</p>
              </li>
            </ul>
          </div>
        </li>

        <li>
          <p>The following <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators">arithmetic operators</a>:</p>

          <div class="ulist">
            <ul>
              <li>
                <p>Subtraction (-)</p>
              </li>

              <li>
                <p>Division ()</p>
              </li>

              <li>
                <p>Remainder operator (%)</p>
              </li>

              <li>
                <p>Subtraction assignment operator (-=)</p>
              </li>

              <li>
                <p>Divide assignment operator (=)</p>
              </li>
            </ul>
          </div>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      if ( a == a ) // always true
      { 
      doZ();
      }
      if ( a != a ) // always false
      {
      doY();
      }
      if ( a == b && a == b ) // if the first one is true, the second one is too
      { 
      doX();
      }
      if ( a == b || a == b ) // if the first one is true, the second one is too
      { 
      doW();
      }

      int j = 5 / 5; // always 1
      int k = 5 - 5; // always 0

      c.Equals(c);    // always true
      Object.Equals(c, c); // always true
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Floating point numbers should not be tested for equality">
    <div class="paragraph">
      <p>Floating point numbers in C# (and in most other programming languages) are not precise. They are a binary approximation of the actual value. This means that even if two floating point numbers appear to be equal, they might not be due to the tiny differences in their binary representation.</p>
    </div>

    <div class="paragraph">
      <p>Even simple floating point assignments are not simple:</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      float f = 0.100000001f; // 0.1
      double d = 0.10000000000000001; // 0.1
      ```

      ```csharp Fix theme={null}
      float myNumber = 3.146f;

      if (myNumber == 3.146f) //Noncompliant: due to floating point imprecision, this will likely be false
      {
      // ...
      }

      if (myNumber < 4 || myNumber > 4) // Noncompliant: indirect inequality test
      {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="async methods should not return void">
    <div class="paragraph">
      <p>An <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/async">async</a> method with a void return type does not follow the <a href="https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/task-asynchronous-programming-model">task asynchronous programming (TAP)</a> model since the return type should be <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task">Task</a> or <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1">Task\<TResult></a></p>
    </div>

    <div class="paragraph">
      <p>Doing so prevents control over the <a href="https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/async-scenarios">asynchronous execution</a>, such as:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>waiting for the execution to complete</p>
        </li>

        <li>
          <p>catching any exception that might occur during execution</p>
        </li>

        <li>
          <p>testing execution behavior</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public async void button1_Click(object sender, EventArgs e)
      {
      await DoSomethingAsync();
      }
      ```

      ```csharp Fix theme={null}
      public async void OnClick(EventContext data)
      {
      await DoSomethingAsync();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Classes that provide Equals(<T>) should implement IEquatable<T>">
    <div class="paragraph">
      <p>The \`IEquatable\<T> interface has only one method in it: Equals(\<T>). If you’ve already written Equals(T), there’s no reason not to explicitly implement IEquatable\<T>. Doing so expands the utility of your class by allowing it to be used where an IEquatable is called for.</p>
    </div>

    <div class="paragraph">
      <p><strong>Note</strong>: Classes that implement IEquatable\<T> should also be sealed\`.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      class MyClass  // Noncompliant
      {
      public bool Equals(MyClass other)
      {
      //...
      }
      }
      ```

      ```csharp Fix theme={null}
      sealed class MyClass : IEquatable<MyClass>
      {
      public override bool Equals(object other)
      {
      return Equals(other as MyClass);
      }

      public bool Equals(MyClass other) 
      {
      //...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Related if/else if statements should not have the same condition">
    <div class="paragraph">
      <p>A chain of <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/selection-statements#the-if-statement">if/else if</a> statements is evaluated from top to bottom. At most, only one branch will be executed: the first statement with a condition that evaluates to true.
      Therefore, duplicating a condition leads to unreachable code inside the duplicated condition block. Usually, this is due to a copy/paste error.</p>
    </div>

    <div class="paragraph">
      <p>The result of such duplication can lead to unreachable code or even to unexpected behavior.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if (param == 1)
      {
      OpenWindow();
      }
      else if (param == 2)
      {
      CloseWindow();
      }
      else if (param == 1) // Noncompliant: condition has already been checked
      {
      MoveWindowToTheBackground(); // unreachable code
      }
      ```

      ```csharp Fix theme={null}
      if (param == 1)
      {
      OpenWindow();
      }
      else if (param == 2)
      {
      CloseWindow();
      }
      else if (param == 3)
      {
      MoveWindowToTheBackground();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Loops and recursions should not be infinite">
    <div class="paragraph">
      <p>Having an infinite loop or recursion will lead to a program failure or a program never finishing the execution.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public int Sum()
      {
      var i = 0;
      var result = 0;
      while (true) // Noncompliant: the program will never stop
      {
          result += i;
          i++;
      }
      return result;
      }
      ```

      ```csharp Fix theme={null}
      int Pow(int num, int exponent)
      {
      return num * Pow(num, exponent - 1); // Noncompliant: no condition under which Pow isn't re-called
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Literals should not be passed as localized parameters">
    <div class="paragraph">
      <p>String literals embedded in the source code will not be localized properly.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a literal string is passed as a parameter or property and one or more of the following cases is true:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>The \`LocalizableAttribute attribute of the parameter or property is set to true.</p>
        </li>

        <li>
          <p>The parameter or property name contains "Text", "Message", or "Caption".</p>
        </li>

        <li>
          <p>The name of the string parameter that is passed to a Console.Write or Console.WriteLine\` method is either "value" or "format".</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;
      using System.Globalization;
      using System.Reflection;
      using System.Windows.Forms;

      [assembly: NeutralResourcesLanguageAttribute("en-US")]
      namespace MyLibrary
      {
      public class Foo
      {
          public void SetHour(int hour)
          {
              if (hour < 0 || hour > 23)
              {
                  MessageBox.Show("The valid range is 0 - 23."); // Noncompliant
              }
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;
      using System.Globalization;
      using System.Reflection;
      using System.Resources;
      using System.Windows.Forms;



      [assembly: NeutralResourcesLanguageAttribute("en-US")]
      namespace MyLibrary
      {
      public class Foo
      {
          ResourceManager rm;
          public Foo()
          {
              rm = new ResourceManager("en-US", Assembly.GetExecutingAssembly());
          }

          public void SetHour(int hour)
          {
              if (hour < 0 || hour > 23)
              {
                  MessageBox.Show(
                  rm.GetString("OutOfRangeMessage", CultureInfo.CurrentUICulture));
              }
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Multidimensional arrays should not be used">
    <div class="paragraph">
      <p>A jagged array is an array whose elements are arrays. It is recommended over a multidimensional array because the arrays that make up the elements can be of different sizes, which avoids wasting memory space.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      int [,] myArray =  // Noncompliant
      {
          {1,2,3,4},
          {5,6,7,0},
          {8,0,0,0},
          {9,0,0,0}
      };
      // ...
      myArray[1,1] = 0;
      ```

      ```csharp Fix theme={null}
      int[][] myArray = 
      { 
          new int[] {1,2,3,4},
          new int[] {5,6,7},
          new int[] {8},
          new int[] {9}
      };
      // ...
      myArray[1][1] = 0;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Multiple OrderBy calls should not be used">
    <div class="paragraph">
      <p>There’s no point in chaining multiple \`OrderBy calls in a LINQ; only the last one will be reflected in the result because each subsequent call  completely reorders the list. Thus, calling OrderBy multiple times is a performance issue as well, because all of the sorting will be executed, but only the result of the last sort will be kept.</p>
    </div>

    <div class="paragraph">
      <p>Instead, use ThenBy\` for each call after the first.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      var x = personList
      .OrderBy(person => person.Age)
      .OrderBy(person => person.Name)  // Noncompliant
      .ToList();  // x is sorted by Name, not sub-sorted
      ```

      ```csharp Fix theme={null}
      var x = personList
      .OrderBy(person => person.Age)
      .ThenBy(person => person.Name)
      .ToList();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="[Optional] should not be used on ref or out parameters">
    <div class="paragraph">
      <p>The use of <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref">ref</a> or <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier">out</a> in combination with <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.optionalattribute">Optional</a> attribute is both confusing and contradictory. \[Optional] indicates that the parameter doesn’t have to be provided, while out and ref mean that the parameter will be used to return data to the caller (ref additionally indicates that the parameter may also be used to pass data into the method).</p>
    </div>

    <div class="paragraph">
      <p>Thus, making it \[Optional] to provide the parameter in which you will be passing back the method results doesn’t make sense. In fact, the compiler will raise an error on such code. Unfortunately, it raises the error on method calls where the \[Optional] parameter has been omitted, not the source of the problem, the method declaration.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      class MyClass
      {
      public void DoStuff([Optional] ref int i) // Noncompliant
      {
      Console.WriteLine(i);
      }

      public static void Main()
      {
      new MyClass().DoStuff(); // Compilation Error [CS7036]
      }
      }
      ```

      ```csharp Fix theme={null}
      class MyClass
      {
      public void DoStuff(ref int i)
      {
      Console.WriteLine(i);
      }

      public static void Main()
      {
      var i = 42;
      new MyClass().DoStuff(ref i); 
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Types should be named in PascalCase">
    <div class="paragraph">
      <p>Shared naming conventions allow teams to collaborate efficiently.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a type name is not PascalCased.</p>
    </div>

    <div class="paragraph">
      <p>For example, the classes</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      class my_class {...}
      class SOMEName42 {...}
      ```

      ```csharp Fix theme={null}
      class MyClass {...}
      class SomeName42 {...}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="[DefaultValue] should not be used when [DefaultParameterValue] is meant">
    <div class="paragraph">
      <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.defaultvalueattribute">DefaultValue</a> does not make the compiler set the default value, as its name may suggest. What you probably wanted to use is <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.defaultparametervalueattribute">DefaultParameterValue</a>.</p>
    </div>

    <div class="paragraph">
      <p>The <a href="https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.defaultvalueattribute">DefaultValue</a> attribute from the System.ComponentModel namespace, is sometimes used to declare a member’s default value. This can be used, for instance, by the reset feature of a visual designer or by a code generator.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public void DoStuff([DefaultValue(4)] int i) 
      { 
      // i is not automatically assigned 4
      }
      ```

      ```csharp Fix theme={null}
      public void DoStuff([Optional] int i) 
      { 
      // i would be assigned default(int) = 0 
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Field-like events should not be virtual">
    <div class="paragraph">
      <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/event-pattern#define-and-raise-field-like-events">Field-like</a> events are events that do not have explicit <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/add">add</a> and <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/remove">remove</a> accessors.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public event EventHandler MyEvent; // No add and remove accessors
      ```

      ```csharp Fix theme={null}
      abstract class Car
      {
      public virtual event EventHandler OnRefuel; // Noncompliant

      public void Refuel()
      {
      // This OnRefuel will always be null
       if (OnRefuel != null)
       {
         OnRefuel(this, EventArgs.Empty);
       }
      }
      }

      class R2 : Car
      {
      public override event EventHandler OnRefuel;
      }

      class Program
      {
      static void Main(string[] args)
      {
      var r2 = new R2();
      r2.OnRefuel += (o, a) =>
      {
          Console.WriteLine("This event will be called");
      };
      r2.Refuel();
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Members should not be initialized to default values">
    <div class="paragraph">
      <p>The compiler automatically initializes class fields, auto-properties and events to their default values before setting them with any initialization values, so there is no need to explicitly set a member to its default value. Further, under the logic that cleaner code is better code, it’s considered poor style to do so.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      class X
      {
      public int field = 0; // Noncompliant
      public object o = null; // Noncompliant
      public object MyProperty { get; set; } = null; // Noncompliant
      public event EventHandler MyEvent = null;  // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      class X
      {
      public int field;
      public object o;
      public object MyProperty { get; set; }
      public event EventHandler MyEvent;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Inheritance list should not be redundant">
    <div class="paragraph">
      <p>An inheritance list entry is redundant if:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>It is \`Object - all classes extend Object implicitly.</p>
        </li>

        <li>
          <p>It is int for an enum\`</p>
        </li>

        <li>
          <p>It is a base class of another listed inheritance.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Such redundant declarations should be removed because they needlessly clutter the code and can be confusing.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class MyClass : Object  // Noncompliant

      enum MyEnum : int  // Noncompliant
      ```

      ```csharp Fix theme={null}
      public class MyClass

      enum MyEnum
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Assembly.Load should be used">
    <div class="paragraph">
      <p>The parameter to \`Assembly.Load includes the full specification of the dll to be loaded. Use another method, and you might end up with a dll other than the one you expected.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when Assembly.LoadFrom, Assembly.LoadFile, or Assembly.LoadWithPartialName\` is called.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      static void Main(string[] args)
      {
      Assembly.LoadFrom(...); // Noncompliant
      Assembly.LoadFile(...); // Noncompliant
      Assembly.LoadWithPartialName(...); // Noncompliant + deprecated
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Assertions should be complete">
    <div class="paragraph">
      <p>This rule addresses the issue of incomplete assertions that can occur when using certain test frameworks. Incomplete assertions can lead to tests that do not effectively verify anything. The rule enforces the use of complete assertions in specific cases, namely:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Fluent Assertions: <a href="https://fluentassertions.com/introduction">Should()</a> is not followed by an assertion invocation.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      string actual = "Using Fluent Assertions";
      actual.Should(); // Noncompliant
      ```

      ```csharp Fix theme={null}
      string actual = "Using NFluent";
      Check.That(actual); // Noncompliant
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Console logging should not be used">
    <div class="paragraph">
      <p>Debug statements are always useful during development. But include them in production code - particularly in code that runs client-side - and you run the risk of inadvertently exposing sensitive information.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      private void DoSomething()
      {
      // ...
      Console.WriteLine("so far, so good..."); // Noncompliant
      // ...
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Component parameter type should match the route parameter type constraint">
    <div class="paragraph">
      <p>In Blazor, when a <a href="https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/routing#route-constraints">route parameter constraint</a> is applied, the value is automatically cast to the corresponding component parameter type. If the constraint type does not match the component parameter type, it can lead to confusion and potential runtime errors due to unsuccessful casting. Therefore, it is crucial to ensure that the types of route parameters and component parameters match to prevent such issues and maintain code clarity.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      @page "/my-route/{Param:datetime}"

      @code {
      [Parameter]
      public string Param { get; set; } // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      @page "/my-route/{Param:datetime}"

      @code {
      [Parameter]
      public DateTime Param { get; set; } // Compliant
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="switch statements should have at least 3 case clauses">
    <div class="paragraph">
      <p>\`switch statements and expressions are useful when there are many different cases depending on the value of the same expression.</p>
    </div>

    <div class="paragraph">
      <p>When a switch statement or expression is simple enough, the code will be more readable with a single if, if-else\` or ternary conditional operator.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      switch (variable)
      {
      case 0:
      doSomething();
      break;
      default:
      doSomethingElse();
      break;
      }

      var foo = variable switch
      {
      0 => doSomething(),
      _ => doSomethingElse(),
      }
      ```

      ```csharp Fix theme={null}
      if (variable == 0)
      {
      doSomething();
      }
      else
      {
      doSomethingElse();
      }

      var foo = variable == 0
      ? doSomething() 
      : doSomethingElse();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Types should not have members with visibility set higher than the types visibility">
    <div class="paragraph">
      <p>There’s no point in having a <code>public member in a non-public</code> type because objects that can’t access the type will never have the chance to access the member.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a type has methods, fields, or inner types with higher visibility than the type itself has.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      internal class MyClass
      {
      public static decimal PI = 3.14m;  // Noncompliant

      public int GetOne() // Noncompliant
      {
          return 1;
      }

      protected record NestedType // Noncompliant: outer class is internal
      {
          public bool FlipCoin() // Noncompliant: outer class is internal
          {
              return false;
          }
          // ...
      }
      }
      ```

      ```csharp Fix theme={null}
      public class MyClass // Class visibility upgrade makes members compliant
      {
      public static decimal PI = 3.14m;

      public int GetOne()
      {
          return 1;
      }

      protected record NestedType
      {
          public bool FlipCoin() // Outer type is public
          {
              return false;
          }
          // ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="abstract classes should not have public constructors">
    <div class="paragraph">
      <p>The <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/abstract">abstract</a> modifier in a class declaration is used to indicate that a class is intended only to be a base class of other classes, not instantiated on its own.</p>
    </div>

    <div class="paragraph">
      <p>Since abstract classes cannot be instantiated, there is no need for public or internal constructors. If there is basic initialization logic that should run when an extending class instance is created, you can add it in a private, private protected or protected constructor.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      abstract class Base
      {
      public Base() // Noncompliant: should be private, private protected or protected.
      {
        //...
      }
      }
      ```

      ```csharp Fix theme={null}
      abstract class Base
      {
      protected Base()
      {
        //...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Anonymous delegates should not be used to unsubscribe from Events">
    <div class="paragraph">
      <p>When working with <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions">anonymous functions</a>, it is important to keep in mind that each time you create one, it is a completely new instance.</p>
    </div>

    <div class="paragraph">
      <p>In this example, even though the same lambda expression is used, the expressions are stored separately in the memory and are therefore not equal or the same.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      Func<int, int> lambda1 = x => x + 1;
      Func<int, int> lambda2 = x => x + 1;

      var result = lambda1 == lambda2; // result is false here
      ```

      ```csharp Fix theme={null}
      event EventHandler myEvent;

      void DoWork()
      {
          myEvent += (s, e) => Console.WriteLine($"Event raised with sender {s} and arguments {e}!");
          // ...
          myEvent -= (s, e) => Console.WriteLine($"Event raised with sender {s} and arguments {e}!"); // Noncompliant: this callback was never subscribed
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="static readonly constants should be const instead">
    <div class="paragraph">
      <p>The value of a \`static readonly field is computed at runtime while the value of a const field is calculated at compile time, which improves performance.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a static readonly\` field is initialized with a value that is computable at compile time.</p>
    </div>

    <div class="paragraph">
      <p>As specified by Microsoft, the list of types that can have a constant value are:</p>
    </div>

    <table class="tableblock frame-all grid-all stretch">
      <thead>
        <tr>
          <th class="tableblock halign-center valign-top">C# type</th>
          <th class="tableblock halign-center valign-top">.Net Fwk type</th>
        </tr>
      </thead>

      <tbody>
        <tr>
          <td class="tableblock halign-center valign-top"><p class="tableblock">bool</p></td>
          <td class="tableblock halign-center valign-top"><p class="tableblock">System.Boolean</p></td>
        </tr>

        <tr>
          <td class="tableblock halign-center valign-top"><p class="tableblock">byte</p></td>
          <td class="tableblock halign-center valign-top"><p class="tableblock">System.Byte</p></td>
        </tr>

        <tr>
          <td class="tableblock halign-center valign-top"><p class="tableblock">sbyte</p></td>
          <td class="tableblock halign-center valign-top"><p class="tableblock">System.SByte</p></td>
        </tr>

        <tr>
          <td class="tableblock halign-center valign-top"><p class="tableblock">char</p></td>
          <td class="tableblock halign-center valign-top"><p class="tableblock">System.Char</p></td>
        </tr>

        <tr>
          <td class="tableblock halign-center valign-top"><p class="tableblock">decimal</p></td>
          <td class="tableblock halign-center valign-top"><p class="tableblock">System.Decimal</p></td>
        </tr>

        <tr>
          <td class="tableblock halign-center valign-top"><p class="tableblock">double</p></td>
          <td class="tableblock halign-center valign-top"><p class="tableblock">System.Double</p></td>
        </tr>

        <tr>
          <td class="tableblock halign-center valign-top"><p class="tableblock">float</p></td>
          <td class="tableblock halign-center valign-top"><p class="tableblock">System.Single</p></td>
        </tr>

        <tr>
          <td class="tableblock halign-center valign-top"><p class="tableblock">int</p></td>
          <td class="tableblock halign-center valign-top"><p class="tableblock">System.Int32</p></td>
        </tr>

        <tr>
          <td class="tableblock halign-center valign-top"><p class="tableblock">uint</p></td>
          <td class="tableblock halign-center valign-top"><p class="tableblock">System.UInt32</p></td>
        </tr>

        <tr>
          <td class="tableblock halign-center valign-top"><p class="tableblock">long</p></td>
          <td class="tableblock halign-center valign-top"><p class="tableblock">System.Int64</p></td>
        </tr>

        <tr>
          <td class="tableblock halign-center valign-top"><p class="tableblock">ulong</p></td>
          <td class="tableblock halign-center valign-top"><p class="tableblock">System.UInt64</p></td>
        </tr>

        <tr>
          <td class="tableblock halign-center valign-top"><p class="tableblock">short</p></td>
          <td class="tableblock halign-center valign-top"><p class="tableblock">System.Int16</p></td>
        </tr>

        <tr>
          <td class="tableblock halign-center valign-top"><p class="tableblock">ushort</p></td>
          <td class="tableblock halign-center valign-top"><p class="tableblock">System.UInt16</p></td>
        </tr>

        <tr>
          <td class="tableblock halign-center valign-top"><p class="tableblock">string</p></td>
          <td class="tableblock halign-center valign-top"><p class="tableblock">System.String</p></td>
        </tr>
      </tbody>
    </table>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      namespace myLib
      {
      public class Foo
      {
      static readonly int x = 1;  // Noncompliant
      static readonly int y = x + 4; // Noncompliant
      static readonly string s = "Bar";  // Noncompliant
      }
      }
      ```

      ```csharp Fix theme={null}
      namespace myLib
      {
      public class Foo
      {
      const int x = 1;
      const int y = x + 4;
      const string s = "Bar";
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Whitespace and control characters in string literals should be explicit">
    <div class="paragraph">
      <p>Non-encoded <a href="https://en.wikipedia.org/wiki/Control_character">control characters</a> and whitespace characters are often injected in the source code because of a bad manipulation. They are either invisible or difficult to recognize, which can result in bugs when the string is not what the developer expects. If you actually need to use a control character use their encoded version:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://en.wikipedia.org/wiki/ASCII">ASCII</a>, for example \n and \t</p>
        </li>

        <li>
          <p><a href="https://en.wikipedia.org/wiki/Unicode">Unicode</a>, for example U+000D and U+0009</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when the following characters are seen in a <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/">string literal</a>:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://en.wikipedia.org/wiki/ASCII#Control_characters">ASCII control character</a>. (character index \< 32 or = 127)</p>
        </li>

        <li>
          <p>Unicode <a href="https://en.wikipedia.org/wiki/Unicode_character_property#Whitespace">whitespace characters</a>.</p>
        </li>

        <li>
          <p>Unicode <a href="https://en.wikipedia.org/wiki/C0_and_C1_control_codes">C0 control characters</a></p>
        </li>

        <li>
          <p>Unicode characters <code>U+200B, U+200C, U+200D, U+2060, U+FEFF, U+2028, U+2029</code></p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      string tabInside = "A	B";                 // Noncompliant: contains a tabulation
      string zeroWidthSpaceInside = "foo​bar";     // Noncompliant: contains a U+200B character inside
      Console.WriteLine(zeroWidthSpaceInside);    // Prints "foo?bar"
      ```

      ```csharp Fix theme={null}
      string tabInside = "A\tB";                      // Compliant: escaped value
      string zeroWidthSpaceInside = "foo\u200Bbar";   // Compliant: escaped value
      Console.WriteLine(zeroWidthSpaceInside);        // Prints "foo?bar"
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Test method signatures should be correct">
    <div class="paragraph">
      <p>A method is identified as a test method if it is marked with one of the following attributes:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>\[TestMethod] or \[DataTestMethod] (for <strong>MSTest</strong>).</p>
        </li>

        <li>
          <p>\[Fact] or \[Theory] (for <strong>xUnit</strong>).</p>
        </li>

        <li>
          <p>\[Test], \[TestCase], \[TestCaseSource], or \[Theory] (for <strong>NUnit</strong>).</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>However, non-public methods are not considered test methods and will not be executed, regardless of whether they have a test attribute.
      Additionally, methods with the async void modifier or methods that contain generics \<T> anywhere in their signatures are also excluded from being recognized as tests and will not be executed.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      [TestMethod]
      void TestNullArg()  // Noncompliant, method is not public
      {  /* ... */  }

      [TestMethod]
      public async void MyIgnoredTestMethod()  // Noncompliant, this is an 'async void' method
      { /* ... */ }

      [TestMethod]
      public void MyIgnoredGenericTestMethod<T>(T foo)  // Noncompliant, method has generics in its signature
      { /* ... */ }
      ```

      ```csharp Fix theme={null}
      [TestMethod]
      public void TestNullArg()
      {  /* ... */  }

      [TestMethod]
      public async Task MyIgnoredTestMethod()
      { /* ... */ }

      [TestMethod]
      public void MyIgnoredGenericTestMethod(int foo)
      { /* ... */ }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Exceptions should not be explicitly rethrown">
    <div class="paragraph">
      <p>In C#, the <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/statements#13106-the-throw-statement">throw</a> statement can be used in two different ways:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>by specifying an expression</p>
        </li>

        <li>
          <p>without specifying an expression</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      try
      {
      }
      catch(Exception exception)
      {
      // code that uses the exception
      throw exception; // The exception stack trace is cleared up to this point.
      }
      ```

      ```csharp Fix theme={null}
      try
      {
      }
      catch(Exception exception)
      {
      // code that uses the exception
      throw; // The stack trace of the initial exception is preserved.
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Collection sizes and array length comparisons should make sense">
    <div class="paragraph">
      <p>The size of a collection and the length of an array are always greater than or equal to zero. Testing it doesn’t make sense, since the result is always <code>true</code>.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if(collection.Count >= 0){...} // Noncompliant: always true

      if(array.Length >= 0){...} // Noncompliant: always true
      ```

      ```csharp Fix theme={null}
      if(enumerable.Count() < 0){...} // Noncompliant: always false
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Types should not extend outdated base types">
    <div class="paragraph">
      <p>With the advent of .NET framework version 2, certain practices have become obsolete.</p>
    </div>

    <div class="paragraph">
      <p>In particular, exceptions should now extend \`System.Exception instead of System.ApplicationException. Similarly, generic collections should be used instead of the older, non-generic, ones. Finally when creating an XML view, you should not extend System.Xml.XmlDocument.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when an externally visible type extends one of these types:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>System.ApplicationException</p>
        </li>

        <li>
          <p>System.Xml.XmlDocument</p>
        </li>

        <li>
          <p>System.Collections.CollectionBase</p>
        </li>

        <li>
          <p>System.Collections.DictionaryBase</p>
        </li>

        <li>
          <p>System.Collections.Queue</p>
        </li>

        <li>
          <p>System.Collections.ReadOnlyCollectionBase</p>
        </li>

        <li>
          <p>System.Collections.SortedList</p>
        </li>

        <li>
          <p>System.Collections.Stack\`</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;
      using System.Collections;

      namespace MyLibrary
      {
      public class MyCollection : CollectionBase  // Noncompliant
      {
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;
      using System.Collections;

      namespace MyLibrary
      {
      public class MyCollection : Collection<T>
      {
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Variables should not be self-assigned">
    <div class="paragraph">
      <p>Re-assigning a variable to itself is a defect as it has no actual effect and indicates meaning to do something else.
      It usually means that:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>The statement is redundant and should be removed</p>
        </li>

        <li>
          <p>The re-assignment is a mistake, and another value or variable was intended for the assignment instead</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Choice {
      private bool selected;

      public void MakeChoice(bool selected)
      {
          selected = selected; // Noncompliant
      }
      }
      ```

      ```csharp Fix theme={null}
      public class Choice {
      private bool selected;

      public void MakeChoice(bool selected)
      {
          this.selected = selected; // Compliant
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="GC.Collect should not be called">
    <div class="paragraph">
      <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.gc.collect">GC.Collect</a> is a method that forces or suggests to the <a href="https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/">garbage collector</a> to run a collection of objects in the managed heap that are no longer being used and free their memory.</p>
    </div>

    <div class="paragraph">
      <p>Calling GC.Collect is rarely necessary and can significantly affect application performance. That’s because it is a <a href="https://en.wikipedia.org/wiki/Tracing_garbage_collection">tracing garbage collector</a> and needs to examine <em>every object in memory</em> for cleanup and analyze all reachable objects from every application’s root (static fields, local variables on thread stacks, etc.).</p>
    </div>

    <div class="paragraph">
      <p>To perform tracing and memory releasing correctly, the garbage collection <a href="https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/latency">may</a> need to block all threads currently in execution. That is why, as a general rule, the <a href="https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/performance#troubleshoot-performance-issues">performance implications</a> of calling GC.Collect far outweigh the benefits.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when any overload of Collect is invoked.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      static void Main(string[] args)
      {
      // ...
      GC.Collect();                              // Noncompliant
      GC.Collect(2, GCCollectionMode.Optimized); // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Equals and the comparison operators should be overridden when implementing IComparable">
    <div class="paragraph">
      <p>When you implement \`IComparable or IComparable\<T> on a class you should also override Equals(object) and overload the comparison operators (==, !=, \<, \<=, >, >=). That’s because the CLR cannot automatically call your CompareTo implementation from Equals(object) or from the base comparison operator implementations. Additionally, it is best practice to override GetHashCode along with Equals.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a class implements IComparable without also overriding Equals(object)\` and the comparison operators.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Foo: IComparable  // Noncompliant
      {
      public int CompareTo(object obj) { /* ... */ }
      }
      ```

      ```csharp Fix theme={null}
      public class Foo: IComparable
      {
      public int CompareTo(object obj) { /* ... */ }
      public override bool Equals(object obj)
      {
      var other = obj as Foo;
      if (object.ReferenceEquals(other, null))
      {
        return false;
      }
      return this.CompareTo(other) == 0;
      }
      public int GetHashCode() { /* ... */ }
      public static bool operator == (Foo left, Foo right) 
      {
      if (object.ReferenceEquals(left, null))
      {
        return object.ReferenceEquals(right, null);
      }
      return left.Equals(right);
      }
      public static bool operator > (Foo left, Foo right) 
      {
      return Compare(left, right) > 0;
      }
      public static bool operator < (Foo left, Foo right) 
      {
      return Compare(left, right) < 0;
      }
      public static bool operator != (Foo left, Foo right) 
      {
      return !(left == right);
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Method overrides should not change parameter defaults">
    <div class="paragraph">
      <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments#optional-arguments">Default arguments</a> are determined by the static type of the object.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      class Base
      {
      public virtual void Run(int distance = 42) { /* ... */ }
      }

      class Derived : Base
      {
      public override void Run(int distance = 5) { /* ... */ }
      }

      Base x = new Base();
      x.Run(); // Here the default value of distance is 42
      Derived d = new Derived();
      d.Run(); // Here the default value of distance is 5
      Base b = new Derived();
      b.Run(); // Here the default value of distance is 42, not 5
      ```

      ```csharp Fix theme={null}
      interface IRunner
      {
      void Run(int distance = 42) { /* ... */ }
      }

      class Runner : IRunner
      {
      void IRunner.Run(int distance = 5) { /* ... */ }
      }

      IRunner x = new Runner();
      x.Run(); // Here the default value of distance is 42
      Runner d = new Runner();
      d.Run(); // This will not compile as the Run method is only visible through the specified interface
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="IDisposable should be implemented correctly">
    <div class="paragraph">
      <p>The \`IDisposable interface is a mechanism to release unmanaged resources, if not implemented correctly this could result in resource leaks or more severe bugs.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when the recommended dispose pattern, as defined by Microsoft, is not adhered to. See the <strong>Compliant Solution</strong> section for examples.</p>
    </div>

    <div class="paragraph">
      <p>Satisfying the rule’s conditions will enable potential derived classes to correctly dispose the members of your class:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>sealed classes are not checked.</p>
        </li>

        <li>
          <p>If a base class implements IDisposable your class should not have IDisposable in the list of its interfaces. In such cases it is recommended to override the base class’s protected virtual void Dispose(bool) method or its equivalent.</p>
        </li>

        <li>
          <p>The class should not implement IDisposable explicitly, e.g. the Dispose() method should be public.</p>
        </li>

        <li>
          <p>The class should contain protected virtual void Dispose(bool) method. This method allows the derived classes to correctly dispose the resources of this class.</p>
        </li>

        <li>
          <p>The content of the Dispose() method should be invocation of Dispose(true) followed by GC.SuppressFinalize(this)</p>
        </li>

        <li>
          <p>If the class has a finalizer, i.e. a destructor, the only code in its body should be a single invocation of Dispose(false).</p>
        </li>

        <li>
          <p>If the class inherits from a class that implements IDisposable it must call the Dispose, or Dispose(bool) method of the base class from within its own implementation of Dispose or Dispose(bool)\`, respectively. This ensures that all resources from the base class are properly released.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Foo1 : IDisposable // Noncompliant - provide protected overridable implementation of Dispose(bool) on Foo or mark the type as sealed.
      {
      public void Dispose() // Noncompliant - should contain only a call to Dispose(true) and then GC.SuppressFinalize(this)
      {
          // Cleanup
      }
      }

      public class Foo2 : IDisposable
      {
      void IDisposable.Dispose() // Noncompliant - Dispose() should be public
      {
          Dispose(true);
          GC.SuppressFinalize(this);
      }

      public virtual void Dispose() // Noncompliant - Dispose() should be sealed
      {
          Dispose(true);
          GC.SuppressFinalize(this);
      }
      }

      public class Foo3 : IDisposable
      {
      public void Dispose()
      {
          Dispose(true);
          GC.SuppressFinalize(this);
      }

      protected virtual void Dispose(bool disposing)
      {
          // Cleanup
      }

      ~Foo3() // Noncompliant - Modify Foo.~Foo() so that it calls Dispose(false) and then returns.
      {
          // Cleanup
      }
      }{code}
      ```

      ```csharp Fix theme={null}
      // Sealed class
      public sealed class Foo1 : IDisposable
      {
      public void Dispose()
      {
          // Cleanup
      }
      }

      // Simple implementation
      public class Foo2 : IDisposable
      {
      public void Dispose()
      {
          Dispose(true);
          GC.SuppressFinalize(this);
      }

      protected virtual void Dispose(bool disposing)
      {
          // Cleanup
      }
      }

      // Implementation with a finalizer
      public class Foo3 : IDisposable
      {
      public void Dispose()
      {
          Dispose(true);
          GC.SuppressFinalize(this);
      }

      protected virtual void Dispose(bool disposing)
      {
          // Cleanup
      }

      ~Foo3()
      {
          Dispose(false);
      }
      }

      // Base disposable class
      public class Foo4 : DisposableBase
      {
      protected override void Dispose(bool disposing)
      {
          // Cleanup
          // Do not forget to call base
          base.Dispose(disposing);
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="is should not be used with this">
    <div class="paragraph">
      <p>One of the possible ways of performing <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast">type-testing</a> is via the <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/is">is operator</a>: food is Pizza.</p>
    </div>

    <div class="paragraph">
      <p>The is operator is often used before a direct <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast#cast-expression">cast</a> to the target type, as a more flexible and powerful alternative to the <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast#as-operator">as operator</a>, especially when used to perform <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast#type-testing-with-pattern-matching">pattern matching</a>.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if (food is Pizza pizza)
      ```

      ```csharp Fix theme={null}
      public class Food
      {
      public void DoSomething() 
      {
      if (this is Pizza) // Noncompliant 
      {
        // Code specific to Pizza...
      }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Namespaces should correspond to file locations">
    <div class="paragraph">
      <p>By convention, namespaces within a project should start with the project default namespace, and end with the file’s position within the project. Anything else may confuse maintainers and callers.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      // file path: Gui/Screen.cs
      namespace Green  // Noncompliant
      {
      class Screen
      {
      }
      }
      ```

      ```csharp Fix theme={null}
      // file path: Gui/Screen.cs
      namespace Gui
      {
      class Screen
      {
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Enumeration types should comply with a naming convention">
    <div class="paragraph">
      <p>Shared naming conventions allow teams to collaborate efficiently. This rule checks that all <code>enum</code> names match a provided regular expression.</p>
    </div>

    <div class="paragraph">
      <p>The default configuration is the one recommended by Microsoft:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Pascal casing, starting with an upper case character, e.g. BackColor</p>
        </li>

        <li>
          <p>Short abbreviations of 2 letters can be capitalized, e.g. GetID</p>
        </li>

        <li>
          <p>Longer abbreviations need to be lower case, e.g. GetHtml</p>
        </li>

        <li>
          <p>If the enum is marked as \[Flags] then its name should be plural (e.g. MyOptions), otherwise, names should be singular (e.g. MyOption)</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public enum foo // Noncompliant
      {
      FooValue = 0
      }
      ```

      ```csharp Fix theme={null}
      [Flags]
      public enum Option // Noncompliant
      {
      None = 0,
      Option1 = 1,
      Option2 = 2
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Serialization constructors should be secured">
    <div class="paragraph">
      <p>Because serialization constructors allocate and initialize objects, security checks that are present on regular constructors must also be present on a serialization constructor. Failure to do so would allow callers that could not otherwise create an instance to use the serialization constructor to do this.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a type implements the <code>System.Runtime.Serialization.ISerializable interface, is not a delegate or interface, is declared in an assembly that allows partially trusted callers and has a constructor that takes a System.Runtime.Serialization.SerializationInfo object and a System.Runtime.Serialization.StreamingContext</code> object which is not secured by a security check, but one or more of the regular constructors in the type is secured.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;
      using System.IO;
      using System.Runtime.Serialization;
      using System.Runtime.Serialization.Formatters.Binary;
      using System.Security;
      using System.Security.Permissions;

      [assembly: AllowPartiallyTrustedCallersAttribute()]
      namespace MyLibrary
      {
      [Serializable]
      public class Foo : ISerializable
      {
          private int n;

          [FileIOPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]
          public Foo()
          {
             n = -1;
          }

          protected Foo(SerializationInfo info, StreamingContext context) // Noncompliant
          {
             n = (int)info.GetValue("n", typeof(int));
          }

          void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
          {
             info.AddValue("n", n);
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;
      using System.IO;
      using System.Runtime.Serialization;
      using System.Runtime.Serialization.Formatters.Binary;
      using System.Security;
      using System.Security.Permissions;

      [assembly: AllowPartiallyTrustedCallersAttribute()]
      namespace MyLibrary
      {
      [Serializable]
      public class Foo : ISerializable
      {
          private int n;

          [FileIOPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]
          public Foo()
          {
             n = -1;
          }

          [FileIOPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]
          protected Foo(SerializationInfo info, StreamingContext context)
          {
             n = (int)info.GetValue("n", typeof(int));
          }

          void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
          {
             info.AddValue("n", n);
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="base should not be used to access members in anonymous methods, iterator results, or lambda and query expressions">
    <div class="paragraph">
      <p>Using the <code>base</code> keyword to access a member in anonymous methods, iterator results, and lambda and query expressions results in the compiler creating extra classes under the covers. Those extra classes are "unverifiable", meaning that the under some trust levels, the code will not be allowed to run.</p>
    </div>

    <div class="paragraph">
      <p>Instead, the access should be made from a helper method.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public Person GetBasePerson() 
      {
      return delegate () { base.GetThePerson();  } // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      string BasePerson() 
      { 
      return base.GetThePerson();
      }

      public Person GetBasePerson() 
      {
      return delegate () { BasePerson();  } // Noncompliant
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="GetHashCode should not reference mutable fields">
    <div class="paragraph">
      <p>GetHashCode is used to file an object in a Dictionary or Hashtable. If GetHashCode uses non-readonly fields and those fields change after the object is stored, the object immediately becomes mis-filed in the Hashtable. Any subsequent test to see if the object is in the Hashtable will return a false negative.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Person
      {
      public int age;
      public string name;

      public override int GetHashCode()
      {
      int hash = 12;
      hash += this.age.GetHashCode(); // Noncompliant
      hash += this.name.GetHashCode(); // Noncompliant
      return hash;
      }
      ```

      ```csharp Fix theme={null}
      public class Person
      {
      public readonly DateTime birthday;
      public string name;

      public override int GetHashCode()
      {
      int hash = 12;
      hash += this.birthday.GetHashCode();
      return hash;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Extension methods should not extend object">
    <div class="paragraph">
      <p>﻿Creating an extension method that extends <code>object is not recommended because it makes the method available on <em>every</em> type. Extensions should be applied at the most specialized level possible, and that is very unlikely to be object</code>.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public static class MyExtensions
      {
      public static void SomeExtension(this object obj) // Noncompliant
      {
          // ...
      }
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="static fields should be initialized inline">
    <div class="paragraph">
      <p>When a <code>static constructor serves no other purpose that initializing static fields, it comes with an unnecessary performance cost because the compiler generates a check before each static</code> method or instance constructor invocation.</p>
    </div>

    <div class="paragraph">
      <p>Instead, inline initialization is highly recommended.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      namespace myLib
      {
      public class Foo
      {
      static int i;
      static string s;

      static Foo() // Noncompliant
      {
        i = 3;
        ResourceManager sm =  new ResourceManager("strings", Assembly.GetExecutingAssembly());
        s = sm.GetString("mystring");
      }
      }
      }
      ```

      ```csharp Fix theme={null}
      namespace myLib
      {
      public class Foo
      {
      static int i =3;
      static string s = InitString();

      static string InitString()
      {
        ResourceManager sm = new ResourceManager("strings", Assembly.GetExecutingAssembly());
        return sm.GetString("mystring");
      }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Flags enumerations zero-value members should be named None">
    <div class="paragraph">
      <p>An enumeration can be decorated with the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.flagsattribute">FlagsAttribute</a> to indicate that it can be used as a <a href="https://en.wikipedia.org/wiki/Bit_field">bit field</a>: a set of flags, that can be independently set and reset.</p>
    </div>

    <div class="paragraph">
      <p>For example, the following definition of the day of the week:</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      [Flags]
      enum Days
      {
      Monday = 1,    // 0b00000001
      Tuesday = 2,   // 0b00000010
      Wednesday = 4, // 0b00000100
      Thursday = 8,  // 0b00001000
      Friday = 16,   // 0b00010000
      Saturday = 32, // 0b00100000
      Sunday = 64    // 0b01000000
      }
      ```

      ```csharp Fix theme={null}
      [Flags]
      enum Days
      {
      // ...
      None = 0,                                                    // 0b00000000
      Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday, // 0b00011111
      Weekend = Saturday | Sunday,                                 // 0b01100000
      All = Weekdays | Weekend                                     // 0b01111111
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Declarations and initializations should be as concise as possible">
    <div class="paragraph">
      <p>In C#, the type of a variable can often be inferred by the compiler. The use of the \[var keyword]\(<a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/implicitly-typed-local-variables" class="bare">[https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/implicitly-typed-local-variables](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/implicitly-typed-local-variables)</a>) allows you to avoid repeating the type name in a variable declaration and object instantiation because the declared type can often be inferred by the compiler.</p>
    </div>

    <div class="paragraph">
      <p>Additionally, initializations providing the default value can also be omitted, helping to make the code more concise and readable.</p>
    </div>

    <div class="paragraph">
      <p>Unnecessarily verbose declarations and initializations should be simplified. Specifically, the following should be omitted when they can be inferred:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>array element type</p>
        </li>

        <li>
          <p>array size</p>
        </li>

        <li>
          <p>\`new DelegateType</p>
        </li>

        <li>
          <p>new Nullable\<Type>\`</p>
        </li>

        <li>
          <p>object or collection initializers (\{})</p>
        </li>

        <li>
          <p>type of lambda expression parameters</p>
        </li>

        <li>
          <p>parameter declarations of anonymous methods when the parameters are not used.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      var l = new List<int>() {}; // Noncompliant, {} can be removed
      var o = new object() {}; // Noncompliant, {} can be removed

      var ints = new int[] {1, 2, 3}; // Noncompliant, int can be omitted
      ints = new int[3] {1, 2, 3}; // Noncompliant, the size specification can be removed

      int? i = new int?(5); // Noncompliant new int? could be omitted, it can be inferred from the declaration, and there's implicit conversion from T to T?
      var j = new int?(5);

      Func<int, int> f1 = (int i) => 1; //Noncompliant, can be simplified

      class Class
      {
      private event EventHandler MyEvent;

      public Class()
      {
          MyEvent += new EventHandler((a,b)=>{ }); // Noncompliant, needlessly verbose
      }
      }
      ```

      ```csharp Fix theme={null}
      var l = new List<int>();
      var o = new object();

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

      int? i = 5;
      var j = new int?(5); 

      Func<int, int> f1 = (i) => 1;

      class Class
      {
      private event EventHandler MyEvent;

      public Class()
      {
          MyEvent += (a,b)=>{ };
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Methods and properties should be named in PascalCase">
    <div class="paragraph">
      <p>Shared naming conventions allow teams to collaborate efficiently.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a method or a property name is not PascalCased.</p>
    </div>

    <div class="paragraph">
      <p>For example, the method</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public int doSomething() {...} // Noncompliant
      ```

      ```csharp Fix theme={null}
      public int DoSomething() {...}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="StringBuilder data should be used">
    <div class="paragraph">
      <p>StringBuilder instances that never build a string clutter the code and worse are a drag on performance. Either they should be removed, or the missing ToString() call should be added.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public void DoSomething(List<string> strings) {
      var sb = new StringBuilder();  // Noncompliant
      sb.Append("Got: ");
      foreach(var str in strings) {
      sb.Append(str).Append(", ");
      // ...
      }
      }
      ```

      ```csharp Fix theme={null}
      public void DoSomething(List<string> strings) {
      foreach(var str in strings) {
      // ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Control flow statements if, switch, for, foreach, while, do  and try should not be nested too deeply">
    <div class="paragraph">
      <p>Nested control flow statements <code>if, switch, for, foreach, while, do, and try</code>  are often key ingredients in creating
      what’s known as "Spaghetti code". This code smell can make your program difficult to understand and maintain.</p>
    </div>

    <div class="paragraph">
      <p>When numerous control structures are placed inside one another, the code becomes a tangled, complex web.
      This significantly reduces the code’s readability and maintainability, and it also complicates the testing process.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if (condition1)                  // Compliant - depth = 1
      {             
      /* ... */
      if (condition2)                // Compliant - depth = 2
      {              
      /* ... */
      for (int i = 0; i < 10; i++)  // Compliant - depth = 3
      {
        /* ... */
        if (condition4)            // Noncompliant - depth = 4, which exceeds the limit
        {            
          if (condition5)          // Depth = 5, exceeding the limit, but issues are only reported on depth = 4
          {          
            /* ... */
          }
          return;
        }
      }
      }
      }
      ```

      ```csharp Fix theme={null}
      if (!condition1)
      {
      return;
      }
      /* ... */
      if (!condition2)
      {
      return;
      }
      for (int i = 0; i < 10; i++)
      {
      /* ... */
      if (condition4)
      {
      if (condition5)
      {
        /* ... */
      }
      return;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Objects should not be created to be dropped immediately without being used">
    <div class="paragraph">
      <p>Creating objects that are not used is a vulnerability that can lead to unexpected behavior.</p>
    </div>

    <div class="paragraph">
      <p>If this was done intentionally due to side effects in the object’s constructor, the code should be moved to a dedicated method.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public void Method(MyObject myObject)
      {
      if (myObject is null)
      {
          new MyObject(); // Noncompliant
      }

      if (myObject.IsCorrupted)
      {
          new ArgumentException($"{nameof(myObject)} is corrupted"); // Noncompliant
      }

      // ...
      }
      ```

      ```csharp Fix theme={null}
      public void Method(MyObject myObject)
      {
      if (myObject is null)
      {
          myObject = new MyObject(); // Compliant
      }

      if (myObject.IsCorrupted)
      {
          throw new ArgumentException($"{nameof(myObject)} is corrupted"); // Compliant
      }

      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Enumeration members should not be named Reserved">
    <div class="paragraph">
      <p>If an <code>enum member’s name contains the word "reserved" it implies it is not currently used and will be change in the future. However changing an enum member is a breaking change and can create significant problems. There is no need to reserve an enum</code> member since a new member can be added in the future, and such an addition will usually not be a breaking change.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when the name of an enumeration member contains "reserved".</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      namespace MyLibrary
      {
      public enum Color
      { 
          None, 
          Red, 
          Orange, 
          Yellow,
          ReservedColor  // Noncompliant
      }  
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="IDisposables should be disposed">
    <div class="paragraph">
      <p>When writing <a href="https://learn.microsoft.com/en-us/dotnet/standard/managed-code">managed code</a>, there is no need to worry about memory allocation or deallocation as it is taken care of by the <a href="https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection">garbage collector</a>. However, certain objects, such as Bitmap, utilize unmanaged memory for specific purposes like <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/unsafe-code">pointer arithmetic</a>. These objects may have substantial unmanaged memory footprints while having minimal managed footprints. Unfortunately, the garbage collector only recognizes the small managed footprint and does not promptly reclaim the corresponding unmanaged memory (by invoking the finalizer method of Bitmap) for efficiency reasons.</p>
    </div>

    <div class="paragraph">
      <p>In addition, it’s essential to manage other system resources besides memory. The operating system has limits on the number of <a href="https://en.wikipedia.org/wiki/File_descriptor">file descriptors</a> (e.g., FileStream) or <a href="https://en.wikipedia.org/wiki/Network_socket">sockets</a> (e.g., WebClient) that can remain open simultaneously. Therefore, it’s crucial to Dispose of these resources promptly when they are no longer required, instead of relying on the garbage collector to invoke the finalizers of these objects at an unpredictable time in the future.</p>
    </div>

    <div class="paragraph">
      <p>This rule keeps track of private fields and local variables of specific types that implement IDisposable or IAsyncDisposable. It identifies instances of these types that are not properly disposed, closed, aliased, returned, or passed to other methods. This applies to instances that are either directly created using the new operator or instantiated through a predefined list of factory methods.</p>
    </div>

    <div class="paragraph">
      <p>Here is the list of predefined factory methods tracked by this rule:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>System.IO.File.Create()</p>
        </li>

        <li>
          <p>System.IO.File.Open()</p>
        </li>

        <li>
          <p>System.Drawing.Image.FromFile()</p>
        </li>

        <li>
          <p>System.Drawing.Image.FromStream()</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public Stream WriteToFile(string path, string text)
      {
      var fs = new FileStream(path, FileMode.Open); // Compliant: it is returned
      var bytes = Encoding.UTF8.GetBytes(text);
      fs.Write(bytes, 0, bytes.Length);
      return fs;
      }

      public void ReadFromStream(Stream s)
      {
      var sr = new StreamReader(s); // Compliant: it would close the underlying stream.
      // ...
      }
      ```

      ```csharp Fix theme={null}
      public class ResourceHolder 
      {
      private FileStream fs; // Noncompliant: dispose or close are never called

      public void OpenResource(string path)
      {
      this.fs = new FileStream(path, FileMode.Open);
      }

      public void WriteToFile(string path, string text)
      {
      var fs = new FileStream(path, FileMode.Open); // Noncompliant: not disposed, returned or initialized with another disposable object
      var bytes = Encoding.UTF8.GetBytes(text);
      fs.Write(bytes, 0, bytes.Length);
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Type inheritance should not be recursive">
    <div class="paragraph">
      <p><a href="https://en.wikipedia.org/wiki/Recursion">Recursion</a> is a technique used to define a problem in terms of the problem itself, usually in terms of a simpler version of the problem itself.</p>
    </div>

    <div class="paragraph">
      <p>For example, the implementation of the generator for the n-th value of the <a href="https://en.wikipedia.org/wiki/Fibonacci_sequence">Fibonacci sequence</a> comes naturally from its mathematical definition, when recursion is used:</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      int NthFibonacciNumber(int n)
      {
      if (n <= 1)
      {
          return 1;
      }
      else
      {
          return NthFibonacciNumber(n - 1) + NthFibonacciNumber(n - 2);
      }
      }
      ```

      ```csharp Fix theme={null}
      int NthFibonacciNumber(int n)
      {
      int previous = 0;
      int last = 1;
      for (var i = 0; i < n; i++)
      {
          (previous, last) = (last, last + previous);
      }
      return last;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Impure methods should not be called on readonly value type fields">
    <div class="paragraph">
      <p>A field marked \`readonly can only be assigned as part of its declaration or in a constructor. While readonly reference types (e.g. classes) can still have their state changed subsequently, the same is not true of value types such as struct s. Thus, calling a method that updates object state on a readonly value type field simply has no effect (but runs without error!). The result is code that probably doesn’t do what you thought it did.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a method that is not marked \[Pure] is invoked on a readonly\` value type field.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public struct S1
      {
      public int value;

      public void SetValue()
      {
          value = 10;
      }
      }

      class Test
      {
      static readonly S1 first;
      static S1 second;

      static void Main()
      {
          first.SetValue();  // Noncompliant
          second.SetValue();
          Console.WriteLine(first.value);  // Surprise! This writes 0
          Console.WriteLine(second.value); // This writes 10
      }
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Explicit conversions of foreach loops should not be used">
    <div class="paragraph">
      <p>The <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/iteration-statements#the-foreach-statement">foreach</a> statement was introduced in the C# language prior to generics to make it easier to work with the non-generic collections available at that time such as <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.arraylist">ArrayList</a>. The foreach statements allow you to downcast elements of a collection of <a href="https://learn.microsoft.com/en-us/dotnet/api/system.object">Objects</a> to any other type.</p>
    </div>

    <div class="paragraph">
      <p>The problem is that to achieve the cast, the foreach statements silently perform <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions#explicit-conversions">explicit type conversion</a>, which at runtime can result in an <a href="https://learn.microsoft.com/en-us/dotnet/api/system.invalidcastexception">InvalidCastException</a>.</p>
    </div>

    <div class="paragraph">
      <p>C# code iterating on generic collections or arrays should not rely on foreach statement’s silent explicit conversions.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Fruit { }
      public class Orange : Fruit { }
      public class Apple : Fruit { }

      class MyTest
      {
      public void Test()
      {
      var fruitBasket = new List<Fruit>();
      fruitBasket.Add(new Orange());
      fruitBasket.Add(new Orange());
      fruitBasket.Add(new Apple());

      foreach (Orange orange in fruitBasket) // Noncompliant
      {
        //...
      } 
      }
      }
      ```

      ```csharp Fix theme={null}
      public class Fruit { }
      public class Orange : Fruit { }
      public class Apple : Fruit { }

      class MyTest
      {
      public void Test()
      {
      var fruitBasket = new List<Fruit>();
      fruitBasket.Add(new Orange());
      fruitBasket.Add(new Orange());
      fruitBasket.Add(new Apple());

      foreach (Orange orange in fruitBasket.OfType<Orange>())
      {
        //...
      } 
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Inherited member visibility should not be decreased">
    <div class="paragraph">
      <p>Decreasing the <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers">accessibility level</a> of an inherited method that is not <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/override">overridable</a> to <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private">private</a> will shadow the name of the base method and can lead to confusion.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Base
      {
      public void SomeMethod(int count) { }
      }
      public class Derived : Base
      {
      private void SomeMethod(int count) { } // Noncompliant
      }

      class Program
      {
      public void DoWork()
      {
          var derived = new Derived();
          derived.SomeMethod(42); // Base.SomeMethod is accessed here
      }
      }
      ```

      ```csharp Fix theme={null}
      public class Base
      {
      public void SomeMethod(int count) { }
      }
      public class Derived : Base
      {
      private void SomeMethod(int count) { } // Noncompliant
      }

      public class SecondDerived : Derived
      {
      public void DoWork()
      {
          SomeMethod(42); // Base.SomeMethod is accessed here
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Constructors should only call non-overridable methods">
    <div class="paragraph">
      <p>Calling an overridable method from a constructor could result in failures or strange behaviors when instantiating a subclass which overrides the method.</p>
    </div>

    <div class="paragraph">
      <p>When constructing an object of a derived class, the constructor of the parent class is invoked first, and only then the constructor of the derived class is called. This sequential construction process applies to multiple levels of inheritance as well, starting from the base class and progressing to the most derived class.</p>
    </div>

    <div class="paragraph">
      <p>If an overridable method is called within the constructor of the parent class, it may inadvertently invoke an overridden implementation in the derived class. This can lead to unexpected failures or strange behaviors because the object’s construction is still in progress and may not have reached a fully initialized state. Consequently, the overridden method may rely on uninitialized members or have assumptions about the object’s state that are not yet valid.</p>
    </div>

    <div class="paragraph">
      <p>For example:</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Parent 
      {
      public Parent() 
      {
      DoSomething();  // Noncompliant
      }

      public virtual void DoSomething() // can be overridden
      {  
      ...
      }
      }

      public class Child : Parent 
      {
      private string foo;

      public Child(string foo) // leads to call DoSomething() in Parent constructor which triggers a NullReferenceException as foo has not yet been initialized
      {
      this.foo = foo;
      }

      public override void DoSomething() 
      {
      Console.WriteLine(this.foo.Length);
      }
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Empty nullable value should not be accessed">
    <div class="paragraph">
      <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.nullable-1">Nullable value types</a> can hold either a value or null.</p>
    </div>

    <div class="paragraph">
      <p>The value held in the nullable type can be accessed with the Value property or by casting it to the underlying type. Still, both operations throw an InvalidOperationException when the value is null. A nullable type should always be tested before accessing the value to avoid raising exceptions.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      void Sample(bool condition)
      {
      int? nullableValue = condition ? 42 : null;
      Console.WriteLine(nullableValue.Value); // Noncompliant: InvalidOperationException is raised

      int? nullableCast = condition ? 42 : null;
      Console.WriteLine((int)nullableCast);   // Noncompliant: InvalidOperationException is raised
      }
      ```

      ```csharp Fix theme={null}
      void Sample(bool condition)
      {
      int? nullableValue = condition ? 42 : null;
      if (nullableValue.HasValue)
      {
        Console.WriteLine(nullableValue.Value);
      }

      int? nullableCast = condition ? 42 : null;
      if (nullableCast is not null)
      {
        Console.WriteLine((int)nullableCast);
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Trivial properties should be auto-implemented">
    <div class="paragraph">
      <p>Trivial properties, which include no logic but setting and getting a backing field should be converted to auto-implemented properties, yielding cleaner and more readable code.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Car 
      {
      private string _make;
      public string Make // Noncompliant
      {
      get { return _make; }
      set { _make = value; }
      }
      }
      ```

      ```csharp Fix theme={null}
      public class Car 
      {
      public string Make { get; set; }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="General or reserved exceptions should never be thrown">
    <div class="paragraph">
      <p>Throwing general exceptions such as \`Exception, SystemException and ApplicationException will have a negative impact on any code trying to catch these exceptions.</p>
    </div>

    <div class="paragraph">
      <p>From a consumer perspective, it is generally a best practice to only catch exceptions you intend to handle. Other exceptions should ideally be let to propagate up the stack trace so that they can be dealt with appropriately. When a general exception is thrown, it forces consumers to catch exceptions they do not intend to handle, which they then have to re-throw.</p>
    </div>

    <div class="paragraph">
      <p>Besides, when working with a general type of exception, the only way to distinguish between multiple exceptions is to check their message, which is error-prone and difficult to maintain. Legitimate exceptions may be unintentionally silenced and errors may be hidden.</p>
    </div>

    <div class="paragraph">
      <p>For instance, if an exception such as StackOverflowException is caught and not re-thrown, it may prevent the program from terminating gracefully.</p>
    </div>

    <div class="paragraph">
      <p>When throwing an exception, it is therefore recommended to throw the most specific exception possible so that it can be handled intentionally by consumers.</p>
    </div>

    <div class="paragraph">
      <p>Additionally, some reserved exceptions should not be thrown manually. Exceptions such as IndexOutOfRangeException, NullReferenceException, OutOfMemoryException or ExecutionEngineException\` will be thrown automatically by the runtime when the corresponding error occurs. Many of them indicate serious errors, which the application may not be able to recover from. It is therefore recommended to avoid throwing them as well as using them as base classes.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public void DoSomething(object obj)
      {
      if (obj == null)
      {
      throw new NullReferenceException("obj");  // Noncompliant: This reserved exception should not be thrown manually
      }
      // ...
      }
      ```

      ```csharp Fix theme={null}
      public void DoSomething(object obj)
      {
      if (obj == null)
      {
      throw new ArgumentNullException("obj");  // Compliant: this is a specific and non-reserved exception type
      }
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Operators should be overloaded consistently">
    <div class="paragraph">
      <p>When implementing operator overloads, it is very important to make sure that all related operators and methods are consistent in their implementation.</p>
    </div>

    <div class="paragraph">
      <p>The following guidelines should be followed:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>When providing \`operator == you should also provide operator != and vice-versa.</p>
        </li>

        <li>
          <p>When providing operator == you should also provide Equals(Object) and GetHashCode().</p>
        </li>

        <li>
          <p>When providing operator +, -, \*, / or % you should also provide operator ==\`, respecting previous guidelines.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when any of these guidelines are not followed on publicly-visible type (public, protected or protected internal).</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      namespace MyLibrary
      {
      public class Foo // Noncompliant
      {
      private int left;
      private int right;

      public Foo(int l, int r)
      {
        this.left = l;
        this.right = r;
      }

      public static Foo operator +(Foo a, Foo b)
      {
        return new Foo(a.left + b.left, a.right + b.right);
      }

      public static Foo operator -(Foo a, Foo b)
      {
        return new Foo(a.left - b.left, a.right - b.right);
      }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;

      namespace MyLibrary
      {
      public class Foo
      {
      private int left;
      private int right;

      public Foo(int l, int r)
      {
        this.left = l;
        this.right = r;
      }

      public static Foo operator +(Foo a, Foo b)
      {
        return new Foo(a.left + b.left, a.right + b.right);
      }

      public static Foo operator -(Foo a, Foo b)
      {
        return new Foo(a.left - b.left, a.right - b.right);
      }

      public static bool operator ==(Foo a, Foo b)
      {
        return (a.left == b.left && a.right == b.right);
      }

      public static bool operator !=(Foo a, Foo b)
      {
        return !(a == b);
      }

      public override bool Equals(Object obj)
      {
        Foo a = obj as Foo;
        if (a == null)
          return false;
        return this == a;
      }

      public override int GetHashCode()
      {
         return (this.left * 10) + this.right;
      }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using lambda expressions in loops should be avoided in Blazor markup section">
    <div class="paragraph">
      <p>In Blazor, using <a href="https://learn.microsoft.com/en-us/aspnet/core/blazor/components/event-handling#lambda-expressions">lambda expressions</a> as <a href="https://learn.microsoft.com/en-us/aspnet/core/blazor/components/event-handling#lambda-expressions">event handlers</a> when the UI elements are rendered in a loop can lead to negative user experiences and performance issues. This is particularly noticeable when rendering a large number of elements.</p>
    </div>

    <div class="paragraph">
      <p>The reason behind this is that Blazor rebuilds all lambda expressions within the loop every time the UI elements are rendered.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      @for (var i = 1; i < 100; i++)
      {
      var buttonNumber = i;

      <button @onclick="@(e => DoAction(e, buttonNumber))"> @* Noncompliant *@
          Button #@buttonNumber
      </button>
      }

      @code {
      private void DoAction(MouseEventArgs e, int button)
      {
          // Do something here
      }
      }
      ```

      ```csharp Fix theme={null}
      @foreach (var button in Buttons)
      {
      <button @key="button.Id" @onclick="button.Action">  @* Compliant *@
          Button #@button.Id
      </button>
      }

      @code {
      private List<Button> Buttons { get; set; } = new();

      protected override void OnInitialized()
      {
          for (var i = 0; i < 100; i++)
          {
              var button = new Button();

              button.Action = (e) => DoAction(e, button);

              Buttons.Add(button);
          }
      }

      private void DoAction(MouseEventArgs e, Button button)
      {
          // Do something here
      }

      private class Button
      {
          public string? Id { get; } = Guid.NewGuid().ToString();
          public Action<MouseEventArgs> Action { get; set; } = e => { };
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Interface methods should be callable by derived types">
    <div class="paragraph">
      <p>When a base type explicitly implements a public interface method, that method is only accessible in derived types through a reference to the current instance (namely \`this). If the derived type explicitly overrides that interface method, the base implementation becomes inaccessible.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when an unsealed, externally visible type provides an explicit method implementation of a public interface\` and does not provide an alternate, externally visible method with the same name.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public interface IMyInterface
      {
      void MyMethod();
      }

      public class Foo : IMyInterface
      {
      void IMyInterface.MyMethod() // Noncompliant
      {
          MyMethod();
      }

      void MyMethod()
      {
          // Do something ...
      }
      }

      public class Bar : Foo, IMyInterface
      {
      public void MyMethod()
      {
          // Can't access base.MyMethod()
          // ((IMyInterface)this).MyMethod() would be a recursive call
      }
      }
      ```

      ```csharp Fix theme={null}
      public interface IMyInterface
      {
      void MyMethod();
      }

      public class Foo : IMyInterface
      {
      void IMyInterface.MyMethod()
      {
          MyMethod();
      }

      protected void MyMethod() // or public
      {
          // Do something ...
      }
      }

      public class Bar : Foo, IMyInterface
      {
      public void MyMethod()
      {
          // Do something
          base.MyMethod();
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Method parameters should be declared with base types">
    <div class="paragraph">
      <p>When a derived type is used as a parameter instead of the base type, it limits the uses of the method. If the additional functionality that is provided in the derived type is not required then that limitation isn’t required, and should be removed.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a method declaration includes a parameter that is a derived type and accesses only members of the base type.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;
      using System.IO;

      namespace MyLibrary
      {
      public class Foo
      {
      public void ReadStream(FileStream stream) // Noncompliant: Uses only System.IO.Stream methods
      {
        int a;
        while ((a = stream.ReadByte()) != -1)
        {
              // Do something.
        }
      }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;
      using System.IO;

      namespace MyLibrary
      {
      public class Foo
      {
      public void ReadStream(Stream stream)
      {
        int a;
        while ((a = stream.ReadByte()) != -1)
        {
              // Do something.
        }
      }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Getters and setters should access the expected fields">
    <div class="paragraph">
      <p>Properties provide a way to enforce <a href="https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)">encapsulation</a> by providing accessors that give controlled access to private fields. However, in classes with multiple fields, it is not unusual that <a href="https://en.wikipedia.org/wiki/Copy-and-paste_programming">copy-and-paste</a> is used to quickly create the needed properties, which can result in the wrong field being accessed by a getter or setter.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      class C
      {
      private int x;
      private int y;
      public int Y => x; // Noncompliant: The returned field should be 'y'
      }
      ```

      ```csharp Fix theme={null}
      class A
      {
      private int x;
      private int y;

      public int X
      {
          get { return x; }
          set { x = value; }
      }

      public int Y
      {
          get { return x; }  // Noncompliant: field 'y' is not used in the return value
          set { x = value; } // Noncompliant: field 'y' is not updated
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Composite format strings should not lead to unexpected behavior at runtime">
    <div class="paragraph">
      <p>Composite format strings in C# are evaluated at runtime, which means they are not verified by the compiler. Introducing an ill-formed format item, or indexing mismatch can lead to unexpected behaviors or runtime errors. The purpose of this rule is to perform static validation on composite format strings used in various string formatting functions to ensure their correct usage.
      This rule validates the proper behavior of composite formats when invoking the following methods:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>String.Format</p>
        </li>

        <li>
          <p>StringBuilder.AppendFormat</p>
        </li>

        <li>
          <p>Console.Write</p>
        </li>

        <li>
          <p>Console.WriteLine</p>
        </li>

        <li>
          <p>TextWriter.Write</p>
        </li>

        <li>
          <p>TextWriter.WriteLine</p>
        </li>

        <li>
          <p>Debug.WriteLine(String, Object\[])</p>
        </li>

        <li>
          <p>Trace.TraceError(String, Object\[])</p>
        </li>

        <li>
          <p>Trace.TraceInformation(String, Object\[])</p>
        </li>

        <li>
          <p>Trace.TraceWarning(String, Object\[])</p>
        </li>

        <li>
          <p>TraceSource.TraceInformation(String, Object\[])</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      s = string.Format("[0}", arg0); // Noncompliant: square bracket '[' instead of curly bracket '{'
      s = string.Format("{{0}", arg0); // Noncompliant: double starting curly brackets '{{'
      s = string.Format("{0}}", arg0); // Noncompliant: double ending curly brackets '}}'
      s = string.Format("{-1}", arg0); // Noncompliant: invalid index for the format item, must be >= 0
      s = string.Format("{0} {1}", arg0); // Noncompliant: two format items in the string but only one argument provided
      ```

      ```csharp Fix theme={null}
      s = string.Format("{0}", 42); // Compliant
      s = string.Format("{0,10}", 42); // Compliant
      s = string.Format("{0,-10}", 42); // Compliant
      s = string.Format("{0:0000}", 42); // Compliant
      s = string.Format("{2}-{0}-{1}", 1, 2, 3); // Compliant
      s = string.Format("no format"); // Compliant
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Overriding members should do more than simply call the same member in the base class">
    <div class="paragraph">
      <p>Overriding a method just to call the same method from the base class without performing any other actions is useless and misleading. The only time this is justified is in <code>sealed overriding methods, where the effect is to lock in the parent class behavior. This rule ignores overrides of Equals and GetHashCode</code>.</p>
    </div>

    <div class="paragraph">
      <p>NOTE: In some cases it might be dangerous to add or remove empty overrides, as they might be breaking changes.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public override void Method() // Noncompliant
      {
      base.Method(); 
      }
      ```

      ```csharp Fix theme={null}
      public override void Method()
      {
      //do something else
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Exit methods should not be called">
    <div class="paragraph">
      <p>Calling <code>Environment.Exit(exitCode) or Application.Exit()</code> terminates the process and returns an exit code to the operating system..</p>
    </div>

    <div class="paragraph">
      <p>Each of these methods should be used with extreme care, and only when the intent is to stop the whole application.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      Environment.Exit(0);
      Application.Exit();
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="The outputs of as casts should be null-checked, not the inputs">
    <div class="paragraph">
      <p>The output of an <code>as</code> cast will be null if the input to the cast cannot safely be cast to the desired type. So it makes sense that after such a cast you would null-check the output. But it doesn’t make sense to check the input.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      void DoTheThing(Toy toy) 
      {
      Ball ball = toy as Ball;
      if (toy != null) // Noncompliant
      {
      //...
      }
      }
      ```

      ```csharp Fix theme={null}
      void DoTheThing(Toy toy) 
      {
      Ball ball = toy as Ball;
      if (ball != null)
      {
      //...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Method signatures should not contain nested generic types">
    <div class="paragraph">
      <p>A nested type is a type argument that is also a generic type. Calling a method with such a nested type argument requires complicated and confusing code. It should be avoided as much as possible.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;
      using System.Collections.Generic;

      namespace MyLibrary
      {
      public class Foo
      {
      public void DoSomething(ICollection<ICollection<int>> outerCollect) // Noncompliant
      {
      }
      }
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Parameters with SupplyParameterFromQuery attribute should be used only in routable components">
    <div class="paragraph">
      <p><a href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.supplyparameterfromqueryattribute">SupplyParameterFromQuery</a> attribute is used to specify that a component parameter of a routable component comes from the <a href="https://en.wikipedia.org/wiki/Query_string">query string</a>.</p>
    </div>

    <div class="paragraph">
      <p>In the case of non-routable components, the SupplyParameterFromQuery does not contribute to the functionality, and removing it will not affect the behavior.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      <h3>Component</h3>

      @code {
      [Parameter]
      [SupplyParameterFromQuery]  // Noncompliant
      public bool Param { get; set; }
      }
      ```

      ```csharp Fix theme={null}
      @page "/component"

      <h3>Component</h3>

      @code {
      [Parameter]
      [SupplyParameterFromQuery]  // Compliant
      public bool Param { get; set; }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="IndexOf checks should not be for positive numbers">
    <div class="paragraph">
      <p>Most checks against an <a href="https://learn.microsoft.com/en-us/dotnet/api/system.string.indexof">IndexOf</a> value compare it with -1 because <strong>0 is a valid index</strong>.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      strings.IndexOf(someString) == -1 // Test for "index not found"
      strings.IndexOf(someString) < 0   // Test for "index not found"
      strings.IndexOf(someString) >= 0  // Test for "index found"
      ```

      ```csharp Fix theme={null}
      strings.Contains(someString) // bool result
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="switch statements should not have too many case clauses">
    <div class="paragraph">
      <p>When <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/selection-statements#the-switch-statement">switch</a> statements have large sets of case clauses, it is usually an attempt to map two sets of data. A <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2">Dictionary</a> should be used instead to make the code more readable and maintainable.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class TooManyCase
      {
      public int mapValues(char ch)
      {
          switch(ch) {  // Noncompliant: 5 cases, "default" excluded, more than maximum = 4
              case 'a':
                  return 1;
              case 'b':
              case 'c':
                  return 2;
              case 'd':
                  return 3;
              case 'e':
                  return 4;
              case 'f':
              case 'g':
              case 'h':
                  return 5;
              default:
                  return 6;
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System.Collections.Generic;

      public class TooManyCase
      {
      Dictionary<char, int> matching = new Dictionary<char, int>()
      {
          { 'a', 1 }, 
          { 'b', 2 }, 
          { 'c', 2 }, 
          { 'd', 3 },
          { 'e', 4 }, 
          { 'f', 5 }, 
          { 'g', 5 }, 
          { 'h', 5 }
      };

      public int mapValues(char ch)
      {
          int value;
          if (this.matching.TryGetValue(ch, out value)) {
              return value;
          } else {
              return 6;
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Exceptions should not be thrown from unexpected methods">
    <div class="paragraph">
      <p>The rule is reporting when an exception is thrown from certain methods and constructors. These methods are expected to behave in a specific way and throwing an exception from them can lead to unexpected behavior and break the calling code.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public override string ToString()
      {
      if (string.IsNullOrEmpty(Name))
      {
      throw new ArgumentException(nameof(Name));  // Noncompliant
      }
      //...
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Methods without side effects should not have their return values ignored">
    <div class="paragraph">
      <p>When you do not use the return value of a method with no side effects, it indicates that something is wrong. Either this method is unnecessary, or the source code does not behave as expected and could lead to code defects.
      For example, there are methods, such as <a href="https://learn.microsoft.com/en-us/dotnet/api/system.datetime.addyears">DateTime.AddYears</a>, that don’t change the value of the input object, but instead, they return a new object whose value is the result of this operation, and as a result that you will have unexpected effects if you do not use the return value.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when the results of the following methods are ignored:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/">LINQ</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.contracts.pureattribute">Pure methods</a></p>
        </li>

        <li>
          <p>Any method on <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/built-in-types">build-in types</a></p>
        </li>

        <li>
          <p>Any method on <a href="https://learn.microsoft.com/en-us/archive/msdn-magazine/2017/march/net-framework-immutable-collections">Immutable collections</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Special cases:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Although <a href="https://learn.microsoft.com/en-us/dotnet/api/system.string.intern">string.Intern</a> has a side effect, ignoring its return value is still suspicious as it is the only reference ensured to point to the intern pool.</p>
        </li>

        <li>
          <p>LINQ methods can have side effects if they are misused. For example:</p>
        </li>
      </ul>
    </div>

    <div class="listingblock">
      <div class="content">
        <pre>data.All(x =>
        \{
        x.Property = "foo";
        return true;
        });</pre>
      </div>
    </div>

    <div class="paragraph">
      <p>Such code should be rewritten as a loop because <a href="https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.all">Enumerable.All\<TSource></a> method should be used to determine if all elements satisfy a condition and not to change their state.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      data.Where(x => x > 5).Select(x => x * x); // Noncompliant
      "this string".Equals("other string"); // Noncompliant

      data.All(x =>  // Noncompliant
      {
      x.Property = "foo";
      return true;
      });
      ```

      ```csharp Fix theme={null}
      var res = data.Where(x => x > 5).Select(x => x * x); 
      var isEqual = "this string".Equals("other string");

      foreach (var x in data)
      {
      x.Property = "foo";
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="SHA-1 and Message-Digest hash algorithms should not be used in secure contexts">
    <div class="paragraph">
      <p>The MD5 algorithm and its successor, SHA-1, are no longer considered secure, because it is too easy to create hash collisions with them. That is, it takes too little computational effort to come up with a different input that produces the same MD5 or SHA-1 hash, and using the new, same-hash value gives an attacker the same access as if he had the originally-hashed value. This applies as well to the other Message-Digest algorithms: MD2, MD4, MD6.</p>
    </div>

    <div class="paragraph">
      <p>This rule tracks usage of the <code>System.Security.Cryptography.CryptoConfig.CreateFromName(), and System.Security.Cryptography.HashAlgorithm.Create() methods to instantiate MD5, DSA, HMACMD5, HMACRIPEMD160, RIPEMD-160 or SHA-1 algorithms, and of derived class instances of System.Security.Cryptography.SHA1 and System.Security.Cryptography.MD5</code>.</p>
    </div>

    <div class="paragraph">
      <p>Consider using safer alternatives, such as SHA-256, or SHA-3.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      var hashProvider1 = new MD5CryptoServiceProvider(); //Noncompliant
      var hashProvider2 = (HashAlgorithm)CryptoConfig.CreateFromName("MD5"); //Noncompliant
      var hashProvider3 = new SHA1Managed(); //Noncompliant
      var hashProvider4 = HashAlgorithm.Create("SHA1"); //Noncompliant
      ```

      ```csharp Fix theme={null}
      var hashProvider1 = new SHA256Managed();
      var hashProvider2 = (HashAlgorithm)CryptoConfig.CreateFromName("SHA256Managed");
      var hashProvider3 = HashAlgorithm.Create("SHA256Managed");
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Mutable collection or array members should not be stored or returned directly">
    <div class="paragraph">
      <p>Mutable collections are those whose state can be changed. For instance, \`Array and List\<T> are mutable, but System.Collections.ObjectModel.ReadOnlyCollection\<T> and System.Collections.Immutable.ImmutableList\<T> are not. Mutable collection class members should not be returned to a caller or accepted and stored directly. Doing so leaves you vulnerable to unexpected changes in your class state.</p>
    </div>

    <div class="paragraph">
      <p>Instead use and store a copy of the mutable collection, or return an immutable collection wrapper, e.g. System.Collections.ObjectModel.ReadOnlyCollection\<T>.</p>
    </div>

    <div class="paragraph">
      <p>Note that you can’t just return your mutable collection through the IEnumerable\<T>\` interface because the caller of your method/property could cast it down to the mutable type and then change it.</p>
    </div>

    <div class="paragraph">
      <p>This rule checks that mutable collections are not stored or returned directly.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      class A 
      {
      private List<string> names = new List<string>();

      public ICollection<string> Names => names; // Noncompliant

      public IEnumerable<string> GetNames()  // Noncompliant
      {
          return names;
      }

      public void SetNames(List<string> strings) 
      {
          this.names = strings;  // Noncompliant
      }
      }
      ```

      ```csharp Fix theme={null}
      class A 
      {
      private List<string> names = new List<string>();
      private ReadOnlyCollection<string> readOnlyNames = new ReadOnlyCollection<string>(names);

      public ICollection<string> Names => readOnlyNames; // Return a collection wrapper

      public IEnumerable<string> GetNames()
      {
          names.ToList(); // Make a copy
      }

      public void SetNames(List<string> strings) 
      {
          this.names.Clear();
          this.names.AddRange(strings); // Make a copy
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Property assignments should not be made for readonly fields not constrained to reference types">
    <div class="paragraph">
      <p>While the properties of a <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/readonly">readonly</a> <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types">reference type</a> field can still be changed after initialization, those of a readonly <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-types">value type</a> field, such as a <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct">struct</a>, cannot.</p>
    </div>

    <div class="paragraph">
      <p>If the member could be either a class or a struct then assignment to its properties could be unreliable, working sometimes but not others.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      interface IPoint
      {
      int X { get; set; }
      int Y { get; set; }
      }

      class PointManager<T1, T2> 
      where T1 : IPoint
      where T2 : IPoint
      {
      readonly T1 point1;  // this could be a struct
      readonly T2 point2;  // this could be a struct

      public PointManager(T1 point1, T2 point2)
      {
          this.point1 = point1;
          this.point2 = point2;
      }

      public void MovePoints(int newX)
      {
          point1.X = newX; //Noncompliant: if point is a struct, then nothing happened
          point2.X = newX; //Noncompliant: if point is a struct, then nothing happened
      }
      }
      ```

      ```csharp Fix theme={null}
      interface IPoint
      {
      int X { get; set; }
      int Y { get; set; }
      }

      class PointManager<T1, T2> 
      where T1 : IPoint
      where T2 : class, IPoint
      {
      readonly T1 point1;  // this could be a struct
      readonly T2 point2;  // this is a class

      public PointManager(T1 point1, T2 point2)
      {
          this.point1 = point1;
          this.point2 = point2;
      }

      public void MovePoints(int newX) // assignment to point1 has been removed
      {
          point2.X = newX; // Compliant: point2 is a class
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Values should not be uselessly incremented">
    <div class="paragraph">
      <p>When using the <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#postfix-increment-operator">postfix increment</a> operator, it is important to know that the result of the expression x++ is the value <strong>before</strong> the operation x.</p>
    </div>

    <div class="paragraph">
      <p>This means that in some cases, the result might not be what you expect:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>When assigning x++ to x, it’s the same as assigning x to itself, since the value is assigned before the increment takes place</p>
        </li>

        <li>
          <p>When returning x++, the returning value is x, not x+1</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>The same applies to the postfix and prefix <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#decrement-operator---">decrement</a> operators.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      int PickNumber()
      {
      int i = 0;
      int j = 0;

      i = i++;      // Noncompliant: i is still 0 
      return j--;   // Noncompliant: returns 0 
      }
      ```

      ```csharp Fix theme={null}
      int PickNumber()
      {
      int i = 0;
      int j = 0;

      i++;          // Compliant: i is incremented to 1
      return --j;   // Compliant: returns -1
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Generics should be used when appropriate">
    <div class="paragraph">
      <p>When a reference parameter (keyword \`ref) is used, the passed argument type must exactly match the reference parameter type. This means that to be able to pass a derived type, it must be cast and assigned to a variable of the proper type. Use of generic methods eliminates that cumbersome down casting and should therefore be preferred.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a method contains a ref parameter of type System.Object\`.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      namespace MyLibrary
      {
      public class Foo
      {
      public void Bar(ref object o1, ref object o2) // Noncompliant
      {
      }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;

      namespace MyLibrary
      {
      public class Foo
      {
      public void Bar<T>(ref T ref1, ref T ref2)
      {
      }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Exceptions should provide standard constructors">
    <div class="paragraph">
      <p>Exceptions types should provide the following constructors:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>public MyException()</p>
        </li>

        <li>
          <p>public MyException(string)</p>
        </li>

        <li>
          <p>public MyException(string, Exception)</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>The absence of these constructors can complicate exception handling and limit the information that can be provided when an exception is thrown.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class MyException : Exception // Noncompliant: several constructors are missing
      {
      public MyException()
      {
      }
      }
      ```

      ```csharp Fix theme={null}
      public class MyException : Exception
      {
      public MyException()
      {
      }

      public MyException(string message)
          : base(message)
      {
      }

      public MyException(string message, Exception innerException)
          : base(message, innerException)
      {
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Multiple variables should not be declared on the same line">
    <div class="paragraph">
      <p>Declaring multiple variable on one line is difficult to read.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      class MyClass 
      {
      private int a, b; // Noncompliant

      public void Method()
      {
      int c, d; // Noncompliant
      }
      }
      ```

      ```csharp Fix theme={null}
      class MyClass 
      {
      private int a;
      private int b;

      public void Method()
      {
      int c;
      int d;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Inner class members should not shadow outer class static or type members">
    <CodeGroup>
      ```csharp Bad theme={null}
      class Outer
      {
      public static int A;

      public class Inner
      {
      public int A; // Noncompliant

      public int MyProp
      {
        get => A; // Returns inner A. Was that intended?
      }
      }
      }
      ```

      ```csharp Fix theme={null}
      class Outer
      {
      public static int A;

      public class Inner
      {
      public int B; // Compliant

      public int MyProp
      {
        get => A; // Returns outer A
      }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Array covariance should not be used">
    <div class="paragraph">
      <p>Array covariance is the principle that if an implicit or explicit reference conversion exits from type \`A to B, then the same conversion exists from the array type A\[] to B\[].</p>
    </div>

    <div class="paragraph">
      <p>While this array conversion can be useful in readonly situations to pass instances of A\[] where B\[] is expected, it must be used with care, since assigning an instance of B into an array of A will cause an ArrayTypeMismatchException\` to be thrown at runtime.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      abstract class Fruit { }
      class Apple : Fruit { }
      class Orange : Fruit { }

      class Program
      {
      static void Main(string[] args)
      {
      Fruit[] fruits = new Apple[1]; // Noncompliant - array covariance is used
      FillWithOranges(fruits);
      }

      // Just looking at the code doesn't reveal anything suspicious
      static void FillWithOranges(Fruit[] fruits)
      {
      for (int i = 0; i < fruits.Length; i++)
      {
        fruits[i] = new Orange(); // Will throw an ArrayTypeMismatchException
      }
      }
      }
      ```

      ```csharp Fix theme={null}
      abstract class Fruit { }
      class Apple : Fruit { }
      class Orange : Fruit { }

      class Program
      {
      static void Main(string[] args)
      {
      Orange[] fruits = new Orange[1]; // Compliant
      FillWithOranges(fruits);
      }

      static void FillWithOranges(Orange[] fruits)
      {
      for (int i = 0; i < fruits.Length; i++)
      {
        fruits[i] = new Orange();
      }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Keywords should not be used as names">
    <div class="paragraph">
      <p>The ability to target the common language runtime from several languages means that clashes are possible when a word that is reserved in one language is used as the name of a namespace, type or member in another.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a keyword from C++/CLI, C# or Visual Basic is used as an identifier.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public string nameof(string s) { return s; }  // Noncompliant
      ...
      public string Hello { get { return "World!"; } }
      ...
      Console.WriteLine(nameof(Hello)); // prints "World!" instead of "Hello" as expected
      ```

      ```csharp Fix theme={null}
      public string GetValue(string s) { return s; }
      ...
      public string Hello { get { return "World!"; } }
      ...
      Console.WriteLine(GetValue(Hello));
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Interfaces for durable entities should satisfy the restrictions">
    <div class="paragraph">
      <p>The recommended way to access Azure Durable Entities is through generated proxy objects with the help of interfaces.</p>
    </div>

    <div class="paragraph">
      <p>The following restrictions, during interface design, are enforced:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Entity interfaces must be defined in the same assembly as the entity class. This is not detected by the rule.</p>
        </li>

        <li>
          <p>Entity interfaces must only define methods.</p>
        </li>

        <li>
          <p>Entity interfaces must not contain generic parameters.</p>
        </li>

        <li>
          <p>Entity interface methods must not have more than one parameter.</p>
        </li>

        <li>
          <p>Entity interface methods must return void, Task, or Task\<T>.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>If any of these rules are violated, an InvalidOperationException is thrown at runtime when the interface is used as a type argument to IDurableEntityContext.SignalEntity\<TEntityInterface>, IDurableEntityClient.SignalEntityAsync\<TEntityInterface> or IDurableOrchestrationContext.CreateEntityProxy\<TEntityInterface>. The exception message explains which rule was broken.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue in case any of the restrictions above is not respected.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      namespace Foo // Noncompliant, must be defined in the same assembly as the entity class that implements it
      {
      public interface ICounter<T> // Noncompliant, interfaces cannot contain generic parameters
      {
          string Name { get; set; } // Noncompliant, interface must only define methods
          void Add(int amount, int secondParameter); // Noncompliant, methods must not have more than one parameter
          int Get(); // Noncompliant, methods must return void, Task, or Task<T>
      }
      }

      namespace Bar
      {
      public class Counter : ICounter
      {
          // do stuff
      }

      public static class AddToCounterFromQueue
      {
          [FunctionName("AddToCounterFromQueue")]
          public static Task Run(
              [QueueTrigger("durable-function-trigger")] string input,
              [DurableClient] IDurableEntityClient client)
          {
              var entityId = new EntityId("Counter", "myCounter");
              int amount = int.Parse(input);
              return client.SignalEntityAsync<ICounter>(entityId, proxy => proxy.Add(amount, 10));
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      namespace Bar
      {
      public interface ICounter
      {
          void Add(int amount);
          Task<int> Get();
      }
      }

      namespace Bar
      {
      public class Counter : ICounter
      {
          // do stuff
      }

      public static class AddToCounterFromQueue
      {
          [FunctionName("AddToCounterFromQueue")]
          public static Task Run(
              [QueueTrigger("durable-function-trigger")] string input,
              [DurableClient] IDurableEntityClient client)
          {
              var entityId = new EntityId("Counter", "myCounter");
              int amount = int.Parse(input);
              return client.SignalEntityAsync<ICounter>(entityId, proxy => proxy.Add(amount));
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Interfaces should not be empty">
    <div class="paragraph">
      <p>Empty interfaces are either useless or used as a <a href="https://en.wikipedia.org/wiki/Marker_interface_pattern">marker</a>. <a href="https://learn.microsoft.com/en-us/dotnet/standard/attributes/writing-custom-attributes">Custom attributes</a> are a better alternative to marker interfaces. See the <em>How to fix it</em> section for more information.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public interface IAggregate: IComparable, IFormattable { } // Compliant: Aggregates two interfaces
      ```

      ```csharp Fix theme={null}
      // Compliant: Bound to a concrete type
      public interface IStringEquatable: IEquatable<string> { }
      // Compliant: Specialized by type parameter constraint
      public interface ICreateableEquatable<T>: IEquatable<T> where T: new() { }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Any() should be used to test for emptiness">
    <div class="paragraph">
      <p>When you call Any(), it clearly communicates the code’s intention, which is to check if the collection is empty. Using \`Count()</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      private static bool HasContent(IEnumerable<string> strings)
      {
      return strings.Count() > 0;  // Noncompliant
      }

      private static bool HasContent2(IEnumerable<string> strings)
      {
      return strings.Count() >= 1;  // Noncompliant
      }

      private static bool IsEmpty(IEnumerable<string> strings)
      {
      return strings.Count() == 0;  // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      private static bool HasContent(IEnumerable<string> strings)
      {
      return strings.Any();
      }

      private static bool HasContent2(IEnumerable<string> strings)
      {
      return strings.Any();
      }

      private static bool IsEmpty(IEnumerable<string> strings)
      {
      return !strings.Any();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Blocks should not be synchronized on local variables">
    <div class="paragraph">
      <p>Locking on a local variable can undermine synchronization because two different threads running the same method in parallel will potentially lock on different instances of the same object, allowing them to access the synchronized block at the same time.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      private void DoSomething()
      {
      object local = new object();
      // Code potentially modifying the local variable ...

      lock (local) // Noncompliant
      {
      // ...
      }
      }
      ```

      ```csharp Fix theme={null}
      private readonly object lockObj = new object();

      private void DoSomething()
      {
      lock (lockObj) 
      {
      //...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Extensions should be in separate namespaces">
    <div class="paragraph">
      <p>It makes little sense to create an extension method when it is possible to just add that method to the class itself.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when an extension is declared in the same namespace as the class it is extending.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      namespace MyLibrary
      {
      public class Foo
      {
          // ...
      }

      public static class MyExtensions
      {
          public static void Bar(this Foo a) // Noncompliant
          {
              // ...
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      namespace MyLibrary
      {
      public class Foo
      {
          // ...
      }
      }

      namespace Helpers
      {
      public static class MyExtensions
      {
          public static void Bar(this Foo a)
          {
              // ...
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Non-flags enums should not be used in bitwise operations">
    <div class="paragraph">
      <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum">Enumerations</a> are commonly used to identify distinct elements from a set of values.</p>
    </div>

    <div class="paragraph">
      <p>However, they can also serve as <a href="https://en.wikipedia.org/wiki/Bit_field">bit flags</a>, enabling bitwise operations to combine multiple elements within a single value.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      // Saturday = 0b00100000, Sunday = 0b01000000, weekend = 0b01100000
      var weekend = Days.Saturday | Days.Sunday;  // Combining elements
      ```

      ```csharp Fix theme={null}
      enum Permissions
      {
      None = 0,
      Read = 1,
      Write = 2,
      Execute = 4
      }

      // ...

      var x = Permissions.Read | Permissions.Write;  // Noncompliant: enum is not annotated with [Flags]
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Collections should not be passed as arguments to their own methods">
    <div class="paragraph">
      <p>Passing a collection as an argument to the collection’s own method is a code defect. Doing so might either have unexpected side effects or always have the same result.</p>
    </div>

    <div class="paragraph">
      <p>Another case is using set-like operations. For example, using <a href="https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.union">Union</a> between a list and itself will always return the same list.
      Conversely, using <a href="https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.except">Except</a> between a list and itself will always return an empty list.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      var list = new List<int>();

      list.AddRange(list);          // Noncompliant
      list.Concat(list);            // Noncompliant

      list.Union(list);             // Noncompliant: always returns list
      list.Intersect(list);         // Noncompliant: always returns list
      list.Except(list);            // Noncompliant: always returns empty
      list.SequenceEqual(list);     // Noncompliant: always returns true

      var set = new HashSet<int>();
      set.UnionWith(set);           // Noncompliant: no changes
      set.IntersectWith(set);       // Noncompliant: no changes
      set.ExceptWith(set);          // Noncompliant: always returns empty
      set.SymmetricExceptWith(set); // Noncompliant: always returns empty
      set.IsProperSubsetOf(set);    // Noncompliant: always returns false
      set.IsProperSupersetOf(set);  // Noncompliant: always returns false
      set.IsSubsetOf(set);          // Noncompliant: always returns true
      set.IsSupersetOf(set);        // Noncompliant: always returns true
      set.Overlaps(set);            // Noncompliant: always returns true
      set.SetEquals(set);           // Noncompliant: always returns true
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Methods named Dispose should implement IDisposable.Dispose">
    <div class="paragraph">
      <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.idisposable">IDisposable</a> is an interface implemented by all types which need to provide a mechanism for <a href="https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/unmanaged">releasing unmanaged resources</a>.</p>
    </div>

    <div class="paragraph">
      <p>Unlike managed memory, which is taken care of by the <a href="https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals">garbage collection</a>,</p>
    </div>

    <div class="paragraph">
      <p>The interface declares a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.idisposable.dispose">Dispose</a> method, which the implementer has to define.</p>
    </div>

    <div class="paragraph">
      <p>The method name Dispose should be used exclusively to implement IDisposable.Dispose to prevent any confusion.</p>
    </div>

    <div class="paragraph">
      <p>It may be tempting to create a Dispose method for other purposes, but doing so will result in confusion and likely lead to problems in production.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class GarbageDisposal : IDisposable
      {
      protected virtual void Dispose(bool disposing)
      {
      //...
      }
      public void Dispose() 
      {
      Dispose(true);
      GC.SuppressFinalize(this);
      }
      }
      ```

      ```csharp Fix theme={null}
      public class GarbageDisposal 
      {
      private int Dispose()  // Noncompliant
      {
      // ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="using directives should be in the standard order">
    <div class="paragraph">
      <p>The standard order for <code>using directives is alphabetic with the exception of System</code> directives, which come first for higher visibility. Using a different order may cause maintainers to overlook a directive or misunderstand what’s being used.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using C;  // Noncompliant
      using System.A.A;
      using A;
      using D;
      using B;
      using System;
      using System.A;
      using System.B;
      ```

      ```csharp Fix theme={null}
      using System;
      using System.A;
      using System.A.A;
      using System.B;
      using A;
      using C;
      using B;
      using D;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="value contextual keyword should be used">
    <div class="paragraph">
      <p>When you need to get external input for set and init methods defined for properties and indexers or for remove and add methods for events, you should
      always get this input throught the value contextual keyword.</p>
    </div>

    <div class="paragraph">
      <p>The contextual keyword value is similar to an input parameter of a method; it references the value that the client code is attempting to assign to the property, indexer or event.</p>
    </div>

    <div class="paragraph">
      <p>The keyword value holds the value the accessor was called with. Not using it means that the accessor ignores the caller’s intent which could cause unexpected results at runtime.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      private int count;
      public int Count
      {
      get { return count; }
      set { count = 42; } // Noncompliant 
      }
      ```

      ```csharp Fix theme={null}
      private int count;
      public int Count
      {
      get { return count; }
      set { count = value; }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="async and await should not be used as identifiers">
    <div class="paragraph">
      <p>Since C# 5.0, async and await are <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/#contextual-keywords">contextual keywords</a>. Contextual keywords do have a particular meaning in some contexts, but are not reserved and therefore can be used as variable names.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      int await = 42; // Noncompliant, but compiles
      int async = 42; // Noncompliant, but compiles
      ```

      ```csharp Fix theme={null}
      int abstract = 42; // Error CS1585: Member modifier 'abstract' must precede the member type and name
      int foreach = 42; // Error CS1519: Invalid token 'foreach' in class, struct, or interface member declaration
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Events should be invoked">
    <div class="paragraph">
      <p>Events that are not invoked anywhere are dead code, and there’s no good reason to keep them in the source.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      class UninvokedEventSample
      {
      private event Action<object, EventArgs> Happened; //Noncompliant

      public void RegisterEventHandler(Action<object, EventArgs> handler)
      {
          Happened += handler; //we register some event handlers
      }

      public void RaiseEvent()
      {
          if (Happened != null)
          {
              // Happened(this, null); // the event is never triggered, because this line is commented out.
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="The length returned from a stream read should be checked">
    <div class="paragraph">
      <p>You cannot assume that any given stream reading call will fill the \`byte\[] passed in to the method with the number of bytes requested. Instead, you must check the value returned by the read method to see how many bytes were read. Fail to do so, and you introduce a bug that is both harmful and difficult to reproduce.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a Stream.Read or a Stream.ReadAsync\` method is called, but the return value is not checked.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public void DoSomething(string fileName) 
      {
      using (var stream = File.Open(fileName, FileMode.Open))
      {
      var result = new byte[stream.Length];
      stream.Read(result, 0, (int)stream.Length); // Noncompliant
      // ... do something with result
      }
      }
      ```

      ```csharp Fix theme={null}
      public void DoSomething(string fileName) 
      {
      using (var stream = File.Open(fileName, FileMode.Open))
      {
      var buffer = new byte[1024];
      using (var ms = new MemoryStream())
      {
          int read;
          while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
          {
              ms.Write(buffer, 0, read);
          }
          // ... do something with ms
      }    
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using unsafe code blocks is security-sensitive">
    <div class="paragraph">
      <p>cks can lead to unintended security or stability risks.</p>
    </div>

    <div class="paragraph">
      <p>unsafe code blocks allow developers to use features such as pointers, fixed buffers, function calls through pointers and manual memory management. Such features may be necessary for interoperability with native libraries, as these often require pointers. It may also increase performance in some critical areas, as certain bounds checks are not executed in an unsafe context.</p>
    </div>

    <div class="paragraph">
      <p>unsafe code blocks aren’t necessarily dangerous, however, the contents of such blocks are not verified by the Common Language Runtime. Therefore, it is up to the programmer to ensure that no bugs are introduced through manual memory management or casting. If not done correctly, then those bugs can lead to memory corruption vulnerabilities such as stack overflows. unsafe code blocks should be used with caution because of these security and stability risks.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public unsafe int SubarraySum(int[] array, int start, int end)  // Sensitive
      {
      var sum = 0;

      // Skip array bound checks for extra performance
      fixed (int* firstNumber = array)
      {
          for (int i = start; i < end; i++)
              sum += *(firstNumber + i);
      }

      return sum;
      }
      ```

      ```csharp Fix theme={null}
      public int SubarraySum(int[] array, int start, int end)
      {
      var sum = 0;

      Span<int> span = array.AsSpan();
      for (int i = start; i < end; i++)
          sum += span[i];

      return sum;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unassigned members should be removed">
    <div class="paragraph">
      <p>Fields and auto-properties that are never assigned to hold the default values for their types. They are either pointless code or, more likely, mistakes.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      class MyClass
      {
      private int field; // Noncompliant, shouldn't it be initialized? This way the value is always default(int), 0.
      private int Property { get; set; }  // Noncompliant
      public void Print()
      {
      Console.WriteLine(field); //Will always print 0
      Console.WriteLine(Property); //Will always print 0
      }
      }
      ```

      ```csharp Fix theme={null}
      class MyClass
      {
      private int field = 1;
      private int Property { get; set; } = 42;
      public void Print()
      {
      field++;
      Console.WriteLine(field);
      Console.WriteLine(Property);
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Interfaces should not simply inherit from base interfaces with colliding members">
    <div class="paragraph">
      <p>When an interface inherits from two interfaces that both define a member with the same name, trying to access that member through the derived interface will result in the compiler error <code>CS0229 Ambiguity between 'IBase1.SomeProperty' and 'IBase2.SomeProperty'</code>.</p>
    </div>

    <div class="paragraph">
      <p>So instead, every caller will be forced to cast instances of the derived interface to one or the other of its base interfaces to resolve the ambiguity and be able to access the member. Instead, it is better to resolve the ambiguity in the definition of the derived interface either by:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>renaming the member in one of the base interfaces to remove the collision</p>
        </li>

        <li>
          <p>also defining that member in the derived interface. Use this only if all copies of the member are meant to hold the same value.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public interface IBase1
      {
      string SomeProperty { get; set; }
      }

      public interface IBase2
      {
      string SomeProperty { get; set; }
      }

      public interface IDerived : IBase1, IBase2 // Noncompliant, accessing IDerived.SomeProperty is ambiguous
      {
      }

      public class MyClass : IDerived
      {
      // Implements both IBase1.SomeProperty and IBase2.SomeProperty
      public string SomeProperty { get; set; } = "Hello";

      public static void Main()
      {
      MyClass myClass = new MyClass();
      Console.WriteLine(myClass.SomeProperty); // Writes "Hello" as expected
      Console.WriteLine(((IBase1)myClass).SomeProperty); // Writes "Hello" as expected
      Console.WriteLine(((IBase2)myClass).SomeProperty); // Writes "Hello" as expected
      Console.WriteLine(((IDerived)myClass).SomeProperty); // Error CS0229 Ambiguity between 'IBase1.SomeProperty' and 'IBase2.SomeProperty'
      }
      }
      ```

      ```csharp Fix theme={null}
      public interface IDerived : IBase1, IBase2
      {
      new string SomeProperty { get; set; }
      }

      public class MyClass : IDerived
      {
      // Implements IBase1.SomeProperty, IBase2.SomeProperty and IDerived.SomeProperty
      public string SomeProperty { get; set; } = "Hello";

      public static void Main()
      {
      MyClass myClass = new MyClass();
      Console.WriteLine(myClass.SomeProperty); // Writes "Hello" as expected
      Console.WriteLine(((IBase1)myClass).SomeProperty); // Writes "Hello" as expected
      Console.WriteLine(((IBase2)myClass).SomeProperty); // Writes "Hello" as expected
      Console.WriteLine(((IDerived)myClass).SomeProperty); // Writes "Hello" as expected
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Method arguments with default values should be last">
    <div class="paragraph">
      <p>The ability to define default values for method arguments can make a method easier to use. Default argument values allow callers to specify as many or as few arguments as they want while getting the same functionality and minimizing boilerplate, wrapper code.</p>
    </div>

    <div class="paragraph">
      <p>But all method arguments with default values should be declared after the method arguments without default values. Otherwise, it makes it cumbersome for callers to take advantage of defaults; they must either use named arguments or re-specify the defaulted values in order to "get to" the non-default arguments.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      class MyClass
      {
      public void DoStuff([Optional]int i, int j)  // Noncompliant
      {
      // ...
      }
      }
      ```

      ```csharp Fix theme={null}
      class MyClass
      {
      public void DoStuff(int j, [Optional]int i)
      {
      // ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Methods and properties that dont access instance data should be static">
    <div class="paragraph">
      <p>Methods and properties that don’t access instance data can be <code>static</code> to prevent any misunderstanding about the contract of the method.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Utilities
      {
      public int MagicNum // Noncompliant
      {
          get 
          {
              return 42;
          }
      }

      private static string magicWord = "please";
      public string MagicWord  // Noncompliant
      {
          get 
          {
              return magicWord;
          }
          set 
          {
              magicWord = value;
          }
      }

      public int Sum(int a, int b)  // Noncompliant
      {
          return a + b;
      }
      }
      ```

      ```csharp Fix theme={null}
      public class Utilities
      {
      public static int MagicNum
      {
          get 
          {
              return 42;
          }
      }

      private static string magicWord = "please";
      public static string MagicWord 
      {
          get 
          {
              return magicWord;
          }
          set 
          {
              magicWord = value;
          }
      }

      public static int Sum(int a, int b)
      {
          return a + b;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unassigned read-only members should be removed">
    <div class="paragraph">
      <p>Read-only fields and properties (properties with only an auto-implemented getter) can only be set in a constructor or as part of their declaration. A read-only member that isn’t set in either place will retain its default value for the life of the object. At best, such properties clutter the source code. At worst, they are bugs.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      class Person 
      {
      int Age { get; }  // Noncompliant; will always be 0.

      Person () {}
      }
      ```

      ```csharp Fix theme={null}
      class Person 
      {
      int Age { get; } = 42;

      Person () {}
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Parameter names used into ArgumentException constructors should match an existing one ">
    <div class="paragraph">
      <p>Some constructors of the <code>ArgumentException, ArgumentNullException, ArgumentOutOfRangeException and DuplicateWaitObjectException</code> classes must be fed with a valid parameter name. This rule raises an issue in two cases:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>When this parameter name doesn’t match any existing ones.</p>
        </li>

        <li>
          <p>When a call is made to the default (parameterless) constructor</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public void Foo(Bar a, int[] b)
      {
      throw new ArgumentException();                                        // Noncompliant
      throw new ArgumentException("My error message", "c");                 // Noncompliant
      throw new ArgumentException("My error message", "c", innerException); // Noncompliant

      throw new ArgumentNullException("c");                     // Noncompliant
      throw new ArgumentNullException(nameof(c));               // Noncompliant
      throw new ArgumentNullException("My error message", "a"); // Noncompliant

      throw new ArgumentOutOfRangeException("c");                           // Noncompliant
      throw new ArgumentOutOfRangeException("c", "My error message");       // Noncompliant
      throw new ArgumentOutOfRangeException("c", b, "My error message");    // Noncompliant

      throw new DuplicateWaitObjectException("c", "My error message");      // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      public void Foo(Bar a, int[] b)
      {
      throw new ArgumentException("My error message", "a");
      throw new ArgumentException("My error message", "b", innerException);

      throw new ArgumentNullException("a");
      throw new ArgumentNullException(nameof(a));
      throw new ArgumentNullException("a", "My error message");

      throw new ArgumentOutOfRangeException("b");
      throw new ArgumentOutOfRangeException("b", "My error message");
      throw new ArgumentOutOfRangeException("b", b, "My error message");

      throw new DuplicateWaitObjectException("b", "My error message");
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Generic parameters not constrained to reference types should not be compared to null">
    <div class="paragraph">
      <p>In C#, without constraints on a generic type parameter, both <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types">reference</a> and <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-types">value</a> types can be passed. However, comparing this type parameter to null can be misleading as value types, like struct, can never be null.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      bool IsDefault<T>(T value)
      {
      if (value == null) // Noncompliant
      {
      // ...
      }
      }
      ```

      ```csharp Fix theme={null}
      bool IsDefault<T>(T value)
      {
      if (EqualityComparer<T>.Default.Equals(value, default(T)))
      {
      // ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Arguments of public methods should be validated against null">
    <div class="paragraph">
      <p>Methods declared as public, protected, or protected internal can be accessed from other assemblies, which means you should validate parameters to be within the expected constraints. In general, checking against null is recommended in defensive programming.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a parameter of a publicly accessible method is not validated against null before being dereferenced.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class MyClass
      {
      private MyOtherClass other;

      public void Foo(MyOtherClass other)
      {
          this.other = other.Clone(); // Noncompliant
      }

      protected void Bar(MyOtherClass other)
      {
          this.other = other.Clone(); // Noncompliant
      }
      }
      ```

      ```csharp Fix theme={null}
      public class MyClass
      {
      private MyOtherClass other;

      public void Foo(MyOtherClass other)
      {
          if (other != null)
          {
              this.other = other.Clone();
          }
      }

      protected void Bar(MyOtherClass other)
      {
          if (other != null)
          {
              this.other = other.Clone();
          }
      }

      public void Baz(MyOtherClass other)
      {
          ArgumentNullException.ThrowIfNull(other);

          this.other = other.Clone();
      }

      public void Qux(MyOtherClass other)
      {
          this.other = other; // Compliant: "other" is not being dereferenced
      }

      private void Xyzzy(MyOtherClass other)
      {
          this.other = other.Clone(); // Compliant: method is not publicly accessible
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Empty default clauses should be removed">
    <div class="paragraph">
      <p>The <code>default clause should take appropriate action. Having an empty default</code> is a waste of keystrokes.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      enum Fruit
      {
      Apple,
      Orange,
      Banana
      }

      void PrintName(Fruit fruit)
      {
      switch(fruit)
      {
      case Fruit.Apple:
        Console.WriteLine("apple");
        break;
      default:  //Noncompliant
        break;
      }
      }
      ```

      ```csharp Fix theme={null}
      enum Fruit
      {
      Apple,
      Orange,
      Banana
      }

      void PrintName(Fruit fruit)
      {
      switch(fruit)
      {
      case Fruit.Apple:
        Console.WriteLine("apple");
        break;
      default:
        throw new NotSupportedException();
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Logging templates should be constant">
    <div class="paragraph">
      <p>Logging arguments should not require evaluation in order to avoid unnecessary performance overhead. When passing concatenated strings or string interpolations directly into a logging method, the evaluation of these expressions occurs every time the logging method is called, regardless of the log level. This can lead to inefficient code execution and increased resource consumption.</p>
    </div>

    <div class="paragraph">
      <p>Instead, it is recommended to use the overload of the logger that accepts a log format and its arguments as separate parameters. By separating the log format from the arguments, the evaluation of expressions can be deferred until it is necessary, based on the log level. This approach improves performance by reducing unnecessary evaluations and ensures that logging statements are only evaluated when needed.</p>
    </div>

    <div class="paragraph">
      <p>Furthermore, using a constant log format enhances observability and facilitates searchability in log aggregation and monitoring software.</p>
    </div>

    <div class="paragraph">
      <p>The rule covers the following logging frameworks:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://www.nuget.org/packages/Microsoft.Extensions.Logging">Microsoft.Extensions.Logging</a></p>
        </li>

        <li>
          <p><a href="https://www.nuget.org/packages/Castle.Core">Castle.Core</a></p>
        </li>

        <li>
          <p><a href="https://www.nuget.org/packages/log4net">log4net</a></p>
        </li>

        <li>
          <p><a href="https://www.nuget.org/packages/Serilog">Serilog</a></p>
        </li>

        <li>
          <p><a href="https://www.nuget.org/packages/NLog">Nlog</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public void Method(ILogger logger, bool parameter)
      {
      logger.DebugFormat($"The value of the parameter is: {parameter}.");
      }
      ```

      ```csharp Fix theme={null}
      public void Method(ILogger logger, bool parameter)
      {
      logger.DebugFormat("The value of the parameter is: {Parameter}.", parameter);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Null checks should not be used with is">
    <div class="paragraph">
      <p>There’s no need to null test in conjunction with an <code>is test. null</code> is not an instance of anything, so a null check is redundant.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      if (x != null && x is MyClass) { ... }  // Noncompliant

      if (x == null || !(x is MyClass)) { ... } // Noncompliant
      ```

      ```csharp Fix theme={null}
      if (x is MyClass) { ... }

      if (!(x is MyClass)) { ... }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Parameters with [DefaultParameterValue] attributes should also be marked [Optional]">
    <div class="paragraph">
      <p>There is no point in providing a default value for a parameter if callers are required to provide a value for it anyway. Thus, <code>\[DefaultParameterValue] should always be used in conjunction with \[Optional]</code>.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public void MyMethod([DefaultParameterValue(5)] int j) //Noncompliant, useless
      {
      Console.WriteLine(j);
      }
      ```

      ```csharp Fix theme={null}
      public void MyMethod(int j = 5)
      {
      Console.WriteLine(j);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="string.ToCharArray() and ReadOnlySpan<T>.ToArray() should not be called redundantly">
    <div class="paragraph">
      <p>The string type offers an indexer property that allows you to treat it as a char array. Therefore, if you just need to access a specific character or iterate over all of them, the ToCharArray call should be omitted. For these cases, not omitting makes the code harder to read and less efficient as ToCharArray copies the characters from the string object into a new Unicode character array.</p>
    </div>

    <div class="paragraph">
      <p>The same principle applies to <a href="https://devblogs.microsoft.com/dotnet/csharp-11-preview-updates/#utf-8-string-literals">utf-8 literals types</a> (ReadOnlySpan\<byte>, Span\<byte>) and the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.span-1.toarray?view=net-7.0">ToArray</a> method.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      string str = "some string";
      foreach (var c in str.ToCharArray()) // Noncompliant
      {
      // ...    
      }

      ReadOnlySpan<byte> span = "some UTF-8 string literal"u8;
      foreach (var c in span.ToArray()) // Noncompliant
      {
      // ...    
      }
      ```

      ```csharp Fix theme={null}
      string str = "some string";
      foreach (var c in str)
      {
      // ...    
      }

      ReadOnlySpan<byte> span = "some UTF-8 string literal"u8;
      foreach (var b in span) // Compliant 
      {
      // ...    
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Child class members should not shadow parent class members">
    <div class="paragraph">
      <p>Shadowing parent class members by creating properties and methods with the same signatures as non-<code>virtual</code> parent class members can result in seemingly strange behavior if an instance of the child class is cast to the parent class. In such cases, the parent class' code will be executed instead of the code in the child class, confusing callers and potentially causing hard-to-find bugs.</p>
    </div>

    <div class="paragraph">
      <p>Instead the child class member should be renamed.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Fruit 
      {
      public double GetCost() 
      {
      return 3.5;
      } 
      }

      public class Raspberry : Fruit 
      {
      public new double GetCost()  // Noncompliant
      { 
      return 7.5;
      }
      }

      // ...
      var r = new Raspberry();
      var f = (Fruit) r;
      Console.WriteLine(r.GetCost());  // prints 7.5
      Console.WriteLine(f.GetCost());  // prints 3.5; there's only one instance but different code executes depending on cast
      ```

      ```csharp Fix theme={null}
      public class Fruit 
      {
      public double GetCost() 
      {
      return 3.5;
      } 
      }

      public class Raspberry : Fruit 
      {
      public double GetInflatedCost() 
      { 
      return 7.5;
      }
      }

      // ...
      var r = new Raspberry();
      var f = (Fruit) r;
      Console.WriteLine(r.GetCost());  // prints 3.5
      Console.WriteLine(f.GetCost());  // prints 3.5; same code executes every time
      Console.WriteLine(r.GetInflatedCost()); // prints 7.5
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="AES encryption algorithm should be used with secured mode">
    <div class="paragraph">
      <p>Encryption algorithms can be used with various modes. Some combinations are not secured:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Electronic Codebook (ECB) mode: Under a given key, any given plaintext block always gets encrypted to the same ciphertext block. Thus, it does not hide data patterns well. In some senses, it doesn’t provide serious message confidentiality, and it is not recommended for use in cryptographic protocols at all.</p>
        </li>

        <li>
          <p>Cipher Block Chaining (CBC) with PKCS#5 padding (or PKCS#7) is susceptible to padding oracle attacks. CBC + PKCS#7 can be used if combined with an authenticity check (HMAC-SHA256 for example) on the cipher text.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>In both cases, Galois/Counter Mode (GCM) with no padding should be preferred. As the .NET framework doesn’t provide this natively, the use of a certified third party lib is recommended.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when any of the following CipherMode is detected: ECB, CBC, OFB, CFB, CTS.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      AesManaged aes = new AesManaged
      {
      KeySize = 128,
      BlockSize = 128,
      Mode = CipherMode.OFB, // Noncompliant
      Padding = PaddingMode.PKCS7
      };
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="GC.SuppressFinalize should not be invoked for types without destructors">
    <div class="paragraph">
      <p>\`GC.SuppressFinalize asks the Common Language Runtime not to call the finalizer of an object. This is useful when implementing the dispose pattern where object finalization is already handled in IDisposable.Dispose. However, it has no effect if there is no finalizer defined in the object’s type, so using it in such cases is just confusing.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when GC.SuppressFinalize is called for objects of sealed\` types without a finalizer.</p>
    </div>

    <div class="paragraph">
      <p><strong>Note:</strong> S3971 is a stricter version of this rule. Typically it makes sense to activate only one of these 2 rules.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      sealed class MyClass
      {
      public void Method()
      {
      ...
      GC.SuppressFinalize(this); //Noncompliant
      }
      }
      ```

      ```csharp Fix theme={null}
      sealed class MyClass
      {
      public void Method()
      {
      ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Calls to async methods should not be blocking in Azure Functions">
    <div class="paragraph">
      <p>Making <a href="https://en.wikipedia.org/wiki/Blocking_(computing)">blocking calls</a> to async methods transforms the code into a synchronous operation. Doing so inside an Azure Function can lead to thread pool exhaustion.</p>
    </div>

    <div class="paragraph">
      <p>Thread pool exhaustion refers to a situation where all available threads in a thread pool are occupied, and new tasks or work items cannot be scheduled for execution due to the lack of available threads. This can lead to delayed execution and degraded performance.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      class RequestParser
      {
      [FunctionName(nameof(ParseRequest))]
      public static async Task<IActionResult> ParseRequest([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req)
      {
      	// This can lead to thread exhaustion
      	string requestBody = new StreamReader(req.Body).ReadToEndAsync().Result;
      	// do stuff...
      }
      }
      ```

      ```csharp Fix theme={null}
      class RequestParser
      {
      [FunctionName(nameof(ParseRequest))]
      public static async Task<IActionResult> ParseRequest([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req)
      {
      	// Non-blocking, asynchronous operation
      	string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
      	// do stuff...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Classes should Dispose of members from the classes own Dispose methods">
    <div class="paragraph">
      <p>It is possible in an <code>IDisposable to call Dispose on class members from any method, but the contract of Dispose</code> is that it will clean up all unmanaged resources. Move disposing of members to some other method, and you risk resource leaks.</p>
    </div>

    <div class="paragraph">
      <p>This rule also applies for disposable ref structs.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class ResourceHolder : IDisposable
      {
      private FileStream fs;  
      public void OpenResource(string path)
      {
      this.fs = new FileStream(path, FileMode.Open);
      }
      public void CloseResource()
      {
      this.fs.Close();
      }

      public void CleanUp() 
      {
      this.fs.Dispose(); // Noncompliant; Dispose not called in class' Dispose method
      }

      public void Dispose() 
      {
      // method added to satisfy demands of interface
      }
      }
      ```

      ```csharp Fix theme={null}
      public class ResourceHolder : IDisposable
      {
      private FileStream fs;
      public void OpenResource(string path)
      {
      this.fs = new FileStream(path, FileMode.Open);
      }
      public void CloseResource()
      {
      this.fs.Close();
      }

      public void Dispose() 
      {
      this.fs.Dispose();
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Track uses of in-source issue suppressions">
    <div class="paragraph">
      <p>This rule allows you to track the usage of the <code>SuppressMessage attributes and #pragma warning disable</code> mechanism.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      [SuppressMessage("", "S100")]
      ...

      #pragma warning disable S100
      ...
      #pragma warning restore S100
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Instance members should not write to static fields">
    <div class="paragraph">
      <p>Updating a static field from a non-static method introduces significant challenges and potential bugs. Multiple class instances and threads can access and modify the static field concurrently, leading to unintended consequences for other instances or threads (unexpected behavior, <a href="https://www.c-sharpcorner.com/UploadFile/1d42da/race-conditions-in-threading-C-Sharp/">race conditions</a> and synchronization problems).</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      class MyClass 
      {
      private static int count = 0;

      public void DoSomething() 
      {
      //...
      count++;  // Noncompliant: make the enclosing instance property 'static' or remove this set on the 'static' field.
      }
      }

      interface MyInterface
      {
      private static int count = 0;

      public void DoSomething() 
      {
      //...
      count++;  // Noncompliant: remove this set, which updates a 'static' field from an instance method.
      }
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Field declarations should be as concise as possible">
    <div class="paragraph">
      <p>Unnecessarily verbose type declarations make it harder to read the code, and should be simplified to auto-property declarations when the getters and setters contain no logic other than a simple get/set.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      private int myVar;

      public int MyProperty
      {
      get { return myVar; }
      set { myVar = value; }
      }
      ```

      ```csharp Fix theme={null}
      public int MyProperty { get;  set; }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Client instances should not be recreated on each Azure Function invocation">
    <div class="paragraph">
      <p>To avoid holding more connections than necessary and to avoid potentially exhausting the number of available sockets when using HttpClient, DocumentClient, QueueClient, ConnectionMultiplexer or Azure Storage clients, consider:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Creating a single, thread-safe static client that every Azure Function invocation can use. Provide it in a shared class when different Azure Functions need it.</p>
        </li>

        <li>
          <p>Instantiate the client as a thread-safe Singleton or a pool of reusable instances and use it with dependency injection.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>These classes typically manage their own connections to the resource, and thus are intended to be instantiated once and reused throughout the lifetime of an application.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class HttpExample
      {
          [FunctionName("HttpExample")]
          public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest request)
          {
              HttpClient httpClient = new HttpClient(); // Noncompliant

              var response = await httpClient.GetAsync("https://example.com");
              // rest of the function
          }
      }
      ```

      ```csharp Fix theme={null}
      public class HttpExample
      {
          [FunctionName("HttpExample")]
          public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest request, IHttpClientFactory clientFactory)
          {
              var httpClient = clientFactory.CreateClient();
              var response = await httpClient.GetAsync("https://example.com");
              // rest of the function
          }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Culture should be specified for string operations">
    <div class="paragraph">
      <p>\`string.ToLower(), ToUpper, IndexOf, LastIndexOf, and Compare are all culture-dependent, as are some (floating point number and DateTime-related) calls to ToString. Fortunately, all have variants which accept an argument specifying the culture or formatter to use. Leave that argument off and the call will use the system default culture, possibly creating problems with international characters.</p>
    </div>

    <div class="paragraph">
      <p>string.CompareTo() is also culture specific, but has no overload that takes a culture information, so instead it’s better to use CompareOrdinal, or Compare\` with culture.</p>
    </div>

    <div class="paragraph">
      <p>Calls without a culture may work fine in the system’s "home" environment, but break in ways that are extremely difficult to diagnose for customers who use different encodings. Such bugs can be nearly, if not completely, impossible to reproduce when it’s time to fix them.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      var lowered = someString.ToLower(); //Noncompliant
      ```

      ```csharp Fix theme={null}
      var lowered = someString.ToLower(CultureInfo.InvariantCulture);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="ServiceContract and OperationContract attributes should be used together">
    <div class="paragraph">
      <p>The <code>ServiceContract attribute specifies that a class or interface defines the communication contract of a Windows Communication Foundation (WCF) service. The service operations of this class or interface are defined by OperationContract attributes added to methods. It doesn’t make sense to define a contract without any service operations; thus, in a ServiceContract class or interface at least one method should be annotated with OperationContract. Similarly, WCF only serves OperationContract methods that are defined inside ServiceContract classes or interfaces; thus, this rule also checks that ServiceContract is added to the containing type of OperationContract</code> methods.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      [ServiceContract]
      interface IMyService // Noncompliant
      {
      int MyServiceMethod();
      }
      ```

      ```csharp Fix theme={null}
      [ServiceContract]
      interface IMyService
      {
      [OperationContract]
      int MyServiceMethod();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Disposable types should declare finalizers">
    <div class="paragraph">
      <p>This rule raises an issue when a disposable type contains fields of the following types and does not implement a finalizer:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>\`System.IntPtr</p>
        </li>

        <li>
          <p>System.UIntPtr</p>
        </li>

        <li>
          <p>System.Runtime.InteropService.HandleRef\`</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;
      using System.Runtime.InteropServices;

      namespace MyLibrary
      {
      public class Foo : IDisposable // Noncompliant: Doesn't have a finalizer
      {
      private IntPtr myResource;
      private bool disposed = false;

      protected virtual void Dispose(bool disposing) 
      {
        if (!disposed) 
        {
          // Dispose of resources held by this instance.
          FreeResource(myResource);
          disposed = true;

          // Suppress finalization of this disposed instance.
          if (disposing)
          {
            GC.SuppressFinalize(this);
          }
        }
      }

      public void Dispose() {
        Dispose(true);
      }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;
      using System.Runtime.InteropServices;

      namespace MyLibrary
      {
      public class Foo : IDisposable
      {
      private IntPtr myResource;
      private bool disposed = false;

      protected virtual void Dispose(bool disposing) 
      {
        if (!disposed) 
        {
          // Dispose of resources held by this instance.
          FreeResource(myResource);
          disposed = true;

          // Suppress finalization of this disposed instance.
          if (disposing)
          {
            GC.SuppressFinalize(this);
          }
        }
      }

      ~Foo()
      {
        Dispose(false);
      }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Methods should be named according to their synchronicities">
    <div class="paragraph">
      <p>According to the Task-based Asynchronous Pattern (TAP), methods returning  either a <code>System.Threading.Tasks.Task or a System.Threading.Tasks.Task\<TResult> are considered "asynchronous". Such methods should use the Async</code> suffix. Conversely methods which do not return such Tasks should not have an "Async" suffix in their names.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;
      using  System.Threading.Tasks;

      namespace myLibrary
      {

      public class Foo
      {
      public Task Read(byte [] buffer, int offset, int count, // Noncompliant
                                  CancellationToken cancellationToken)
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;
      using  System.Threading.Tasks;

      namespace myLibrary
      {

      public class Foo
      {
      public Task ReadAsync(byte [] buffer, int offset, int count, CancellationToken cancellationToken)
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Composite format strings should be used correctly">
    <div class="paragraph">
      <p>A \[composite format string]\(<a href="https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting" class="bare">[https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting](https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting)</a>) is a string that contains placeholders, represented by indices inside curly braces "\{0}", "\{1}", etc. These placeholders are replaced by values when the string is printed or logged.</p>
    </div>

    <div class="paragraph">
      <p>Because composite format strings are interpreted at runtime, rather than validated by the compiler, they can contain errors that lead to unexpected behaviors or runtime errors.</p>
    </div>

    <div class="paragraph">
      <p>This rule validates the correspondence between arguments and composite formats when calling the
      following methods:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.string.format?view=net-7.0">String.Format</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.appendformat?view=net-7.0">StringBuilder.AppendFormat</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.console.write?view=net-7.0">Console.Write</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.console.writeline?view=net-7.0">Console.WriteLine</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.io.textwriter.write?view=net-7.0">TextWriter.Write</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.io.textwriter.writeline?view=net-7.0">TextWriter.WriteLine</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.debug.writeline?view=net-7.0">Debug.WriteLine(String, Object\[</a>)]</p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.trace.traceerror?view=net-7.0">Trace.TraceError(String, Object\[</a>)]</p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.trace.traceinformation?view=net-7.0">Trace.TraceInformation(String, Object\[</a>)]</p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.trace.tracewarning?view=net-7.0">Trace.TraceWarning(String, Object\[</a>)]</p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.tracesource.traceinformation?view=net-7.0">TraceSource.TraceInformation(String, Object\[</a>)]</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      var pattern = "{0} {1} {2}";
      var res = string.Format(pattern, 1, 2); // Incorrect, but the analyzer doesn't raise any warnings here
      ```

      ```csharp Fix theme={null}
      var array = new int[] {};
      var res = string.Format("{0} {1}", array); // Compliant; we don't know the size of the array
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Obsolete methods should not be overridden">
    <div class="paragraph">
      <p>Obsoleted method should be avoided, rather than overridden. Obsolescence is a warning that the method has been superseded, and will eventually be removed. The obsolescence period allows you to make a smooth transition away from the aging, soon-to-be-retired technology.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Car
      {

      [Obsolete("Replaced by the automatic starter")]
      public void CrankEngine(int turnsOfCrank) 
      { ... }
      }

      public class R2 : Car
      {

      public void CrankEngine(int turnsOfCrank)   // Noncompliant
      { ... }

      ...
      }
      ```

      ```csharp Fix theme={null}
      public class Car
      {

      [Obsolete("Replaced by the automatic starter")]
      public void CrankEngine(int turnsOfCrank) 
      { ... }
      }

      public class R2 : Car
      {

      ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Strings should not be concatenated using + in a loop">
    <div class="paragraph">
      <p><code>StringBuilder</code> is more efficient than string concatenation, especially when the operator is repeated over and over as in loops.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      string str = "";
      for (int i = 0; i < arrayOfStrings.Length ; ++i) 
      {
      str = str + arrayOfStrings[i];
      }
      ```

      ```csharp Fix theme={null}
      StringBuilder bld = new StringBuilder();
      for (int i = 0; i < arrayOfStrings.Length; ++i) 
      {
      bld.Append(arrayOfStrings[i]);
      }
      string str = bld.ToString();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="operator== should not be overloaded on reference types">
    <div class="paragraph">
      <p>The use of == to compare two objects is expected to do a reference comparison. That is, it is expected to return true if and only if they are the same object instance. Overloading the operator to do anything else will inevitably lead to the introduction of bugs by callers.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public static bool operator ==(MyType x, MyType y) // Noncompliant: confusing for the caller
      {
      // custom implementation
      }
      ```

      ```csharp Fix theme={null}
      public static bool operator ==(MyType x, MyType y) // Noncompliant: redundant 
      {
      if (x == null)
      {
          return y == null;
      }

      return object.ReferenceEquals(x,y);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Pointers to unmanaged memory should not be visible">
    <div class="paragraph">
      <p>Pointer and unmanaged function pointer types such as IntPtr, UIntPtr, <code>int\* etc. are used to access unmanaged memory, usually in order to use C or C++ libraries.  If such a pointer is not secured by making it private, internal or readonly</code>, it can lead to a vulnerability allowing access to arbitrary locations.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      namespace MyLibrary
      {
      public class MyClass
      {
      public IntPtr myPointer;  // Noncompliant
      protected UIntPtr myOtherPointer; // Noncompliant
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;

      namespace MyLibrary
      {
      public class MyClass
      {
      private IntPtr myPointer;
      protected readonly UIntPtr myOtherPointer;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Calculations should not overflow">
    <div class="paragraph">
      <p>Numbers are infinite, but the types that hold them are not. Each numeric type has hard upper and lower bounds. Try to calculate or assign numbers beyond those bounds, and the result will be a value that has silently wrapped around from the expected positive value to a negative one, or vice versa.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public int Transform(int value)
      {
      if (value <= 0)
      {
          return value;
      }
      int number = int.MaxValue;
      return number + value;  // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      public long Transform(int value)
      {
      if (value <= 0)
      {
          return value;
      }
      long number = int.MaxValue;
      return number + value;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Type names should not match namespaces">
    <div class="paragraph">
      <p>When a type name matches the name of a publicly defined namespace, for instance one in the .NET framework class library, it leads to confusion and makes the library that much harder to use.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a name of a public type matches the name of a .NET Framework namespace, or a namespace of the project assembly, in a case-insensitive comparison.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      namespace MyLibrary
      {
      public class Text   // Noncompliant: Collides with System.Text
      {
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;

      namespace MyLibrary
      {
      public class MyText
      {
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Array.Empty<TElement>() should be used to instantiate empty arrays">
    <div class="paragraph">
      <p>Method for creating empty arrays <code>Array.Empty\<TElement>()</code> was introduced in .NET 4.6 to optimize object instantiation and memory allocation. It also improves code readability by making developer’s intent more explicit. This new method should be preferred over empty array declaration.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public void Method()
      {
      var zero_length = new int[0]; // Noncompliant
      var empty_array = new string[] { }; // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      public void Method()
      {
      var zero_length = Array.Empty<int>();
      var empty_array = Array.Empty<string>();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="params should be used on overrides">
    <div class="paragraph">
      <p>Overriding methods automatically inherit the <code>params</code> behavior. To ease readability, this modifier should be explicitly used in the overriding method as well.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      class Base
      {
      public virtual void Method(params int[] numbers)
      {
      ...
      }
      }
      class Derived : Base
      {
      public override void Method(int[] numbers) // Noncompliant, the params is missing.
      {
      ...
      }
      }
      ```

      ```csharp Fix theme={null}
      class Base
      {
      public virtual void Method(params int[] numbers)
      {
      ...
      }
      }
      class Derived : Base
      {
      public override void Method(params int[] numbers)
      {
      ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Runtime type checking should be simplified">
    <div class="paragraph">
      <p>To check the type of an object there are several options:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><code>expr is SomeType or </code>++expr.GetType()</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      class Fruit { }
      sealed class Apple : Fruit { }

      class Program
      {
      static void Main()
      {
      var apple = new Apple();
      var b = apple != null && apple.GetType() == typeof (Apple); // Noncompliant
      b = typeof(Apple).IsInstanceOfType(apple); // Noncompliant
      if (apple != null)
      {
        b = typeof(Apple).IsAssignableFrom(apple.GetType()); // Noncompliant
      }
      var appleType = typeof (Apple);
      if (apple != null)
      {
        b = appleType.IsAssignableFrom(apple.GetType()); // Noncompliant
      }

      Fruit f = apple;
      if (f as Apple != null) // Noncompliant
      {
      }
      if (apple is Apple) // Noncompliant
      {
      }
      }
      }
      ```

      ```csharp Fix theme={null}
      class Fruit { }
      sealed class Apple : Fruit { }

      class Program
      {
      static void Main()
      {
      var apple = new Apple();
      var b = apple is Apple;
      b = apple is Apple;
      b = apple is Apple;
      var appleType = typeof(Apple);
      b = appleType.IsInstanceOfType(apple);

      Fruit f = apple;
      if (f is Apple)
      {
      }
      if (apple != null)
      {
      }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Empty arrays and collections should be returned instead of null">
    <div class="paragraph">
      <p>Returning \`null or default instead of an actual collection forces the method callers to explicitly test for null, making the code more complex and less readable.</p>
    </div>

    <div class="paragraph">
      <p>Moreover, in many cases, null or default\` is used as a synonym for empty.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      public Result[] GetResults()
      {
      return null; // Noncompliant
      }

      public IEnumerable<Result> GetResults(bool condition)
      {
      var results = GenerateResults();
      return condition 
          ? results 
          : null; // Noncompliant
      }

      public IEnumerable<Result> GetResults() => null; // Noncompliant

      public IEnumerable<Result> Results 
      {
      get
      {
          return default(IEnumerable<Result>); // Noncompliant
      }
      }

      public IEnumerable<Result> Results => default; // Noncompliant
      ```

      ```csharp Fix theme={null}
      public Result[] GetResults()
      {
      return new Result[0];
      }

      public IEnumerable<Result> GetResults(bool condition)
      {
      var results = GenerateResults();
      return condition 
          ? results 
          : Enumerable.Empty<Result>(); 
      }

      public IEnumerable<Result> GetResults() => Enumerable.Empty<Result>();

      public IEnumerable<Result> Results 
      {
      get
      {
          return Enumerable.Empty<Result>();
      }
      }

      public IEnumerable<Result> Results => Enumerable.Empty<Result>();
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Redundant property names should be omitted in anonymous classes">
    <div class="paragraph">
      <p>When an anonymous type’s properties are copied from properties or variables with the same names, it yields cleaner code to omit the new type’s property name and the assignment operator.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      var X = 5;

      var anon = new 
      {
      X = X, //Noncompliant, the new object would have the same property without the "X =" part.
      Y = "my string"
      };
      ```

      ```csharp Fix theme={null}
      var X = 5;

      var anon = new 
      {
      X,
      Y = "my string"
      };
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Non-flags enums should not be marked with FlagsAttribute">
    <div class="paragraph">
      <p>This rule raises an issue when an externally visible enumeration is marked with <code>FlagsAttribute</code> and one, or more, of its values is not a power of 2 or a combination of the other defined values.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      namespace MyLibrary
      {
      [Flags]
      public enum Color // Noncompliant, Orange is neither a power of two, nor a combination of any of the defined values
      {
          None    = 0,
          Red     = 1,
          Orange  = 3,
          Yellow  = 4
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;

      namespace MyLibrary
      {
      public enum Color // Compliant - no FlagsAttribute
      {
          None = 0,
          Red = 1,
          Orange = 3,
          Yellow = 4
      }

      [Flags]    
      public enum Days    
      {        
          None = 0,        
          Monday = 1,        
          Tuesday = 2,        
          Wednesday = 4,        
          Thursday = 8,        
          Friday = 16,        
          All = Monday| Tuesday | Wednesday | Thursday | Friday    // Compliant - combination of other values
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="switch/Select statements should contain a default/Case Else clauses">
    <div class="paragraph">
      <p>The requirement for a final <code>default clause is defensive programming. The clause should either take appropriate action, or contain a suitable comment as to why no action is taken. Even when the switch covers all current values of an enum, a default case should still be used because there is no guarantee that the enum</code> won’t be extended.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      int foo = 42;
      switch (foo) // Noncompliant
      {
      case 0:
      Console.WriteLine("foo = 0");
      break;
      case 42:
      Console.WriteLine("foo = 42");
      break;
      }
      ```

      ```csharp Fix theme={null}
      int foo = 42;
      switch (foo) // Compliant
      {
      case 0:
      Console.WriteLine("foo = 0");
      break;
      case 42:
      Console.WriteLine("foo = 42");
      break;
      default:
      throw new InvalidOperationException("Unexpected value foo = " + foo);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="A conditionally executed single line should be denoted by indentation">
    <div class="paragraph">
      <p>When the line immediately after conditional statements has neither curly braces nor indentation, the intent of the code is unclear and perhaps not executed as expected.
      Additionally, such code is confusing to maintainers.</p>
    </div>

    <div class="paragraph">
      <p>The rule will check the line indentation after the following conditional statements:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/selection-statements#the-if-statement">if and if-else statements</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/iteration-statements#the-for-statement">for statement</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/iteration-statements#the-foreach-statement">foreach statement</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/iteration-statements#the-do-statement">do statement</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/iteration-statements#the-while-statement">while statement</a></p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if (condition)  // Noncompliant
      DoTheThing();
      DoTheOtherThing(); // Was the intent to call this function unconditionally?
      ```

      ```csharp Fix theme={null}
      if (condition)  // Noncompliant
      //   DoTheThing();
      DoTheOtherThing(); // Was the intent to call this function conditionally?
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="for loop increment clauses should modify the loops counters">
    <div class="paragraph">
      <p>The for loop is designed to iterate over a range using a counter variable, with the counter being updated in the loop’s increment section. Misusing this structure can lead to issues such as infinite loops if the counter is not updated correctly. If this is intentional, use a while or do while loop instead of a for loop.</p>
    </div>

    <div class="paragraph">
      <p>Using a for loop for purposes other than its intended use can lead to confusion and potential bugs. If the for loop structure does not fit your needs, consider using an alternative <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/iteration-statements">iteration statement</a>.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      int sum = 0;
      for (int i = 0; i < 10; sum++) // Noncompliant: `i` is not updated in the increment section
      {
      // ...
      i++;
      }
      ```

      ```csharp Fix theme={null}
      for (int i = 0;; i++) // Noncompliant: the loop condition is empty although incrementing `i`
      {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="TestFixtures should only have one SetUp method.">
    <div class="paragraph">
      <p>NUnit <code>TestFixtures may only have one \[SetUp] method. Any more than that and the TestFixture</code> will compile but not run.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      namespace NUnit.Tests
      {
      using System;
      using NUnit.Framework;

      [TestFixture]
      public class MyTests
      {
      [SetUp] public void Init()
      { /* ... */ }

      [Setup] public void Prep()  // Noncompliant
      { /* ... */ }
      }
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Tests should not be ignored">
    <div class="paragraph">
      <p>When a test fails due, for example, to infrastructure issues, you might want to ignore it temporarily. But without some kind of notation about why the test is being ignored, it may never be reactivated. Such tests are difficult to address without comprehensive knowledge of the project, and end up polluting their projects.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue for each ignored test that does not have a <code>WorkItem attribute nor a comment about why it is being skipped on the right side of the Ignore</code> attribute.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      [TestMethod]
      [Ignore]
      public void Test_DoTheThing() 
      { 
      // ...
      }
      ```

      ```csharp Fix theme={null}
      [TestMethod]
      [Ignore]  // renable when TCKT-1234 is fixed
      public void Test_DoTheThing() 
      { 
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Tests should include assertions">
    <div class="paragraph">
      <p>The rule targets test methods that lack an assertion and consist solely of an action and, optionally, a setup.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      [TestMethod]
      public void Add_SingleNumber_ReturnsSameNumber()
      {
      var stringCalculator = new StringCalculator();
      var actual = stringCalculator.Add("0");
      }
      ```

      ```csharp Fix theme={null}
      using System;
      using Microsoft.VisualStudio.TestTools.UnitTesting;

      [TestClass]
      public class CustomTestExample
      {
      [TestMethod]
      public void Add_SingleNumber_ReturnsSameNumber()
      {
          var stringCalculator = new StringCalculator();
          var actual = stringCalculator.Add("0");
          Validator.AssertCustomEquality(0, actual); // Compliant
      }
      }

      public static class Validator
      {
      [AssertionMethod]
      public static void AssertCustomEquality(int expected, int actual)
      {
          // ...    
      }
      }

      public class AssertionMethodAttribute : Attribute { }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Explicit Event subscriptions should be explicitly unsubscribed.">
    <div class="paragraph">
      <p>Subscribing to events without unsubscribing later on can lead to memory leaks or even duplicate subscriptions, i.e. code which is executed multiple times by mistake.</p>
    </div>

    <div class="paragraph">
      <p>Even if there is no problem right now, the code is more difficult to review and a simple refactoring can create a bug. For example the lifetime of the event publisher could change and prevent subscribers from being garbage collected.</p>
    </div>

    <div class="paragraph">
      <p>There are patterns to automatically unsubscribe, but the simplest and most readable solution remains to unsubscribe from events explicitly using \`-=.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a class subscribes to an even using += without explicitly unsubscribing with -=\`.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      class MyEventProcucer
      {
      public static event EventHandler eventFired;
      }

      public class MyEventSubscriber : IDisposable
      {

      public MyEventSubscriber()
      {
          MyEventProcucer.eventFired += c_EventFired;  // Noncompliant.
      }

      static void c_EventFired(object sender, EventArgs e)
      {}

      public void Dispose()
      {}
      }
      ```

      ```csharp Fix theme={null}
      using System;

      class MyEventProcucer
      {
      public static event EventHandler eventFired;
      }

      public class MyEventSubscriber : IDisposable
      {

      public MyEventSubscriber()
      {
          MyEventProcucer.eventFired += c_EventFired;
      }

      static void c_EventFired(object sender, EventArgs e)
      {}

      public void Dispose()
      {
          MyEventProcucer.eventFired -= c_EventFired;  // Unsubscribe
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Implementations should be provided for partial methods">
    <div class="paragraph">
      <p><code>partial</code> methods allow an increased degree of flexibility in programming a system. Hooks can be added to generated code by invoking methods that define their signature, but might not have an implementation yet. But if the implementation is still missing when the code makes it to production, the compiler silently removes the call. In the best case scenario, such calls simply represent cruft, but in they worst case they are critical, missing functionality, the loss of which will lead to unexpected results at runtime.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue for partial methods for which no implementation can be found in the assembly.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      partial class C
      {
      partial void M(); //Noncompliant

      void OtherM()
      {
      M(); //Noncompliant. Will be removed.
      }
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="ISerializable should be implemented correctly">
    <div class="paragraph">
      <p>The <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.iserializable">ISerializable</a> interface is the mechanism to control the type serialization process. If not implemented correctly this could result in an invalid serialization and hard-to-detect bugs.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue on types that implement ISerializable without following the <a href="https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/serialization">serialization pattern recommended by Microsoft</a>.</p>
    </div>

    <div class="paragraph">
      <p>Specifically, this rule checks for these problems:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>The <a href="https://learn.microsoft.com/en-us/dotnet/api/system.serializableattribute">SerializableAttribute</a> attribute is missing.</p>
        </li>

        <li>
          <p>Non-serializable fields are not marked with the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.nonserializedattribute">NonSerializedAttribute</a> attribute.</p>
        </li>

        <li>
          <p>There is no serialization constructor.</p>
        </li>

        <li>
          <p>An unsealed type has a serialization constructor that is not protected.</p>
        </li>

        <li>
          <p>A sealed type has a serialization constructor that is not private.</p>
        </li>

        <li>
          <p>An unsealed type has an <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.iserializable.getobjectdata">ISerializable.GetObjectData</a> that is not both public and virtual.</p>
        </li>

        <li>
          <p>A derived type has a serialization constructor that does not call the base constructor.</p>
        </li>

        <li>
          <p>A derived type has an ISerializable.GetObjectData method that does not call the base method.</p>
        </li>

        <li>
          <p>A derived type has serializable fields but the ISerializable.GetObjectData method is not overridden.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Classes that inherit from <a href="https://learn.microsoft.com/en-us/dotnet/api/system.exception">Exception</a> are implementing ISerializable. Make sure the \[Serializable] attribute is used and that ISerializable is correctly implemented. Even if you don’t plan to explicitly serialize the object yourself, it might still require serialization, for instance when crossing the boundary of an <a href="https://learn.microsoft.com/en-us/dotnet/api/system.appdomain">AppDomain</a>.</p>
    </div>

    <div class="paragraph">
      <p>This rule only raises an issue on classes that indicate that they are interested in serialization (see the <em>Exceptions</em> section). That is to reduce noise because a lot of classes in the base class library are implementing ISerializable, including the following classes: <a href="https://learn.microsoft.com/en-us/dotnet/api/system.exception">Exception</a>, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.uri">Uri</a>, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.hashtable">Hashtable</a>, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2">Dictionary\<TKey,TValue></a>, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.data.dataset">DataSet</a>, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest">HttpWebRequest</a>, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex">Regex</a> <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.treenode">TreeNode</a>, and others. There is often no need to add serialization support in classes derived from these types.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```csharp Bad theme={null}
      [Serializable]                                                                                 // 1.
      public class SerializationOptIn_Attribute
      {
      }

      public class SerializationOptIn_Interface : ISerializable                                      // 2.
      {
      }

      public class SerializationOptIn_Constructor
      {
      protected SerializationOptIn_Constructor(SerializationInfo info, StreamingContext context) // 3.
      { 
      }
      }
      ```

      ```csharp Fix theme={null}
      public class Bar
      {
      }

      public class Foo : ISerializable // Noncompliant: serialization constructor is missing
                                   // Noncompliant: the [Serializable] attribute is missing
      {
      private readonly Bar bar; // Noncompliant: the field is not marked with [NonSerialized]
      }

      public sealed class SealedFoo : Foo
      {
      private int val; // Noncompliant: 'val' is serializable and GetObjectData is not overridden

      public SealedFoo()
      {
          // ...
      }

      public SealedFoo(SerializationInfo info, StreamingContext context) // Noncompliant: serialization constructor is not `private`
                                                                         // Noncompliant: serialization constructor does not call base constructor
      {
          // ...
      }
      }

      public class UnsealedFoo : Foo
      {
      public UnsealedFoo()
      {
          // ...
      }

      public UnsealedFoo(SerializationInfo info, StreamingContext context) // Noncompliant: serialization constructor is not `protected`
          : base(info, context)
      {
          // ...
      }

      protected void GetObjectData(SerializationInfo info, StreamingContext context) // Noncompliant: GetObjectData is not public virtual
      {
          // Noncompliant: does not call base.GetObjectData(info, context)
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Use a testable date/time provider">
    <div class="paragraph">
      <p>One of the principles of a unit test is that it must have full control of the system under test. This is problematic when production code includes calls to static methods, which cannot be changed or controlled. Date/time functions are usually provided by system libraries as static methods.</p>
    </div>

    <div class="paragraph">
      <p>This can be improved by wrapping the system calls in an object or service that can be controlled inside the unit test.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Foo
      {
      public string HelloTime() =>
          $"Hello at {DateTime.UtcNow}";
      }
      ```

      ```csharp Fix theme={null}
      public interface IClock
      {
      DateTime UtcNow();
      }

      public class Foo
      {
      public string HelloTime(IClock clock) =>
          $"Hello at {clock.UtcNow()}";
      }

      public class FooTest
      {
      public record TestClock(DateTime now) : IClock
      {
          public DateTime UtcNow() => now;
      }

      [Fact]
      public void HelloTime_Gives_CorrectTime()
      {
          var dateTime = new DateTime(2017, 06, 11);
          Assert.Equal((new Foo()).HelloTime(new TestClock(dateTime)), $"Hello at {dateTime}");
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Locks should be released on all paths">
    <div class="paragraph">
      <p>If a lock is acquired and released within a method, then it must be released along all execution paths of that method.</p>
    </div>

    <div class="paragraph">
      <p>Failing to do so will expose the conditional locking logic to the method’s callers and hence be deadlock-prone.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      class MyClass
      {
      private object obj = new object();

      public void DoSomethingWithMonitor()
      {
      Monitor.Enter(obj); // Noncompliant: not all paths release the lock
      if (IsInitialized())
      {
        // ...
        Monitor.Exit(obj);
      }
      }
      }
      ```

      ```csharp Fix theme={null}
      class MyClass
      {
      private ReaderWriterLockSlim lockObj = new ReaderWriterLockSlim();

      public void DoSomethingWithReaderWriteLockSlim()
      {
      lockObj.EnterReadLock(); // Noncompliant: not all paths release the lock
      if (IsInitialized())
      {
        // ...
        lockObj.ExitReadLock();
      }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Boolean checks should not be inverted">
    <div class="paragraph">
      <p>It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if ( !(a == 2)) { ...}  // Noncompliant
      bool b = !(i < 10);  // Noncompliant
      ```

      ```csharp Fix theme={null}
      if (a != 2) { ...} 
      bool b = (i >= 10);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Regular expressions should be syntactically valid">
    <div class="paragraph">
      <p>Regular expressions have their own syntax that is understood by regular expression engines. Those engines will throw an exception at runtime if they are given a regular expression that does not conform to that syntax.</p>
    </div>

    <div class="paragraph">
      <p>To avoid syntax errors, special characters should be escaped with backslashes when they are intended to be matched literally and references to capturing groups should use the correctly spelled name or number of the group.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      void Regexes(string input)
      {
      var regex = new Regex("[A");                                                    // Noncompliant
      var match = Regex.Match(input, "[A");                                           // Noncompliant
      var negativeLookahead = new Regex("a(?!b)", RegexOptions.NonBacktracking);      // Noncompliant
      var negativeLookbehind = new Regex("(?<!a)b", RegexOptions.NonBacktracking);    // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      void Regexes(string input)
      {
      var regex = new Regex("[A-Z]");
      var match = Regex.Match(input, "[A-Z]");
      var negativeLookahead = new Regex("a(?!b)");
      var negativeLookbehind = new Regex("(?<!a)b");
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using publicly writable directories is security-sensitive">
    <div class="paragraph">
      <p>Operating systems have global directories where any user has write access. Those folders are mostly used as temporary storage areas like \`/tmp in Linux based systems. An application  manipulating files from these folders is exposed to race conditions on filenames: a malicious user can try to create a file with a predictable name before the application does. A successful attack can result in other files being accessed, modified, corrupted or deleted. This risk is even higher if the application runs with elevated permissions.</p>
    </div>

    <div class="paragraph">
      <p>In the past, it has led to the following vulnerabilities:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://nvd.nist.gov/vuln/detail/CVE-2012-2451">CVE-2012-2451</a></p>
        </li>

        <li>
          <p><a href="https://nvd.nist.gov/vuln/detail/CVE-2015-1838">CVE-2015-1838</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue whenever it detects a hard-coded path to a publicly writable directory like /tmp (see examples bellow). It also detects access to environment variables that point to publicly writable directories, e.g., TMP and TMPDIR.</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>/tmp</p>
        </li>

        <li>
          <p>/var/tmp</p>
        </li>

        <li>
          <p>/usr/tmp</p>
        </li>

        <li>
          <p>/dev/shm</p>
        </li>

        <li>
          <p>/dev/mqueue</p>
        </li>

        <li>
          <p>/run/lock</p>
        </li>

        <li>
          <p>/var/run/lock</p>
        </li>

        <li>
          <p>/Library/Caches</p>
        </li>

        <li>
          <p>/Users/Shared</p>
        </li>

        <li>
          <p>/private/tmp</p>
        </li>

        <li>
          <p>/private/var/tmp</p>
        </li>

        <li>
          <p>\Windows\Temp</p>
        </li>

        <li>
          <p>\Temp</p>
        </li>

        <li>
          <p>\TMP\`</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      var randomPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

      // Creates a new file with write, non inheritable permissions which is deleted on close.
      using var fileStream = new FileStream(randomPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.DeleteOnClose);
      using var writer = new StreamWriter(fileStream);
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="this should not be exposed from constructors">
    <div class="paragraph">
      <p>In single-threaded environments, the use of \`this in constructors is normal, and expected. But in multi-threaded environments, it could expose partially-constructed objects to other threads, and should be used with caution.</p>
    </div>

    <div class="paragraph">
      <p>The classic example is a class with a static list of its instances. If the constructor stores this in the list, another thread could access the object before it’s fully-formed. Even when the storage of this is the last instruction in the constructor, there’s still a danger if the class is not final. In that case, the initialization of subclasses won’t be complete before this is exposed.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when this\` is assigned to any globally-visible object in a constructor, and when it is passed to the method of another object in a constructor</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Monument
      {
      public static readonly List<Monument> ALL_MONUMENTS = new List<Monument>();
      // ...

      public Monument(string location, ...)
      {
      ALL_MONUMENTS.Add(this);  // Noncompliant; passed to a method of another object 

      this.location = location;
      // ...
      }
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="A close curly brace should be located at the beginning of a line">
    <div class="paragraph">
      <p>Shared coding conventions make it possible for a team to efficiently collaborate. This rule makes it mandatory to place a close curly brace at the beginning of a line.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if(condition) 
      {
      doSomething();}
      ```

      ```csharp Fix theme={null}
      if(condition) 
      {
      doSomething();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Test classes should comply with a naming convention">
    <div class="paragraph">
      <p>Shared naming conventions allow teams to collaborate efficiently. This rule raises an issue when a test class name does not match the provided regular expression.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      [TestClass]
      public class Foo // Noncompliant
      {
      ```

      ```csharp Fix theme={null}
      [TestClass]
      public class FooTest
      {
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Statements should be on separate lines">
    <div class="paragraph">
      <p>Putting multiple statements on a single line lowers the code readability and makes debugging the code more complex.</p>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{noncompliant}\[]</p>
    </div>

    <div class="paragraph">
      <p>Write one statement per line to improve readability.</p>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{compliant}\[]</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      Func<object, bool> item1 = o => { return true; }; // Compliant by exception
      Func<object, bool> item1 = o => { var r = false; return r; }; // Noncompliant
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Enumeration type names should not have Flags or Enum suffixes">
    <div class="paragraph">
      <p>The information that an enumeration type is actually an enumeration or a set of flags should not be duplicated in its name.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      enum FooFlags // Noncompliant
      {
      Foo = 1
      Bar = 2
      Baz = 4
      }
      ```

      ```csharp Fix theme={null}
      enum Foo
      {
      Foo = 1
      Bar = 2
      Baz = 4
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Expressions should not be too complex">
    <div class="paragraph">
      <p>The complexity of an expression is defined by the number of <code>&&, || and condition ? ifTrue : ifFalse</code> operators it contains.</p>
    </div>

    <div class="paragraph">
      <p>A single expression’s complexity should not become too high to keep the code readable.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if (((condition1 && condition2) || (condition3 && condition4)) && condition5) { ... }
      ```

      ```csharp Fix theme={null}
      if ((MyFirstCondition() || MySecondCondition()) && MyLastCondition()) { ... }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Disabling CSRF protections is security-sensitive">
    <div class="paragraph">
      <p>A cross-site request forgery (CSRF) attack occurs when a trusted user of a web application can be forced, by an attacker, to perform sensitive actions that he didn’t intend, such as updating his profile or sending a message, more generally anything that can change the state of the application.</p>
    </div>

    <div class="paragraph">
      <p>The attacker can trick the user/victim to click on a link, corresponding to the privileged action, or to visit a malicious web site that embeds a hidden web request and as web browsers automatically include cookies, the actions can be authenticated and sensitive.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public void ConfigureServices(IServiceCollection services)
      {
      // ...
      services.AddControllersWithViews(options => options.Filters.Add(new IgnoreAntiforgeryTokenAttribute())); // Sensitive
      // ...
      }
      ```

      ```csharp Fix theme={null}
      [HttpPost, IgnoreAntiforgeryToken] // Sensitive
      public IActionResult ChangeEmail(ChangeEmailModel model) => View("~/Views/...");
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Searching OS commands in PATH is security-sensitive">
    <div class="paragraph">
      <p>When executing an OS command and unless you specify the full path to the executable, then the locations in your application’s <code>PATH environment variable will be searched for the executable. That search could leave an opening for an attacker if one of the elements in PATH</code> is a directory under his control.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      Process p = new Process();
      p.StartInfo.FileName = @"C:\Apps\binary.exe"; // Compliant
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Having a permissive Cross-Origin Resource Sharing policy is security-sensitive">
    <div class="paragraph">
      <p>Having a permissive Cross-Origin Resource Sharing policy is security-sensitive. It has led in the past to the following vulnerabilities:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-0269">CVE-2018-0269</a></p>
        </li>

        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-14460">CVE-2017-14460</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p><a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy">Same origin policy</a> in browsers prevents, by default and for security-reasons, a javascript frontend to perform a cross-origin HTTP request to a resource that has a different origin (domain, protocol, or port) from its own. The requested target can append additional HTTP headers in response, called <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">CORS</a>, that act like directives for the browser and change the access control policy / relax the same origin policy.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      String origin = Request.Headers["Origin"];
      Response.Headers.Add("Access-Control-Allow-Origin", origin); // Sensitive
      ```

      ```csharp Fix theme={null}
      [HttpGet]
      public string Get()
      {
      Response.Headers.Add("Access-Control-Allow-Origin", "https://trustedwebsite.com"); // Safe
      Response.Headers.Add(HeaderNames.AccessControlAllowOrigin, "https://trustedwebsite.com"); // Safe
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Exceptions should not be thrown from property getters">
    <div class="paragraph">
      <p>Property getters should be simple operations that are always safe to call. If exceptions need to be thrown, it is best to convert the property to a method.</p>
    </div>

    <div class="paragraph">
      <p>It is valid to throw exceptions from indexed property getters and from property setters, which are not detected by this rule.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public int Foo
      {
      get
      {
          throw new Exception(); // Noncompliant
      }
      }
      ```

      ```csharp Fix theme={null}
      public int Foo
      {
      get
      {
          return 42;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Empty case clauses that fall through to the default should be omitted">
    <div class="paragraph">
      <p>Empty `case clauses that fall through to the default are useless. Whether or not such a case is present, the default clause will be invoked. Such case`s simply clutter the code, and should be removed.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      switch(ch) 
      {
      case 'a' :
      HandleA();
      break;
      case 'b' :
      HandleB();
      break;
      case 'c' :  // Noncompliant
      default:
      HandleTheRest();
      break;
      }
      ```

      ```csharp Fix theme={null}
      switch(ch) 
      {
      case 'a' :
      HandleA();
      break;
      case 'b' :
      HandleB();
      break;
      default:
      HandleTheRest();
      break;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Collection elements should not be replaced unconditionally">
    <CodeGroup>
      ```csharp Bad theme={null}
      list[index] = "value 1";
      list[index] = "value 2";  // Noncompliant

      dictionary.Add(key, "value 1");
      dictionary[key] = "value 2"; // Noncompliant
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Local variables should not be declared and then immediately returned or thrown">
    <div class="paragraph">
      <p>Declaring a variable only to immediately return or throw it is considered a bad practice because it adds unnecessary complexity to the code. This practice can make the code harder to read and understand, as it introduces an extra step that doesn’t add any value. Instead of declaring a variable and then immediately returning or throwing it, it is generally better to return or throw the value directly. This makes the code cleaner, simpler, and easier to understand.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public long ComputeDurationInMilliseconds()
      {
      long duration = (((hours * 60) + minutes) * 60 + seconds ) * 1000 ;
      return duration;
      }

      public void DoSomething()
      {
      ApplicationException myException = new ApplicationException();
      throw myException;
      }
      ```

      ```csharp Fix theme={null}
      public long ComputeDurationInMilliseconds() 
      {
      return (((hours * 60) + minutes) * 60 + seconds ) * 1000 ;
      }

      public void DoSomething() 
      {
      throw new ApplicaitonException();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="One-way OperationContract methods should have void return type">
    <div class="paragraph">
      <p>When declaring a Windows Communication Foundation (WCF) <a href="https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.operationcontractattribute?view=dotnet-plat-ext-7.0">OperationContract</a> method as <a href="https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.operationcontractattribute.isoneway?view=dotnet-plat-ext-7.0">one-way</a>, that service method won’t return any result, not even an underlying empty confirmation message. These are fire-and-forget methods that are useful in event-like communication. Therefore, specifying a return type has no effect and can confuse readers.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      [ServiceContract]
      interface IMyService 
      {
      [OperationContract(IsOneWay = true)]
      int SomethingHappened(int parameter); // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      [ServiceContract]
      interface IMyService 
      {
      [OperationContract(IsOneWay = true)]
      void SomethingHappened(int parameter);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="General catch clauses should not be used">
    <div class="paragraph">
      <p>A general <code>catch</code> block seems like an efficient way to handle multiple possible exceptions. Unfortunately, it traps all exception types, casting too broad a net, and perhaps mishandling extraordinary cases. Instead, specific exception sub-types should be caught.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      string text = "";
      try
      {
      text = File.ReadAllText(fileName);
      } catch {  // Noncompliant
      // ...
      }

      try
      {
      text = File.ReadAllText(fileName);
      } catch (Exception exc) {  // Noncompliant
      // ...
      }
      ```

      ```csharp Fix theme={null}
      string text = "";
      try
      {
      text = File.ReadAllText(fileName);
      } catch (UnauthorizedAccessException exc) {
      // you do not have the required permission
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Delivering code in production with debug features activated is security-sensitive">
    <div class="paragraph">
      <p>Development tools and frameworks usually have options to make debugging easier for developers. Although these features are useful during development, they should never be enabled for applications deployed in production. Debug instructions or error messages can leak detailed information about the system, like the application’s path or file names.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      using Microsoft.AspNetCore.Builder;
      using Microsoft.AspNetCore.Hosting;

      namespace mvcApp
      {
      public class Startup2
      {
          public void Configure(IApplicationBuilder app, IHostingEnvironment env)
          {
              // Those calls are Sensitive because it seems that they will run in production
              app.UseDeveloperExceptionPage(); // Sensitive
              app.UseDatabaseErrorPage(); // Sensitive
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      using Microsoft.AspNetCore.Builder;
      using Microsoft.AspNetCore.Hosting;

      namespace mvcApp
      {
      public class Startup2
      {
          public void Configure(IApplicationBuilder app, IHostingEnvironment env)
          {
              if (env.IsDevelopment())
              {
                  // The following calls are ok because they are disabled in production
                  app.UseDeveloperExceptionPage(); // Compliant
                  app.UseDatabaseErrorPage(); // Compliant
              }
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Static fields should not be updated in constructors">
    <div class="paragraph">
      <p>Assigning a value to a \`static field in a constructor could cause unreliable behavior at runtime since it will change the value for all instances of the class.</p>
    </div>

    <div class="paragraph">
      <p>Instead remove the field’s static\` modifier, or initialize it statically.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Person 
      {
      private static DateTime dateOfBirth;
      private static int expectedFingers;

      public Person(DateTime birthday) 
      {
      dateOfBirth = birthday;  // Noncompliant; now everyone has this birthday
      expectedFingers = 10;  // Noncompliant
      }
      }
      ```

      ```csharp Fix theme={null}
      public class Person 
      {
      private DateTime dateOfBirth;
      private static int expectedFingers = 10;

      public Person(DateTime birthday) 
      {
      this.dateOfBirth = birthday;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Standard outputs should not be used directly to log anything">
    <div class="paragraph">
      <p>In software development, logs serve as a record of events within an application, providing crucial insights for debugging.
      When logging, it is essential to ensure that the logs are:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>easily accessible</p>
        </li>

        <li>
          <p>uniformly formatted for readability</p>
        </li>

        <li>
          <p>properly recorded</p>
        </li>

        <li>
          <p>securely logged when dealing with sensitive data</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Those requirements are not met if a program directly writes to the standard outputs (e.g., \{language\_std\_outputs}).
      That is why defining and using a dedicated logger is highly recommended.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class MyClass
      {
      private void DoSomething()
      {
          // ...
          Console.WriteLine("My Message"); // Noncompliant
          // ...
      }
      }
      ```

      ```csharp Fix theme={null}
      public class MyClass
      {
      private readonly ILogger _logger;

      // ...

      private void DoSomething()
      {
          // ...
          _logger.LogInformation("My Message");
          // ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Magic numbers should not be used">
    <div class="paragraph">
      <p>Magic numbers make the code more complex to understand as it requires the reader to have knowledge about the global context to understand the number itself.
      Their usage may seem obvious when writing the code, but it may not be the case for another developer or later once the context faded away.
      -1, 0, and 1 are not considered magic numbers.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public void DoSomething()
      {
      for (int i = 0; i < 4; i++)  // Noncompliant, 4 is a magic number
      {
          ...
      }
      }
      ```

      ```csharp Fix theme={null}
      private const int NUMBER_OF_CYCLES = 4;

      public void DoSomething()
      {
      for (int i = 0; i < NUMBER_OF_CYCLES; i++)  // Compliant
      {
          ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Boolean literals should not be redundant">
    <div class="paragraph">
      <p>A boolean literal can be represented in two different ways: \{true} or \{false}.
      They can be combined with logical operators (\{ops}) to produce logical expressions that represent truth values.
      However, comparing a boolean literal to a variable or expression that evaluates to a boolean value is unnecessary and can make the code harder to read and understand.
      The more complex a boolean expression is, the harder it will be for developers to understand its meaning and expected behavior, and it will favour the introduction of new bugs.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if (booleanMethod() == true) { /* ... */ }
      if (booleanMethod() == false) { /* ... */ }
      if (booleanMethod() || false) { /* ... */ }
      doSomething(!false);
      doSomething(booleanMethod() == true);

      booleanVariable = booleanMethod() ? true : false;
      booleanVariable = booleanMethod() ? true : exp;
      booleanVariable = booleanMethod() ? false : exp;
      booleanVariable = booleanMethod() ? exp : true;
      booleanVariable = booleanMethod() ? exp : false;

      for (var x = 0; true; x++)
      {
      ...
      }
      ```

      ```csharp Fix theme={null}
      if (booleanMethod()) { /* ... */ }        
      if (!booleanMethod()) { /* ... */ }
      if (booleanMethod()) { /* ... */ }
      doSomething(true);
      doSomething(booleanMethod());

      booleanVariable = booleanMethod();
      booleanVariable = booleanMethod() || exp;
      booleanVariable = !booleanMethod() && exp;
      booleanVariable = !booleanMethod() || exp;
      booleanVariable = booleanMethod() && exp;

      for (var x = 0; ; x++)
      {
      ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Deprecated code should be removed">
    <div class="paragraph">
      <p>This rule is meant to be used as a way to track code which is marked as being deprecated. Deprecated code should eventually be removed.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      [Obsolete] // Noncompliant
      void Method()
      {
      // ..
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Write-only properties should not be used">
    <div class="paragraph">
      <p>Properties with only setters are confusing and counterintuitive. Instead, a property getter should be added if possible, or the property should be replaced with a setter method.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      class Program
      {
      public int Foo  //Non-Compliant
      {
          set
          {
              // ... some code ...
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      class Program
      {
      private int foo;

      public void SetFoo(int value)
      {
          // ... some code ...
          foo = value;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using pseudorandom number generators (PRNGs) is security-sensitive">
    <div class="paragraph">
      <p>Using pseudorandom number generators (PRNGs) is security-sensitive. For example, it has led in the past to the following vulnerabilities:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2013-6386">CVE-2013-6386</a></p>
        </li>

        <li>
          <p><a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-3419">CVE-2006-3419</a></p>
        </li>

        <li>
          <p><a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-4102">CVE-2008-4102</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>When software generates predictable values in a context requiring unpredictability, it may be possible for an attacker to guess the next value that will be generated, and use this guess to impersonate another user or access sensitive information.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      using System.Security.Cryptography;
      ...
      var randomGenerator = RandomNumberGenerator.Create(); // Compliant for security-sensitive use cases
      byte[] data = new byte[16];
      randomGenerator.GetBytes(data);
      return BitConverter.ToString(data);
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Optional parameters should be passed to base calls">
    <div class="paragraph">
      <p>When optional parameter values are not passed to base method calls, the value passed in by the caller is ignored. This can cause the function to behave differently than expected, leading to errors and making the code difficult to debug.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class BaseClass
      {
      public virtual void MyMethod(int i = 1)
      { 
          Console.WriteLine(i);
      }
      }

      public class DerivedClass : BaseClass
      {
      public override void MyMethod(int i = 1)
      {
          // ... 
          base.MyMethod(); // Noncompliant: caller's value is ignored
      }

      static int Main(string[] args) 
      {
          DerivedClass dc = new DerivedClass();
          dc.MyMethod(12);  // prints 1
      }
      }
      ```

      ```csharp Fix theme={null}
      public class BaseClass
      {
      public virtual void MyMethod(int i = 1)
      { 
          Console.WriteLine(i);
      }
      }

      public class DerivedClass : BaseClass
      {
      public override void MyMethod(int i = 1)
      {
          // ... 
          base.MyMethod(i);
      }

      static int Main(string[] args) 
      {
          DerivedClass dc = new DerivedClass();
          dc.MyMethod(12);  // prints 12
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Fields should be private">
    <div class="paragraph">
      <p>Fields should not be part of an API, and therefore should always be private. Indeed, they cannot be added to an interface for instance, and validation cannot be added later on without breaking backward compatibility. Instead, developers should encapsulate their fields into properties. Explicit property getters and setters can be introduced for validation purposes or to smooth the transition to a newer system.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Foo
      {
      public int MagicNumber = 42; 
      }
      ```

      ```csharp Fix theme={null}
      public class Foo
      {
      public int MagicNumber 
      { 
      get { return 42; }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Utility classes should not have public constructors">
    <div class="paragraph">
      <p>Whenever there are portions of code that are duplicated and do not depend on the state of their
      container class, they can be centralized inside a "utility class".
      A utility class is a class that only has static members, hence it should not be instantiated.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class StringUtils // Noncompliant: implicit public constructor
      { 
      public static string Concatenate(string s1, string s2) 
      {
      return s1 + s2;
      }
      }
      ```

      ```csharp Fix theme={null}
      public class StringUtils // Noncompliant: explicit public constructor
      { 
      public StringUtils()
      {
      }

      public static string Concatenate(string s1, string s2) 
      {
      return s1 + s2;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Expanding archive files without controlling resource consumption is security-sensitive">
    <div class="paragraph">
      <p>Successful Zip Bomb attacks occur when an application expands untrusted archive files without controlling the size of the expanded data, which can lead to denial of service. A Zip bomb is usually a malicious archive file of a few kilobytes of compressed data but turned into gigabytes of uncompressed data. To achieve this extreme <a href="https://en.wikipedia.org/wiki/Data_compression_ratio">compression ratio</a>, attackers will compress irrelevant data (eg: a long string of repeated bytes).</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      int THRESHOLD_ENTRIES = 10000;        
      int THRESHOLD_SIZE = 1000000000; // 1 GB
      double THRESHOLD_RATIO = 10;         
      int totalSizeArchive = 0;
      int totalEntryArchive = 0;

      using var zipToOpen = new FileStream(@"ZipBomb.zip", FileMode.Open);
      using var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read);
      foreach (ZipArchiveEntry entry in archive.Entries)
      {
      totalEntryArchive ++;

      using (Stream st = entry.Open())
      {
      byte[] buffer = new byte[1024];
      int totalSizeEntry = 0;
      int numBytesRead = 0;

      do
      {
        numBytesRead = st.Read(buffer, 0, 1024);
        totalSizeEntry += numBytesRead;
        totalSizeArchive += numBytesRead;
        double compressionRatio = totalSizeEntry / entry.CompressedLength;          

        if(compressionRatio > THRESHOLD_RATIO) {
          // ratio between compressed and uncompressed data is highly suspicious, looks like a Zip Bomb Attack
          break;
        }
      } 
      while (numBytesRead > 0);
      }

      if(totalSizeArchive > THRESHOLD_SIZE) {
        // the uncompressed data size is too much for the application resource capacity
        break;
      }

      if(totalEntryArchive > THRESHOLD_ENTRIES) {
        // too much entries in this archive, can lead to inodes exhaustion of the system
        break;
      } 
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Sequential tests should not check the same condition">
    <div class="paragraph">
      <p>When the same condition is checked twice in a row, it is either confusing - why have separate checks? - or an error - some other condition should have been checked in the second test.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if (a == b)
      {
      doTheThing(b);
      }
      if (a == b) // Noncompliant; is this really what was intended?
      {
      doTheThing(c);
      }
      ```

      ```csharp Fix theme={null}
      if (a == b)
      {
      doTheThing(b);
      doTheThing(c);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Child class fields should not differ from parent class fields only by capitalization">
    <div class="paragraph">
      <p>Having a field in a child class with a name that differs from a parent class' field only by capitalization is sure to cause confusion. Such child class fields should be renamed.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Fruit
      {
      protected string plantingSeason;
      //...
      }

      public class Raspberry : Fruit
      {
      protected string plantingseason;  // Noncompliant
      // ...
      }
      ```

      ```csharp Fix theme={null}
      public class Fruit
      {
      protected string plantingSeason;
      //...
      }

      public class Raspberry : Fruit
      {
      protected string whenToPlant;
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Mergeable if statements should be combined">
    <div class="paragraph">
      <p>Nested code - blocks of code inside blocks of code - is eventually necessary, but increases complexity. This is why keeping the code as flat as possible, by avoiding unnecessary nesting, is considered a good practice.</p>
    </div>

    <div class="paragraph">
      <p>Merging if statements when possible will decrease the nesting of the code and improve its readability.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if (condition1)
      {
      if (condition2)           // Noncompliant
      {        
          // ...
      }
      }
      ```

      ```csharp Fix theme={null}
      if (condition1 && condition2) // Compliant
      {        
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Methods should not be empty">
    <div class="paragraph">
      <p>An empty \{operationName} is generally considered bad practice and can lead to confusion, readability, and maintenance issues.
      Empty \{operationName}s bring no functionality and are misleading to others as they might think the \{operationName} implementation fulfills a specific and identified requirement.</p>
    </div>

    <div class="paragraph">
      <p>There are several reasons for a \{operationName} not to have a body:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>It is an unintentional omission, and should be fixed to prevent an unexpected behavior in production.</p>
        </li>

        <li>
          <p>It is not yet, or never will be, supported. In this case an exception should be thrown.</p>
        </li>

        <li>
          <p>The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public void ShouldNotBeEmpty() {  // Noncompliant - method is empty
      }

      public void NotImplementedYet() {  // Noncompliant - method is empty
      }

      public void WillNeverBeImplemented() {  // Noncompliant - method is empty
      }

      public void EmptyOnPurpose() {  // Noncompliant - method is empty
      }
      ```

      ```csharp Fix theme={null}
      public void ShouldNotBeEmpty() {
      DoSomething();
      }

      public void NotImplementedYet() {
      throw new NotImplementedException();
      }

      public void WillNeverBeImplemented() {
      throw new NotSupportedException();
      }

      public void EmptyOnPurpose() {
      // comment explaining why the method is empty
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Literal suffixes should be upper case">
    <div class="paragraph">
      <p>Using upper case literal suffixes removes the potential ambiguity between "1" (digit 1) and "l" (letter el) for declaring literals.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      const long b = 0l;      // Noncompliant
      ```

      ```csharp Fix theme={null}
      const long b = 0L;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="A for loop update clause should move the counter in the right direction">
    <div class="paragraph">
      <p>A for loop with a counter that moves in the wrong direction, away from the stop condition, is not an infinite loop. Because of <a href="https://en.wikipedia.org/wiki/Integer_overflow#:~:text=The%20most%20common%20result%20of%20an%20overflow%20is%20that%20the%20least%20significant%20representable%20digits%20of%20the%20result%20are%20stored%3B%20the%20result%20is%20said%20to%20wrap%20around%20the%20maximum">wraparound</a>, the loop will eventually reach its stop condition, but in doing so, it will probably run more times than anticipated, potentially causing unexpected behavior.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      for (int i = 0; i < maximum; i--)  // Noncompliant: runs until it underflows to int.MaxValue
      {
      // ...
      }

      for (int i = maximum; i >= maximum; i++)  // Noncompliant: runs until it overflows to int.MinValue
      {
      // ...
      }
      ```

      ```csharp Fix theme={null}
      for (int i = 0; i < maximum; i++) // Compliant: Increment towards the maximum value
      {
      }

      for (int i = maximum; i >= 0; i--) // Compliant: Decrement towards the minimum value
      {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using clear-text protocols is security-sensitive">
    <div class="paragraph">
      <p>Clear-text protocols such as \`ftp, telnet, or http lack
      encryption of transported data, as well as the capability to build an
      authenticated connection. It means that an attacker able to sniff traffic from
      the network can read, modify, or corrupt the transported content. These
      protocols are not secure as they expose applications to an extensive range of
      risks:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>sensitive data exposure</p>
        </li>

        <li>
          <p>traffic redirected  to a malicious endpoint</p>
        </li>

        <li>
          <p>malware-infected software update or installer</p>
        </li>

        <li>
          <p>execution of client-side code</p>
        </li>

        <li>
          <p>corruption of critical information</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Even in the context of isolated networks like offline environments or segmented
      cloud environments, the insider threat exists. Thus, attacks involving
      communications being sniffed or tampered with can still happen.</p>
    </div>

    <div class="paragraph">
      <p>For example, attackers could successfully compromise prior security layers by:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>bypassing isolation mechanisms</p>
        </li>

        <li>
          <p>compromising a component of the network</p>
        </li>

        <li>
          <p>getting the credentials of an internal IAM account (either from a service
          account or an actual person)</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>In such cases, encrypting communications would decrease the chances of attackers
      to successfully leak data or steal credentials from other network components.
      By layering various security practices (segmentation and encryption, for
      example), the application will follow the <em>defense-in-depth</em> principle.</p>
    </div>

    <div class="paragraph">
      <p>Note that using the http\` protocol is being deprecated by
      <a href="https://blog.mozilla.org/security/2015/04/30/deprecating-non-secure-http">major web browsers</a>.</p>
    </div>

    <div class="paragraph">
      <p>In the past, it has led to the following vulnerabilities:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://nvd.nist.gov/vuln/detail/CVE-2019-6169">CVE-2019-6169</a></p>
        </li>

        <li>
          <p><a href="https://nvd.nist.gov/vuln/detail/CVE-2019-12327">CVE-2019-12327</a></p>
        </li>

        <li>
          <p><a href="https://nvd.nist.gov/vuln/detail/CVE-2019-11065">CVE-2019-11065</a></p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      var urlHttp = "http://example.com";                 // Noncompliant
      var urlFtp = "ftp://anonymous@example.com";         // Noncompliant
      var urlTelnet = "telnet://anonymous@example.com";   // Noncompliant
      ```

      ```csharp Fix theme={null}
      using var smtp = new SmtpClient("host", 25); // Noncompliant, EnableSsl is not set
      using var telnet = new MyTelnet.Client("host", port); // Noncompliant, rule raises Security Hotspot on any member containing "Telnet"
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Creating cookies without the HttpOnly flag is security-sensitive">
    <div class="paragraph">
      <p>When a cookie is configured with the <code>HttpOnly attribute set to <em>true</em>, the browser guaranties that no client-side script will be able to read it. In most cases, when a cookie is created, the default value of HttpOnly is <em>false</em> and it’s up to the developer to decide whether or not the content of the cookie can be read by the client-side script. As a majority of Cross-Site Scripting (XSS) attacks target the theft of session-cookies, the HttpOnly</code> attribute can help to reduce their impact as it won’t be possible to exploit the XSS vulnerability to steal session-cookies.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      HttpCookie myCookie = new HttpCookie("Sensitive cookie");
      myCookie.HttpOnly = true; // Compliant: the sensitive cookie is protected against theft thanks to the HttpOnly property set to true (HttpOnly = true)
      ```

      ```csharp Fix theme={null}
      <httpCookies httpOnlyCookies="true" requireSSL="true" />
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Redundant casts should not be used">
    <div class="paragraph">
      <p>Casting expressions are utilized to convert one data type to another, such as transforming an integer into a string. This is especially crucial in strongly typed languages like C, C++, C#, Java, Python, and others.</p>
    </div>

    <div class="paragraph">
      <p>However, there are instances where casting expressions are not needed. These include situations like:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>casting a variable to its own type</p>
        </li>

        <li>
          <p>casting a subclass to a parent class (in the case of polymorphism)</p>
        </li>

        <li>
          <p>the programming language is capable of automatically converting the given type to another</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>These scenarios are considered unnecessary casting expressions. They can complicate the code and make it more difficult to understand, without offering any advantages.</p>
    </div>

    <div class="paragraph">
      <p>As a result, it’s generally advised to avoid unnecessary casting expressions. Instead, rely on the language’s type system to ensure type safety and code clarity.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public int Example(int i) 
      {
      return (int) (i + 42); // Noncompliant
      }

      public IEnumerable<int> ExampleCollection(IEnumerable<int> coll) 
      {
      return coll.Reverse().OfType<int>(); // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      public int Example(int i) 
      {
      return i + 42;
      }

      public IEnumerable<int> ExampleCollection(IEnumerable<int> coll) 
      {
      return coll.Reverse();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using shell interpreter when executing OS commands is security-sensitive">
    <div class="paragraph">
      <p>Arbitrary OS command injection vulnerabilities are more likely when a shell is spawned rather than a new process, indeed shell meta-chars can be used (when parameters are user-controlled for instance) to inject OS commands.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public void CompliantExample() {
      String cmd="/usr/bin/file.exe";
      var startInfo = new ProcessStartInfo();
      startInfo.FileName = cmd; // Compliant
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Short-circuit logic should be used to prevent null pointer dereferences in conditionals">
    <div class="paragraph">
      <p>When either the equality operator in a null test or the logical operator that follows it is reversed, the code has the appearance of safely null-testing the object before dereferencing it. Unfortunately the effect is just the opposite - the object is null-tested and then dereferenced <em>only</em> if it is null, leading to a guaranteed null pointer dereference.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if (str == null && str.Length == 0)
      {
      Console.WriteLine("String is empty");
      }

      if (str != null || str.Length > 0)
      {
      Console.WriteLine("String is not empty");
      }
      ```

      ```csharp Fix theme={null}
      if (str == null || str.Length == 0)
      {
      Console.WriteLine("String is empty");
      }

      if (str != null && str.Length > 0)
      {
      Console.WriteLine("String is not empty");
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Allowing requests with excessive content length is security-sensitive">
    <div class="paragraph">
      <p>Rejecting requests with significant content length is a good practice to control the network traffic intensity and thus resource consumption in order to prevent DoS attacks.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      using Microsoft.AspNetCore.Mvc;

      public class MyController : Controller
      {
      [HttpPost]
      [DisableRequestSizeLimit] // Sensitive: No size  limit
      [RequestSizeLimit(10485760)] // Sensitive: 10485760 B = 10240 KB = 10 MB is more than the recommended limit of 8MB
      public IActionResult PostRequest(Model model)
      {
      // ...
      }

      [HttpPost]
      [RequestFormLimits(MultipartBodyLengthLimit = 10485760)] // Sensitive: 10485760 B = 10240 KB = 10 MB is more than the recommended limit of 8MB
      public IActionResult MultipartFormRequest(Model model)
      {
      // ...
      }
      }
      ```

      ```csharp Fix theme={null}
      <configuration>
      <system.web>
          <httpRuntime maxRequestLength="81920" executionTimeout="3600" />
          <!-- Sensitive: maxRequestLength is expressed in KB, so 81920 KB = 80 MB  -->
      </system.web>
      <system.webServer>
          <security>
              <requestFiltering>
                  <requestLimits maxAllowedContentLength="83886080" />
                  <!-- Sensitive: maxAllowedContentLength is expressed in bytes, so 83886080 B = 81920 KB = 80 MB  -->
              </requestFiltering>
          </security>
      </system.webServer>
      </configuration>
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Assignments should not be made from within sub-expressions">
    <div class="paragraph">
      <p>A common code smell that can hinder the clarity of source code is making assignments within sub-expressions.
      This practice involves assigning a value to a variable inside a larger expression, such as within a loop or a conditional statement.</p>
    </div>

    <div class="paragraph">
      <p>This practice essentially gives a side-effect to a larger expression, thus making it less readable. This often leads to confusion and potential errors.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      var result = Foo(() =>
      {
      int x = 100; // dead store, but ignored
      x = 200;
      return x;
      }
      ```

      ```csharp Fix theme={null}
      var a = b = c = 10;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Formatting SQL queries is security-sensitive">
    <div class="paragraph">
      <p>Formatted SQL queries can be difficult to maintain, debug and can increase the risk of SQL injection when concatenating untrusted values into the query. However, this rule doesn’t detect SQL injections (unlike rule S3649), the goal is only to highlight complex/formatted queries.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public void Foo(DbContext context, string query, string param)
      {
      context.Database.ExecuteSqlCommand("SELECT * FROM mytable WHERE mycol=@p0", param); // Compliant, it's a parametrized safe query
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unused method parameters should be removed">
    <div class="paragraph">
      <p>A typical code smell known as unused function parameters refers to parameters declared in a function but not used anywhere within the function’s body.
      While this might seem harmless at first glance, it can lead to confusion and potential errors in your code.
      Disregarding the values passed to such parameters, the function’s behavior will be the same, but the programmer’s intention won’t be clearly expressed anymore.
      Therefore, removing function parameters that are not being utilized is considered best practice.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      private void DoSomething(int a, int b) // Noncompliant, "b" is unused
      {
      Compute(a);
      }

      private void DoSomething2(int a) // Noncompliant, the value of "a" is unused
      {
      a = 10;
      Compute(a);
      }
      ```

      ```csharp Fix theme={null}
      private void DoSomething(int a)
      {
      Compute(a);
      }

      private void DoSomething2()
      {
      var a = 10;
      Compute(a);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Fields should not have public accessibility">
    <div class="paragraph">
      <p>Public fields in public classes do not respect the encapsulation principle and have three main disadvantages:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Additional behavior such as validation cannot be added.</p>
        </li>

        <li>
          <p>The internal representation is exposed, and cannot be changed afterwards.</p>
        </li>

        <li>
          <p>Member values are subject to change from anywhere in the code and may not meet the programmer’s assumptions.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>To prevent unauthorized modifications, private attributes and accessor methods (set and get) should be used.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Foo
      {
      public int InstanceData = 32; // Noncompliant
      public int AnotherInstanceData = 32; // Noncompliant

      }
      ```

      ```csharp Fix theme={null}
      public class Foo
      {
      // using auto-implemented properties
      public int InstanceData { get; set; } = 32;

      // using field encapsulation
      private int _anotherInstanceData = 32;

      public int AnotherInstanceData
      {
          get { return _anotherInstanceData; }
          set
          {
              // perform validation
              _anotherInstanceData = value;
          }
      }

      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Assemblies should explicitly specify COM visibility">
    <div class="paragraph">
      <p>Assemblies should explicitly indicate whether they are meant to be COM visible or not. If the <code>ComVisibleAttribute</code> is not present, the default is to make the content of the assembly visible to COM clients.</p>
    </div>

    <div class="paragraph">
      <p>Note that COM visibility can be overridden for individual types and members.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      namespace MyLibrary  // Noncompliant
      {
      }
      ```

      ```csharp Fix theme={null}
      using System;

      [assembly: System.Runtime.InteropServices.ComVisible(false)]
      namespace MyLibrary
      {
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="break statements should not be used except for switch cases">
    <div class="paragraph">
      <p><code>break;</code> is an unstructured control flow statement which makes code harder to read.</p>
    </div>

    <div class="paragraph">
      <p>Ideally, every loop should have a single termination condition.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      int i = 0;
      while (true)
      {
      if (i == 10)
      {
      break;      // Non-Compliant
      }

      Console.WriteLine(i);
      i++;
      }
      ```

      ```csharp Fix theme={null}
      int i = 0;
      while (i != 10) // Compliant
      {
      Console.WriteLine(i);
      i++;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Deserializing objects without performing data validation is security-sensitive">
    <div class="paragraph">
      <p>Deserialization process extracts data from the serialized representation of an object and reconstruct it directly, without calling constructors. Thus, data validation implemented in constructors can be bypassed if serialized objects are controlled by an attacker.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      [Serializable]
      public class InternalUrl : ISerializable
      {
      private string url;

      public InternalUrl(string tmpUrl)
      {
          if(!tmpUrl.StartsWith("http://localhost/")) // there is some input validation
          {
              url= "http://localhost/default";
          }
          else 
          {
              url= tmpUrl;
          }
      }

      // special constructor used during deserialization
      protected InternalUrl(SerializationInfo info, StreamingContext context)
      {
         string tmpUrl= (string) info.GetValue("url", typeof(string));

         if(!tmpUrl.StartsWith("http://localhost/") { // Compliant
            url= "http://localhost/default";
         }
         else {
            url= tmpUrl;
         }
       }

      void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
      {
          info.AddValue("url", url);
      }
      }
      ```

      ```csharp Fix theme={null}
      [Serializable]
      public class InternalUrl : IDeserializationCallback
      {
      private string url;

      public InternalUrl(string tmpUrl)
      {
         if(!tmpUrl.StartsWith("http://localhost/")) // there is some input validation
         {
            url= "http://localhost/default";
         }
         else
         {
            url= tmpUrl;
         }
      }

      void IDeserializationCallback.OnDeserialization(object sender) // Compliant
      {
          if(!url.StartsWith("http://localhost/"))
          {
              url= "http://localhost/default";
          }
          else 
          {
          }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Conditionally executed code should be reachable">
    <div class="paragraph">
      <p>Conditional expressions which are always true or false can lead to <a href="https://en.wikipedia.org/wiki/Unreachable_code">unreachable code</a>.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      var a = false;
      if (a)
      {
      Dispose(); // Never reached
      }
      ```

      ```csharp Fix theme={null}
      const bool debug = false;
      //...
      if (debug)
      {
      // Print something
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Constructing arguments of system commands from user input is security-sensitive">
    <div class="paragraph">
      <p>Constructing arguments of system commands from user input is security-sensitive. It has led in the past to the following vulnerabilities:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-9920">CVE-2016-9920</a></p>
        </li>

        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-29472">CVE-2021-29472</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Arguments of system commands are processed by the executed program. The arguments are usually used to configure and influence the behavior of the programs.
      Control over a single argument might be enough for an attacker to trigger dangerous features like executing arbitrary commands or writing files into specific directories.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      using System.Diagnostics;
      Process p = new Process();
      p.StartInfo.FileName = "/usr/bin/find";
      if (allowed.Contains(input)) {
      p.StartInfo.ArgumentList.Add(input);
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="URIs should not be hardcoded">
    <div class="paragraph">
      <p>Hard-coding a URI makes it difficult to test a program for a variety of reasons:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>path literals are not always portable across operating systems</p>
        </li>

        <li>
          <p>a given absolute path may not exist in a specific test environment</p>
        </li>

        <li>
          <p>a specified Internet URL may not be available when executing the tests</p>
        </li>

        <li>
          <p>production environment filesystems usually differ from the development environment</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>In addition, hard-coded URIs can contain sensitive information, like IP addresses, and they should not be stored in the code.</p>
    </div>

    <div class="paragraph">
      <p>For all those reasons, a URI should never be hard coded. Instead, it should be replaced by a customizable parameter.</p>
    </div>

    <div class="paragraph">
      <p>Further, even if the elements of a URI are obtained dynamically, portability can still be limited if the path delimiters are hard-coded.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when URIs or path delimiters are hard-coded.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Foo {
      public List<User> ListUsers() {
      string userListPath = "/home/mylogin/Dev/users.txt"; // Noncompliant
      return ParseUsers(userListPath);
      }
      }
      ```

      ```csharp Fix theme={null}
      public class Foo {
      // Configuration is a class that returns customizable properties: it can be mocked to be injected during tests. 
      private Configuration config;
      public Foo(Configuration myConfig) {
      this.config = myConfig;
      }
      public List<User> ListUsers() {
      // Find here the way to get the correct folder, in this case using the Configuration object
      string listingFolder = config.GetProperty("myApplication.listingFolder");
      // and use this parameter instead of the hard coded path
      string userListPath = Path.Combine(listingFolder, "users.txt"); // Compliant
      return ParseUsers(userListPath);
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Method parameters, caught exceptions and foreach variables initial values should not be ignored">
    <div class="paragraph">
      <p>While it is technically correct to assign to parameters from within method bodies, doing so before the parameter value is read is likely a bug. Instead, initial values of parameters, caught exceptions, and foreach parameters should be, if not treated as <code>final</code>, then at least read before reassignment.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public void DoTheThing(string str, int i, List<string> strings)
      {
      str = i.ToString(i);  // Noncompliant

      foreach (var s in strings)
      {
      s = "hello world";  // Noncompliant
      }
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="if ... else if constructs should end with else clauses">
    <div class="paragraph">
      <p>This rule applies whenever an \`if statement is followed by one or more else if statements; the final else if should be followed by an else statement.</p>
    </div>

    <div class="paragraph">
      <p>The requirement for a final else statement is defensive programming.</p>
    </div>

    <div class="paragraph">
      <p>The else statement should either take appropriate action or contain a suitable comment as to why no action is taken. This is consistent with the requirement to have a final default clause in a switch\` statement.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if (x == 0) 
      {
      DoSomething();
      } 
      else if (x == 1) 
      {
      DoSomethingElse();
      }
      ```

      ```csharp Fix theme={null}
      if (x == 0) 
      {
      DoSomething();
      } 
      else if (x == 1) 
      {
      DoSomethingElse();
      } 
      else 
      {
      throw new InvalidOperationException();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="for loop stop conditions should be invariant">
    <div class="paragraph">
      <p>A \`for loop stop condition should test the loop counter against an invariant value (i.e. one that is true at both the beginning and ending of every loop iteration). Ideally, this means that the stop condition is set to a local variable just before the loop begins.</p>
    </div>

    <div class="paragraph">
      <p>Stop conditions that are not invariant are slightly less efficient, as well as being difficult to understand and maintain, and likely lead to the introduction of errors in the future.</p>
    </div>

    <div class="paragraph">
      <p>This rule tracks three types of non-invariant stop conditions:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>When the loop counters are updated in the body of the for\` loop</p>
        </li>

        <li>
          <p>When the stop condition depend upon a method call</p>
        </li>

        <li>
          <p>When the stop condition depends on an object property, since such properties could change during the execution of the loop.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      for (int i = 1; i <= 5; i++) 
      {
      Console.WriteLine(i);
      if (condition) 
      {
          i = 20;
      }
      }
      ```

      ```csharp Fix theme={null}
      int i = 1;
      while (i <= 5) 
      {
      Console.WriteLine(i);
      if (condition) 
      {
          i = 20;
      }
      else
      {
          i++;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Serialization event handlers should be implemented correctly">
    <div class="paragraph">
      <p>Serialization event handlers that don’t have the correct signature will not be called, bypassing augmentations to automated serialization and deserialization events.</p>
    </div>

    <div class="paragraph">
      <p>A method is designated a serialization event handler by applying one of the following serialization event attributes:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.onserializingattribute">OnSerializingAttribute</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.onserializedattribute">OnSerializedAttribute</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.ondeserializingattribute">OnDeserializingAttribute</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.ondeserializedattribute">OnDeserializedAttribute</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Serialization event handlers take a single parameter of type <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.streamingcontext">StreamingContext</a>, return void, and have private visibility.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when any of these constraints are not respected.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      [Serializable]
      public class Foo
      {
      [OnSerializing]
      public void OnSerializing(StreamingContext context) {} // Noncompliant: should be private

      [OnSerialized]
      int OnSerialized(StreamingContext context) {} // Noncompliant: should return void

      [OnDeserializing]
      void OnDeserializing() {} // Noncompliant: should have a single parameter of type StreamingContext

      [OnSerializing]
      public void OnSerializing2<T>(StreamingContext context) {} // Noncompliant: should have no type parameters

      [OnDeserialized]
      void OnDeserialized(StreamingContext context, string str) {} // Noncompliant: should have a single parameter of type StreamingContext
      }
      ```

      ```csharp Fix theme={null}
      [Serializable]
      public class Foo
      {
      [OnSerializing]
      private void OnSerializing(StreamingContext context) {}

      [OnSerialized]
      private void OnSerialized(StreamingContext context) {}

      [OnDeserializing]
      private void OnDeserializing(StreamingContext context) {}

      [OnDeserialized]
      private void OnDeserialized(StreamingContext context) {}
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Assemblies should be marked as CLS compliant">
    <div class="paragraph">
      <p>Assemblies should conform with the Common Language Specification (CLS) in order to be usable across programming languages. To be compliant an assembly has to indicate it with <code>System.CLSCompliantAttribute</code>.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      [assembly:CLSCompliant(true)]
      namespace MyLibrary
      {
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Public constant members should not be used">
    <div class="paragraph">
      <p>Constant members are copied at compile time to the call sites, instead of being fetched at runtime.</p>
    </div>

    <div class="paragraph">
      <p>As an example, say you have a library with a constant \`Version  member set to 1.0, and a client application linked to it. This library is then updated and Version is set to 2.0. Unfortunately, even after the old DLL is replaced by the new one,  Version will still be 1.0 for the client application. In order to see 2.0, the client application would need to be rebuilt against the new version of the library.</p>
    </div>

    <div class="paragraph">
      <p>This means that you should use constants to hold values that by definition will never change, such as Zero\`. In practice, those cases are uncommon, and therefore it is generally better to avoid constant members.</p>
    </div>

    <div class="paragraph">
      <p>This rule only reports issues on public constant fields, which can be reached from outside the defining assembly.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Foo
      {
      public const double Version = 1.0;           // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      public class Foo
      {
      public static double Version 
      {
        get { return 1.0; }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="HTTP response headers should not be vulnerable to injection attacks">
    <div class="paragraph">
      <p>User-provided data, such as URL parameters, POST data payloads, or cookies, should always be considered untrusted and tainted. Applications constructing HTTP response headers based on tainted data could allow attackers to change security sensitive headers like Cross-Origin Resource Sharing headers.</p>
    </div>

    <div class="paragraph">
      <p>Web application frameworks and servers might also allow attackers to inject new line characters in headers to craft malformed HTTP response. In this case the application would be vulnerable to a larger range of attacks like HTTP Response Splitting/Smuggling. Most of the time this type of attack is mitigated by default modern web application frameworks but there might be rare cases where older versions are still vulnerable.</p>
    </div>

    <div class="paragraph">
      <p>As a best practice, applications that use user-provided data to construct the response header should always validate the data first. Validation should be based on a whitelist.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      string value = Request.QueryString["value"];
      Response.AddHeader("X-Header", value); // Noncompliant
      ```

      ```csharp Fix theme={null}
      string value = Request.QueryString["value"];
      // Allow only alphanumeric characters
      if (value == null || !Regex.IsMatch(value, "^[a-zA-Z0-9]+$"))
      {
      throw new Exception("Invalid value");
      }
      Response.AddHeader("X-Header", value);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Creating cookies without the secure flag is security-sensitive">
    <div class="paragraph">
      <p>When a cookie is protected with the <code>secure</code> attribute set to <em>true</em> it will not be send by the browser over an unencrypted HTTP request and thus cannot be observed by an unauthorized person during a man-in-the-middle attack.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      HttpCookie myCookie = new HttpCookie("Sensitive cookie");
      myCookie.Secure = true; // Compliant
      ```

      ```csharp Fix theme={null}
      <httpCookies httpOnlyCookies="true" requireSSL="true" />
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Classes should not be coupled to too many other classes">
    <div class="paragraph">
      <p>According to the Single Responsibility Principle, introduced by Robert C. Martin in his book "Principles of Object Oriented Design", a class should have only one responsibility:</p>
    </div>

    <div class="quoteblock">
      <blockquote>
        <div class="paragraph">
          <p>If a class has more than one responsibility, then the responsibilities become coupled.</p>
        </div>

        <div class="paragraph">
          <p>Changes to one responsibility may impair or inhibit the class' ability to meet the others.</p>
        </div>

        <div class="paragraph">
          <p>This kind of coupling leads to fragile designs that break in unexpected ways when changed.</p>
        </div>
      </blockquote>
    </div>

    <div class="paragraph">
      <p>Classes which rely on many other classes tend to aggregate too many responsibilities and should be split into several smaller ones.</p>
    </div>

    <div class="paragraph">
      <p>Nested classes dependencies are not counted as dependencies of the outer class.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Foo    // Noncompliant - Foo depends on too many classes: T1, T2, T3, T4, T5, T6 and T7
      {
      private T1 a1;    // Foo is coupled to T1
      private T2 a2;    // Foo is coupled to T2
      private T3 a3;    // Foo is coupled to T3

      public T4 Compute(T5 a, T6 b)    // Foo is coupled to T4, T5 and T6
      {
      T7 result = a.Process(b);    // Foo is coupled to T7
      return result;
      }

      public static class Bar    // Compliant - Bar depends on 2 classes: T8 and T9
      {
      public T8 a8;
      public T9 a9;
      }
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Ternary operators should not be nested">
    <div class="paragraph">
      <p>Nested ternaries are hard to read and can make the order of operations complex to understand.</p>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{noncompliant}\[]</p>
    </div>

    <div class="paragraph">
      <p>Instead, use another line to express the nested operation in a separate statement.</p>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{compliant}\[]</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public string GetReadableStatus(Job j)
      {
      return j.IsRunning ? "Running" : j.HasErrors ? "Failed" : "Succeeded";  // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      public string GetReadableStatus(Job j) 
      {
      if (j.IsRunning) 
      {
      return "Running";
      }
      return j.HasErrors ? "Failed" : "Succeeded";
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Classes named like Exception should extend Exception or a subclass">
    <div class="paragraph">
      <p>Clear, communicative naming is important in code. It helps maintainers and API users understand the intentions for and uses of a unit of code. Using "exception" in the name of a class that does not extend <code>Exception</code> or one of its subclasses is a clear violation of the expectation that a class' name will indicate what it is and/or does.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class FruitException // Noncompliant - this has nothing to do with Exception
      {
      private Fruit expected;
      private string unusualCharacteristics;
      private bool appropriateForCommercialExploitation;
      // ...
      }

      public class CarException // Noncompliant - does not derive from any Exception-based class
      {
      public CarException(string message, Exception inner) 
      {
       // ...
      }
      }
      ```

      ```csharp Fix theme={null}
      public class FruitSport // Compliant - class name does not end with 'Exception'
      {
      private Fruit expected;
      private string unusualCharacteristics;
      private bool appropriateForCommercialExploitation;
      // ...
      }

      public class CarException: Exception // Compliant - correctly extends System.Exception
      {
      public CarException(string message, Exception inner): base(message, inner)    
      {
       // ...
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Method overloads should be grouped together">
    <div class="paragraph">
      <p>For clarity, all overloads of the same method should be grouped together. That lets both users and maintainers quickly understand all the current available options.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      interface IMyInterface 
      {
      int DoTheThing(); // Noncompliant - overloaded method declarations are not grouped together
      string DoTheOtherThing();
      int DoTheThing(string s);
      }
      ```

      ```csharp Fix theme={null}
      interface IMyInterface 
      {
      int DoTheThing();
      int DoTheThing(string s);
      string DoTheOtherThing();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Control structures should use curly braces">
    <div class="paragraph">
      <p>While not technically incorrect, the omission of curly braces can be misleading and may lead to the introduction of errors during maintenance.</p>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{noncompliant}\[]</p>
    </div>

    <div class="paragraph">
      <p>Adding curly braces improves the code readability and its robustness:</p>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{compliant}\[]</p>
    </div>

    <div class="paragraph">
      <p>The rule raises an issue when a control structure has no curly braces.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if (condition) // Noncompliant
      ExecuteSomething();
      CheckSomething();
      ```

      ```csharp Fix theme={null}
      if (condition)
      {
      ExecuteSomething();
      CheckSomething();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="String literals should not be duplicated">
    <div class="paragraph">
      <p>Duplicated string literals make the process of refactoring complex and error-prone, as any change would need to be propagated on all occurrences.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Foo
      {
      private string name = "foobar"; // Noncompliant

      public string DefaultName { get; } = "foobar"; // Noncompliant

      public Foo(string value = "foobar") // Noncompliant
      {
          var something = value ?? "foobar"; // Noncompliant
      }
      }
      ```

      ```csharp Fix theme={null}
      public class Foo
      {
      private const string Foobar = "foobar";

      private string name = Foobar;

      public string DefaultName { get; } = Foobar;

      public Foo(string value = Foobar)
      {
          var something = value ?? Foobar;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Types should be defined in named namespaces">
    <div class="paragraph">
      <p>Types are declared in namespaces in order to prevent name collisions and as a way to organize them into the object hierarchy. Types that are defined outside any named namespace are in a global namespace that cannot be referenced in code.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Foo // Noncompliant
      {
      }

      public struct Bar // Noncompliant
      {
      }
      ```

      ```csharp Fix theme={null}
      namespace SomeSpace
      {
      public class Foo
      {
      }

      public struct Bar
      {
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Reflection should not be used to increase accessibility of classes, methods, or fields">
    <div class="paragraph">
      <p>Altering or bypassing the accessibility of classes, methods, or fields through reflection violates the encapsulation principle. This can break the internal contracts of the accessed target and lead to maintainability issues and runtime errors.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when reflection is used to change the visibility of a class, method or field, and when it is used to directly update a field value.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      using System.Reflection;

      Type dynClass = Type.GetType("MyInternalClass");
      // Noncompliant. Using BindingFlags.NonPublic will return non-public members
      BindingFlags bindingAttr = BindingFlags.NonPublic | BindingFlags.Static;
      MethodInfo dynMethod = dynClass.GetMethod("mymethod", bindingAttr);
      object result = dynMethod.Invoke(dynClass, null);
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Private fields only used as local variables in methods should become local variables">
    <div class="paragraph">
      <p>When the value of a private field is always assigned to in a class' methods before being read, then it is not being used to store class information. Therefore, it should become a local variable in the relevant methods to prevent any misunderstanding.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Foo
      {
      private int singularField;

      public void DoSomething(int x)
      {
      singularField = x + 5;

      if (singularField == 0) { /* ... */ }
      }
      }
      ```

      ```csharp Fix theme={null}
      public class Foo
      {
      public void DoSomething(int x)
      {
      int localVariable = x + 5;

      if (localVariable == 0) { /* ... */ }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="CoSetProxyBlanket and CoInitializeSecurity should not be used">
    <div class="paragraph">
      <p><code>CoSetProxyBlanket and CoInitializeSecurity</code> both work to set the permissions context in which the process invoked immediately after is executed. Calling them from within that process is useless because it’s too late at that point; the permissions context has already been set.</p>
    </div>

    <div class="paragraph">
      <p>Specifically, these methods are meant to be called from non-managed code such as a C++ wrapper that then invokes the managed, i.e. C# or VB.NET, code.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      [DllImport("ole32.dll")]
      static extern int CoSetProxyBlanket([MarshalAs(UnmanagedType.IUnknown)]object pProxy, uint dwAuthnSvc, uint dwAuthzSvc,
      [MarshalAs(UnmanagedType.LPWStr)] string pServerPrincName, uint dwAuthnLevel, uint dwImpLevel, IntPtr pAuthInfo,
      uint dwCapabilities);

      public enum RpcAuthnLevel
      {
      Default = 0,
      None = 1,
      Connect = 2,
      Call = 3,
      Pkt = 4,
      PktIntegrity = 5,
      PktPrivacy = 6
      }

      public enum RpcImpLevel
      {
      Default = 0,
      Anonymous = 1,
      Identify = 2,
      Impersonate = 3,
      Delegate = 4
      }

      public enum EoAuthnCap
      {
      None = 0x00,
      MutualAuth = 0x01,
      StaticCloaking = 0x20,
      DynamicCloaking = 0x40,
      AnyAuthority = 0x80,
      MakeFullSIC = 0x100,
      Default = 0x800,
      SecureRefs = 0x02,
      AccessControl = 0x04,
      AppID = 0x08,
      Dynamic = 0x10,
      RequireFullSIC = 0x200,
      AutoImpersonate = 0x400,
      NoCustomMarshal = 0x2000,
      DisableAAA = 0x1000
      }

      [DllImport("ole32.dll")]
      public static extern int CoInitializeSecurity(IntPtr pVoid, int cAuthSvc, IntPtr asAuthSvc, IntPtr pReserved1,
      RpcAuthnLevel level, RpcImpLevel impers, IntPtr pAuthList, EoAuthnCap dwCapabilities, IntPtr pReserved3);

      static void Main(string[] args)
      {
      var hres1 = CoSetProxyBlanket(null, 0, 0, null, 0, 0, IntPtr.Zero, 0); // Noncompliant

      var hres2 = CoInitializeSecurity(IntPtr.Zero, -1, IntPtr.Zero, IntPtr.Zero, RpcAuthnLevel.None,
      	RpcImpLevel.Impersonate, IntPtr.Zero, EoAuthnCap.None, IntPtr.Zero); // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Not specifying a timeout for regular expressions is security-sensitive">
    <div class="paragraph">
      <p>Not specifying a timeout for regular expressions can lead to a Denial-of-Service attack.
      Pass a timeout when using System.Text.RegularExpressions to process untrusted input because a malicious user might craft a value for which the evaluation lasts excessively long.</p>
    </div>

    <div class="sect1">
      <h2 id="_ask_yourself_whether">Ask Yourself Whether</h2>

      <div class="sectionbody">
        <div class="ulist">
          <ul>
            <li>
              <p>the input passed to the regular expression is untrusted.</p>
            </li>

            <li>
              <p>the regular expression contains patterns vulnerable to <a href="https://www.regular-expressions.info/catastrophic.html">catastrophic backtracking</a>.</p>
            </li>
          </ul>
        </div>

        <div class="paragraph">
          <p>There is a risk if you answered yes to any of those questions.</p>
        </div>
      </div>
    </div>

    <div class="sect1">
      <h2 id="_recommended_secure_coding_practices">Recommended Secure Coding Practices</h2>

      <div class="sectionbody">
        <div class="ulist">
          <ul>
            <li>
              <p>It is recommended to specify a <a href="https://learn.microsoft.com/dotnet/standard/base-types/best-practices#use-time-out-values">matchTimeout</a> when executing a regular expression.</p>
            </li>

            <li>
              <p>Make sure regular expressions are not vulnerable to Denial-of-Service attacks by reviewing the patterns.</p>
            </li>

            <li>
              <p>Consider using a non-backtracking algorithm by specifying <a href="https://learn.microsoft.com/dotnet/api/system.text.regularexpressions.regexoptions?view=net-7.0">RegexOptions.NonBacktracking</a>.</p>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public void RegexPattern(string input)
      {
      var emailPattern = new Regex(".+@.+", RegexOptions.None);
      var isNumber = Regex.IsMatch(input, "[0-9]+");
      var isLetterA = Regex.IsMatch(input, "(a+)+");
      }
      ```

      ```csharp Fix theme={null}
      public void RegexPattern(string input)
      {
      var emailPattern = new Regex(".+@.+", RegexOptions.None, TimeSpan.FromMilliseconds(100));
      var isNumber = Regex.IsMatch(input, "[0-9]+", RegexOptions.None, TimeSpan.FromMilliseconds(100));
      var isLetterA = Regex.IsMatch(input, "(a+)+", RegexOptions.NonBacktracking); // .Net 7 and above
      AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromMilliseconds(100)); // process-wide setting
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Modulus results should not be checked for direct equality">
    <div class="paragraph">
      <p>When the modulus of a negative number is calculated, the result will either be negative or zero. Thus, comparing the modulus of a variable for equality with a positive number (or a negative one) could result in unexpected results.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public bool IsOdd(int x) 
      {
      return x % 2 == 1;  // Noncompliant; if x is an odd negative, x % 2 == -1
      }
      ```

      ```csharp Fix theme={null}
      public bool IsOdd(int x) 
      {
      return x % 2 != 0;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Neither DES (Data Encryption Standard) nor DESede (3DES) should be used">
    <div class="paragraph">
      <p>According to the US National Institute of Standards and Technology (NIST), the Data Encryption Standard (DES) is no longer considered secure:</p>
    </div>

    <div class="quoteblock">
      <blockquote>
        <div class="paragraph">
          <p>Adopted in 1977 for federal agencies to use in protecting sensitive, unclassified information, the DES is being withdrawn because it no longer provides the security that is needed to protect federal government information.</p>
        </div>

        <div class="paragraph">
          <p>Federal agencies are encouraged to use the Advanced Encryption Standard, a faster and stronger algorithm approved as FIPS 197 in 2001.</p>
        </div>
      </blockquote>
    </div>

    <div class="paragraph">
      <p>For similar reasons, RC2 should also be avoided.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      using (var tripleDES = new TripleDESCryptoServiceProvider()) //Noncompliant
      {
      //...
      }
      ```

      ```csharp Fix theme={null}
      using (var aes = new AesCryptoServiceProvider())
      {
      //...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Disabling ASP.NET Request Validation feature is security-sensitive">
    <div class="paragraph">
      <p>ASP.NET 1.1+ comes with a feature called <em>Request Validation</em>, preventing the server to accept content containing un-encoded HTML. This feature comes as a first protection layer against Cross-Site Scripting (XSS) attacks and act as a simple Web Application Firewall (WAF) rejecting requests potentially containing malicious content.</p>
    </div>

    <div class="paragraph">
      <p>While this feature is not a silver bullet to prevent all XSS attacks, it helps to catch basic ones. It will for example prevent <code>\<script type="text/javascript" src="[https://malicious.domain/payload.js](https://malicious.domain/payload.js)"></code> to reach your Controller.</p>
    </div>

    <div class="paragraph">
      <p>Note: <em>Request Validation</em> feature being only available for ASP.NET, no Security Hotspot is raised on ASP.NET Core applications.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      [ValidateInput(true)]
      public ActionResult Welcome(string name)
      {
      ...
      }
      ```

      ```csharp Fix theme={null}
      public ActionResult Welcome(string name)
      {
      ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Optional parameters should not be used">
    <div class="paragraph">
      <p>The overloading mechanism should be used in place of optional parameters for several reasons:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Optional parameter values are baked into the method call site code, thus, if a default value has been changed, all referencing assemblies need to be rebuilt, otherwise the original values will be used.</p>
        </li>

        <li>
          <p>The Common Language Specification (CLS) allows compilers to ignore default parameter values, and thus require the caller to explicitly specify the values. For example, if you want to consume a method with default argument from another .NET compatible language (for instance C++/CLI), you will have to provide all arguments. When using method overloads, you could achieve similar behavior as default arguments.</p>
        </li>

        <li>
          <p>Optional parameters prevent muddying the definition of the function contract. Here is a simple example: if there are two optional parameters, when one is defined, is the second one still optional or mandatory?</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      void Notify(string company, string office = "QJZ") // Noncompliant
      {
      }
      ```

      ```csharp Fix theme={null}
      void Notify(string company)
      {
      Notify(company, "QJZ");
      }
      void Notify(string company, string office)
      {
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="PartCreationPolicyAttribute should be used with ExportAttribute">
    <div class="paragraph">
      <p>To customize the default behavior for an export in the <a href="https://learn.microsoft.com/en-us/dotnet/framework/mef/">Managed Extensibility Framework</a> (MEF), applying the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.composition.partcreationpolicyattribute">PartCreationPolicyAttribute</a> is necessary.
      For the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.composition.partcreationpolicyattribute">PartCreationPolicyAttribute</a> to be meaningful in the context of an export, the class must also be annotated with the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.composition.exportattribute">ExportAttribute</a>.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a class is annotated with the PartCreationPolicyAttribute but not with the ExportAttribute.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      using System.ComponentModel.Composition;

      [PartCreationPolicy(CreationPolicy.Any)] // Noncompliant
      public class FooBar : IFooBar { }
      ```

      ```csharp Fix theme={null}
      using System.ComponentModel.Composition;

      [Export(typeof(IFooBar))]
      [PartCreationPolicy(CreationPolicy.Any)]
      public class FooBar : IFooBar { }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Methods should not have too many parameters">
    <div class="paragraph">
      <p>\{upper\_function}s with a long parameter list are difficult to use because maintainers must figure out the role of each parameter and keep track of their position.</p>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{language}/noncompliant.adoc\[]</p>
    </div>

    <div class="paragraph">
      <p>The solution can be to:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Split the \{function} into smaller ones</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{language}/split-example.adoc\[]</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Find a better data structure for the parameters that group data in a way that makes sense for the specific application domain</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{language}/struct-example.adoc\[]</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a \{function} has more parameters than the provided threshold.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class BaseClass
      {
      public BaseClass(int param1)
      {
          // ...
      }
      }

      public class DerivedClass : BaseClass
      {
      public DerivedClass(int param1, int param2, int param3, string param4, long param5) : base(param1) // Compliant by exception
      {
          // ...
      }
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="switch case clauses should not have too many lines of code">
    <div class="paragraph">
      <p>The <code>switch statement should be used only to clearly define some new branches in the control flow. As soon as a case clause contains too many statements this highly decreases the readability of the overall control flow statement. In such case, the content of the case</code> clause should be extracted into a dedicated method.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      switch (myVariable) 
      {
      case 0: // Noncompliant: 9 statements in the case
          methodCall1("");
          methodCall2("");
          methodCall3("");
          methodCall4("");
          methodCall5("");
          methodCall6("");
          methodCall7("");
          methodCall8("");
          methodCall9("");
          break;
      case 1:
          ...
      }
      ```

      ```csharp Fix theme={null}
      switch (myVariable) 
      {
      case 0:                  
          DoSomething()
          break;
      case 1:
          ...
      }
      ...
      private void DoSomething()
      {
      methodCall1("");
      methodCall2("");
      methodCall3("");
      methodCall4("");
      methodCall5("");
      methodCall6("");
      methodCall7("");
      methodCall8("");
      methodCall9("");
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Methods should not have identical implementations">
    <div class="paragraph">
      <p>Two \{func\_name}s having the same implementation are suspicious.
      It might be that something else was intended. Or the duplication is intentional, which becomes a maintenance burden.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      private const string CODE = "secret";
      private int callCount = 0;

      public string GetCode() 
      {
      callCount++;
      return CODE;
      }

      public string GetName() // Noncompliant: duplicates GetCode
      {
      callCount++;
      return CODE;
      }
      ```

      ```csharp Fix theme={null}
      private const string CODE = "secret";
      private int callCount = 0;

      public string GetCode() 
      {
      callCount++;
      return CODE;
      }

      public string GetName() // Intent is clear
      {
      return GetCode();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using hardcoded IP addresses is security-sensitive">
    <div class="paragraph">
      <p>Hardcoding IP addresses is security-sensitive. It has led in the past to the following vulnerabilities:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-5901">CVE-2006-5901</a></p>
        </li>

        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2005-3725">CVE-2005-3725</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Today’s services have an ever-changing architecture due to their scaling and redundancy needs. It is a mistake to think that a service will always have the same IP address. When it does change, the hardcoded IP will have to be modified too. This will have an impact on the product development, delivery, and deployment:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>The developers will have to do a rapid fix every time this happens, instead of having an operation team change a configuration file.</p>
        </li>

        <li>
          <p>It misleads to use the same address in every environment (dev, sys, qa, prod).</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Last but not least it has an effect on application security. Attackers might be able to decompile the code and thereby discover a potentially sensitive address. They can perform a Denial of Service attack on the service, try to get access to the system, or try to spoof the IP address to bypass security checks. Such attacks can always be possible, but in the case of a hardcoded IP address solving the issue will take more time, which will increase an attack’s impact.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      var ip = ConfigurationManager.AppSettings["myapplication.ip"];
      var address = IPAddress.Parse(ip);
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="new Guid() should not be used">
    <div class="paragraph">
      <p>When the syntax new Guid() (i.e. parameterless instantiation) is used, it must be that one of three things is wanted:</p>
    </div>

    <div class="olist arabic">
      <ol class="arabic">
        <li>
          <p>An empty GUID, in which case Guid.Empty is clearer.</p>
        </li>

        <li>
          <p>A randomly-generated GUID, in which case Guid.NewGuid() should be used.</p>
        </li>

        <li>
          <p>A new GUID with a specific initialization, in which case the initialization parameter is missing.</p>
        </li>
      </ol>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a parameterless instantiation of the Guid struct is found.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public void Foo()
      {
      var g1 = new Guid();    // Noncompliant - what's the intent?
      Guid g2 = new();        // Noncompliant
      var g3 = default(Guid); // Noncompliant
      Guid g4 = default;      // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      public void Foo(byte[] bytes)
      {
      var g1 = Guid.Empty;
      var g2 = Guid.NewGuid();
      var g3 = new Guid(bytes);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Track uses of TODO tags">
    <div class="paragraph">
      <p>Developers often use TODO tags to mark areas in the code where additional work or improvements are needed but are not implemented immediately.
      However, these TODO tags sometimes get overlooked or forgotten, leading to incomplete or unfinished code.
      This rule aims to identify and address unattended TODO tags to ensure a clean and maintainable codebase.
      This description explores why this is a problem and how it can be fixed to improve the overall code quality.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      private void DoSomething() 
      {
      // TODO
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Log message template should be syntactically correct">
    <div class="paragraph">
      <p>A <a href="https://messagetemplates.org/">message template</a> must conform to the specification. The rule raises an issue if the template string violates the template string grammar.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      logger.LogError("Login failed for {User", user);       // Noncompliant: Syntactically incorrect
      logger.LogError("Login failed for {}", user);          // Noncompliant: Empty placeholder
      logger.LogError("Login failed for {User-Name}", user); // Noncompliant: Only letters, numbers, and underscore are allowed for placeholders
      logger.LogDebug("Retry attempt {Cnt,r}", cnt);         // Noncompliant: The alignment specifier must be numeric
      logger.LogDebug("Retry attempt {Cnt:}", cnt);          // Noncompliant: Empty format specifier is not allowed
      ```

      ```csharp Fix theme={null}
      logger.LogError("Login failed for {User}", user);
      logger.LogError("Login failed for {User}", user);
      logger.LogError("Login failed for {User_Name}", user);
      logger.LogDebug("Retry attempt {Cnt,-5}", cnt);
      logger.LogDebug("Retry attempt {Cnt:000}", cnt);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="All branches in a conditional structure should not have exactly the same implementation">
    <div class="paragraph">
      <p>Having all branches of a switch or if chain with the same implementation indicates a problem.</p>
    </div>

    <div class="paragraph">
      <p>In the following code:</p>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{example}\[]</p>
    </div>

    <div class="paragraph">
      <p>Either there is a copy-paste error that needs fixing or an unnecessary switch or if chain that should be removed.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if (b == 0)    //no issue, this could have been done on purpose to make the code more readable
      {
      DoSomething();
      } 
      else if (b == 1)
      {
      DoSomething();
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="View data dictionaries should be replaced by models">
    <div class="paragraph">
      <p>ViewBag and ViewData dictionaries enable controllers to pass data to their views as weakly typed collections. Reading the provided values is dynamically resolved at runtime without any compile-time checking. This can lead to unexpected behavior, since reading a missing value does not produce an exception.</p>
    </div>

    <div class="paragraph">
      <p>Controllers should pass data to their views via a strongly typed view model class.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      using System.Web.Mvc;

      public class HomeController : Controller
      {
      public ActionResult Article()
      {
          ViewBag.Title = "Title"; // Noncompliant, model should be used
          ViewData["Text"] = "Text"; // Noncompliant, model should be used
          return View();
      }
      }
      ```

      ```csharp Fix theme={null}
      using System.Web.Mvc;

      public class ArticleModel
      {
      public string Title { get; set; }
      public string Text { get; set; }
      }

      public class HomeController : Controller
      {
      public ActionResult Article()
      {
          var model = new ArticleModel { Title = "Title", Text = "Text" };
          return View(model);
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Nested code blocks should not be used">
    <div class="paragraph">
      <p>Nested code blocks create new scopes where variables declared within are inaccessible from the outside, and their lifespan ends with the block.</p>
    </div>

    <div class="paragraph">
      <p>Although this may appear beneficial, their usage within a function often suggests that the function is overloaded.
      Thus, it may violate the Single Responsibility Principle, and the function needs to be broken down into smaller functions.</p>
    </div>

    <div class="paragraph">
      <p>The presence of nested blocks that don’t affect the control flow might suggest possible mistakes in the code.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public void Evaluate()
      {
      /* ... */
      {     // Noncompliant - nested code block '{' ... '}'
            int a = stack.pop();
            int b = stack.pop();
            int result = a + b;
            stack.push(result);
      }
      /* ... */
      }
      ```

      ```csharp Fix theme={null}
      public void Evaluate()
      {
      /* ... */
      StackAdd();
      /* ... */
      }

      private void StackAdd()
      {
        int a = stack.pop();
        int b = stack.pop();
        int result = a + b;
        stack.push(result);
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="ExcludeFromCodeCoverage attributes should include a justification">
    <div class="paragraph">
      <p>The <a href="https://learn.microsoft.com/dotnet/api/system.diagnostics.codeanalysis.excludefromcodecoverageattribute">ExcludeFromCodeCoverageAttribute</a> is used to exclude portions of code from <a href="https://learn.microsoft.com/dotnet/core/testing/unit-testing-code-coverage">code coverage reporting</a>. It is a bad practice to retain code that is not covered by unit tests. In .Net 5, the Justification property was added to the ExcludeFromCodeCoverageAttribute as an opportunity to document the rationale for the exclusion. This rule raises an issue when no such justification is given.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public struct Coordinates
      {
      public int X { get; }
      public int Y { get; }

      [ExcludeFromCodeCoverage] // Noncompliant
      public override bool Equals(object obj) => obj is Coordinates coordinates && X == coordinates.X && Y == coordinates.Y;

      [ExcludeFromCodeCoverage] // Noncompliant
      public override int GetHashCode()
      {
          var hashCode = 1861411795;
          hashCode = hashCode * -1521134295 + X.GetHashCode();
          hashCode = hashCode * -1521134295 + Y.GetHashCode();
          return hashCode;
      }
      }
      ```

      ```csharp Fix theme={null}
      public struct Coordinates
      {
      public int X { get; }
      public int Y { get; }

      [ExcludeFromCodeCoverage(Justification = "Code generated by Visual Studio refactoring")] // Compliant
      public override bool Equals(object obj) => obj is Coordinates coordinates && X == coordinates.X && Y == coordinates.Y;

      [ExcludeFromCodeCoverage(Justification = "Code generated by Visual Studio refactoring")] // Compliant
      public override int GetHashCode()
      {
          var hashCode = 1861411795;
          hashCode = hashCode * -1521134295 + X.GetHashCode();
          hashCode = hashCode * -1521134295 + Y.GetHashCode();
          return hashCode;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Flags enumerations should explicitly initialize all their members">
    <div class="paragraph">
      <p>When you annotate an <a href="https://learn.microsoft.com/en-us/dotnet/api/system.enum">Enum</a> with the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.flagsattribute">Flags attribute</a>, you must not rely on the values that are automatically set by the language to the Enum members, but you should define the enumeration constants in powers of two (1, 2, 4, 8, and so on). Automatic value initialization will set the first member to zero and increment the value by one for each subsequent member. As a result, you won’t be able to use the enum members with bitwise operators.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      var bananaAndStrawberry = FruitType.Banana | FruitType.Strawberry; 
      Console.WriteLine(bananaAndStrawberry.ToString());  // Will display only "Strawberry"

      [Flags]
      enum FruitType    // Noncompliant
      {
      None,
      Banana,
      Orange,
      Strawberry
      }
      ```

      ```csharp Fix theme={null}
      var bananaAndStrawberry = FruitType.Banana | FruitType.Strawberry;
      Console.WriteLine(bananaAndStrawberry.ToString()); // Will display "Banana, Strawberry"

      [Flags]
      enum FruitType
      {
      None = 0,
      Banana = 1,
      Orange = 2,
      Strawberry = 4
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Field names should comply with a naming convention">
    <div class="paragraph">
      <p>A naming convention in software development is a set of guidelines for naming code elements like variables, functions, and classes.</p>
    </div>

    <div class="paragraph">
      <p>The goal of a naming convention is to make the code more readable and understandable, which makes it easier to maintain and debug.
      It also ensures consistency in the code, especially when multiple developers are working on the same project.</p>
    </div>

    <div class="paragraph">
      <p>This rule checks that field names match a provided regular expression.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      class MyClass {
      private int my_field;
      }
      ```

      ```csharp Fix theme={null}
      class MyClass {
      private int myField;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unused private types or members should be removed">
    <div class="paragraph">
      <p>This rule raises an issue when a \{visibility} \{operationName} is never referenced in the code.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Foo
      {
      private void UnusedPrivateMethod(){...} // Noncompliant, this private method is unused and can be removed.

      private class UnusedClass {...} // Noncompliant, unused private class that can be removed.
      }
      ```

      ```csharp Fix theme={null}
      public class Foo
      {
      public Foo()
      {
          UsedPrivateMethod();
      }

      private void UsedPrivateMethod()
      {
          var c = new UsedClass();
      }

      private class UsedClass {...}
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Classes should not be empty">
    <div class="paragraph">
      <p>There is no good excuse for an empty class. If it’s being used simply as a common extension point, it should be replaced with an <code>interface</code>. If it was stubbed in as a placeholder for future development it should be fleshed-out. In any other case, it should be eliminated.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Empty // Noncompliant
      {
      }
      ```

      ```csharp Fix theme={null}
      public interface IEmpty
      {
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Setting loose file permissions is security-sensitive">
    <div class="paragraph">
      <p>In Unix file system permissions, the "`others`" category refers to all
      users except the owner of the file system resource and the members of the group
      assigned to this resource.</p>
    </div>

    <div class="paragraph">
      <p>Granting permissions to this category can lead to unintended access to files or
      directories that could allow attackers to obtain sensitive information, disrupt
      services or elevate privileges.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      var safeAccessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Deny);

      var fileSecurity = File.GetAccessControl("path");
      fileSecurity.AddAccessRule(safeAccessRule);
      File.SetAccessControl("path", fileSecurity);
      ```

      ```csharp Fix theme={null}
      var safeAccessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Deny);

      var fileInfo = new FileInfo("path");
      var fileSecurity = fileInfo.GetAccessControl();
      fileSecurity.SetAccessRule(safeAccessRule);
      fileInfo.SetAccessControl(fileSecurity);
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Track uses of disallowed classes">
    <div class="paragraph">
      <p>This rule allows banning certain classes.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      System.Console.WriteLine("foo");  // Noncompliant
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Methods should not return constants">
    <div class="paragraph">
      <p>There’s no point in forcing the overhead of a method call for a method that always returns the same constant value. Even worse, the fact that a method call must be made will likely mislead developers who call the method thinking that something more is done. Declare a constant instead.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue if on methods that contain only one  statement: the <code>return</code> of a constant value.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      int GetBestNumber()
      {
      return 12;  // Noncompliant
      }
      ```

      ```csharp Fix theme={null}
      const int BestNumber = 12;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Useless if(true) {...} and if(false){...} blocks should be removed">
    <div class="paragraph">
      <p>\`if statements with conditions that are always false have the effect of making blocks of code non-functional. if statements with conditions that are always true are completely redundant, and make the code less readable.</p>
    </div>

    <div class="paragraph">
      <p>There are three possible causes for the presence of such code:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>An if statement was changed during debugging and that debug code has been committed.</p>
        </li>

        <li>
          <p>Some value was left unset.</p>
        </li>

        <li>
          <p>Some logic is not doing what the programmer thought it did.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>In any of these cases, unconditional if\` statements should be removed.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if (true) 
      {  
      DoSomething(); 
      }
      ...
      if (false) 
      {
      DoSomethingElse(); 
      }
      ```

      ```csharp Fix theme={null}
      DoSomething(); 
      ...
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Empty statements should be removed">
    <div class="paragraph">
      <p>Empty statements represented by a semicolon ; are statements that do not perform any operation. They are often the result of a typo or a misunderstanding of the language syntax.
      It is a good practice to remove empty statements since they don’t add value and lead to confusion and errors.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      void DoSomething() 
      {
      ; // Noncompliant - was used as a kind of TODO marker
      }

      void DoSomethingElse() 
      {
      Console.WriteLine("Hello, world!");;  // Noncompliant - double ;
      // ...
      // Rarely, they are used on purpose as the body of a loop. It is a bad practice to 
      // have side-effects outside of the loop:
      for (int i = 0; i < 3; Console.WriteLine(i), i++); // Noncompliant
      // ...
      }
      ```

      ```csharp Fix theme={null}
      void DoSomething() 
      {
      }

      void DoSomethingElse() 
      {
      Console.WriteLine("Hello, world!");
      // ...
      for (int i = 0; i < 3; i++)
      {
          Console.WriteLine(i);
       }
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Child class fields should not shadow parent class fields">
    <div class="paragraph">
      <p>Having a variable with the same name in two unrelated classes is fine, but do the same thing within a class hierarchy and you’ll get confusion at best, chaos at worst.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Fruit 
      { 
      protected Season ripe; 
      protected Color flesh; 

      // ... 
      } 

      public class Raspberry : Fruit 
      { 
      private bool ripe; // Noncompliant 
      private static Color FLESH; // Noncompliant 
      }
      ```

      ```csharp Fix theme={null}
      public class Fruit 
      { 
      protected Season ripe; 
      protected Color flesh; 

      // ... 
      } 

      public class Raspberry : Fruit 
      { 
      private bool ripened; 
      private static Color FLESH_COLOR; 
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="The ternary operator should not return the same value regardless of the condition">
    <div class="paragraph">
      <p>When the second and third operands of a ternary operator are the same, the operator will always return the same value regardless of the condition. Either the operator itself is pointless, or a mistake was made in coding it.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public bool CanVote(Person person) 
      {
      return person.GetAge() > 18 ? true : true; // Noncompliant; is this what was intended?
      }
      ```

      ```csharp Fix theme={null}
      public bool CanVote(Person person) 
      {
      return person.GetAge() > 18 ? true : false; 
      // or even better: 
      // return person.GetAge() > 18;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unnecessary using should be removed">
    <div class="paragraph">
      <p>Although they don’t affect the runtime behavior of the application after compilation, removing them will:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Improve the readability and maintainability of the code.</p>
        </li>

        <li>
          <p>Help avoid potential naming conflicts.</p>
        </li>

        <li>
          <p>Improve the build time, as the compiler has fewer lines to read and fewer types to resolve.</p>
        </li>

        <li>
          <p>Reduce the number of items the code editor will show for auto-completion, thereby showing fewer irrelevant suggestions.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      global using System.Net.Sockets; // Compliant by exception
      ```

      ```csharp Fix theme={null}
      using System.IO;
      using System.Linq;
      using System.Collections.Generic;   // Noncompliant - no types are used from this namespace    
      using MyApp.Helpers;                // Noncompliant - FileHelper is in the same namespace
      using MyCustomNamespace;            // Noncompliant - no types are used from this namespace

      namespace MyApp.Helpers
      {
      public class FileHelper
      {
          public static string ReadFirstLine(string filePath) =>
              File.ReadAllLines(filePath).First();
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using weak hashing algorithms is security-sensitive">
    <div class="paragraph">
      <p>Cryptographic hash algorithms such as <code>MD2, MD4, MD5, MD6, HAVAL-128, HMAC-MD5, DSA (which uses SHA-1), RIPEMD, RIPEMD-128, RIPEMD-160, HMACRIPEMD160 and SHA-1 are no longer considered secure, because it is possible to have collisions</code> (little computational effort is enough to find two or more different inputs that produce the same hash).</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      var hashProvider1 = new SHA512Managed(); // Compliant
      var hashProvider2 = (HashAlgorithm)CryptoConfig.CreateFromName("SHA512Managed"); // Compliant
      var hashProvider3 = HashAlgorithm.Create("SHA512Managed"); // Compliant
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Exception constructors should not throw exceptions">
    <div class="paragraph">
      <p>It may be a good idea to raise an exception in a constructor if you’re unable to fully flesh the object in question, but not in an <code>exception</code> constructor. If you do, you’ll interfere with the exception that was originally being thrown. Further, it is highly unlikely that an exception raised in the creation of an exception will be properly handled in the calling code, and the unexpected, unhandled exception will lead to program termination.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      class MyException: Exception
      {
      public void MyException()
      {
           if (bad_thing) 
           {
               throw new Exception("A bad thing happened");  // Noncompliant
            }
      }
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Deserialization methods should be provided for OptionalField members">
    <div class="paragraph">
      <p>Fields marked with \`System.Runtime.Serialization.OptionalFieldAttribute are serialized just like any other field. But such fields are ignored on deserialization, and retain the default values associated with their types. Therefore, deserialization event handlers should be declared to set such fields during the deserialization process.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises when at least one field with the System.Runtime.Serialization.OptionalFieldAttribute attribute is declared but one (or both) of the following event handlers System.Runtime.Serialization.OnDeserializingAttribute or System.Runtime.Serialization.OnDeserializedAttribute\` are not present.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      [Serializable]
      public class Foo
      {
      [OptionalField(VersionAdded = 2)]
      int optionalField = 5;    
      }
      ```

      ```csharp Fix theme={null}
      [Serializable]
      public class Foo
      {
      [OptionalField(VersionAdded = 2)]
      int optionalField = 5;

      [OnDeserializing]
      void OnDeserializing(StreamingContext context)
      {
          optionalField = 5;
      }

      [OnDeserialized]
      void OnDeserialized(StreamingContext context)
      {
          // Set optionalField if dependent on other deserialized values.
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Zip function calls should not be vulnerable to path traversal attacks">
    <div class="paragraph">
      <p>Libraries used to unarchive a file (zip, bzip2, tar, …​) do what they were made for: they extract the content of the archive blindly, creating on the filesystem directories and files corresponding exactly to the content of the archive. Using a specially crafted archive containing some path traversal filenames, it is possible to create directories/files outside of the dir where the archive is extracted. This can lead to overwriting an executable or a configuration file with a file containing malicious code and transform a simple archive into a way to execute arbitrary code.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      using System.IO;
      using System.IO.Compression;

      public class ZipHelper
      {
      public void Extract(ZipFile zipFile, string destinationDirectory)
      {
          foreach (var entry in zipFile.Entries)
          {
              var destinationFileName = Path.GetFullPath(Path.Combine(destinationDirectory, entry.FullName));
              entry.ExtractToFile(destinationFileName); // entry.FullName could contain parent directory references (..) and make the
                                                        // file to be extracted in an arbitrary directory, outside of destinationDirectory
          }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System.IO;
      using System.IO.Compression;

      public class ZipHelper
      {
      public void Extract(ZipFile zipFile, string destinationDirectory)
      {
          foreach (var entry in zipFile.Entries)
          {
              var destinationFileName = Path.GetFullPath(Path.Combine(destinationDirectory, entry.FullName));
              if (destinationFullName.StartsWith(destinationDirectory)) // Do not extract files if the destination file path will be outside of destinationDirectory
              {
                  entry.ExtractToFile(destinationFileName); // Compliant, destinationFileName is ensured to be under destinationDirectory
              }
          }
      }
      }{code}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using non-standard cryptographic algorithms is security-sensitive">
    <div class="paragraph">
      <p>The use of a non-standard algorithm is dangerous because a determined attacker may be able to break the algorithm and compromise whatever data has been protected. Standard algorithms like \`SHA-256, SHA-384, SHA-512, …​ should be used instead.</p>
    </div>

    <div class="paragraph">
      <p>This rule tracks creation of java.security.MessageDigest\` subclasses.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      SHA256 mySHA256 = SHA256.Create()
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Hard-coded credentials are security-sensitive">
    <div class="paragraph">
      <p>Because it is easy to extract strings from an application source code or binary, credentials should not be hard-coded. This is particularly true for applications that are distributed or that are open-source.</p>
    </div>

    <div class="paragraph">
      <p>In the past, it has led to the following vulnerabilities:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-13466">CVE-2019-13466</a></p>
        </li>

        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-15389">CVE-2018-15389</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Credentials should be stored outside of the code in a configuration file, a database, or a management service for secrets.</p>
    </div>

    <div class="paragraph">
      <p>This rule flags instances of hard-coded credentials used in database and LDAP connections. It looks for hard-coded credentials in connection strings, and for variable names that match any of the patterns from the provided list.</p>
    </div>

    <div class="paragraph">
      <p>It’s recommended to customize the configuration of this rule with additional credential words such as "oauthToken", "secret", …​</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      string username = "admin";
      string password = GetEncryptedPassword();
      string usernamePassword = string.Format("user={0}&password={1}", GetEncryptedUsername(), GetEncryptedPassword());
      string url = $"scheme://{username}:{password}@domain.com";

      string url2 = "http://guest:guest@domain.com"; // Compliant
      const string Password_Property = "custom.password"; // Compliant
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Duplicate values should not be passed as arguments">
    <div class="paragraph">
      <p>There are valid cases for passing a variable multiple times into the same method call, but usually doing so is a mistake, and something else was intended for one of the arguments.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      if (Compare(point.X, point.X) != 0) // Noncompliant 
      {
        //... 
      } 

      if (DoSomething(GetNextValue(), GetNextValue()))  // Noncompliant 
      {
        // ... 
      }
      ```

      ```csharp Fix theme={null}
      if (Compare(point.X, point.Y) != 0)
      { 
        //... 
      } 

      var v1 = GetNextValue(); 
      var v2 = GetNextValue(); 
      if (DoSomething(v1, v2))
      { 
        // ... 
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Methods with Pure attribute should return a value ">
    <div class="paragraph">
      <p>Marking a method with the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.contracts.pureattribute">Pure</a> attribute indicates that the method doesn’t make any visible state changes. Therefore, a Pure method should return a result. Otherwise, it indicates a no-operation call.</p>
    </div>

    <div class="paragraph">
      <p>Using Pure on a void method is either by mistake or the method is not doing a meaningful task.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      class Person
      {
      private int age;

      [Pure] // Noncompliant: The method makes a state change
      void ConfigureAge(int age) =>
      this.age = age;
      }
      ```

      ```csharp Fix theme={null}
      class Person
      {
      private int age;

      void ConfigureAge(int age) =>
      this.age = age;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="[ExpectedException] should not be used">
    <div class="paragraph">
      <p>It should be clear to a casual reader what code a test is testing and what results are expected. Unfortunately, that’s not usually the case with the ExpectedException attribute since an exception could be thrown from almost any line in the method.</p>
    </div>

    <div class="paragraph">
      <p>This rule detects MSTest and NUnit ExpectedException attribute.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      [TestMethod]
      [ExpectedException(typeof(ArgumentNullException))]  // Noncompliant
      public void TestNullArg()
      {
      //...
      }
      ```

      ```csharp Fix theme={null}
      [TestMethod]
      public void TestNullArg()
      {
      bool callFailed = false;
      try
      {
      //...
      }
      catch (ArgumentNullException)
      {
      callFailed = true;
      }
      Assert.IsTrue(callFailed, "Expected call to MyMethod to fail with ArgumentNullException");
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unused local variables should be removed">
    <div class="paragraph">
      <p>An unused local variable is a variable that has been declared but is not used anywhere in the block of code where it is defined. It is dead code, contributing to unnecessary complexity and leading to confusion when reading the code. Therefore, it should be removed from your code to maintain clarity and efficiency.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      using(var t = new TestTimer()) // t never used, but compliant.
      {
      //...
      }
      ```

      ```csharp Fix theme={null}
      public int NumberOfMinutes(int hours)
      {
      int seconds = 0;   // Noncompliant - seconds is unused 
      return hours * 60;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Loop boundaries should not be vulnerable to injection attacks">
    <div class="paragraph">
      <p>Loop boundary injections occur in an application when the application retrieves
      data from a user or a third-party service and inserts it into a loop or a
      function acting as a loop, without sanitizing it first.</p>
    </div>

    <div class="paragraph">
      <p>If an application contains a loop that is vulnerable to injections,
      it is exposed to attacks that target its availability where that loop is used.</p>
    </div>

    <div class="paragraph">
      <p>A user with malicious intent carefully performs actions whose goal is to cause
      the loop to run for more iterations than the developer intended, resulting in
      unexpected behavior or even a crash of the program.</p>
    </div>

    <div class="paragraph">
      <p>After creating the malicious request, the attacker can attack the servers
      affected by this vulnerability without relying on any prerequisites.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class ExampleController : Controller
      {
      public IActionResult Compute(int data)
      {
          for (int i = 0; i < data; i++) // Noncompliant
          {
              Console.WriteLine("Hello");
          }

          Enumerable
              .Range(1, data) // Noncompliant
              .ToList()
              .ForEach(i => Console.WriteLine("World"));

          return Ok();
      }
      }
      ```

      ```csharp Fix theme={null}
      public class ExampleController : Controller
      {
      public static int MAX_BOUNDARY = 1337;
      public static int MIN_BOUNDARY = 1;

      public IActionResult Compute(int data)
      {
          
          if (MIN_BOUNDARY > data)
          {
              data = MIN_BOUNDARY;
          }
          else if (data > MAX_BOUNDARY)
          {
              data = MAX_BOUNDARY;
          }

          for (int i = 0; i < data; i++)
          {
              Console.WriteLine("Hello");
          }

          Enumerable
              .Range(1, data) // Noncompliant
              .ToList()
              .ForEach(i => Console.WriteLine("World"));

          return Ok();
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Objects should not be disposed more than once">
    <div class="paragraph">
      <p>Disposing an object twice in the same method, either with the \{usingArg} or by calling Dispose directly, is confusing and error-prone. For example, another developer might try to use an already-disposed object, or there can be runtime errors for specific paths in the code.</p>
    </div>

    <div class="paragraph">
      <p>In addition, even if the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.idisposable.dispose#System_IDisposable_Dispose">documentation</a> explicitly states that calling the Dispose method multiple times should not throw an exception, some implementations still do it. Thus it is safer to not dispose of an object twice when possible.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      var foo = new Disposable();
      foo.Dispose();
      foo.Dispose(); // Noncompliant
      ```

      ```csharp Fix theme={null}
      using (var bar = new Disposable()) // Noncompliant
      {
      bar.Dispose();
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Exceptions should not be thrown in finally blocks">
    <div class="paragraph">
      <p>If an exception is already being thrown within the try block or caught in a catch block, throwing another exception in the finally block will override the original exception.
      This means that the original exception’s message and stack trace will be lost, potentially making it challenging to diagnose and troubleshoot the root cause of the problem.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      try 
      {
      // Some work which end up throwing an exception
      throw new ArgumentException();
      }
      finally 
      {
      // Cleanup
      throw new InvalidOperationException(); // Noncompliant: will mask the ArgumentException
      }
      ```

      ```csharp Fix theme={null}
      try 
      {
      // Some work which end up throwing an exception
      throw new ArgumentException();
      }
      finally 
      {
      // Cleanup without throwing
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unused assignments should be removed">
    <div class="paragraph">
      <p>Dead stores refer to assignments made to local variables that are subsequently never used or immediately overwritten. Such assignments are unnecessary and don’t contribute to the functionality or clarity of the code. They may even negatively impact performance. Removing them enhances code cleanliness and readability.
      Even if the unnecessary operations do not do any harm in terms of the program’s correctness, they are - at best - a waste of computing resources.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      int Foo(int y)
      {
      int x = 100; // Noncompliant: dead store
      x = 150;     // Noncompliant: dead store  
      x = 200;
      return x + y;
      }
      ```

      ```csharp Fix theme={null}
      int Foo(int y)
      {
      int x = 200; // Compliant: no unnecessary assignment
      return x + y;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="ConstructorArgument parameters should exist in constructors">
    <div class="paragraph">
      <p>When creating a custom <a href="https://learn.microsoft.com/en-us/dotnet/desktop/wpf/advanced/markup-extensions-and-wpf-xaml">Markup Extension</a> that accepts parameters in WPF, the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.markup.constructorargumentattribute">ConstructorArgument</a> markup must be used to identify the discrete properties that match these parameters. However since this is done via a string, the compiler won’t give you any warning in case there are typos.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when the string argument to ConstructorArgumentAttribute doesn’t match any parameter of any constructor.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      using System;

      namespace MyLibrary
      {
      public class MyExtension : MarkupExtension
      {
      public MyExtension() { }

      public MyExtension(object value1)
      {
        Value1 = value1;
      }

      [ConstructorArgument("value2")]   // Noncompliant
      public object Value1 { get; set; }
      }
      }
      ```

      ```csharp Fix theme={null}
      using System;

      namespace MyLibrary
      {
      public class MyExtension : MarkupExtension
      {
      public MyExtension() { }

      public MyExtension(object value1)
      {
        Value1 = value1;
      }

      [ConstructorArgument("value1")] 
      public object Value1 { get; set; }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Cognitive Complexity of methods should not be too high">
    <div class="paragraph">
      <p>Cognitive Complexity is a measure of how hard it is to understand the control flow of a unit of code.
      Code with high cognitive complexity is hard to read, understand, test, and modify.</p>
    </div>

    <div class="paragraph">
      <p>As a rule of thumb, high cognitive complexity is a sign that the code should be refactored into smaller, easier-to-manage pieces.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      decimal CalculateFinalPrice(User user, Cart cart)
      {
      decimal total = CalculateTotal(cart);
      if (user.HasMembership()               // +1 (if)
          && user.OrdersCount > 10           // +1 (more than one condition)
          && user.AccountActive
          && !user.HasDiscount
          || user.OrdersCount == 1)          // +1 (change of operator in condition)
      {
          
          total = ApplyDiscount(user, total);
      }
      return total;
      }
      ```

      ```csharp Fix theme={null}
      decimal CalculateFinalPrice(User user, Cart cart)
      {
      decimal total = CalculateTotal(cart);
      if (IsEligibleForDiscount(user))       // +1 (if)
      {
          total = applyDiscount(user, total);
      }
      return total;
      }

      bool IsEligibleForDiscount(User user)
      {
      return user.HasMembership()
              && user.OrdersCount > 10       // +1 (more than one condition)
              && user.AccountActive
              && !user.HasDiscount
              || user.OrdersCount == 1;      // +1 (change of operator in condition)
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Assemblies should have version information">
    <div class="paragraph">
      <p>The <a href="https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assemblyversionattribute">AssemblyVersion</a> attribute is used to specify the version number of an assembly. An assembly is a compiled unit of code, which can be marked with a version number by applying the attribute to an assembly’s source code file.</p>
    </div>

    <div class="paragraph">
      <p>The AssemblyVersion attribute is useful for many reasons:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><strong>Versioning</strong>: The attribute allows developers to track and manage different versions of an assembly. By incrementing the version number for each new release, you can easily identify and differentiate between different versions of the same assembly. This is particularly useful when distributing and deploying software, as it helps manage updates and compatibility between different versions.</p>
        </li>

        <li>
          <p><strong>Dependency management</strong>: When an assembly references another assembly, it can specify the specific version of the dependency it requires. By using the AssemblyVersion attribute, you can ensure that the correct version of the referenced assembly is used. This helps avoid compatibility issues and ensures that the expected behavior and functionality are maintained.</p>
        </li>

        <li>
          <p><strong>GAC management</strong>: The <a href="https://learn.microsoft.com/en-us/dotnet/framework/app-domains/gac">GAC</a>, also known as Global Assembly Cache, is a central repository for storing shared assemblies on a system. The AssemblyVersion attribute plays a crucial role in managing assemblies in the GAC. Different versions of an assembly can coexist in the GAC, allowing applications to use the specific version they require.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>If no AssemblyVersion is provided, the same default version will be used for every build. Since the version number is used by .NET Framework to uniquely identify an assembly, this can lead to broken dependencies.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      using System.Reflection;

      [assembly: AssemblyTitle("MyAssembly")] // Noncompliant
      namespace MyLibrary
      {
      // ...
      }
      ```

      ```csharp Fix theme={null}
      using System.Reflection;

      [assembly: AssemblyTitle("MyAssembly")] 
      [assembly: AssemblyVersion("42.1.125.0")]
      namespace MyLibrary
      {
      // ...
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unread private fields should be removed">
    <div class="paragraph">
      <p>Private fields which are written but never read are a case of "dead store". Changing the value of such a field is useless and most probably indicates an error in the code.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Rectangle
      {
      private readonly int length;
      private readonly int width;  // Noncompliant: width is written but never read

      public Rectangle(int length, int width)
      {
      this.length = length;
      this.width = width;
      }

      public int Surface
      {
      get
      {
        return length * width;
      }
      }
      }
      ```

      ```csharp Fix theme={null}
      public class Rectangle
      {
      private readonly int length;
      private readonly int width;

      public Rectangle(int length, int width)
      {
      this.length = length;
      this.width = width;
      }

      public int Surface
      {
      get
      {
        return length * width;
      }
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Fields that are only assigned in the constructor should be readonly">
    <div class="paragraph">
      <p>readonly fields can only be assigned in a class constructor. If a class has a field that’s not marked readonly but is only set in the constructor, it could cause confusion about the field’s intended use. To avoid confusion, such fields should be marked readonly to make their intended use explicit, and to prevent future maintainers from inadvertently changing their use.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Person
      {
      private int _birthYear; // Noncompliant

      Person(int birthYear)
      {
          _birthYear = birthYear;
      }
      }
      ```

      ```csharp Fix theme={null}
      public class Person
      {
      private readonly int _birthYear;

      Person(int birthYear)
      {
          _birthYear = birthYear;
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Classes should implement their ExportAttribute interfaces">
    <div class="paragraph">
      <p>The <a href="https://learn.microsoft.com/en-us/dotnet/framework/mef/attributed-programming-model-overview-mef">Attributed Programming Model</a>, also known as <a href="https://en.wikipedia.org/wiki/Attribute-oriented_programming">Attribute-oriented programming (@OP)</a>, is a programming model used to embed attributes within codes.</p>
    </div>

    <div class="paragraph">
      <p>In this model, objects are required to conform to a specific structure so that they can be used by the <a href="https://learn.microsoft.com/en-us/dotnet/framework/mef/">Managed Extensibility Framework (MEF)</a>.</p>
    </div>

    <div class="paragraph">
      <p>MEF provides a way to discover available components implicitly, via <strong>composition</strong>. A MEF component, called a <strong>part</strong>, declaratively specifies:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>both its dependencies, known as <strong>imports</strong></p>
        </li>

        <li>
          <p>and what capabilities it makes available, known as <strong>exports</strong></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>The <a href="https://learn.microsoft.com/en-us/dotnet/api/system.composition.exportattribute">ExportAttribute</a> declares that a part "exports", or provides to the composition container, an object that fulfills a particular contract.</p>
    </div>

    <div class="paragraph">
      <p>During composition, parts with imports that have matching contracts will have those dependencies filled by the exported object.</p>
    </div>

    <div class="paragraph">
      <p>If the type doesn’t implement the interface it is exporting there will be an issue at runtime (either a cast exception or just a container not filled with the exported type) leading to unexpected behaviors/crashes.</p>
    </div>

    <div class="paragraph">
      <p>The rule raises an issue when a class doesn’t implement or inherit the type declared in the ExportAttribute.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      [Export(typeof(ISomeType))]
      public class SomeType // Noncompliant: doesn't implement 'ISomeType'.
      {
      }
      ```

      ```csharp Fix theme={null}
      [Export(typeof(ISomeType))]
      public class SomeType : ISomeType
      {
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unchanged variables should be marked as const">
    <div class="paragraph">
      <p>If a variable that is not supposed to change is not marked as const, it could be accidentally reassigned elsewhere in the code, leading to unexpected behavior and bugs that can be hard to track down.</p>
    </div>

    <div class="paragraph">
      <p>By declaring a variable as const, you ensure that its value remains constant throughout the code. It also signals to other developers that this value is intended to remain constant. This can make the code easier to understand and maintain.</p>
    </div>

    <div class="paragraph">
      <p>In some cases, using const can lead to performance improvements. The compiler might be able to make optimizations knowing that the value of a const variable will not change.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public bool Seek(int[] input)
      {
      var target = 32;  // Noncompliant
      foreach (int i in input)
      {
      if (i == target) 
      {
        return true;
      }
      }
      return false;
      }
      ```

      ```csharp Fix theme={null}
      public bool Seek(int[] input)
      {
      const int target = 32;
      foreach (int i in input)
      {
      if (i == target)
      {
        return true;
      }
      }
      return false;
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Boolean expressions should not be gratuitous">
    <div class="paragraph">
      <p>Control flow constructs like if-statements allow the programmer to direct the
      flow of a program depending on a boolean expression.
      However, if the condition is always true or always false, only one of the
      branches will ever be executed.
      In that case, the control flow construct and the condition no longer serve a
      purpose; they become <em>gratuitous</em>.</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      string d = null;
      var v1 = d ?? "value";      // Noncompliant
      ```

      ```csharp Fix theme={null}
      const bool debug = false;
      //...
      if (debug)                  // Compliant
      {
      // Print something
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Date and time should not be used as a type for primary keys">
    <div class="paragraph">
      <p>Date and time should not be used as a type for primary keys</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      internal class Account
      {
      public DateTime Id { get; set; }

      public string Name { get; set; }
      public string Surname { get; set; }
      }
      ```

      ```csharp Fix theme={null}
      internal class Account
      {
      public Guid Id { get; set; }

      public string Name { get; set; }
      public string Surname { get; set; }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Local variables should not shadow class fields or properties">
    <div class="paragraph">
      <p>Local variables should not shadow class fields or properties</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      class Foo
      {
      public int myField;
      public int MyProperty { get; set; }

      public void DoSomething()
      {
      int myField = 0;    // Noncompliant
      int MyProperty = 0; // Noncompliant
      }
      }
      ```

      ```csharp Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Azure Functions should be stateless">
    <div class="paragraph">
      <p>Azure Functions should be stateless</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public static class HttpExample
      {
          private static readonly int port = 2000;
          private static int numOfRequests = 1;

          [FunctionName("HttpExample")]
          public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest request, ILogger log)
          {
              numOfRequests += 1; // Noncompliant
              log.LogInformation($"Number of POST requests is {numOfRequests}.");

              string responseMessage = $"HttpRequest was made on port {port}."; // Compliant, state is only read.

              return new OkObjectResult(responseMessage);
          }
      }
      ```

      ```csharp Fix theme={null}
      public static class HttpExample
      {
          private static readonly int port = 2000;

          [FunctionName("HttpExample")]
          public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest request, ILogger log)
          {
              // A compliant solution would be to manage the `numOfRequests` with an entity function or would use storage (e.g., Azure Blob storage, Azure Queue Storage)
              // to share the state between functions.

              string responseMessage = $"HttpRequest was made on port {port}.";

              return new OkObjectResult(responseMessage);
          }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Azure Functions should use Structured Error Handling">
    <div class="paragraph">
      <p>Azure Functions should use Structured Error Handling</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      [FunctionName("HttpExample")]
      public static async Task<IActionResult> Run(
      [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req)
      {
      // Noncompliant
      string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
      dynamic data = JsonConvert.DeserializeObject(requestBody);
      // do stuff
      }
      ```

      ```csharp Fix theme={null}
      [FunctionName("HttpExample")]
      public static async Task<IActionResult> Run(
      [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req)
      {
      try
      {
          string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
          dynamic data = JsonConvert.DeserializeObject(requestBody);
          // do stuff
      }
      catch (Exception ex)
      {
          // do stuff
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Logger fields should be private static readonly">
    <div class="paragraph">
      <p>Logger fields should be "private static readonly"</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public Logger logger;
      ```

      ```csharp Fix theme={null}
      private static readonly Logger logger;
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Azure Functions should log all failures">
    <div class="paragraph">
      <p>Azure Functions should log all failures</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      [FunctionName("Foo")]
      public static async Task<IActionResult> Run(
      [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
      ILogger log)
      {
      try
      {
      	// do stuff that can fail
      }
      catch (Exception ex)
      {
      	// the failure is not logged at all OR is logged at DEBUG/TRACE level
      }
      }
      ```

      ```csharp Fix theme={null}
      [FunctionName("Foo")]
      public static async Task<IActionResult> Run(
      [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
      ILogger log)
      {
      try
      {
      	// do stuff that can fail
      }
      catch (Exception ex)
      {
      	log.LogError(ex, "Give details that will help investigations");
      }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Obsolete attributes should include explanations">
    <div class="paragraph">
      <p>"Obsolete" attributes should include explanations</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      public class Car
      {

      [Obsolete]  // Noncompliant
      public void CrankEngine(int turnsOfCrank)
      { ... }
      }
      ```

      ```csharp Fix theme={null}
      public class Car
      {

      [Obsolete("Replaced by the automatic starter")]
      public void CrankEngine(int turnsOfCrank)
      { ... }
      }
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Integral numbers should not be shifted by zero or more than their number of bits-1">
    <div class="paragraph">
      <p>Integral numbers should not be shifted by zero or more than their number of bits-1</p>
    </div>

    <CodeGroup>
      ```csharp Bad theme={null}
      var number = 14;         // ...01110 (14)
      var left = number << 1;  // ...11100 (28) 
      var right = number >> 1; // ...00111 (7)
      ```

      ```csharp Fix theme={null}
      var one =         0b0_00001;
      var thirtyThree = 0b1_00001; // Same five low-order bits, 33 % 32 = 1

      var shifted1 = 42 << one;           // Results in 84
      var shifted2 = 42 << thirtyThree;   // Results in 84
      ```
    </CodeGroup>
  </Accordion>
</AccordionGroup>
