2 May 2012

Generics in Dotnet

Generics  in Dotnet


·         In generic class, you can create a collection that is type-safe at compile-time.
   
      Generics are the most powerful feature of C# 2.0. Generics allow you to define type-safe data structures, without committing to actual data types. This results in a significant performance boost and higher quality code, because you get to reuse data processing algorithms without duplicating type-specific code. In concept, generics are similar to C++ templates, but are drastically different in implementation and capabilities. This article discusses the problem space generics address, how they are implemented, the benefits of the programming model, and unique innovations, such as constrains, generic methods and delegates, and generic inheritance. You will also see how generics are utilized in other areas of the .NET Framework such as reflection, arrays, collections, serialization, and remoting.


            If the items are value types, they must be boxed when they are added to the list, and unboxed when they are retrieved. 
·       
            Both the casting and the boxing and unboxing operations decrease performance; the effect of boxing and unboxing can be very significant in scenarios where you must iterate over large collections.
    
      The other limitation is lack of compile-time type checking; because an ArrayList casts everything to Object, there is no way at compile-time to prevent client code from doing something such as this:

    System.Collections.ArrayList list = new System.Collections.ArrayList();
    // Add an integer to the list.
    list.Add(3);
    // Add a string to the list. This will compile, but may cause an error later.
    list.Add("It is raining in Redmond.");
    int t = 0;

    // This causes an InvalidCastException to be returned.
    foreach (int x in list)
    {   t += x;
    }


No comments:

Post a Comment

Comments Welcome

Consistency level in Azure cosmos db

 Consistency level in Azure cosmos db Azure Cosmos DB offers five well-defined consistency levels to provide developers with the flexibility...