Saturday, 3 March 2012

How to apply Constraints On Generics in method level?

Yes we can apply constrains on any method then that method only works for that type of data only
Ex:
Static sort(T) where T : [Class]/[Sturct]/[Interface]
{

}
Then T works for that specific type of data only.
Ex:
Where T : MyparenetClass

Classà MyParentClass[Ex: ] and derived types only can use this Sort(T) method. 
Struct-> MyValueStruct[Ex:..] and derived type only can  use this Sort(T) method.
Interface-> MyInterface and dervided types whatever classes and structures
implemnets this Interface[ex:IComparable].those only can implement this interface.

Ex
  class ConstraintsOnGenerics
    {       
        static void sort<mytype>(mytype[] A) where mytype :IComparable
        {            
            mytype T;
           // my k;
            for (int i = 0; i < A.Length; i++)
            {
                for (int j = i + 1; j < A.Length; j++)
                {
                    if (A[i].CompareTo(A[j])>0)
                    {
                        T = A[i];
                        A[i] = A[j];
                        A[j] = T;
                    }
                }//j is closed           
            }//i is closed         
        }//ConstraintsOnGenerics is closed
        static void my<ty>(ty[] A)           //where ty:IComparable
        {
            foreach (ty i in A)                   // Single foreach for three different type :int,double,string also
            {
                Console.WriteLine("{0}\t", i);   // Generic Foreach
            }
        }
        static void Main()
        {
           int[] A = { 12, 63, 89, 19, 56 };
            double[] d = {12.3,56.2,85.9,45.5 };
            string[] s = {"kasi","mani","sai","babu","pavani"};
            sort<int>(A);
            sort<double>(d);
            sort<string>(s);
            my<int>(A);
            my<double>(d);
            my<string>(s);
            Console.ReadKey();
        }
    }

Here IComparable is Interface which is implemented by intger,string,double also
As well as this method accepts any type(it can be referencetype,valuetype) which implement IComparable interface.

No comments:

Post a Comment