Professional Documents
Culture Documents
Generic Types in C# 2
Generic Types in C# 2
0 with Sample
TECHNOLOGIES ANSWERS BLOGS VIDEOS INTERVIEWS BOOKS LINKS NEWS CHAPTERS CAREER ADVICE
0 Reader Level:
Generic Types
Generics are the most powerful feature of C# 2.0. It allows defining type-safe data structures,
without committing to actual data types. In C# 1.0 we can either declare reference type or value
type. But in most of the application we come across situation where we need type that can hold
both reference & value type. In such situation we use generic types.
Why Generics?
TRENDING UP
1. Generic type doesn't care what the type is. We can specify the type at runtime.
Object Oriented Design Principles
2. It avoids boxing difficulties. In C# 1.0, if we want to put any object into a List, Stack, or
Queue objects, we have to take type as System.Object. Tips & Tricks - Compare Database Project in Solution
3. It boosts the performance of the application because we can reuse data processing algorithm With SQL Server Database
without duplicating type-specific code. Caching in ASP.NET
www.c-sharpcorner.com/uploadfile/abhishekbhatore/generictypewithsample07292005092634am/generictypewithsample.aspx 1/3
4/17/13 Generic Types in C# 2.0 with Sample
list.Add(20); //Argument is boxed
list.Add(40); //Argument is boxed
list.Add("Sixty"); //Error in retrieving
Abstract Class ArrayList
Boxing Console Constructors enum EventHandler
Console.WriteLine("Item Added");
int val = (int)list[0]; //Casting required FileStream Hashtable
Extension Methods
Console.WriteLine("Value retrived : " + val);
} inheritance Interfaces List objectdatasource
Memory Consumption OOP Sorting StreamReader StreamWriter
In C# 1.0 boxing is necessary evil to make type system work. While working with structures of
System.Collection namespace (Stacks,List,Hashtable etc) we face the problem in insertion &
Thread unboxing
Class Strings System.Text
In C# int takes 4 byte but when it boxed it take (4+8) 12 bytes, which is 3 times to normal size.
In C# 2.0 the type is decided at runtime so boxing does not take place. SPONSORED BY
It compiles successfully but later on if some one pulls value and cast it into integer it fails. The
problem is fixed in C# 2.0; we will get compilation error there.
Constraint Description
Public class Books where T: struct The type argument for class Books must be a value type
The type argument for class Books must be a reference
Public class Books where T: class
type
Public class Books where T: new( ) The type argument for class Books must have a public
default constructor
Public class Programmer where T: The type argument for class Programmer must be of
<Employee> Employee type.
www.c-sharpcorner.com/uploadfile/abhishekbhatore/generictypewithsample07292005092634am/generictypewithsample.aspx 2/3