Understanding Custom Generic Methods in C#

I hope reader of this blog are introduced to Generic(System.Collections.Generic).

In this blogI will show how Method overloading can be achieved with Custom Generic Methods –and in this process will explain Custom Generic method.

Let's understand it with Swapping of 2 numbers program.

Say You need to swap 2 integers - you would write-

static void Swap(ref int a, ref int b)
{

    int
temp;
    temp = a;
    a = b;
    b = temp;
}


Now assume you need to write code for swapping of 2 strings

static void Swap(ref string a, ref string b)
{

    string
temp;
    temp = a;
    a = b;
    b = temp;
}

Now if you need to Swap 2 floats, or a user 2 defined Class type then you would need to go and write corresponding version of Swap methods – Right??- Then it would be bit tedious.

Yeah – I know – few of you would have thought by now- that you can replace all these version of Swap methods by a single[Non Generic] method which will be operating on object parameters.

But then you face all the problems of Boxing, Unboxing, Type Safety issue, explicit casting and so on…

So came the Generics -> So in other words if we have a bunch of overloaded methods which vary by incoming arguments – Generic method is the better answer for it.

So lets see how we can code a generic method for Swap() which would work for all types

//This method would swap any 2 items as specified by parameter Type T

static void Swap<T>(ref T a, ref T b)

{
    T temp;
    temp = a;
   a = b;
    b = temp;
}


So here our Generic Swap method can operate on any 2 parameters of Type<T>

With this approach of Custom Generic method – We have only one version of Swap<T>() to maintain and it can operate in a type safe manner on any 2 items of a given type.

Since there is no casting required from (Value type ? ? Reference Type) ? So stack based items stay on the Stack ,while Heap based items stay on the Heap.

I have attached the Source Code used for this explanation.

Happy Learning!