Translate

Thursday, May 23, 2013

Introduction to generics in c# (Simplified version)



If you have a need, where you want to a general purpose class or method that can deal with any type (int,string etc), that's where generics come into play. Its much easier to understand this with an example.

Defining a generic method

Consider the example below. It shows a generic method Print() that accepts any type (string,int,double,float etc) of variable. You declare the type you are passing in, in the angle brackets <> where you call the method.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
 
            Print<int>(2);
            Print<string>("hello");
        }
 
        static void Print<T>(T myVariable)//This is a generic method

        {
            Console.WriteLine(myVariable.ToString());
        }
 
    }
}

The T in the angle brackets after Print means that any type can be passed in. 

As you can see, the type being passed in has to be known at compile time. If you want type to be resolved at run time, you would have to use reflection.

Defining a generic class


In the code below Hello is a generic class. The type of T is established at the point where you instantiate the class.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication
{
    namespace ConsoleApplication
    {
        class Program
        {
            static void Main(string[] args)
            {
 
                var h1 = new Hello<int>();
                h1.Print(10);
 
                var h2 = new Hello<string>();
                h2.Print("hi");
            }
 
        }
 
        public class Hello<T>//This is a generic class
        {
 
            public void Print(T myVariable)
            {
                Console.WriteLine(myVariable.ToString());
 
            }
        }
    }
 
}


Note here that Print is NOT a generic method.

A generic class has angle brackets <> after the class name. 
A generic method has angle brackets<> after the method name.

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator