What are generic methods in C#?

CsharpProgrammingServer Side Programming

Generics allow you to write a class or method that can work with any data type. Declare a generic method with a type parameter −

static void Swap(ref T lhs, ref T rhs) {}

To call the above shown generic method, here is an example −

Swap(ref a, ref b);

Let us see how to create a generic method in C# −

Example

 Live Demo

using System;
using System.Collections.Generic;

namespace Demo {
   class Program {
      static void Swap(ref T lhs, ref T rhs) {
         T temp;
         temp = lhs;
         lhs = rhs;
         rhs = temp;
      }

      static void Main(string[] args) {
         int a, b;
         char c, d;
         a = 45;
         b = 60;
         c = 'K';
         d = 'P';
         Console.WriteLine("Int values before calling swap:");
         Console.WriteLine("a = {0}, b = {1}", a, b);
         Console.WriteLine("Char values before calling swap:");
         Console.WriteLine("c = {0}, d = {1}", c, d);
         Swap(ref a, ref b);
         Swap(ref c, ref d);
         Console.WriteLine("Int values after calling swap:");
         Console.WriteLine("a = {0}, b = {1}", a, b);
         Console.WriteLine("Char values after calling swap:");
         Console.WriteLine("c = {0}, d = {1}", c, d);
         Console.ReadKey();
      }
   }
}

Output

Int values before calling swap:
a = 45, b = 60
Char values before calling swap:
c = K, d = P
Int values after calling swap:
a = 60, b = 45
Char values after calling swap:
c = P, d = K
raja
Published on 10-Aug-2018 08:15:35
Advertisements