This documentation is archived and is not being maintained.

Use generics where appropriate







Breaking Change


An externally visible method contains a reference parameter of type System.Object, and the containing assembly targets .NET Framework 2.0.

A reference parameter is a parameter modified with the ref (ByRef in Visual Basic) keyword. The argument type supplied for a reference parameter must exactly match the reference parameter type. To use a type derived from the reference parameter type, the type must first be cast and assigned to a variable of the reference parameter type. Use of a generic method allows all types, subject to constraints, to be passed to the method without first casting the type to the reference parameter type.

To fix a violation of this rule, make the method generic and replace the Object parameter with a type parameter.

Do not exclude a warning from this rule.

The following example shows a general-purpose swap routine implemented as both non-generic and generic methods. Note how efficiently the strings are swapped using the generic method as compared to the non-generic method.

Imports System

Namespace DesignLibrary

   Public NotInheritable Class ReferenceParameters
      Private Sub New()
      End Sub

      ' This method violates the rule.
      Public Shared Sub Swap( _  
         ByRef object1 As Object, ByRef object2 As Object)

         Dim temp As Object = object1
         object1 = object2
         object2 = temp

      End Sub

      ' This method satifies the rule.
      Public Shared Sub GenericSwap(Of T)( _ 
         ByRef reference1 As T, ByRef reference2 As T)
         Dim temp As T = reference1
         reference1 = reference2
         reference2 = temp

      End Sub

   End Class

   Class Test
      Shared Sub Main()
         Dim string1 As String = "Swap"
         Dim string2 As String = "It"

         Dim object1 As Object = DirectCast(string1, Object)
         Dim object2 As Object = DirectCast(string2, Object)
         ReferenceParameters.Swap(object1, object2)
         string1 = DirectCast(object1, String)
         string2 = DirectCast(object2, String)
         Console.WriteLine("{0} {1}", string1, string2)

         ReferenceParameters.GenericSwap(string1, string2)
         Console.WriteLine("{0} {1}", string1, string2)

      End Sub

   End Class

End Namespace