Export (0) Print
Expand All
Expand Minimize

Use generics where appropriate

TypeName

UseGenericsWhereAppropriate

CheckId

CA1007

Category

Microsoft.Design

Breaking Change

Breaking

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.

using System;

namespace DesignLibrary
{
   public sealed class ReferenceParameters
   {
      private ReferenceParameters(){}

      // This method violates the rule.
      public static void Swap(ref object object1, ref object object2)
      {
         object temp = object1;
         object1 = object2;
         object2 = temp;
      }

      // This method satifies the rule.
      public static void GenericSwap<T>(ref T reference1, ref T reference2)
      {
         T temp = reference1;
         reference1 = reference2;
         reference2 = temp;
      }
   }

   class Test
   {
      static void Main()
      {
         string string1 = "Swap";
         string string2 = "It";

         object object1 = (object)string1;
         object object2 = (object)string2;
         ReferenceParameters.Swap(ref object1, ref object2);
         string1 = (string)object1;
         string2 = (string)object2;
         Console.WriteLine("{0} {1}", string1, string2);

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

Community Additions

ADD
Show:
© 2014 Microsoft