Friday, 2 March 2012

Generics are imporve the performance of programm?


Yes, Generics improve the performance of program in cast of application also. we have Generic methods as well as Generic Classes also.

How Generics Improve the Performance?

Instead of converting a type to particular type means explicitly type casting by the developer it provides no’ f methods which are convertible by itself as per our type.

First we will see Generic Methods
Ex:
class GenericList
    {
        public static List<string> GetCourses()
        {
            List<string> obj = new List<string>();
            obj.Add("csharp");
            obj.Add("vb.net");
            obj.Add("fsharp");
            obj.Add("jsharp");
           
            return obj;
        }
        static void Main()
        {
            List<string> a = GetCourses();
            foreach(string item in a)
            {
                Console.WriteLine("{0}", item);
            }
            Console.ReadKey();                               
        }       
}


 but this above method Getcourses() method not useful for handling/casting        other types. Like other types   like,int,double,float,employee,customer,student ect

why because
           Here T- is--àstring=èList<string>

The above GetCousrse()----till that scope to string

In .net Framework
Ex:
class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
{
  Implementations of the the Particular T type
     [T can be int,floaat,employee…….ect]
}
Here List class Implements the type of T(it can be int,string,double,…any custom type(employee,student,customer) also.
As per our sending type[int,string,double,employee,students..ect] the remaining methods return types also changes.
Ex:
List<int> intlist=new List<int>()---intlist accepts only integer data.
List<string> strlist=new List<string>()—strlist accepts only string data.
And those methods returns data also the particular type otherwise optionally we can Use Var as a return type.

ExDemo1:
        List<int> intlist=new List<int>();
1.      List<int> ierint=intlist.GetEnumerator()
      ortherwise we can use
2.      IEnumerable<int> ierint=intlist.GetEnumerator()
 otherwist we can use
3.       Var ierint=intlist.GetEnumerator()
As well as string type also.
ExDemo2:
    List<string> strlist=new List<string>();

4.      List<int> ierint=intlist.GetEnumerator()
              otherwise we can use
5.      IEnumerable<int> ierint=intlist.GetEnumerator()
       otherwist we can use
6.      Var ierint=intlist.GetEnumerator()
As well as string type also.




No comments:

Post a Comment