Wednesday, June 19, 2013

Generic method in C#

Today I will show you how to implement generic method in c#. The term generic means neutral.Hmm.. Confusing ? Ok let me give another example. To make a phone call at first you have to take your phone write?. So to take your phone is generic thing now you will decide whether you will make phone call or you will send SMS or MMS.

Same concept hold true for generic method. A generic method can take various type parameter. Here my Print method can take different parameter depending upon call. Have a look of below code.    

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;

namespace BlogProject
{
    class Person
    {
        public static void Print<T>(T variable)
        {
            Console.Write(variable.ToString());
        }
    }
    class Program
    {
        static void Main(string[] args)
         {
             Person.Print<int>(2);
             Person.Print<string>("hello");
             Console.ReadKey();
         }
    }

}




No comments:

Post a Comment