VisualBuilder
  Home > Dotnet > Tutorials > Introduction to Generics - .NET Tutorial
Tell a friend
Link to us
Total Members
      Members: 84606
     
Sitemap Forum Chat
Home
.NET Tutorial Home
1 . Overview of .Net Framework
2 . .Net Components:
3 . CLR (Common Language Runtime)
4 . Steps to Run a program in CLR
5 . Assembly
6 . GAC (Global Assembly CACHE)
7 . Strong Name in .Net Assembly
8 . ILDASM: Intermediate Language Disassembler in .Net
9 . Custom Attributes in .Net
10 . Application Domain in .Net
11 . Code Access Security in .Net
12 . Type System in .Net -1
13 . Type System in .Net -2
14 . Reflection: Inspection of a Type\'s Metadata
15 . Introduction to Generics
16 . Generic Classes and Methods
17 . Generic Methods in .Net 2.0
18 . Overview of Inheritance in Generics classes
19 . Connection pooling in .Net Applications
20 . Deployment in .Net
 
Dotnet Group Home
Dotnet Discussion (9)
Dotnet Members (2825)
Dotnet Resources
Dotnet Source Code (0)
Dotnet Articles (0)
Dotnet Blogs
Dotnet Jobs
Dotnet Components (2)
Dotnet Books
Dotnet Websites (43)
Dotnet News (186)
Dotnet Q & A (3)
- Dotnet Ask Question
- Dotnet Questions
- Dotnet Unanswered Questions
 
GROUPS
.NET
ASP.NET
.NET
C#
ASP
Visual Basic
Java
Java
JSP
EJB
Other
Delphi
C++
Ajax
UML
JavaScript
PHP
Web Design
Web Hosting
SQL Server
Oracle
Project Management
More Groups

 
LEARNING CENTER
TUTORIALS
.NET
.NET Tutorial
ASP Tutorial
ASP.NET Database Tutorial
ASP.NET Development Tips
ASP.Net Security,Internationalisation And Deployment
ASP.NET Server Controls Tips
ASP.NET Tutorial
C Sharp Tutorial
Web Development
Flex Tutorial
HTML Tutorial
Learn AJAX Tutorial
PHP Tutorial
Software Development
Database Tutorial
SQL Tutorial
UML Tutorial
Java
Ant Tutorial
EJB 3 Tutorial
Hibernate Tutorial
Java Tutorial
Java Web Component Tutorial
Java XML Tutorial
JDBC Tutorial
JDK1.5 Tutorial
JSF Tutorial
JSP And J2EE Design Tutorial
JSP Tutorial
Spring Tutorial
Struts Tutorial

RESOURCES
Q & A (432 )
Source Code (3217 )
Articles (11 )
Components (1589 )
News (880 )
Websites (1207 )

SUBMISSIONS
Submit Article
Submit Website
Submit News
Submit Source Code
Submit Component

COMMUNITY
Members Directory
Discussion Forum
Chat

SITE
About Us
Sitemap
Search
Contact Us
Link To Us
Feedback
Tell a Friend
Partners
Advertise


Dotnet Tutorial
 Introduction to Generics
  << Prev: Reflection: Inspection of a Type\'s Metadata Next: Generic Classes and Methods >>

Type Safety


 


Many of the languages in .NET, like C#, C++, and VB.NET (with option strict on), are strongly typed languages. As a programmer using these languages, you expect the compiler to perform type-safety checks. For e.g. If you try to cast a variable of type “person” to type “student”, then the compiler will give you the message that this type of cast is invalid.


 


But in .Net framework, compiler doesn't provide any type safety help for collections; this means the collections doesn't provide the type safety at the time of compilation


 


Demonstration: Inserting different type values in Arraylist Collection


 


using System;


using System. Collections;


 


namespace TestApp


{


class Test


{


[STAThread]


static void Main (string[] args)


{


ArrayList templist = new ArrayList();


templist.Add(3);


templist.Add(4);


// templist.Add(5.0)


// Runtime Exception Occurs Not CompileTime Error


int listTotal = 0;


foreach(int arrVal in templist)


{


listTotal = listTotal + arrVal;


}


Console.WriteLine ("List Total is {0}", listTotal);


}


}


}


 


Note:- Here I comment the line “ templist.Add(5.0)”. If I uncomment this line this will throw runtime exception. We know the ArrayList collections hold a collection of objects. When we are adding values in the array list this is called boxing. Here also, when we add 5.0 we are boxing a double. But when we are adding the array value, here the double value is unboxed as an int; this causes an exception to occur.


 


Generics:


 


Generics provide type safety, but without any loss of performance or code bloat. While they are similar to templates in C++ in this regard, they are very different in their implementation. They allow developers to realize about type safety at compile time.“System.Collections.Generics” namespace contains the generic collections in .Net2.0.


 


Demonstrate: Type Safe generic list


 


The above example code has to be changed as the below code for generics.


 


List<int> aList = new List<int> ();


aList.Add(3);


aList.Add(4);


// aList.Add(5.0);


int total = 0;


foreach(int val in aList)


{


total = total + val;


}


Console.WriteLine("Total is {0}", total);


 


Here, I am creating an instance of the generic List with the type int, given within the angle brackets (<>), as the parameterized type. This code, when executed, will produce the result "Total is 7." Now, if I uncomment the statement “aList.Add(5.0)”, I will get a compilation error. The compiler determines that it can't send the value 5.0 to the method Add(),as it only accepts an int


 


Constraints and Benefits of Generic Classes:


 


The generic classes provide user to create class that can be indicated at the later stages which type to be used. This also provides some constraints.


 


Example: Demonstrate Constraints while using Generic classes


 


public static T Max<T>(T op1, T op2)


{


If (op1.CompareTo (op2) < 0)


return op1;


return op2;


}


 


Note: The code will produce compilation error. "Error 1 'T' does not contain a definition for 'CompareTo' " Assume I need the type to support the CompareTo () method. I can specify this by using the constraint that the type specified for the parameterized type must implement the IComparable interface. This can be solved by putting public static T Max<T> (T op1, T op2) where T: IComparable


 


Note:- The above constraints can be used, where.



  • T [is struct] type must be a value type (a struct)

  • T [is class] type must be reference type (a class)

  • T [is new ()] type must have a no-parameter constructor

  • T [is class_name] type may be either class_name or one of its sub-classes (or is below class_name in the inheritance hierarchy)

  • T [is interface_name] type must implement the specified interface


 


  << Prev: Reflection: Inspection of a Type\'s Metadata Next: Generic Classes and Methods >>
Dotnet Tutorial Home
Give feedback and win a prize.

 
   Printer Friendly
   Email to a friend
   Add to my Favourites    
  Download PDF version
   Report Bad Submissions
   Submit Feedback
 
  Delicious   Digg   Technorati   Blink   Furl   Reddit   Newsvine   Google Click each image to add
this page to each site.
 
 
Welcome Guest Signup
MEMBER'S PANEL
EMAIL
PASSWORD
Forgot your password?
New User? Click Here!
 
Resend Activation Email!
 
SEARCH
 
 
LINKS
MSN
Video Surveillance
Hosted Exchange, SDSL
Gift to Pakistan
 
ADVERTISEMENT
 
PARTNER LIST

More
 
 
 

Home | Login | About Us | Contact Us | Privacy Policy | Advertising