> ## 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.

# Vbnet

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

    <div class="paragraph">
      <p>In Visual Basic, there are two explicit conversion operators:</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Public Sub Method(Value As Object)
      Dim i As Integer
      i = DirectCast(Value, Integer)  ' Direct casting from object holding an integer type to Integer
      i = CType(Value, Integer)       ' Conversion from the underlying type to Integer
      End Sub
      ```

      ```vbnet Fix theme={null}
      Public Interface IMyInterface
      End Interface

      Public Class Implementer
      Implements IMyInterface
      End Class

      Public Class AnotherClass
      End Class

      Module Program
      Sub Main()
          Dim Another As New AnotherClass
          Dim x As IMyInterface = DirectCast(Another, IMyInterface)   ' Noncompliant: InvalidCastException is being thrown
      End Sub
      End Module
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Return statements should be used instead of assigning values to function names">
    <div class="paragraph">
      <p>Functions can return values using two different syntaxes. The modern, and correct, way to do it is to use a \`Return statement. The VB6 way, i.e. old way, is to assign a return value to the function’s name .</p>
    </div>

    <div class="paragraph">
      <p>The VB6 syntax is obsolete as it was introduced to simplify migration from VB6 projects. The compiler will create a local variable which is implicitly returned when execution exits the function’s scope.</p>
    </div>

    <div class="paragraph">
      <p>Return\` statement should be used instead as they are easier to read and understand.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Public Function FunctionName() As Integer
      FunctionName = 42 ' Noncompliant
      End Function

      Public Function FunctionNameFromVariable() As Integer
      Dim Value As Integer = 42
      FunctionNameFromVariable = Value ' Noncompliant
      End Function
      ```

      ```vbnet Fix theme={null}
      Public Function FunctionName() As Integer
      Return 42
      End Function

      Public Function FunctionNameFromVariable() As Integer
      Dim Value As Integer = 42
      Return Value
      End Function
      ```
    </CodeGroup>
  </Accordion>

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

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Class SurroundingClass
      Public Sub Base()
          Method(New String() { "s1", "s2" }) ' Noncompliant: unnecessary
          Method(New String(12) {}) ' Compliant
      End Sub

      Public Sub Method(ParamArray args As String())
          ' Do something
      End Sub
      End Class
      ```

      ```vbnet Fix theme={null}
      Class SurroundingClass
      Public Sub Base()
          Method("s1", "s2")
          Method(New String(12) {})
      End Sub

      Public Sub Method(ParamArray args As String())
          ' Do something
      End Sub
      End Class
      ```
    </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 evaluate the second argument of the operator if it is not needed to determine the result of the operation.</p>
    </div>

    <div class="paragraph">
      <p>VB.NET provides logical operators that implement short-circuiting evaluations AndAlso and OrElse, as well as the non-short-circuiting versions And and Or. Unlike short-circuiting operators, the non-short-circuiting operators evaluate both operands and afterward perform the logical operation.</p>
    </div>

    <div class="paragraph">
      <p>For example False AndAlso FunctionCall always results in False even when the FunctionCall invocation would raise an exception. In contrast, False And FunctionCall also evaluates FunctionCall, and results in an exception if FunctionCall raises an exception.</p>
    </div>

    <div class="paragraph">
      <p>Similarly, True OrElse 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>
      ```vbnet Bad theme={null}
      If GetTrue() Or GetFalse() Then ' Noncompliant: both sides evaluated
      End If
      ```

      ```vbnet Fix theme={null}
      If GetTrue() OrElse GetFalse() Then ' Compliant: short-circuit logic used
      End If
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Expressions should not be too complex">
    <div class="paragraph">
      <p>Complex boolean expressions are hard to read and so to maintain.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      If ((condition1 AndAlso condition2) OrElse (condition3 AndAlso condition4)) AndAlso condition5) Then  'Noncompliant
      ...
      End If
      ```

      ```vbnet Fix theme={null}
      If ((MyFirstCondition() OrElse MySecondCondition()) AndAlso MyLastCondition()) Then
      ...
      End If
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Indexed properties should be named Item">
    <div class="paragraph">
      <p>In most cases, indexed properties should be named Item for consistency. Exceptions are when there exists a name which is obviously better, for example <code>System.String.Chars(System.Int32)</code>.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Dim array = {"apple", "banana", "orange", "strawberry"}

      ReadOnly Property Foo(ByVal index As Integer)  ' Noncompliant
          Get
              Return array(index)
          End Get
      End Property
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Dim array = {"apple", "banana", "orange", "strawberry"}

      ReadOnly Property Item(ByVal index As Integer)
          Get
              Return array(index)
          End Get
      End Property
      End Module
      ```
    </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/visual-basic/programming-guide/language-features/control-flow/loop-structures">loop</a> statement 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 jump statement or a throw statement, 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/visual-basic/language-reference/statements/exit-statement">Exit</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/continue-statement">Continue</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/return-statement">Return</a></p>
        </li>

        <li>
          <p><a href="https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/throw-statement">Throw</a></p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Public Function Method(items As IEnumerable(Of Object)) As Object
      For i As Integer = 0 To 9
          Console.WriteLine(i)
          Exit For ' Noncompliant: loop only executes once
      Next

      For Each item As Object In items
          Return item ' Noncompliant: loop only executes once
      Next
      Return Nothing
      End Function
      ```

      ```vbnet Fix theme={null}
      Public Function Method(items As IEnumerable(Of Object)) As Object
      For i As Integer = 0 To 9
          Console.WriteLine(i)
      Next

      Dim item = items.FirstOrDefault()
      If item IsNot Nothing Then
          Return item
      End If
      Return Nothing
      End Function
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="With statements should be used for a series of calls to the same object">
    <div class="paragraph">
      <p>Using the <code>With</code> statement for a series of calls to the same object makes the code more readable.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Dim product = New With {.Name = "paperclips", .RetailPrice = 1.2, .WholesalePrice = 0.6, .A = 0, .B = 0, .C = 0}

      Sub Main()
          product.Name = ""           ' Noncompliant
          product.RetailPrice = 0
          product.WholesalePrice = 0
          product.A = 0
          product.B = 0
          product.C = 0
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Dim product = New With {.Name = "paperclips", .RetailPrice = 1.2, .WholesalePrice = 0.6, .A = 0, .B = 0, .C = 0}

      Sub Main()
          With product
              .Name = ""
              .RetailPrice = 0
              .WholesalePrice = 0
              .A = 0
              .B = 0
              .C = 0
          End With
      End Sub
      End Module
      ```
    </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 (Shared Sub Main\` method) of an assembly using Windows Forms is not marked as STA.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Imports System.Windows.Forms

      Public Class Foo
      Shared Sub Main()
      Dim winForm As Form = New Form
      Application.Run(winForm)
      End Sub
      End Class
      ```

      ```vbnet Fix theme={null}
      Imports System.Windows.Forms

      Public Class Foo
      <STAThread()> Shared Sub Main()
      Dim winForm As Form = New Form
      Application.Run(winForm)
      End Sub
      End Class
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Non-private constants should comply with a naming convention">
    <div class="paragraph">
      <p>Shared coding conventions allow teams to collaborate efficiently. This rule checks that all non-private <code>Const</code> field names comply with the 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 cased, e.g. GetHtml</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Public Const foo = 0  ' Noncompliant
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Public Const Foo = 0  ' Compliant
      End Module
      ```
    </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 BC30451 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>
      ```vbnet Bad theme={null}
      <DebuggerDisplay("Name: {Name}")> ' Noncompliant - Name doesn't exist in this context
      Public Class Person

      Public Property FullName As String

      End Class
      ```

      ```vbnet Fix theme={null}
      <DebuggerDisplay("Name: {FullName}")>
      Public Class Person

      Public Property FullName As String

      End Class
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Events should comply with a naming convention">
    <div class="paragraph">
      <p>Shared coding conventions allow teams to collaborate efficiently. This rule checks that all even 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 cased, e.g. GetHtml</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Class Foo
      Event fooEvent() ' Noncompliant
      End Class
      ```

      ```vbnet Fix theme={null}
      Class Foo
      Event FooEvent() ' Compliant
      End Class
      ```
    </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 any string in the Throw\` statement is an exact match for the name of one of the method parameters.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Public Sub DoSomething(param As Integer, secondParam As String)
      If (param < 0) 
          Throw New Exception("param") ' Noncompliant
      End If
      If secondParam is Nothing
        Throw New Exception("secondParam should be valid") ' Noncompliant
      End If
      End Sub
      ```

      ```vbnet Fix theme={null}
      Public Sub DoSomething(param As Integer, secondParam As String)
      If (param < 0) 
          Throw New Exception(NameOf(param))
      End If
      If secondParam is Nothing
        Throw New Exception($"{NameOf(secondParam)} should be valid")
      End If
      End Sub
      ```
    </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>
      ```vbnet Bad theme={null}
      <TestMethod>
      Public Sub SomeTest()
      Threading.Thread.Sleep(500) ' Noncompliant
      ' assertions...
      End Sub
      ```

      ```vbnet Fix theme={null}
      <TestMethod>
      Public Async Function SomeTest() As Task
      Await Task.Delay(500)
      ' assertions...
      End Function
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Exceptions should not be created without being thrown">
    <div class="paragraph">
      <p>Creating a new <code>Exception</code> without actually throwing it is useless and is probably due to a mistake.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      If x < 0 Then
      Dim ex = New ArgumentException("x must be nonnegative")
      End If
      ```

      ```vbnet Fix theme={null}
      If x < 0 Then
      Throw New ArgumentException("x must be nonnegative")
      End If
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Value types should implement IEquatable<T>">
    <div class="paragraph">
      <p>If you’re using a Structure, 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>
      ```vbnet Bad theme={null}
      Structure MyStruct ' Noncompliant

      Public Property Value As Integer

      End Structure
      ```

      ```vbnet Fix theme={null}
      Structure MyStruct
      Implements IEquatable(Of MyStruct)

      Public Property Value As Integer

      Public Overloads Function Equals(other As MyStruct) As Boolean Implements IEquatable(Of MyStruct).Equals
          ' ...
      End Function

      End Structure
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Exit statements should not be used">
    <div class="paragraph">
      <p>Other than \`Exit Select, using an Exit statement is never a good idea.</p>
    </div>

    <div class="paragraph">
      <p>Exit Do, Exit For, Exit Try, and Exit While will all result in unstructured control flow, i.e. spaghetti code.</p>
    </div>

    <div class="paragraph">
      <p>Exit Function, Exit Property, and Exit Sub are all poor, less-readable substitutes for a simple return, and if used with code that should return a value (Exit Function and in some cases Exit Property) they could result in a NullReferenceException.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue for all uses of Exit  except Exit Select and Exit Do\` statements in loops without condition.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Public Class Sample
      Dim condition As Boolean

      Public Sub MySub()
      If condition Then
        Exit Sub                  ' Noncompliant
      End If

      For index = 1 To 10
        If index = 5 Then
            Exit For               ' Noncompliant
        End If
        ' ...
      Next
      End Sub
      Function MyFunction() As Object
      ' ...
      MyFunction = 42
      Exit Function              ' Noncompliant
      End Function
      End Class
      ```

      ```vbnet Fix theme={null}
      Public Class Sample
      Dim condition As Boolean

      Public Sub MySub()
      If condition Then
          Return
      End If

      For index = 1 To 4
          ' ...
      Next
      End Sub
      Function MyFunction() As Object
      ' ...
      Return 42
      End Function
      End Class
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Signed types should be preferred to unsigned ones">
    <div class="paragraph">
      <p>Unsigned integers have different arithmetic operators than signed ones - operators that few developers understand. Therefore, signed types should be preferred where possible.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Sub Main()
          Dim foo1 As UShort   ' Noncompliant
          Dim foo2 As UInteger ' Noncompliant
          Dim foo3 As ULong    ' Noncompliant
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Sub Main()
          Dim foo1 As Short
          Dim foo2 As Integer
          Dim foo3 As Long   
      End Sub
      End Module
      ```
    </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/visual-basic/programming-guide/language-features/operators-and-expressions/logical-and-bitwise-operators#bitwise-operations">bitwise operations</a> are not needed and should not be performed because their results are predictable.</p>
    </div>

    <div class="paragraph">
      <p>Specifically, using And -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/visual-basic/programming-guide/language-features/data-types/numeric-data-types">numeric data type</a> supporting negative numbers, such as Integer or Long, is based on <a href="https://en.wikipedia.org/wiki/Two%27s_complement">two’s complement</a> and made of all 1s: \&B111…​111.</p>
    </div>

    <div class="paragraph">
      <p>Performing And between a value and \&B111…​111 means applying the And 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>
      ```vbnet Bad theme={null}
      anyValue And -1 ' Noncompliant
      anyValue        ' Compliant
      ```

      ```vbnet Fix theme={null}
      anyValue Or 0 ' Noncompliant
      anyValue      ' Compliant
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="ToString() method should not return Nothing">
    <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, overriding the ToString method should never return Nothing because it breaks the method’s implicit contract, and as a result the consumer’s expectations.</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Public Overrides Function ToString() As String
      Return Nothing ' Noncompliant
      End Function
      ```

      ```vbnet Fix theme={null}
      Public Overrides Function ToString() As String
      Return ""
      End Function
      ```
    </CodeGroup>
  </Accordion>

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

    <div class="paragraph">
      <p>The default configuration is:</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 cased, e.g. GetHtml</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Class Foo
      Public Shared ReadOnly foo As Integer  ' Noncompliant
      End Class
      ```

      ```vbnet Fix theme={null}
      Class Foo
      Public Shared ReadOnly Foo As Integer  ' Compliant
      End Class
      ```
    </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/visual-basic/language-reference/operators/bit-shift-operators">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/visual-basic/programming-guide/language-features/data-types/implicit-and-explicit-conversions">implicit conversion</a> to int. However, when the left operand is an object, the compiler’s type checking is turned off, therfore you can pass anything to the right of a shift operator and have it compile. If the argument can’t be implicitly converted to int at runtime, a <a href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.csharp.runtimebinder.runtimebinderexception">RuntimeBinderException</a> will be raised.</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Dim o As Object = 5
      Dim x As Integer = 5

      x = o >> 5 ' Noncompliant
      x = x << o ' Noncompliant
      ```

      ```vbnet Fix theme={null}
      x = Nothing >> 5
      x = 5 << Nothing
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Identical expressions should not be used on both sides of a binary operator">
    <div class="paragraph">
      <p>Using the same value on either side of a binary operator is almost always a mistake. In the case of logical operators, it is either a copy/paste error and therefore a bug, or it is simply wasted code, and should be simplified. In the case of most binary mathematical operators, having the same value on both sides of an operator yields predictable results, and should be simplified.</p>
    </div>

    <div class="paragraph">
      <p>This rule ignores <code>\*, +, &, \<\<,  and >></code>.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      If (a = a) Then
      doZ()
      End If

      If a = b OrElse a = b Then 
      doW()
      End If

      Dim j = 5 / 5
      j = 5 \ 5 
      j = 5 Mod 5 
      Dim k = 5 - 5

      Dim i = 42
      i /= i 
      i -= i
      ```

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

  <Accordion title="Array literals should be used instead of array creation expressions">
    <div class="paragraph">
      <p>Array literals are more compact than array creation expressions.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Sub Main()
          Dim foo = New String() {"a", "b", "c"} ' Noncompliant
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Sub Main()
          Dim foo = {"a", "b", "c"}              ' Compliant
      End Sub
      End Module
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="IIf should not be used">
    <div class="paragraph">
      <p>Visual Basic .NET offers a non-short-circuit conditional function, \`IIf(), which returns either its second or third parameter based on the expression in the first parameter. Using it is slower than using If() because each parameter is unconditionally evaluated. Further, its use can lead to runtime exceptions because IIf always evaluates all three of its arguments.</p>
    </div>

    <div class="paragraph">
      <p>The newer version, If()\`, should be used instead because it short-circuits the evaluation of its parameters.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Public Class Foo
      Public Sub Bar() 
          Dim var As Object = IIf(Date.Now.Year = 1999, "Lets party!", "Lets party like it is 1999!") ' Noncompliant
      End Sub 
      End Class
      ```

      ```vbnet Fix theme={null}
      Public Class Foo 
      Public Sub Bar() 
          Dim var As String = If(Date.Now.Year = 1999, "Lets party!", "Lets party like it is 1999!") 
      End Sub 
      End Class
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Related If/ElseIf statements should not have the same condition">
    <div class="paragraph">
      <p>A chain of <a href="https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/if-then-else-statement">If/ElseIf</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>
      ```vbnet Bad theme={null}
      If param = 1 Then
      OpenWindow()
      ElseIf param = 2 Then
      CloseWindow()
      ElseIf param = 1 Then ' Noncompliant: condition has already been checked
      MoveWindowToTheBackground() ' unreachable code
      End If
      ```

      ```vbnet Fix theme={null}
      If param = 1 Then
      OpenWindow()
      ElseIf param = 2 Then
      CloseWindow()
      ElseIf param = 3 Then
      MoveWindowToTheBackground()
      End If
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Non-existent operators like =+ should not be used">
    <div class="paragraph">
      <p>Using operator pairs (<code>=+ or =-) that look like reversed single operators (+= or -=</code>) is confusing. They compile and run but do not produce the same result as their mirrored counterpart.</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Dim target As Integer = -5
      Dim num As Integer = 3

      target =- num ' Noncompliant: target = -3. Is that the intended behavior?
      target =+ num ' Noncompliant: target = 3
      ```

      ```vbnet Fix theme={null}
      Dim num As Integer = 3

      target -= num  ' target = -8
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Method parameters should follow a naming convention">
    <div class="paragraph">
      <p>Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate.</p>
    </div>

    <div class="paragraph">
      <p>This rule allows to check that all parameter 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>Camel casing, starting with a lower case character, e.g. backColor</p>
        </li>

        <li>
          <p>Short abbreviations of 2 letters can be capitalized only when not at the beginning, e.g. id, productID</p>
        </li>

        <li>
          <p>Longer abbreviations need to be lower cased, e.g. html</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Sub GetSomething(ByVal ID As Integer) ' Noncompliant
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Sub GetSomething(ByVal id As Integer) ' Compliant
      End Sub
      End Module
      ```
    </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>
      ```vbnet Bad theme={null}
      If Collection.Count >= 0 Then ... 'Noncompliant always true

      If array.Length >= 0 Then ... 'Noncompliant always true
      ```

      ```vbnet Fix theme={null}
      If Enumerable.Count < 0 Then ... 'Noncompliant always false

      Dim result As Boolean = Array.Length >= 0 'Noncompliant always true
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="CType should be used for casting and explicit conversions">
    <div class="paragraph">
      <p>For the sake of backward compatibility, Visual Basic .NET continues to offer a set of functions that convert from Object to different primitive types: <code>CChar, CStr, CBool, CDate, CSng, CDbl, CDec, CByte, CSByte, CShort, CUShort, CInt, CUInt, CLng, CULng. However, using these functions is misleading, because it suggests a cast. It is better to cast explicitly using CType(), or use Convert.To()</code> when the value should be converted.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Public Class Foo
      Public Sub Bar(value as Object)
          Dim stringValue As String = CStr(value)
      End Sub
      End Class
      ```

      ```vbnet Fix theme={null}
      Public Class Foo
      Public Sub Bar(value as Object)
          Dim stringValue As String = CType(value, String)
      End Sub
      End Class
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Method parameters and caught exceptions should not be reassigned">
    <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 should be, if not treated as <code>readonly</code> then at least read before reassignment.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Sub Foo(ByVal a As Integer)
          a = 42                  ' Noncompliant
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Sub Foo(ByVal a As Integer)
          Dim tmp = a
          tmp = 42
      End Sub
      End Module
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="If ... ElseIf constructs should end with Else clauses">
    <div class="paragraph">
      <p>This rule applies whenever an \`If statement is followed by one or more ElseIf statements; the final ElseIf 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 Case Else clause in a Select Case\` statement.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      If x = 0 Then
      DoSomething()
      ElseIf x = 1 Then
      DoSomethingElse()
      End If
      ```

      ```vbnet Fix theme={null}
      If x = 0 Then
      DoSomething()
      ElseIf x = 1 Then
      DoSomethingElse()
      Else
      Throw New ArgumentException("...")
      End If
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="ByVal should not be used">
    <div class="paragraph">
      <p>Since Visual Studio 2010 SP1, the <code>ByVal</code> parameter modifier is implicitly applied, and therefore not required anymore. Removing it from your source code will improve readability.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Sub Foo(ByVal bar As String)
      ' ...
      End Sub
      ```

      ```vbnet Fix theme={null}
      Sub Foo(bar As String)
      ' ...
      End Sub
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Event handlers should comply with a naming convention">
    <div class="paragraph">
      <p>Shared coding conventions allow teams to collaborate efficiently. This rule checks that all even handler names match a provided regular expression.</p>
    </div>

    <div class="paragraph">
      <p>The default configuration is:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Either in Pascal case, i.e. starting with an upper case letter, e.g. OnMyButtonClicked</p>
        </li>

        <li>
          <p>Or, a subject, in Pascal or camel case, followed by an underscore followed by an event name, in Pascal case, e.g. btn1\_Clicked</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Event handlers with a <code>handles clause and two-parameter methods with EventArgs</code> second parameter are covered by this rule.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Sub subject__SomeEvent() Handles X.SomeEvent   ' Noncompliant - two underscores
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Sub subject_SomeEvent() Handles X.SomeEvent    ' Compliant
      End Sub
      End Module
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="The & operator should be used to concatenate strings">
    <div class="paragraph">
      <p>Consistently using the \`& operator for string concatenation make the developer intentions clear.</p>
    </div>

    <div class="paragraph">
      <p>&, unlike +, will convert its operands to strings and perform an actual concatenation.</p>
    </div>

    <div class="paragraph">
      <p>+\` on the other hand can be an addition, or a concatenation, depending on the operand types.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Sub Main()
          Console.WriteLine("1" + 2) ' Noncompliant - will display "3"
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Sub Main()
          Console.WriteLine(1 & 2)   ' Compliant - will display "12"
          Console.WriteLine(1 + 2)   ' Compliant - but will display "3"
          Console.WriteLine("1" & 2) ' Compliant - will display "12"
      End Sub
      End Module
      ```
    </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 enum 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>
      ```vbnet Bad theme={null}
      Public Enum foo ' Noncompliant
      FooValue = 0
      End Enum
      ```

      ```vbnet Fix theme={null}
      <Flags()>
      Public Enum Option ' Noncompliant
      None = 0,
      Option1 = 1,
      Option2 = 2
      End Enum
      ```
    </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>
      ```vbnet Bad theme={null}
      Imports System.Runtime.CompilerServices

      Module MyExtensions
      <Extension>
      Sub SomeExtension(obj As Object) ' Noncompliant
          ' ...
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      ```
    </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>
      ```vbnet 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
      End Enum
      ```

      ```vbnet Fix theme={null}
      <Flags()>
      Enum Days
      ' ...
      None = 0                                                        ' 0b00000000
      Weekdays = Monday Or Tuesday Or Wednesday Or Thursday Or Friday ' 0b00011111
      Weekend = Saturday Or Sunday                                    ' 0b01100000
      All = Weekdays Or Weekend                                       ' 0b01111111
      End Enum
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Not boolean operator should not be repeated">
    <div class="paragraph">
      <p>The repetition of the  <code>Not</code> operator is usually a typo. The second operator invalidates the first one:</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Dim b As Boolean = False
      Dim c As Boolean = Not Not b 'Noncompliant: equivalent to "b"
      ```

      ```vbnet Fix theme={null}
      ```
    </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>
      ```vbnet Bad theme={null}
      Public Sub DoSomething(ByVal strings As List(Of String))
      Dim sb As StringBuilder = New StringBuilder() ' Noncompliant
      sb.Append("Got: ")

      For Each str As String In strings
          sb.Append(str).Append(", ")
      Next
      End Sub
      ```

      ```vbnet Fix theme={null}
      Public Sub DoSomething(ByVal strings As List(Of String))
      For Each str As String In strings
      Next
      End Sub
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Line continuations should not be used">
    <div class="paragraph">
      <p>To improve the code readability, the explicit line continuation character, <code>\_</code>, should not be used. Instead, it is better to break lines after an operator.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Sub Main()
          ' Noncompliant
          Console.WriteLine("Hello" _
                            & "world")
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Sub Main()

          Console.WriteLine("Hello" &
                            "world")
      End Sub
      End Module
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Control flow statements If, For, For Each, Do, While, Select and Try should not be nested too deeply">
    <div class="paragraph">
      <p>Nested control flow statements <code>If, Select, For, For Each, 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>
      ```vbnet Bad theme={null}
      If condition1 ' Compliant - depth = 1
      ' ...
      If condition2 ' Compliant - depth = 2
      ' ...
      For i = 0 to 10 ' Compliant - depth = 3, not exceeding the limit
        ' ...
        If condition4 ' Noncompliant - depth = 4 
          If condition5 ' Depth = 5, exceeding the limit, but issues are only reported on depth = 4
            ' ...
          End If
          Return
        End If
      Next
      End If
      End If
      ```

      ```vbnet Fix theme={null}
      ```
    </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>
      ```vbnet Bad theme={null}
      Function NthFibonacciNumber(ByVal n As Integer) As Integer
      If n <= 1 Then
          Return 1
      Else
          Return NthFibonacciNumber(n - 1) + NthFibonacciNumber(n - 2)
      End If
      End Function
      ```

      ```vbnet Fix theme={null}
      Function NthFibonacciNumber(ByVal n As Integer) As Integer
      Dim previous As Integer = 0
      Dim last As Integer = 1

      For i = 0 To n - 1
          Dim temp = previous
          previous = last
          last = last + temp
      Next

      Return last
      End Function
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="catch clauses should do more than rethrow">
    <div class="paragraph">
      <p>A Catch clause that only rethrows the caught exception has the same effect as omitting the Catch altogether and letting it bubble up automatically.</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Dim s As String = ""
      Try
      s = File.ReadAllText(fileName)
      Catch e As Exception
      Throw
      End Try
      ```

      ```vbnet Fix theme={null}
      Dim s As String = File.ReadAllText(fileName)
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Private Shared ReadOnly fields should comply with a naming convention">
    <div class="paragraph">
      <p>Shared coding conventions allow teams to collaborate efficiently. This rule checks that all \`Private Shared ReadOnly field names comply with the provided regular expression.</p>
    </div>

    <div class="paragraph">
      <p>The default configuration is:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Optionally, can start with an underscore character or "s\_", e.g. \_foo, s\_foo\`</p>
        </li>

        <li>
          <p>Camel casing, starting with a lower case character, e.g. backColor</p>
        </li>

        <li>
          <p>Short abbreviations of 2 letters can be capitalized only when not at the beginning, e.g. "id" in productID</p>
        </li>

        <li>
          <p>Longer abbreviations need to be lower cased, e.g. html</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Class Foo
      Private Shared ReadOnly Foo As Integer  ' Noncompliant
      End Class
      ```

      ```vbnet Fix theme={null}
      Class Foo
      Private Shared ReadOnly foo As Integer  ' Compliant
      End Class
      ```
    </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 Nothing.</p>
    </div>

    <div class="paragraph">
      <p>The value stored 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 Nothing. A nullable type should always be tested before accessing the value to avoid raising exceptions.</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Sub Sample(condition As Boolean)
      Dim nullableValue As Integer? = If(condition, 42, Nothing)
      Console.WriteLine(nullableValue.Value)             ' Noncompliant: InvalidOperationException is raised

      Dim nullableCast As Integer? = If(condition, 42, Nothing)
      Console.WriteLine(CType(nullableCast, Integer))    ' Noncompliant: InvalidOperationException is raised
      End Sub
      ```

      ```vbnet Fix theme={null}
      Sub Sample(condition As Boolean)
      Dim nullableValue As Integer? = If(condition, 42, Nothing)
      If nullableValue.HasValue Then
          Console.WriteLine(nullableValue.Value)
      End If
              
      Dim nullableCast As Integer? = If(condition, 42, Nothing)
      If nullableCast.HasValue Then
          Console.WriteLine(CType(nullableCast, Integer))
      End If
      End Sub
      ```
    </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 not be caught and let to propagate up the stack trace so that they can be dealt with appropriately. When a generic 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 generic 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>
      ```vbnet Bad theme={null}
      Public Sub DoSomething(obj As Object)
      If obj Is Nothing Then
      ' Noncompliant
      Throw New NullReferenceException("obj") ' Noncompliant: This reserved exception should not be thrown manually
      End If
      ' ...
      End Sub
      ```

      ```vbnet Fix theme={null}
      Public Sub DoSomething(obj As Object)
      If obj Is Nothing Then
      Throw New ArgumentNullException("obj") ' Compliant: this is a specific and non-reserved exception type
      End If
      ' ...
      End Sub
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Properties should comply with a naming convention">
    <div class="paragraph">
      <p>Shared coding conventions allow teams to collaborate efficiently. This rule checks that property 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 cased, e.g. GetHtml</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Public Property foo As Integer   ' Noncompliant
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Public Property Foo As Integer   ' Compliant
      End Module
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Property procedures 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 property procedures 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 the property procedures.</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Class C
      Private _x As Integer
      Private _Y As Integer

      Public ReadOnly Property Y As Integer
          Get
              Return _x ' Noncompliant: The returned field should be '_y'
          End Get
      End Property
      End Class
      ```

      ```vbnet Fix theme={null}
      Public Class Sample

      Private _x As Integer
      Private _y As Integer

      Public Property Y As Integer
          Get
              Return _x   ' Noncompliant: field '_y' is not used in the return value
          End Get
          Set(value As Integer)
              _x = value  ' Noncompliant: field '_y' is not updated
          End Set
      End Property

      End Class
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="End statements should not be used">
    <div class="paragraph">
      <p><code>End statements exit the control flow of the program in an unstructured way. This statement stops code execution immediately without executing Dispose or Finalize methods, or executing Finally</code> blocks. Therefore, it should be avoided.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Sub Print(ByVal str As String)
         Try
              ...
              End       ' Noncompliant
          Finally
              ' do something important here
              ...
          End Try
      End Sub
      End Module
      ```

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

  <Accordion title="Non-private fields should comply with a naming convention">
    <div class="paragraph">
      <p>Shared coding conventions allow teams to collaborate efficiently. This rule checks that all non-private fields names match a provided regular expression.</p>
    </div>

    <div class="paragraph">
      <p>Note that this rule does not apply to non-private <code>Shared ReadOnly</code> fields, for which there is another rule.</p>
    </div>

    <div class="paragraph">
      <p>The default configuration is:</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 cased, e.g. GetHtml</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Class Foo
      Public foo As Integer  ' Noncompliant
      End Class
      ```

      ```vbnet Fix theme={null}
      Class Foo
      Public Foo As Integer  ' Compliant
      End Class
      ```
    </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>
      ```vbnet 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"
      ```

      ```vbnet Fix theme={null}
      strings.Contains(someString) ' Boolean result
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Select Case statements should not have too many Case clauses">
    <div class="paragraph">
      <p>When <a href="https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/select-case-statement">Select Case</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>
      ```vbnet Bad theme={null}
      Public Class TooManyCase

      Public Function MapValues(Ch As Char) As Integer 
          Select Case Ch ' Noncompliant: 5 cases, "Case Else" excluded, more than maximum = 4
              Case "a"c
                  Return 1
              Case "b"c, "c"c
                  Return 2
              Case "d"c
                  Return 3
              Case "e"c
                  Return 4
              Case "f"c, "g"c, "h"c
                  Return 5
              Case Else
                  Return 6
          End Select
      End Function

      End Class
      ```

      ```vbnet Fix theme={null}
      Public Class TooManyCase

      Private fMatching As New Dictionary(Of Char, Integer) From {
              { "a"c, 1 }, 
              { "b"c, 2 }, 
              { "c"c, 2 }, 
              { "d"c, 3 },
              { "e"c, 4 }, 
              { "f"c, 5 }, 
              { "g"c, 5 }, 
              { "h"c, 5 },
          }

      Public Function MapValues(Ch As Char) As Integer
          Dim Value As Integer
          If fMatching.TryGetValue(Ch, Value) Then
              Return Value
          Else
              Return 6
          End If
      End Function

      End Class
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="GoTo statements should not be used">
    <div class="paragraph">
      <p><code>GoTo is an unstructured control flow statement. It makes code less readable and maintainable. Structured control flow statements such as If, For, While,  or Exit</code> should be used instead.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Sub GoToStatementDemo()
          Dim number As Integer = 1
          Dim sampleString As String
          ' Evaluate number and branch to appropriate label.
          If number = 1 Then GoTo Line1 Else GoTo Line2
      Line1:
          sampleString = "Number equals 1"
          GoTo LastLine
      Line2:
          ' The following statement never gets executed because number = 1.
          sampleString = "Number equals 2"
      LastLine:
          ' Write "Number equals 1" in the Debug window.
          Debug.WriteLine(sampleString)
      End Sub
      ```

      ```vbnet Fix theme={null}
      Sub GoToStatementDemo()
          Dim number As Integer = 1
          Dim sampleString As String
          ' Evaluate number and branch to appropriate label.
          If number = 1 Then
              sampleString = "Number equals 1"
          Else
              sampleString = "Number equals 2"
          End If
          Debug.WriteLine(sampleString)
      End Sub
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Private constants should comply with a naming convention">
    <div class="paragraph">
      <p>Shared coding conventions allow teams to collaborate efficiently. This rule checks that all \`Private Const field names comply with the provided regular expression.</p>
    </div>

    <div class="paragraph">
      <p>The default configuration is:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Optionally, can start with an underscore character or "s\_", e.g. \_foo, s\_foo\`</p>
        </li>

        <li>
          <p>Camel casing, starting with a lower case character, e.g. backColor</p>
        </li>

        <li>
          <p>Short abbreviations of 2 letters can be capitalized only when not at the beginning, e.g. "id" in productID</p>
        </li>

        <li>
          <p>Longer abbreviations need to be lower cased, e.g. html</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Private Const Foo = 0  ' Noncompliant
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Private Const foo = 0  ' Compliant
      End Module
      ```
    </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>
      ```vbnet Bad theme={null}
      Module Module1
      Public Const AAA As Integer = 5, BBB = 42, CCC As String = "foo"  ' Noncompliant
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Public Const AAA As Integer = 5
      Public Const BBB = 42
      Public Const CCC as String = "foo"
      End Module
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Any() should be used to test for emptiness">
    <div class="paragraph">
      <p>Using .Count() to test for emptiness works, but using .Any() makes the intent clearer, and the code more readable. However, there are some cases where special attention should be paid:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>if the collection is an EntityFramework or other ORM query, calling .Count() will cause executing a potentially massive SQL query and could put a large overhead on the application database. Calling .Any() will also connect to the database, but will generate much more efficient SQL.</p>
        </li>

        <li>
          <p>if the collection is part of a LINQ query that contains .Select() statements that create objects, a large amount of memory could be unnecessarily allocated. Calling .Any() will be much more efficient because it will execute fewer iterations of the enumerable.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Private Function HasContent(Strings As IEnumerable(Of String)) As Boolean
      Return Strings.Count() > 0      ' Noncompliant
      End Function

      Private Function HasContent2(Strings As IEnumerable(Of String)) As Boolean
      Return Strings.Count() >= 1     ' Noncompliant
      End Function

      Private Function IsEmpty(Strings As IEnumerable(Of String)) As Boolean
      Return Strings.Count() = 0      ' Noncompliant
      End Function
      ```

      ```vbnet Fix theme={null}
      Private Function HasContent(Strings As IEnumerable(Of String)) As Boolean
      Return Strings.Any
      End Function

      Private Function HasContent2(Strings As IEnumerable(Of String)) As Boolean
      Return Strings.Any
      End Function

      Private Function IsEmpty(Strings As IEnumerable(Of String)) As Boolean
      Return Not Strings.Any
      End Function
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Select...Case clauses should not have too many lines of code">
    <div class="paragraph">
      <p>The <code>Select...Case</code> 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 clause should be extracted into a dedicated procedure.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Select Case number
      Case 1 To 5 ' Noncompliant: 4 statements in the case
          MethodCall1("")
          MethodCall2("")
          MethodCall3("")
          MethodCall4("")
      Case Else
          ' ...
      End Select
      ```

      ```vbnet Fix theme={null}
      Select Case number
      Case 1 To 5
          DoSomething()
      Case Else
          ' ...
      End Select
      ...
      Sub DoSomething()
      MethodCall1("")
      MethodCall2("")
      MethodCall3("")
      MethodCall4("")
      End Sub
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Functions and procedures should comply with a naming convention">
    <div class="paragraph">
      <p>Shared naming conventions allow teams to collaborate efficiently. This rule checks that all subroutine and function 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 cased, e.g. GetHtml</p>
        </li>

        <li>
          <p>Event handlers with a handles clause and two-parameter methods with <code>EventArgs</code> second parameter are not covered by this rule.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Sub bad_subroutine()                      ' Noncompliant
      End Sub

      Public Function Bad_Function() As Integer ' Noncompliant
      Return 42
      End Function
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Sub GoodSubroutine()                      ' Compliant
      End Sub

      Public Function GoodFunction() As Integer ' Compliant
      Return 42
      End Function
      End Module
      ```
    </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 Select Case or If chain with the same implementation indicates a problem.</p>
    </div>

    <div class="paragraph">
      <p>In the following code:</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Dim b As Integer = If(a > 12, 4, 4)  // Noncompliant

      If b = 0 Then  // Noncompliant
      DoTheThing()
      Else
      DoTheThing()
      End If

      Select Case i  // Noncompliant
      Case 1
          DoSomething()
      Case 2
          DoSomething()
      Case 3
          DoSomething()
      Case Else
          DoSomething()
      End Select
      ```

      ```vbnet Fix theme={null}
      If b = 0 Then ' No issue, this could have been done on purpose to make the code more readable
      DoTheThing()
      ElseIf
      DoTheThing()
      End If
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Interface names should comply with a naming convention">
    <div class="paragraph">
      <p>Sharing some naming conventions is a key point to make it possible for a team to efficiently collaborate.</p>
    </div>

    <div class="paragraph">
      <p>This rule allows to check that all interface 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>Must start with an upper case 'I' character, e.g. IFoo</p>
        </li>

        <li>
          <p>Followed by Pascal casing, starting with an upper case character, e.g. IEnumerable</p>
        </li>

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

        <li>
          <p>Longer abbreviations need to be lower cased, e.g. IFooHtml</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Interface Foo  ' Noncompliant
      End Interface
      ```

      ```vbnet Fix theme={null}
      Interface IFoo ' Compliant
      End Interface
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Do loops should not be used without a While or Until condition">
    <div class="paragraph">
      <p>A <code>Do ... Loop without a While or Until condition must be terminated by an unstructured Exit Do</code> statement. It is safer and more readable to use structured loops instead.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Sub Main()
          Dim i = 1

          Do                        ' Non-Compliant
              If i = 10 Then
                  Exit Do
              End If

              Console.WriteLine(i)

              i = i + 1
          Loop
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Sub Main()
          For i = 1 To 9            ' Compliant
              Console.WriteLine(i)
          Next
      End Sub
      End Module
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Generic type parameter names should comply with a naming convention">
    <div class="paragraph">
      <p>Inconsistent naming conventions can lead to confusion and errors when working in a team. This rule ensures that all generic type parameter names follow a consistent naming convention by checking them against a provided regular expression.</p>
    </div>

    <div class="paragraph">
      <p>The default configuration follows Microsoft’s recommended convention:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Generic type parameter names must start with an upper case 'T', e.g. T</p>
        </li>

        <li>
          <p>The rest of the name should use Pascal casing, starting with an upper case character, e.g. TKey</p>
        </li>

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

        <li>
          <p>Longer abbreviations should be lowercased, e.g. TFooHtml</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Public Class Foo(Of tkey) ' Noncompliant
      End Class
      ```

      ```vbnet Fix theme={null}
      Public Class Foo(Of TKey) ' Compliant
      End Class
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Arguments of public methods should be validated against Nothing">
    <div class="paragraph">
      <p>Methods declared as Public, Protected, or Protected Friend can be accessed from other assemblies, which means you should validate parameters to be within the expected constraints. In general, checking against Nothing 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 Nothing before being dereferenced.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Public Class Sample

      Public Property Message As String

      Public Sub PublicMethod(Arg As Exception)
          Message = Arg.Message   ' Noncompliant
      End Sub

      Protected Sub ProtectedMethod(Arg As Exception)
          Message = Arg.Message   ' Noncompliant
      End Sub

      End Class
      ```

      ```vbnet Fix theme={null}
      Public Class Sample

      Public Property Message As String

      Public Sub PublicMethod(Arg As Exception)
          If Arg IsNot Nothing Then Message = Arg.Message   ' Noncompliant
      End Sub

      Protected Sub ProtectedMethod(Arg As Exception)
          ArgumentNullException.ThrowIfNull(Arg)
          Message = Arg.Message   ' Noncompliant
      End Sub

      Private Sub PrivateMethod(Arg As Exception)
          Message = Arg.Message   ' Compliant: method is not publicly accessible
      End Sub

      End Class
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Null checks should not be used with TypeOf Is">
    <div class="paragraph">
      <p>There’s no need to null test in conjunction with an <code>TypeOf ... Is test. Nothing</code> is not an instance of anything, so a null check is redundant.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      If (x IsNot Nothing And TypeOf x Is MyClass)
      ' ...
      End If

      If (x Is Nothing Or TypeOf x IsNot MyClass)
      ' ...
      End If
      ```

      ```vbnet Fix theme={null}
      If (TypeOf x Is MyClass)
      ' ...
      End If

      If (TypeOf x IsNot MyClass)
      ' ...
      End If
      ```
    </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>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Public Class Empty ' Noncompliant

      End Class
      ```

      ```vbnet Fix theme={null}
      Public Interface IEmpty

      End Interface
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Exit Select statements should not be used redundantly">
    <div class="paragraph">
      <p>Visual Basic .NET, unlike many other programming languages, has no "fall-through" for its <code>Select cases. Each case already has an implicit Exit Select</code> as its last instruction. It therefore is redundant to explicitly add one.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Sub Main()
      Dim x = 0
      Select Case x
        Case 0
          Console.WriteLine("0")
          Exit Select                ' Noncompliant
        Case Else
          Console.WriteLine("Not 0")
          Exit Select                ' Noncompliant
      End Select
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Sub Main()
      Dim x = 0
      Select Case x
        Case 0                         ' Compliant
          Console.WriteLine("0")
        Case Else                      ' Compliant
          Console.WriteLine("Not 0")
      End Select
      End Sub
      End Module
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Indexed properties with more than one parameter should not be used">
    <div class="paragraph">
      <p>Indexed properties are meant to represent access to a logical collection. When multiple parameters are required, this design guideline may be violated, and refactoring the property into a method is preferable.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      ReadOnly Property Sum(ByVal a As Integer, ByVal b As Integer) ' Noncompliant
          Get
              Return a + b
          End Get
      End Property
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Function Sum(ByVal a As Integer, ByVal b As Integer)          ' Compliant
          Return a + b
      End Function
      End Module
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Enumeration values should comply with a naming convention">
    <div class="paragraph">
      <p>Shared coding conventions allow teams to collaborate efficiently. This rule checks that all enumeration value 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 cased, e.g. GetHtml</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Enum Foo
      fooValue   ' Noncompliant
      End Enum
      ```

      ```vbnet Fix theme={null}
      Enum Foo
      FooValue   ' Compliant
      End Enum
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="IsNot should be used instead of Not ... Is ...">
    <div class="paragraph">
      <p>The <code>... IsNot ... syntax is more compact and more readable than the Not ... Is ...</code> syntax.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Sub Main()
          Dim a = Not "a" Is Nothing ' Noncompliant
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Sub Main()
          Dim a = "a" IsNot Nothing  ' Compliant
      End Sub
      End Module
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="On Error statements should not be used">
    <div class="paragraph">
      <p>Prefer the use of \`Try ... Catch blocks instead of On Error statements.</p>
    </div>

    <div class="paragraph">
      <p>Visual Basic .NET and Visual Basic 2005 offer structured exception handling that provides a powerful, more readable alternative to the On Error Goto error handling from previous versions of Microsoft Visual Basic. Structured exception handling is more powerful because it allows you to nest error handlers inside other error handlers within the same procedure. Furthermore, structured exception handling uses a block syntax similar to the If...Else...End If\` statement. This makes Visual Basic .NET and Visual Basic 2005 code more readable and easier to maintain.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Sub DivideByZero()
      On Error GoTo nextstep
      Dim result As Integer
      Dim num As Integer
      num = 100
      result = num / 0
      nextstep:
      System.Console.WriteLine("Error")
      End Sub
      ```

      ```vbnet Fix theme={null}
      Sub DivideByZero()
      Try
      Dim result As Integer
      Dim num As Integer
      num = 100
      result = num / 0
      Catch
      System.Console.WriteLine("Error")
      End Try
      End Sub
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Private fields should comply with a naming convention">
    <div class="paragraph">
      <p>Shared coding conventions allow teams to collaborate efficiently. This rule checks that all \`Private field names match the provided regular expression.</p>
    </div>

    <div class="paragraph">
      <p>Note that this rule does not apply to Private Shared ReadOnly fields, which are checked by another rule.</p>
    </div>

    <div class="paragraph">
      <p>The default configuration is:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>Optionally, can start with an underscore character or "s\_", e.g. \_foo, s\_foo\`</p>
        </li>

        <li>
          <p>Camel casing, starting with a lower case character, e.g. backColor</p>
        </li>

        <li>
          <p>Short abbreviations of 2 letters can be capitalized only when not at the beginning, e.g. "id" in productID</p>
        </li>

        <li>
          <p>Longer abbreviations need to be lower cased, e.g. html</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Class Foo
      Private Foo As Integer  ' Noncompliant
      End Class
      ```

      ```vbnet Fix theme={null}
      Class Foo
      Private foo As Integer  ' Compliant
      End Class
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Arrays should be initialized using the ... = {} syntax">
    <div class="paragraph">
      <p>The <code>... = \{}</code> syntax is more compact, more readable and less error-prone.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Sub Main()
      Dim foo(1) As String   ' Noncompliant
      foo(0) = "foo"
      foo(1) = "bar"
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Sub Main()
      Dim foo = {"foo", "bar"}  ' Compliant
      End Sub
      End Module
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Namespace names should comply with a naming convention">
    <div class="paragraph">
      <p>Shared coding conventions allow teams to collaborate efficiently. This rule checks that all namespace 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. Microsoft, System</p>
        </li>

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

        <li>
          <p>Longer abbreviations need to be lower cased</p>
        </li>
      </ul>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Namespace foo  ' Noncompliant
      End Namespace
      ```

      ```vbnet Fix theme={null}
      Namespace Foo  ' Compliant
      End Namespace
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Strings should not be concatenated using + or & 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>
      ```vbnet Bad theme={null}
      Module Module1
      Sub Main()
          Dim foo = ""
          foo &= "Result: "       ' Compliant - outside of loop

          For i = 1 To 9
              foo &= i            ' Noncompliant
          Next
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Sub Main()
          Dim foo = New System.Text.StringBuilder
          foo.Append("Result: ")  ' Compliant

          For i = 1 To 9
              foo.Append(i)       ' Compliant
          Next
      End Sub
      End Module
      ```
    </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 numbers beyond those bounds, and the result will be an OverflowException. When the compilation is configured to remove integer overflow checking, the value will be silently wrapped around from the expected positive value to a negative one, or vice versa.</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Public Function Transform(Value As Integer) As Integer
      If Value <= 0 Then Return Value
      Dim Number As Integer = Integer.MaxValue
      Return Number + Value       ' Noncompliant
      End Function
      ```

      ```vbnet Fix theme={null}
      Public Function Transform(Value As Integer) As Long
      If Value <= 0 Then Return Value
      Dim Number As Long = Integer.MaxValue
      Return Number + Value
      End Function
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Array.Empty(Of TElement) should be used to instantiate empty arrays">
    <div class="paragraph">
      <p>Method for creating empty arrays <code>Array.Empty(Of 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>
      ```vbnet Bad theme={null}
      Public Sub Method()
      Dim Values1(-1) As Integer ' Noncompliant
      Dim Values2 As Integer() = New Integer() {} ' Noncompliant
      Dim Values3 As Integer() = {} ' Noncompliant
      Dim Values4() As Integer = {} ' Noncompliant
      End Sub
      ```

      ```vbnet Fix theme={null}
      Public Sub Method()
      Dim Values1 As Integer() = Array.Empty(Of Integer)
      Dim Values2 As Integer() = Array.Empty(Of Integer)
      Dim Values3 As Integer() = Array.Empty(Of Integer)
      Dim Values4() As Integer = Array.Empty(Of Integer)
      End Sub
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Select statements should end with a Case Else clause">
    <div class="paragraph">
      <p>The requirement for a final <code>Case Else</code> clause is defensive programming.</p>
    </div>

    <div class="paragraph">
      <p>This clause should either take appropriate action or contain a suitable comment as to why no action is taken.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Select Case param ' Noncompliant - Case Else clause is missing
      Case 0
      DoSomething()
      Case 1
      DoSomethingElse()
      End Select
      ```

      ```vbnet Fix theme={null}
      Select Case param
      Case 0
      DoSomething()
      Case 1
      DoSomethingElse()
      Case Else ' Compliant
      DoSomethingElse()
      End Select
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Select Case statements should not be nested">
    <div class="paragraph">
      <p>Nested \`Select Case structures are difficult to understand because you can easily confuse the cases of an inner Select Case as belonging to an outer statement. Therefore nested Select Case statements should be avoided.</p>
    </div>

    <div class="paragraph">
      <p>Specifically, you should structure your code to avoid the need for nested Select Case statements, but if you cannot, then consider moving the inner Select Case\` to another function.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Public Sub Foo(A As Integer, B As Integer)
      Select Case A
          Case 0
              ' ...
          Case 1
              Select Case B   ' Noncompliant; nested Select Case
                  Case 2
                      ' ...
                  Case 3
                      ' ...
                  Case 4
                      ' ...
                  Case Else
                      ' ...
              End Select
          Case 2
              ' ...
          Case Else
              ' ...
      End Select
      End Sub
      ```

      ```vbnet Fix theme={null}
      Public Sub Foo(A As Integer, B As Integer)
      Select Case A
          Case 0
              ' ...
          Case 1
              HandleB(B)
          Case 2
              ' ...
          Case Else
              ' ...
      End Select
      End Sub
      ```
    </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 \`RemoveHandler.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a class subscribes to an even using AddHandler without explicitly unsubscribing with RemoveHandler\`.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Class MyEventProcucer
      Public Shared Event EventFired As EventHandler
      End Class

      Public Class MyEventSubscriber
      Implements IDisposable

      Public Sub New()
          AddHandler MyEventProcucer.EventFired, AddressOf c_EventFired  'Noncompliant
      End Sub

      Private Sub c_EventFired(sender As Object, e As EventArgs)
      End Sub

      Public Sub Dispose() Implements IDisposable.Dispose
      End Sub
      End Class
      ```

      ```vbnet Fix theme={null}
      Class MyEventProcucer
      Public Shared Event EventFired As EventHandler
      End Class

      Public Class MyEventSubscriber
      Implements IDisposable

      Public Sub New()
          AddHandler MyEventProcucer.EventFired, AddressOf c_EventFired
      End Sub

      Private Sub c_EventFired(ByVal sender As Object, ByVal e As EventArgs)
      End Sub

      Public Sub Dispose() Implements IDisposable.Dispose
          RemoveHandler MyEventProcucer.EventFired, AddressOf c_EventFired
      End Sub
      End Class
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Parameters should not be passed by reference">
    <div class="paragraph">
      <p>Passing parameters by reference requires developers to understand the subtle differences between reference and value types. It is preferable to avoid passing parameters by reference when possible.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Sub Foo(ByRef result As Integer) ' Non-Compliant
          result = 42
      End Sub

      Sub Main()
          Dim result As Integer
          Foo(result)
          Console.WriteLine(result)
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Function Foo() As Integer        ' Compliant
          Return 42
      End Function

      Sub Main()
          Dim result As Integer = Foo()
          Console.WriteLine(result)
      End Sub
      End Module
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Event names should not have Before or After as a prefix or suffix">
    <div class="paragraph">
      <p>"After" and "Before" prefixes or suffixes should not be used to indicate pre and post events. The concepts of before and after should be given to events using the present and past tense.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```vbnet Bad theme={null}
      Class Foo
      Event BeforeClose() ' Noncompliant
      Event AfterClose()  ' Noncompliant
      End Class
      ```

      ```vbnet Fix theme={null}
      Class Foo
      Event Closing()     ' Compliant
      Event Closed()      ' Compliant
      End Class
      ```
    </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>
      ```vbnet Bad theme={null}
      Public Class Foo
      Public Function HelloTime() As String
          Return $"Hello at {DateTime.UtcNow}"
      End Function
      End Class
      ```

      ```vbnet Fix theme={null}
      Public Interface IClock
      Function UtcNow() As Date
      End Interface

      Public Class Foo
      Public Function HelloTime(clock As IClock) As String
          Return $"Hello at {clock.UtcNow()}"
      End Function
      End Class

      Public Class FooTest
      Public Class TestClock
          Implements IClock
          ' implement
      End Class

      <Fact>
      Public Sub HelloTime_Gives_CorrectTime()
          Dim dateTime = New DateTime(2017, 06, 11)
          Assert.Equal((New Foo()).HelloTime(New TestClock(dateTime)), $"Hello at {dateTime}")
      End Sub
      End Class
      ```
    </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>
      ```vbnet Bad theme={null}
      Class Example
      Private obj As Object = New Object()

      Public Sub DoSomethingWithMonitor()
          Monitor.Enter(obj) ' Noncompliant: not all paths release the lock

          If IsInitialized() Then
              ' ...
              Monitor.Exit(obj)
          End If
      End Sub
      End Class
      ```

      ```vbnet Fix theme={null}
      Class Example
      Private lockObj As ReaderWriterLockSlim = New ReaderWriterLockSlim()

      Public Sub DoSomethingWithReaderWriteLockSlim()
          lockObj.EnterReadLock() ' Noncompliant: not all paths release the lock
          If IsInitialized() Then
              ' ...
              lockObj.ExitReadLock()
          End If
      End Sub
      End Class
      ```
    </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>
      ```vbnet Bad theme={null}
      If Not (a = 2) Then  // Noncompliant
      Dim b as Boolean = Not (i < 10)  // Noncompliant
      ```

      ```vbnet Fix theme={null}
      If a <> 2 Then
      Dim b as Boolean = 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>
      ```vbnet Bad theme={null}
      Sub Regexes(Input As String)
      Dim Rx As New Regex("[A")                                                       ' Noncompliant: unmatched "["
      Dim Match = Regex.Match(Input, "[A")                                            ' Noncompliant
      Dim NegativeLookahead As New Regex("a(?!b)", RegexOptions.NonBacktracking)      ' Noncompliant: negative lookahead without backtracking
      Dim NegativeLookbehind As New Regex("(?<!a)b", RegexOptions.NonBacktracking)    ' Noncompliant: negative lookbehind without backtracking
      End Sub
      ```

      ```vbnet Fix theme={null}
      Sub Regexes(Input As String)
      Dim Rx As New Regex("[A-Z]")
      Dim Match = Regex.Match(Input, "[A-Z]")
      Dim NegativeLookahead As New Regex("a(?!b)")
      Dim NegativeLookbehind As New Regex("(?<!a)b")
      End Sub
      ```
    </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>
      ```vbnet Bad theme={null}
      Dim RandomPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())

      ' Creates a new file with write, non inheritable permissions which is deleted on close.
      Using FileStream As New FileStream(RandomPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.DeleteOnClose)
      Using Writer As New StreamWriter(FileStream) ' Sensitive
      ' ...
      End Using
      End Using
      ```

      ```vbnet Fix theme={null}
      ```
    </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>
      ```vbnet Bad theme={null}
      Dim a = 0 : Dim b = 0  ' Noncompliant
      ```

      ```vbnet Fix theme={null}
      Dim a = 0
      Dim b = 0
      ```
    </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>
      ```vbnet Bad theme={null}
      Enum FooFlags ' Noncompliant
      Foo = 1
      Bar = 2
      Baz = 4
      End Enum
      ```

      ```vbnet Fix theme={null}
      Enum Foo      ' Compliant
      Foo = 1
      Bar = 2
      Baz = 4
      End Enum
      ```
    </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>
      ```vbnet Bad theme={null}
      Dim p As New Process()
      p.StartInfo.FileName = "C:\Apps\binary.exe" ' Compliant
      ```

      ```vbnet 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>
      ```vbnet Bad theme={null}
      Response.AppendHeader("Access-Control-Allow-Origin", "trustedwebsite.com") // Compliant
      ```

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

  <Accordion title="Map values should not be replaced unconditionally">
    <CodeGroup>
      ```vbnet Bad theme={null}
      towns.Item(x) = "London"
      towns.Item(x) = "Chicago";  // Noncompliant
      ```

      ```vbnet Fix theme={null}
      ```
    </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>
      ```vbnet Bad theme={null}
      <ServiceContract>
      Interface IMyService
      <OperationContract(IsOneWay:=True)>
      Function SomethingHappened(ByVal parameter As Integer) As Integer ' Noncompliant
      End Interface
      ```

      ```vbnet Fix theme={null}
      <ServiceContract>
      Interface IMyService
      <OperationContract(IsOneWay:=True)>
      Sub SomethingHappened(ByVal parameter As Integer)
      End Interface
      ```
    </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>
      ```vbnet Bad theme={null}
      Imports Microsoft.AspNetCore.Builder
      Imports Microsoft.AspNetCore.Hosting

      Namespace MyMvcApp
      Public Class Startup
          Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IHostingEnvironment)
              ' Those calls are Sensitive because it seems that they will run in production
              app.UseDeveloperExceptionPage() 'Sensitive
              app.UseDatabaseErrorPage() 'Sensitive
          End Sub
      End Class
      End Namespace
      ```

      ```vbnet Fix theme={null}
      Imports Microsoft.AspNetCore.Builder
      Imports Microsoft.AspNetCore.Hosting

      Namespace MyMvcApp
      Public Class Startup
          Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IHostingEnvironment)
              If env.IsDevelopment() Then ' Compliant 
                  ' The following calls are ok because they are disabled in production
                  app.UseDeveloperExceptionPage()
                  app.UseDatabaseErrorPage()
              End If
          End Sub
      End Class
      End Namespace
      ```
    </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>
      ```vbnet Bad theme={null}
      If BooleanMethod() = True Then ' Noncompliant
      ' ...
      End If
      If BooleanMethod() = False Then ' Noncompliant
      ' ...
      End If
      If BooleanMethod() OrElse False Then ' Noncompliant
      ' ...
      End If
      DoSomething(Not False) ' Noncompliant
      DoSomething(BooleanMethod() = True) ' Noncompliant

      Dim booleanVariable = If(BooleanMethod(), True, False) ' Noncompliant
      booleanVariable = If(BooleanMethod(), True, exp) ' Noncompliant
      booleanVariable = If(BooleanMethod(), False, exp) ' Noncompliant
      booleanVariable = If(BooleanMethod(), exp, True) ' Noncompliant
      booleanVariable = If(BooleanMethod(), exp, False) ' Noncompliant
      ```

      ```vbnet Fix theme={null}
      If BooleanMethod() Then
      ' ...
      End If
      If Not BooleanMethod() Then
      ' ...
      End If
      If BooleanMethod() Then
      ' ...
      End If
      DoSomething(True)
      DoSomething(BooleanMethod())

      Dim booleanVariable = BooleanMethod()
      booleanVariable = BooleanMethod() OrElse exp
      booleanVariable = Not BooleanMethod() AndAlso exp
      booleanVariable = Not BooleanMethod() OrElse exp
      booleanVariable = BooleanMethod() AndAlso exp
      ```
    </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>
      ```vbnet Bad theme={null}
      <Obsolete> ' Noncompliant
      Sub Procedure()
      End Sub
      ```

      ```vbnet 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>
      ```vbnet Bad theme={null}
      Module Module1
      WriteOnly Property Foo() As Integer ' Non-Compliant
          Set(ByVal value As Integer)
              ' ... some code ...
          End Set
      End Property
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Sub SetFoo(ByVal value As Integer)  ' Compliant
          ' ... some code ...
      End Sub
      End Module
      ```
    </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>
      ```vbnet Bad theme={null}
      Public Class BaseClass
      Public Overridable Sub MyMethod(ByVal Optional i As Integer = 1)
          Console.WriteLine(i)
      End Sub
      End Class

      Public Class DerivedClass
      Inherits BaseClass

      Public Overrides Sub MyMethod(ByVal Optional i As Integer = 1)
          ' ...
          MyBase.MyMethod() ' Noncompliant: caller's value is ignored
      End Sub

      Private Shared Function Main(ByVal args As String()) As Integer
          Dim dc As DerivedClass = New DerivedClass()
          dc.MyMethod(12) ' prints 1
      End Function
      End Class
      ```

      ```vbnet Fix theme={null}
      Public Class BaseClass
      Public Overridable Sub MyMethod(ByVal Optional i As Integer = 1)
          Console.WriteLine(i)
      End Sub
      End Class

      Public Class DerivedClass
      Inherits BaseClass

      Public Overrides Sub MyMethod(ByVal Optional i As Integer = 1)
          ' ...
          MyBase.MyMethod(i)
      End Sub

      Private Shared Function Main(ByVal args As String()) As Integer
          Dim dc As DerivedClass = New DerivedClass()
          dc.MyMethod(12) ' prints 12
      End Function
      End Class
      ```
    </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>
      ```vbnet Bad theme={null}
      Class Foo
      Public Foo = 42          ' Noncompliant
      End Class
      ```

      ```vbnet Fix theme={null}
      Class Foo
      Public Property Foo = 42 ' Compliant
      End Class
      ```
    </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>
      ```vbnet Bad theme={null}
      Const ThresholdRatio As Double = 10
      Const ThresholdSize As Integer = 1024 * 1024 * 1024 ' 1 GB
      Const ThresholdEntries As Integer = 10000
      Dim TotalSizeArchive, TotalEntryArchive, TotalEntrySize, Cnt As Integer
      Dim Buffer(1023) As Byte
      Using ZipToOpen As New FileStream("ZipBomb.zip", FileMode.Open), Archive As New ZipArchive(ZipToOpen, ZipArchiveMode.Read)
      For Each Entry As ZipArchiveEntry In Archive.Entries
          Using s As Stream = Entry.Open
              TotalEntryArchive += 1
              TotalEntrySize = 0
              Do
                  Cnt = s.Read(Buffer, 0, Buffer.Length)
                  TotalEntrySize += Cnt
                  TotalSizeArchive += Cnt
                  If TotalEntrySize / Entry.CompressedLength > ThresholdRatio Then Exit Do    ' Ratio between compressed And uncompressed data Is highly suspicious, looks Like a Zip Bomb Attack
              Loop While Cnt > 0
          End Using
          If TotalSizeArchive > ThresholdSize Then Exit For       ' The uncompressed data size Is too much for the application resource capacity
          If TotalEntryArchive > ThresholdEntries Then Exit For   ' Too much entries in this archive, can lead to inodes exhaustion of the system
      Next
      End Using
      ```

      ```vbnet Fix theme={null}
      ```
    </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>
      ```vbnet Bad theme={null}
      Public Class Fruit

      Protected PlantingSeason As String

      ' ...

      End Class

      Public Class Raspberry
      Inherits Fruit

      Protected Plantingseason As String  ' Noncompliant

      ' ...

      End Class
      ```

      ```vbnet Fix theme={null}
      Public Class Fruit

      Protected PlantingSeason As String

      ' ...

      End Class

      Public Class Raspberry
      Inherits Fruit

      Protected WhenToPlant As String

      ' ...

      End Class
      ```
    </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>
      ```vbnet Bad theme={null}
      If condition1 Then
      If condition2 Then ' Noncompliant
          ' ...
      End If
      End If
      ```

      ```vbnet Fix theme={null}
      If condition1 AndAlso condition2 Then
      ' ...
      End If
      ```
    </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>
      ```vbnet Bad theme={null}
      Sub ShouldNotBeEmpty()  ' Noncompliant - method is empty
      End Sub

      Sub NotImplementedYet()  ' Noncompliant - method is empty
      End Sub

      Sub WillNeverBeImplemented()  ' Noncompliant - method is empty
      End Sub

      Sub EmptyOnPurpose()  ' Noncompliant - method is empty
      End Sub
      ```

      ```vbnet Fix theme={null}
      Sub ShouldNotBeEmpty()
      DoSomething()
      End Sub

      Sub NotImplementedYet()
      Throw New NotImplementedException
      End Sub

      Sub WillNeverBeImplemented()
      Throw New NotSupportedException
      End Sub

      Sub EmptyOnPurpose()
      ' Do nothing because of X
      End Sub
      ```
    </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>
      ```vbnet Bad theme={null}
      Dim UrlHttp As String = "http://example.com"                ' Noncompliant
      Dim UrlFtp As String = "ftp://anonymous@example.com"        ' Noncompliant
      Dim UrlTelnet As String = "telnet://anonymous@example.com"  ' Noncompliant
      ```

      ```vbnet Fix theme={null}
      Using Smtp As New SmtpClient("host", 25)    ' Noncompliant, EnableSsl Is Not Set
      End Using
      Using Telnet As New MyTelnet.Client("host", port) ' Noncompliant, rule raises Security Hotspot On any member containing "Telnet"
      End Using
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Redundant pairs of parentheses should be removed">
    <div class="paragraph">
      <p>The use of parentheses, even those not required to enforce a desired order of operations, can clarify the intent behind a piece of code. However, redundant pairs of parentheses could be misleading and should be removed.</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      If a AndAlso ((x + y > 0)) Then ' Noncompliant
      ' ...
      End If

      Return ((x + 1))  ' Noncompliant
      ```

      ```vbnet Fix theme={null}
      If a AndAlso x + y > 0 Then
      ' ...
      End If

      Return x + 1
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Array designators () should be on the type, not the variable">
    <div class="paragraph">
      <p>Array designators should always be located on the type for better code readability. Otherwise, developers must look both at the type and the variable name to know whether or not a variable is an array.</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Sub Main()
          Dim foo() As String ' Noncompliant
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Sub Main()
          Dim foo As String() ' Compliant
      End Sub
      End Module
      ```
    </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>
      ```vbnet Bad theme={null}
      Imports System.Security
      Imports System.Diagnostics

      Namespace N
      Class A
          Public Sub Foo(ByVal process As Process)
              Process.Start("/usr/bin/file.exe") ' Compliant
          End Sub
      End Class
      End Namespace
      ```

      ```vbnet Fix theme={null}
      ```
    </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>
      ```vbnet Bad theme={null}
      Imports Microsoft.AspNetCore.Mvc

      Public Class MyController
      Inherits 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 Function PostRequest(Model model) As IActionResult
      ' ...
      End Function

      <HttpPost>
      <RequestFormLimits(MultipartBodyLengthLimit = 10485760)> ' Sensitive: 10485760 B = 10240 KB = 10 MB is more than the recommended limit of 8MB
      Public Function MultipartFormRequest(Model model) As IActionResult
      ' ...
      End Function

      End Class
      ```

      ```vbnet Fix theme={null}
      Imports Microsoft.AspNetCore.Mvc

      Public Class MyController
      Inherits Controller

      <HttpPost>
      <RequestSizeLimit(8388608)> ' Compliant: 8388608 B = 8192 KB = 8 MB
      Public Function PostRequest(Model model) As IActionResult
      ' ...
      End Function

      <HttpPost>
      <RequestFormLimits(MultipartBodyLengthLimit = 8388608)> ' Compliant: 8388608 B = 8192 KB = 8 MB
      Public Function MultipartFormRequest(Model model) AS IActionResult
      ' ...
      End Function

      End Class
      ```
    </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>
      ```vbnet Bad theme={null}
      Public Sub Foo(ByVal context As DbContext, ByVal value As String)
      context.Database.ExecuteSqlCommand("SELECT * FROM mytable WHERE mycol=@p0", value) ' Compliant, the query is parameterized
      End Sub
      ```

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

  <Accordion title="Unused procedure 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>
      ```vbnet Bad theme={null}
      Private Sub DoSomething(ByVal a As Integer, ByVal b as Integer) ' "b" is unused
      Compute(a)
      End Sub

      Private Function DoSomething2(ByVal a As Integer, ByVal b As Integer) As Integer ' "a" is unused 
      Compute(b)
      Return b
      End Function
      ```

      ```vbnet Fix theme={null}
      Private Sub DoSomething(ByVal a As Integer)
      Compute(a)
      End Sub

      Private Function DoSomething2(ByVal b As Integer) As Integer
      Compute(b)
      Return b
      End Function
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Class names should comply with a naming convention">
    <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 class name does not match a provided regular expression.</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Class foo ' Noncompliant
      End Class
      ```

      ```vbnet Fix theme={null}
      Class Foo
      End Class
      ```
    </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>
      ```vbnet Bad theme={null}
      Namespace MyLibrary  ' Noncompliant

      End Namespace
      ```

      ```vbnet Fix theme={null}
      <Assembly: Runtime.InteropServices.ComVisible(False)>

      Namespace MyLibrary

      End Namespace
      ```
    </CodeGroup>
  </Accordion>

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

    <div class="paragraph">
      <p>For just one or two cases, however, the code will be more readable with if statements.</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Select Case variable
      Case 0
          doSomething()
      Case Else
          doSomethingElse()
      End Select
      ```

      ```vbnet Fix theme={null}
      If variable = 0 Then
      doSomething()
      Else
      doSomethingElse()
      End If
      ```
    </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>
      ```vbnet Bad theme={null}
      Dim a = False

      If a Then
      Dispose() ' Never reached
      End If
      ```

      ```vbnet Fix theme={null}
      Const debug = False
      '...
      If debug Then
      ' Print something
      End If
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Variables should not be self-assigned">
    <div class="paragraph">
      <p>There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead.</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Public Sub SetName(name As String)
      name = name ' Noncompliant
      End Sub
      ```

      ```vbnet Fix theme={null}
      Public Sub SetName(name As String)
      Me.name = name ' Compliant
      End Sub
      ```
    </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>
      ```vbnet Bad theme={null}
      <Serializable>
      Public Class Foo
      <OnSerializing>
      Public Sub OnSerializing(ByVal context As StreamingContext) ' Noncompliant: should be private
      End Sub

      <OnSerialized>
      Private Function OnSerialized(ByVal context As StreamingContext) As Integer '  Noncompliant: should return void
      End Function

      <OnDeserializing>
      Private Sub OnDeserializing() ' Noncompliant: should have a single parameter of type StreamingContext
      End Sub

      <OnSerializing>
      Public Sub OnSerializing2(Of T)(ByVal context As StreamingContext) ' Noncompliant: should have no type parameters
      End Sub

      <OnDeserialized>
      Private Sub OnDeserialized(ByVal context As StreamingContext, ByVal str As String) ' Noncompliant: should have a single parameter of type StreamingContext
      End Sub
      End Class
      ```

      ```vbnet Fix theme={null}
      <Serializable>
      Public Class Foo
      <OnSerializing>
      Private Sub OnSerializing(ByVal context As StreamingContext)
      End Sub

      <OnSerialized>
      Private Sub OnSerialized(ByVal context As StreamingContext)
      End Sub

      <OnDeserializing>
      Private Sub OnDeserializing(ByVal context As StreamingContext)
      End Sub

      <OnDeserialized>
      Private Sub OnDeserialized(ByVal context As StreamingContext)
      End Sub
      End Class
      ```
    </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>
      ```vbnet Bad theme={null}
      <Assembly: CLSCompliant(True)>

      Namespace MyLibrary

      End Namespace
      ```

      ```vbnet 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>
      ```vbnet Bad theme={null}
      Public Class Foo
      Public Const Version = 1.0           ' Noncompliant
      End Class
      ```

      ```vbnet Fix theme={null}
      Public Class Foo
      Public Shared ReadOnly Property Version = 1.0 ' Compliant
      End Class
      ```
    </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>
      ```vbnet Bad theme={null}
      Class Foo        ' Non-Compliant - depends on too many other classes
      Dim a1 As T1   ' Foo is coupled to T1
      Dim a2 As T2   ' Foo is coupled to T2
      Dim a3 As T3   ' Foo is coupled to T3
      Dim a4 As T4   ' etc.
      Dim a5 As T5
      Dim a6 As T6
      Dim a7 As T7
      Dim a8 As T8
      Dim a9 As T9
      Dim a10 As T10
      Dim a11 As T11
      Dim a12 As T12
      Dim a13 As T13
      Dim a14 As T14
      Dim a15 As T15
      Dim a16 As T16
      Dim a17 As T17
      Dim a18 As T18
      Dim a19 As T19
      Dim a20 As T20
      Dim a21 As T21
      End Class
      ```

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

  <Accordion title="If 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>
      ```vbnet Bad theme={null}
      Public Function GetReadableStatus(job As Job) As String
      Return If(job.IsRunning, "Running", If(job.HasErrors, "Failed", "Succeeded")) ' Noncompliant
      End Function
      ```

      ```vbnet Fix theme={null}
      Public Function GetReadableStatus(job As Job) As String
      If job.IsRunning Then Return "Running"
      Return If(job.HasErrors, "Failed", "Succeeded")
      End Function
      ```
    </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>
      ```vbnet Bad theme={null}
      Public Class FruitException ' Noncompliant - this has nothing to do with Exception
      Private expected As Fruit
      Private unusualCharacteristics As String
      Private appropriateForCommercialExploitation As Boolean
      ' ...
      End Class

      Public Class CarException ' Noncompliant - does not derive from any Exception-based class
      Public Sub New(message As String, inner As Exception)
          ' ...
      End Sub
      End Class
      ```

      ```vbnet Fix theme={null}
      Public Class FruitSport ' Compliant - class name does not end with 'Exception'
      Private expected As Fruit
      Private unusualCharacteristics As String
      Private appropriateForCommercialExploitation As Boolean
      ' ...
      End Class

      Public Class CarException Inherits Exception ' Compliant - correctly extends System.Exception
      Public Sub New(message As String, inner As Exception)
          MyBase.New(message, inner)
          ' ...
      End Sub
      End Class
      ```
    </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>
      ```vbnet Bad theme={null}
      Interface IMyInterface 
      Function DoTheThing() As Integer
      Function DoTheOtherThing() As String // Noncompliant
      Function DoTheThing(ByVal Path As String) As Integer
      End Interface
      ```

      ```vbnet Fix theme={null}
      Interface IMyInterface 
      Function DoTheThing() As Integer
      Function DoTheThing(ByVal Path As String) As Integer
      Function DoTheOtherThing() As String
      End Interface
      ```
    </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>
      ```vbnet Bad theme={null}
      Public Class Foo

      Private Name As String = "foobar" ' Noncompliant

      Public ReadOnly Property DefaultName As String = "foobar" ' Noncompliant

      Public Sub New(Optional Value As String = "foobar") ' Noncompliant

          Dim Something = If(Value, "foobar") ' Noncompliant

      End Sub

      End Class
      ```

      ```vbnet Fix theme={null}
      Public Class Foo

      Private Const Foobar As String = "foobar"

      Private Name As String = Foobar

      Public ReadOnly Property DefaultName As String = Foobar

      Public Sub New(Optional Value As String = Foobar)

          Dim Something = If(Value, Foobar)

      End Sub

      End Class
      ```
    </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>
      ```vbnet Bad theme={null}
      Public Class Foo
      End Class

      Public Structure Bar
      End Structure
      ```

      ```vbnet Fix theme={null}
      Namespace SomeSpace
      Public Class Foo
      End Class

      Public Structure Bar
      End Structure
      End Namespace
      ```
    </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>
      ```vbnet Bad theme={null}
      Imports System.Reflection

      Dim dynClass = Type.GetType("MyInternalClass")
      ' Sensitive. Using BindingFlags.NonPublic will return non-public members
      Dim bindingAttr As BindingFlags = BindingFlags.NonPublic Or BindingFlags.Static
      Dim dynMethod As MethodInfo = dynClass.GetMethod("mymethod", bindingAttr)
      Dim result = dynMethod.Invoke(dynClass, Nothing)
      ```

      ```vbnet Fix theme={null}
      ```
    </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>
      ```vbnet Bad theme={null}
      Public Class Noncompliant

      <DllImport("ole32.dll")>
      Public Shared Function CoSetProxyBlanket(<MarshalAs(UnmanagedType.IUnknown)>pProxy As Object, dwAuthnSvc as UInt32, dwAuthzSvc As UInt32, <MarshalAs(UnmanagedType.LPWStr)> pServerPrincName As String, dwAuthnLevel As UInt32, dwImpLevel As UInt32, pAuthInfo As IntPtr, dwCapabilities As UInt32) As Integer
      End Function

      Public Enum RpcAuthnLevel
          [Default] = 0
          None = 1
          Connect = 2
          [Call] = 3
          Pkt = 4
          PktIntegrity = 5
          PktPrivacy = 6
      End Enum

      Public Enum RpcImpLevel
          [Default] = 0
          Anonymous = 1
          Identify = 2
          Impersonate = 3
          [Delegate] = 4
      End Enum

      Public Enum EoAuthnCap
          None = &H00
          MutualAuth = &H01
          StaticCloaking = &H20
          DynamicCloaking = &H40
          AnyAuthority = &H80
          MakeFullSIC = &H100
          [Default] = &H800
          SecureRefs = &H02
          AccessControl = &H04
          AppID = &H08
          Dynamic = &H10
          RequireFullSIC = &H200
          AutoImpersonate = &H400
          NoCustomMarshal = &H2000
          DisableAAA = &H1000
      End Enum

      <DllImport("ole32.dll")>
      Public Shared Function CoInitializeSecurity(pVoid As IntPtr, cAuthSvc As Integer, asAuthSvc As IntPtr, pReserved1 As IntPtr, level As RpcAuthnLevel, impers As RpcImpLevel, pAuthList As IntPtr, dwCapabilities As EoAuthnCap, pReserved3 As IntPtr) As Integer
      End Function

      Public Sub DoSomething()
          Dim Hres1 As Integer = CoSetProxyBlanket(Nothing, 0, 0, Nothing, 0, 0, IntPtr.Zero, 0) ' Noncompliant
          Dim Hres2 As Integer = CoInitializeSecurity(IntPtr.Zero, -1, IntPtr.Zero, IntPtr.Zero, RpcAuthnLevel.None, RpcImpLevel.Impersonate, IntPtr.Zero, EoAuthnCap.None, IntPtr.Zero) ' Noncompliant
      End Sub

      End Class
      ```

      ```vbnet 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>
      ```vbnet Bad theme={null}
      Public Sub RegexPattern(Input As String)
      Dim EmailPattern As New Regex(".+@.+", RegexOptions.None)
      Dim IsNumber as Boolean = Regex.IsMatch(Input, "[0-9]+")
      Dim IsLetterA as Boolean = Regex.IsMatch(Input, "(a+)+")
      End Sub
      ```

      ```vbnet Fix theme={null}
      Public Sub RegexPattern(Input As String)
      Dim EmailPattern As New Regex(".+@.+", RegexOptions.None, TimeSpan.FromMilliseconds(100))
      Dim IsNumber as Boolean = Regex.IsMatch(Input, "[0-9]+", RegexOptions.None, TimeSpan.FromMilliseconds(100))
      Dim IsLetterA As Boolean = Regex.IsMatch(Input, "(a+)+", RegexOptions.NonBacktracking) '.Net 7 And above
      AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromMilliseconds(100)) 'process-wide setting
      End Sub
      ```
    </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>
      ```vbnet Bad theme={null}
      <ValidateInput(True)>
      Public Function Welcome(Name As String) As ActionResult
      ...
      End Function
      ```

      ```vbnet Fix theme={null}
      Public Function Welcome(Name As String) As ActionResult
      ...
      End Function
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Comments should not be located at the end of lines of code">
    <div class="paragraph">
      <p>This rule verifies that single-line comments are not located at the ends of lines of code. The main idea behind this rule is that in order to be really readable, trailing comments would have to be properly written and formatted (correct alignment, no interference with the visual structure of the code, not too long to be visible) but most often, automatic code formatters would not handle this correctly: the code would end up less readable. Comments are far better placed on the previous empty line of code, where they will always be visible and properly formatted.</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Sub Main()
      Console.WriteLine("Hello, world!") ' Noncompliant - My first program!
      Console.WriteLine("Hello, world!") ' CompliantOneWord
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Sub Main()
      ' Compliant - My first program!
      Console.WriteLine("Hello, world!")
      Console.WriteLine("Hello, world!") ' CompliantOneWord
      End Sub
      End Module
      ```
    </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>
      ```vbnet Bad theme={null}
      Sub Notify(ByVal Company As String, Optional ByVal Office As String = "QJZ") ' Noncompliant

      End Sub
      ```

      ```vbnet Fix theme={null}
      Sub Notify(ByVal Company As String)
      Notify(Company, "QJZ")
      End Sub

      Sub Notify(ByVal Company As String, ByVal Office As String)

      End Sub
      ```
    </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>
      ```vbnet Bad theme={null}
      Imports System.ComponentModel.Composition

      <PartCreationPolicy(CreationPolicy.Any)> ' Noncompliant
      Public Class FooBar
      Inherits IFooBar
      End Class
      ```

      ```vbnet Fix theme={null}
      Imports System.ComponentModel.Composition

      <Export(GetType(IFooBar))>
      <PartCreationPolicy(CreationPolicy.Any)>
      Public Class FooBar
      Inherits IFooBar
      End Class
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Procedures 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>
      ```vbnet Bad theme={null}
      Class BaseClass

      Sub New(Param1 As Integer)
          ' ...
      End Sub

      End Class

      Class DerivedClass
      Inherits BaseClass

      Public Sub New(Param1 As Integer, Param2 As Integer, Param3 As Integer, Param4 As Integer, Param5 As Long)
      ' Compliant by exception: Param1 is used in the base class constructor, so it does not count in the sum of the parameter list.
          MyBase.New(Param1)
          ' ...
      End Sub

      End Class
      ```

      ```vbnet Fix theme={null}
      ```
    </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>
      ```vbnet Bad theme={null}
      Private Const CODE As String = "bounteous"
      Private callCount As Integer = 0

      Public Function GetCode() As String
      callCount = callCount + 1
      Return CODE
      End Function

      Public Function GetName() As String ' Noncompliant: duplicates GetCode
      callCount = callCount + 1
      Return CODE
      End Function
      ```

      ```vbnet Fix theme={null}
      Private Const CODE As String = "bounteous"
      Private callCount As Integer = 0

      Public Function GetCode() As String
      callCount = callCount + 1
      Return CODE
      End Function

      Public Function GetName() As String ' Intent is clear
      Return GetCode()
      End Function
      ```
    </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>
      ```vbnet Bad theme={null}
      Dim ip = ConfigurationManager.AppSettings("myapplication.ip") ' Compliant
      Dim address = IPAddress.Parse(ip)
      ```

      ```vbnet 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>
      ```vbnet Bad theme={null}
      Public Sub Foo()
      Dim G1 As New Guid        ' Noncompliant - what's the intent?
      Dim G2 As Guid = Nothing  ' Noncompliant
      End Sub
      ```

      ```vbnet Fix theme={null}
      public void Foo(byte[] bytes)
      Public Sub Foo(Bytes As Byte())
      Dim G1 As Guid = Guid.Empty
      Dim G2 As Guid = Guid.NewGuid()
      Dim G3 As Guid = New Guid(Bytes)
      End Sub
      ```
    </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>
      ```vbnet Bad theme={null}
      Sub DoSomething() 
      ' TODO
      End Sub
      ```

      ```vbnet 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>
      ```vbnet Bad theme={null}
      Public Class HomeController
      Inherits Controller

      Public Function Article() As ActionResult
          ViewBag.Title = "Title" ' Noncompliant, model should be used
          ViewData("Text") = "Text" ' Noncompliant, model should be used
          Return View()
      End Function

      End Class
      ```

      ```vbnet Fix theme={null}
      Public Class ArticleModel

      Public Property Title As String
      Public Property Text As String

      End Class

      Public Class HomeController
      Inherits Controller

      Public Function Article() As ActionResult
          Dim Model As New ArticleModel With {.Title = "Title", .Text = "Text"}
          Return View(Model)
      End Function

      End Class
      ```
    </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>
      ```vbnet Bad theme={null}
      Public Structure Coordinates

      Public ReadOnly Property X As Integer
      Public ReadOnly Property Y As Integer

      <ExcludeFromCodeCoverage> ' Noncompliant
      Public Overrides Function Equals(obj As Object) As Boolean
          If Not (TypeOf obj Is Coordinates) Then
              Return False
          End If

          Dim coordinates = DirectCast(obj, Coordinates)
          Return X = coordinates.X AndAlso
                 Y = coordinates.Y
      End Function

      <ExcludeFromCodeCoverage> ' Noncompliant
      Public Overrides Function GetHashCode() As Integer
          Dim hashCode As Long = 1861411795
          hashCode = (hashCode * -1521134295 + X.GetHashCode()).GetHashCode()
          hashCode = (hashCode * -1521134295 + Y.GetHashCode()).GetHashCode()
          Return hashCode
      End Function
      End Structure
      ```

      ```vbnet Fix theme={null}
      Public Structure Coordinates

      Public ReadOnly Property X As Integer
      Public ReadOnly Property Y As Integer

      <ExcludeFromCodeCoverage(Justification:="Code generated by Visual Studio refactoring")> ' Compliant
      Public Overrides Function Equals(obj As Object) As Boolean
          If Not (TypeOf obj Is Coordinates) Then
              Return False
          End If

          Dim coordinates = DirectCast(obj, Coordinates)
          Return X = coordinates.X AndAlso
                 Y = coordinates.Y
      End Function

      <ExcludeFromCodeCoverage(Justification:="Code generated by Visual Studio refactoring")> ' Compliant
      Public Overrides Function GetHashCode() As Integer
          Dim hashCode As Long = 1861411795
          hashCode = (hashCode * -1521134295 + X.GetHashCode()).GetHashCode()
          hashCode = (hashCode * -1521134295 + Y.GetHashCode()).GetHashCode()
          Return hashCode
      End Function
      End Structure
      ```
    </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>
      ```vbnet Bad theme={null}
      <Flags()>
      Enum FruitType    ' Non-Compliant
      None
      Banana
      Orange
      Strawberry
      End Enum

      Module Module1
      Sub Main()
      Dim bananaAndStrawberry = FruitType.Banana Or FruitType.Strawberry 
      Console.WriteLine(bananaAndStrawberry.ToString()) ' Will display only "Strawberry"
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      <Flags()>
      Enum FruitType    ' Compliant
      None = 0
      Banana = 1
      Orange = 2
      Strawberry = 4
      End Enum

      Module Module1
      Sub Main()
      Dim bananaAndStrawberry = FruitType.Banana Or FruitType.Strawberry 
      Console.WriteLine(bananaAndStrawberry.ToString()) ' Will display "Banana, Strawberry"
      End Sub
      End Module
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Setting loose POSIX 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>
      ```vbnet Bad theme={null}
      Dim safeAccessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Deny)

      Dim fileSecurity = File.GetAccessControl("path")
      fileSecurity.AddAccessRule(safeAccessRule)
      File.SetAccessControl("path", fileSecurity)
      ```

      ```vbnet Fix theme={null}
      Dim safeAccessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Deny)

      Dim fileInfo = new FileInfo("path")
      Dim fileSecurity = fileInfo.GetAccessControl()
      fileSecurity.SetAccessRule(safeAccessRule)
      fileInfo.SetAccessControl(fileSecurity)
      ```
    </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>
      ```vbnet Bad theme={null}
      If True Then ' Noncompliant
        DoSomething()
      End If

      If False Then ' Noncompliant
        DoSomethingElse()
      End If
      ```

      ```vbnet Fix theme={null}
      DoSomething(); 
      ' ...
      ```
    </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>
      ```vbnet Bad theme={null}
      Public Class Fruit

      Protected Ripe As Season
      Protected Flesh As Color

      ' ...

      End Class

      Public Class Raspberry
      Inherits Fruit

      Private Ripe As Boolean         ' Noncompliant
      Private Shared FLESH As Color   ' Noncompliant

      ' ...

      End Class
      ```

      ```vbnet Fix theme={null}
      Public Class Fruit

      Protected Ripe As Season
      Protected Flesh As Color

      ' ...

      End Class

      Public Class Raspberry
      Inherits Fruit

      Private Riped As Boolean
      Private Shared FLESH_COLOR As Color   ' Noncompliant

      ' ...

      End Class
      ```
    </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>
      ```vbnet Bad theme={null}
      Imports System.Security.Cryptography

      Sub ComputeHash()
      Dim sha256 = New SHA256CryptoServiceProvider() ' Compliant
      Dim sha384 = New SHA384CryptoServiceProvider() ' Compliant
      Dim sha512 = New SHA512CryptoServiceProvider() ' Compliant

      ' ...
      End Sub
      ```

      ```vbnet 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>
      ```vbnet Bad theme={null}
      Class MyException
      Inherits Exception

      Public Sub MyException()
          If bad_thing Then
              Throw New Exception("A bad thing happened")
          End If
      End Sub
      End Class
      ```

      ```vbnet 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>
      ```vbnet Bad theme={null}
      <Serializable>
      Public Class Foo ' Noncompliant
      <OptionalField(VersionAdded:=2)>
      Private optionalField As Integer = 5
      End Class
      ```

      ```vbnet Fix theme={null}
      <Serializable>
      Public Class Foo
      <OptionalField(VersionAdded:=2)>
      Private optionalField As Integer = 5

      <OnDeserializing>
      Private Sub OnDeserializing(ByVal context As StreamingContext)
          optionalField = 5
      End Sub

      <OnDeserialized>
      Private Sub OnDeserialized(ByVal context As StreamingContext)
      End Sub
      End Class
      ```
    </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>
      ```vbnet Bad theme={null}
      Dim mySHA256 As SHA256 = SHA256.Create()
      ```

      ```vbnet 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>
      ```vbnet Bad theme={null}
      Dim username As String = "admin"
      Dim password As String = GetEncryptedPassword()
      Dim usernamePassword As String = String.Format("user={0}&password={1}", GetEncryptedUsername(), GetEncryptedPassword())
      Dim url As String = $"scheme://{username}:{password}@domain.com"

      Dim url2 As String= "http://guest:guest@domain.com" ' Compliant
      Const Password_Property As String = "custom.password" ' Compliant
      ```

      ```vbnet 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>
      ```vbnet Bad theme={null}
      If compare(myPoint.x, myPoint.x) <> 0 Then ' Noncompliant
      '...
      End If

      If compare(getNextValue(), getNextValue()) <> 0 Then ' Noncompliant
      '...
      End If
      ```

      ```vbnet Fix theme={null}
      If compare(myPoint.x, myPoint.y) <> 0 Then
      '...
      End If

      Dim v1 As Integer = getNextValue()
      Dim v2 As Integer = getNextValue()
      If compare(v1, v2) <> 0 Then
      '...
      End If
      ```
    </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>
      ```vbnet Bad theme={null}
      Class Person
      Private age As Integer

      <Pure> ' Noncompliant: The method makes a state change
      Private Sub ConfigureAge(ByVal age As Integer)
          Me.age = age
      End Sub

      <Pure>
      Private Sub WriteAge() ' Noncompliant
          Console.WriteLine(Me.age)
      End Sub

      End Class
      ```

      ```vbnet Fix theme={null}
      Class Person
      Private age As Integer

      Private Sub ConfigureAge(ByVal age As Integer)
          Me.age = age
      End Sub

      <Pure>
      Private Function Age() As Integer
          Return Me.age
      End Function

      ' or remove Pure attribute from the method

      Private Sub WriteAge()
          Console.WriteLine(Me.age)
      End Sub

      End Class
      ```
    </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>
      ```vbnet Bad theme={null}
      <TestMethod>
      <ExpectedException(GetType(ArgumentNullException))> ' Noncompliant
      Public Sub TestNullArg()
      '...
      End Sub
      ```

      ```vbnet Fix theme={null}
      <TestMethod>
      Public Sub TestNullArg()
      Dim CallFailed As Boolean = False
      Try
      ' ...
      Catch ex As Exception
          CallFailed = true
      End Try
      Assert.IsTrue(CallFailed, "Expected call to MyMethod to fail with ArgumentNullException")
      End Sub
      ```
    </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>
      ```vbnet Bad theme={null}
      Using t = New TestTimer()
      End Using
      ```

      ```vbnet Fix theme={null}
      Public Function NumberOfMinutes(ByVal hours As Integer) As Integer
      Dim seconds As Integer = 0 ' Noncompliant - seconds is unused
      Return hours * 60
      End Function
      ```
    </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>
      ```vbnet Bad theme={null}
      Dim foo As New Disposable()
      foo.Dispose()
      foo.Dispose() ' Noncompliant
      ```

      ```vbnet Fix theme={null}
      Using bar As New Disposable()  ' Noncompliant
      bar.Dispose()
      End Using
      ```
    </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>
      ```vbnet 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
      End Try
      ```

      ```vbnet Fix theme={null}
      Try
      ' Some work which end up throwing an exception
      Throw New ArgumentException()
      Finally
      ' Cleanup without throwing
      End Try
      ```
    </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>
      ```vbnet Bad theme={null}
      Imports System

      Namespace MyLibrary
      Public Class MyExtension
          Inherits MarkupExtension

          Public Sub New()
          End Sub

          Public Sub New(ByVal value1 As Object)
              Value1 = value1
          End Sub

          <ConstructorArgument("value2")> ' Noncompliant
          Public Property Value1 As Object
      End Class
      End Namespace
      ```

      ```vbnet Fix theme={null}
      Imports System

      Namespace MyLibrary
      Public Class MyExtension
          Inherits MarkupExtension

          Public Sub New()
          End Sub

          Public Sub New(ByVal value1 As Object)
              Value1 = value1
          End Sub

          <ConstructorArgument("value1")>
          Public Property Value1 As Object
      End Class
      End Namespace
      ```
    </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>
      ```vbnet Bad theme={null}
      Function Abs(ByVal n As Integer) As Integer ' Noncompliant: cognitive complexity = 5
      If n >= 0 Then    ' +1
          Return n
      Else              ' +2, due to nesting
          If n = Integer.MinValue Then      ' +1
              Throw New ArgumentException("The absolute value of int.MinValue is outside of int boundaries")
          Else                              ' +1
              Return -n
          End If
      End If
      End Function
      ```

      ```vbnet Fix theme={null}
      Function Abs(ByVal n As Integer) As Integer  ' Compliant: cognitive complexity = 3
      If n = Integer.MinValue Then    ' +1
          Throw New ArgumentException("The absolute value of int.MinValue is outside of int boundaries")
      Else If n >= 0 Then             ' +1
          Return n
      Else                            ' +1
          Return -n
      End If
      End Function
      ```
    </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>
      ```vbnet Bad theme={null}
      Imports System.Reflection
      <Assembly: AssemblyTitle("MyAssembly")> ' Noncompliant
      Namespace MyLibrary
      ' ...
      End Namespace
      ```

      ```vbnet Fix theme={null}
      Imports System.Reflection
      <Assembly: AssemblyTitle("MyAssembly")>
      <Assembly: AssemblyVersion("42.1.125.0")>
      Namespace MyLibrary
      ' ...
      End Namespace
      ```
    </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>
      ```vbnet Bad theme={null}
      <Export(GetType(ISomeType))>
      Public Class SomeType  ' Noncompliant: doesn't implement 'ISomeType'.
      End Class
      ```

      ```vbnet Fix theme={null}
      <Export(GetType(ISomeType))>
      Public Class SomeType
      Inherits ISomeType
      End Class
      ```
    </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>
      ```vbnet Bad theme={null}
      Dim d As String = Nothing
      Dim v1 = If(d, "value")
      ```

      ```vbnet Fix theme={null}
      Const debug = False
      '...
      If debug Then
      ' Print something
      End If
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Local variable 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.
      \{identifier\_capital\_plural} hold the meaning of the written code. Their names should be meaningful and follow a consistent and easily recognizable pattern.
      Adhering to a consistent naming convention helps 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 \{identifier} names match a provided regular expression.</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Module Module1
      Sub Main()
          Dim Foo = 0 ' Noncompliant
      End Sub
      End Module
      ```

      ```vbnet Fix theme={null}
      Module Module1
      Sub Main()
          Dim foo = 0 ' Compliant
      End Sub
      End Module
      ```
    </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>
      ```vbnet Bad theme={null}
      Public Class Account
      Public Property Id As DateTime

      Public Property Name As String
      Public Property Surname As String
      End Class
      ```

      ```vbnet Fix theme={null}
      Public Class Account
      Public Property Id As Guid

      Public Property Name As String
      Public Property Surname As String
      End Class
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Exception types should be Public">
    <div class="paragraph">
      <p>Exception types should be "Public"</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Friend Class MyException    ' Noncompliant
      Inherits Exception
      ' ...
      End Class
      ```

      ```vbnet Fix theme={null}
      Public Class MyException
      Inherits Exception
      ' ...
      End Class
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Obsolete attributes should include explanations">
    <div class="paragraph">
      <p>"Obsolete" attributes should include explanations</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      Public Class Car

      <Obsolete>  ' Noncompliant
      Public Sub CrankEngine(Turns As Integer)
          ' ...
      End Sub

      End Class
      ```

      ```vbnet Fix theme={null}
      Public Class Car

      <Obsolete("Replaced by the automatic starter")>
      Public Sub CrankEngine(Turns As Integer)
          ' ...
      End Sub

      End Class
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Two branches in a conditional structure should not have exactly the same implementation">
    <div class="paragraph">
      <p>Having two Cases in the same Select statement or branches in the same If structure with the same implementation is at best duplicate code, and at worst a coding error.</p>
    </div>

    <CodeGroup>
      ```vbnet Bad theme={null}
      If a >= 0 AndAlso a < 10 Then
      DoFirst()
      DoTheThing()
      ElseIf a >= 10 AndAlso a < 20 Then
      DoTheOtherThing()
      ElseIf a >= 20 AndAlso a < 50   ' Noncompliant; duplicates first condition
      DoFirst()
      DoTheThing()
      Else
      DoTheRest();
      End If
      ```

      ```vbnet Fix theme={null}
      If (a >= 0 AndAlso a < 10) OrElse (a >= 20 AndAlso a < 50) Then
      DoFirst()
      DoTheThing()
      ElseIf a >= 10 AndAlso a < 20 Then
      DoTheOtherThing()
      Else
      DoTheRest();
      End If
      ```
    </CodeGroup>
  </Accordion>
</AccordionGroup>
