Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

4/17/13 Generic Types in C# 2.

0 with Sample

In Focus FEEDBACK NEEDED: Profile and My Account Pages Redesign abhishek

Ask a Question Contribute

TECHNOLOGIES ANSWERS BLOGS VIDEOS INTERVIEWS BOOKS LINKS NEWS CHAPTERS CAREER ADVICE

Object Oriented Design Principles PREMIUM SPONSORS

ARTICLE DynamicPDF Developer


Components
Generic Types in C# 2.0 with Sample DynamicPDF™ product line allows you
Posted by Abhishek Bhatore in Articles | C# Language on August 01, 2005 to dynamically generate PDF
Tags: .NET, C# 2.0, Generic Types, GenericList Class, Memory Consumption documents, merge PDF documents and
add new content to existing PDF
This article discusses generic types available in C# 2.0. The article also shows some sample source code documents from within your
applications.
on how to use generic types.

Tw eet 0 Share 0 Like 0 51882 1

0 Reader Level:

Download Files: GenericType.zip

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

How Generic implemented: Animation in WPF


Unit Test Automation With Visual Studio
(1) Generic type is instantiated at run-time not compiled time
(2) Generic type are checked at time of declaration not at instantiation Using LINQ in .NET
(3) It works for both reference type & value type. ASP.NET Application Life Cycle
Create a Android Project With Eclipse
Let's create simple class "GenericList" using C# 1.0 & 2.0 respectively & compare them.
Introduction to Windows Store Apps
FileSystem Function in PHP: PART 8
Code GenericList Class (C# 1.0)
View All
using System;
using System.Collections.Generic;
using System.Text; MOST LIKED ARTICLE
public class GenericList
WCF Introduction and Contracts - Day 1
{
private object[] elements; Create SSRS Report Using Report Wizard
private int count; CREATE READ UPDATE and DELETE - CRUD Operation Using
public GenericList() LINQ to SQL
{
elements = new object[10]; WCF - Data Contract - Day 4
} WCF - Difference Between Service Application and Service
public object this[int index] Library: Day 5
{
get { return elements[index]; } Follow @csharpcorner 4,032 follow ers
set { elements[index] = value; }
}
Find us on Facebook
public void Add (object parm)
{
C# Corner
if (count == elements.Length)
{ Like
// Increase the
object[] tmpArray = null ;
9,141 people like C# Corner.
elements.CopyTo(tmpArray,0);
elements = new object[count * 2];
elements = tmpArray;
}
elements[count] = parm;
count = count + 1;
}
}
F acebook social plugin
Main Method:

static void Main(string[] args)


{ HOT KEYWORDS
Console.WriteLine("using C# 1.0");
GenericList list = new GenericList();

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

User Controls visual studio Visual


retrieval of values. We need to take System.object as type & System.object is reference type, so
whenever we access the hashtable, the runtime has to box the values to put into the collection &
need to unbox to take it out.
Studio 2005
list.Add(20); //Argument is boxed

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

Type Safe File APIs for Programmers


Easily convert, print, create, modify and
When we use the statement combine files. Manage DOC, XLS, PPT, PDF,
MSG and more with Aspose.
list.Add ("Sixty"); or List [3] = "sixty";

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.

Code GenericList Class (C# 2.0)

public class GenericList<T>


{
public GenericList()
{
elements = new T[10];
}
private T[] elements;
private int count;
public T this[int index]
{
get {return elements [index];}
set {elements [index] = value;}
} WHITEPAPERS AND BOOKS
public void Add (T parm) Interview Questions on SharePoint 2013
{
if (count == elements.Length) SharePoint 2010 Administration & Development
{ Getting Started with Managed Metadata Service in
T[] tmpArray = null; SharePoint 2010
elements.CopyTo(tmpArray, 0);
elements = new T [count * 2]; Windows Phone 7 Hileleri
elements = tmpArray; Windows Phone Development Step by Step Tutorial
}
Essentials of SharePoint 2010: Business Intelligence
elements [count] = parm;
Capabilities
count = count + 1;
} Working with Directories in C#
} FileInfo in C#

Main Method: Programming List with C#


Source Code: Graphics Programming with GDI+
static void Main(string[] args)
{ View All
Console.WriteLine("using C# 1.0");
GenericList<int> genericList = new GenericList<int>(); POLL RESULT ALL POLLS
genericList.Add (10); //No boxing
genericList.Add (20); //No boxing Wi ndows vs . Web vs . Mobi l e
// genericList.Add("Fifty"); //Compile Time Error What do you work mostly these days?
Console.WriteLine("Item Added"); Web (ASP.NET, HTML) applications
int valGeneric = (int)genericList[0]; //No Casting Required
Console.WriteLine("Value retrived : " + valGeneric); Windows (WPF, Windows Forms) applications
} Mobile (iPhone, Android, Windows Phone) Apps

Some other Points: Windows 8 Apps


Vote
(1) Type parameter can be applied to Class, struct, interface & delegates.

struct Buket<K, V>;


interface ICompare<T>

(2) Type parameter can have constraints.

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

You might also like