CSharp - Generics Generic Methods

Introduction

A generic method declares type parameters within the signature of a method.

The following code defines a generic method that swaps the contents of two variables of any type T:

static void Swap<T> (ref T a, ref T b){
       T temp = a;
       a = b;
       b = temp;
}

Swap<T> can be used as follows:

int x = 5;
int y = 10;
Swap (ref x, ref y);

Generic methods can be called with the type arguments as follows to avoid type ambiguity:

Swap<int> (ref x, ref y);

Methods and types are the only constructs that can have introduce parameters.

Properties, indexers, events, fields, constructors, operators, cannot introduce type parameters.

Demo

using System;
class MainClass/*  ww  w  .  j a va 2s  .  c o m*/
{
   public static void Main(string[] args)
   {
        int x = 5;
        int y = 10;

        Console.WriteLine(x);
        Console.WriteLine(y);
        Swap (ref x, ref y);
        Console.WriteLine(x);
        Console.WriteLine(y);
   }
    static void Swap<T> (ref T a, ref T b){
           T temp = a;
           a = b;
           b = temp;
    }
}

Result