Generic Method - A method that can process different data types. - CSharp Custom Type

CSharp examples for Custom Type:Generics

Description

Generic Method - A method that can process different data types.

Demo Code

using System;//from w  ww  . j  a v  a 2 s.c  o m
class Program
{
   static void Main(string[] args)
   {
      //First, test it for int arguments
      int one = 1;
      int two = 2;
      Console.WriteLine("\t\tBefore swap: one = {0}, two = {1}", one, two);
      // Next line instantiates Swap for ints and calls the method.
      Swap<int>(ref one, ref two);
      Console.WriteLine("\t\tAfter swap: one = {0}, two = {1}", one, two);
      Console.WriteLine("\tSecond, test it for string arguments");
      string oneStr = "one";
      string twoStr = "two";
      Console.WriteLine("\t\tBefore swap: oneStr = {0}, twoStr = {1}", oneStr, twoStr);
      Swap<string>(ref oneStr, ref twoStr); // Generic instantiation for string.
      Console.WriteLine("\t\tAfter swap: oneStr = {0}, twoStr = {1}", oneStr, twoStr);
      one = 1;
      two = 2;
      GenericClass<int> genClassInt = new GenericClass<int>();
      Console.WriteLine("\t\tBefore swap: one = {0}, two = {1}", one, two);
      genClassInt.Swap(ref one, ref two);
      Console.WriteLine("\t\tAfter swap: one = {0}, two = {1}", one, two);
      oneStr = "one";
      twoStr = "two";
      GenericClass<string> genClassString = new GenericClass<string>();
      Console.WriteLine("\t\tBefore swap: oneStr = {0}, twoStr = {1}", oneStr, twoStr);
      genClassString.Swap(ref oneStr, ref twoStr);
      Console.WriteLine("\t\tAfter swap: oneStr = {0}, twoStr = {1}", oneStr, twoStr);
   }
   public static void Swap<T>(ref T leftSide, ref T rightSide)
   {
      T temp;
      temp = leftSide;
      leftSide = rightSide;
      rightSide = temp;
   }
}
class GenericClass<T>
{
   public void Swap(ref T leftSide, ref T rightSide)
   {
      T temp;
      temp = leftSide;
      leftSide = rightSide;
      rightSide = temp;
   }
}

Result


Related Tutorials