C#: Generic method

A generic method, as the name implies, allows a general method to be declared for reusability.

It offers us a way to declare a general type called the type parameter.  With these general types, we can input different type of parameters into the methods.

Consider the following example.

Generics method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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

        static void Main(string[] args)
        {
            int a = 1;
            int b = 2;

            string l = "left";
            string r = "right";

            Swap<int>(ref a, ref b);
            Console.WriteLine(a + " " + b);
            Console.WriteLine();

            Swap<string>(ref l, ref r);
            Console.WriteLine(l + " " + r);
            Console.ReadKey();
        }
    }
}

generics

Here in this example, we have one swap function but it can take in either integer or string parameters.

In a way, it offers us a quick way to reuse our code.

 

Series Navigation<< C#: Default ToString method
C#: Generic method for reversing an array >>