Tuesday, May 17, 2011

Generic Programming in C#

Generic Programming is derived from the Template based programming that originated with C++. The syntax remains the same, however the logic has changed a little bit. In C++ the methods are generated automatically based on the type of the Input Parameters. In C# the Type Parameters are specified as a part of the Class Declaration. This Permits type verification at compile time, thus making the system Type Safe.

A template based stack in C++


#include<conio.h>
#include<string.h>
#include<iostream.h>
template<class T>
class Stack
{

private:class data
{
public:T value;
public: data* next;
};
private:data* ptr;
public:Stack()
{
ptr=NULL;
}
public:void push(T value)
{
data* temp=new data();
temp->value=value;
temp->next=ptr;
ptr=temp;
}
public:void pop(T& value)
{
if(ptr==NULL)
value=NULL;
else
value=ptr->value;
ptr=ptr->next;
}
public:int isEmpty()
{
return(ptr==NULL);
}
};
void main()
{
Stack<int> s;
for(int i=0;i<=10;i++)
s.push(i);
cout<<"\n";
while(!s.isEmpty())
{
int n;
s.pop(n);
cout<<n<<",";
}
getch();
}




A Generic Class in C#

Here we implement a class that provides a Generic Max function that compares two inputs and returns the larger of the two. Here is the Code:

Comparer.cs
public   class Comparer<T> where T:IComparable
    {
      public T max(T a, T b)
      {
          if (a.CompareTo (b)>=0)
              return a;
          else
              return b;
      }

    }





Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Generics_Operation
{
    class Program
    {

public static int add(params int[] numbers)
        {
            int sum = 0;
            foreach (int number in numbers)
                sum += number;
            return sum;
        }
        static void Main(string[] args)
        {
            Comparer <int> intcomparer = new Comparer <int>();
            Comparer<string> stringcomparer = new Comparer<string>();
           // Comparer<Program> p = new Comparer<Program>(); This is not allowed as Program does not implement IComparable
         Console.WriteLine (intcomparer.max(1, 2));
         Console.WriteLine(stringcomparer.max ("Sachin","Rahul"));

Console.WriteLine(add(1, 2, 3, 4, 5, 6));
            Console.ReadKey();

        }
    }
}
 



No comments:

Post a Comment