paste it into your Blogger Template ju

Wednesday 25 February 2015

Generic Methods

In the last post we have seen how to write generic class. Now its the time to move on to generic methods. You can use generic types in methods as well.

Example

using System;
using System.Collections.Generic;

namespace GenericsApplication
{
    class SampleProgram
    {
        static void GenericsSwap(ref T var1, ref T var2)
        {
            T temp;
            temp = var1;
            var1 = var2;
            var2 = temp;
        }
        static void Main(string[] args)
        {
            int a, b;
            char c, d;
            a = 200;
            b = 300;
            c = 'L';
            d = 'M';

            //display values before swap:
            Console.WriteLine("Intiger 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);

            //call swap
            GenericsSwap(ref a, ref b);
            GenericsSwap(ref c, ref d);

            //display values after swap:
            Console.WriteLine("Intiger 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 = 200, b = 300
Char values before calling swap:
c = L, d = M
Int values after calling swap:
a = 300, b = 200
Char values after calling swap:
c = M, d = L

No comments:

Post a Comment