Thursday 27 May 2021

Generic Method in C#

 public class GClass {

      static void Swap2Values<T>(T lhs, T rhs) {

         T temp;     temp = lhs;    lhs = rhs;    rhs = temp;

      }

      static void Main(string[] args) {

         int a, b;   char c, d;   a = 5;  b = 10;  c = 'h';  d = 'k';

         // Before swap display values :

         Console.WriteLine("Before Swap:");

         Console.WriteLine("a = {0}, b = {1}", a, b);

         Console.WriteLine("-------:");

         Console.WriteLine("c = {0}, d = {1}", c, d);

         //call generic Method

         Swap<int>(a, b);

         Swap<char>(c,  d);

         //After swap:

         Console.WriteLine("After swap:");

         Console.WriteLine("a = {0}, b = {1}", a, b);

         Console.WriteLine("--------");

         Console.WriteLine("c = {0}, d = {1}", c, d);

}

}

No comments:

Post a Comment