SIGN UP MEMBER LOGIN:    
ARTICLE

Generics in .NET

Posted by Dinkar Chavhan Articles | Learn .NET April 23, 2011
An introduction to Generics
Reader Level:


Generics : Generics allow a type or method to operate on objects of various types while providing compile time type safety; that means if you add in generics class different type variable. Eg., string and int in a same list then it will throw a compile time error. Generics are available in the System.Collections.Generic Namespace.

Let's see other definitions:

Generics are a new feature in version 2.0 of the C# language and the Common Language Runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. (Source MSDN)

Let's see an example.

//Create a Generic Class
public class MyGeneric<T>
{
void Add(T val) { }
}
//Create another class which consume MyGeneric class
class MyGenericTest
{
static void Main()
{
// Declare a generic list of type int
MyGeneric<int> myGenericObj1 = new MyGeneric<int>();
// Declare a generic list of type string
MyGeneric<string> myGenericObj2 = new MyGeneric<string>();
}
}

Benefits of using Generics:

  1. Generics provide Type Safety and the performance is faster.
  2. You can create your own collection class.
  3. You can create your own generic interfaces, classes, methods, events and delegates.

Login to add your contents and source code to this article
share this article :
post comment
 
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor