Tuesday, July 3, 2012

Generics in C#

Introduced in .NET 2.0, Generics introduced type parameters to the framework. Generics makes it possible to design classes or methods to defer the specification of types until the class or method is declared and instantiated by the client code. 



Generic types combines reusability, type safety and efficiency when compared to non-generic counterparts. Generics are frequently used with collections.

You can check if a type is of generic type using Type.IsGenericType property.


Benefits

Before generics, generalization in C# was achieved by casting types to and from Object type. But using generics you can assure type safety at compile time. 

With generics, you don't have to box unbox types as we used to do with ArrayList in .NET 1.0



Benefits of Generics

Generic type parameters ##

It is a placeholder for a specific type the client specifies when instantiating a generic type. 

Generic Classes
Encapsulate operations that are not specific to a single data type. Are commonly used with collection classes. 

Difference between Generic type and Generic type definition
  • Generic type definition : List<T>
    • T is called Generic Type Parameter
  •  Generic type : List<string> 
Constraints on generic type
https://msdn.microsoft.com/en-us/library/d5x73970.aspx

System.Collections.Generic namespace

Contains useful generic collections. 
  • Dictionary
  • LinkedList
  • List




0 comments:

Post a Comment

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook