Content by Category
.NET 1.x
.NET 2.0
.NET 3.0
.NET 3.5
.NET 4.0
.NET Assemblies
.NET Framework
.NET Getting Started
Accessibility
ADO.NET
Advertorials
Agile Development
AJAX
Architecture
ASP.NET
ASP.NET MVC
ASP.NET WebForms
Azure
B2B (Business Integration)
Bing
BizTalk
Book Excerpts
Build and Deploy
C#
C++
ClickOnce
Cloud Computing
Code Contracts
CODE on the Road!
COM+
Community
Conferences
Continuous Integration
Crystal Reports
CSLA.NET
CSS
Data
Design Patterns
Development Process
Display Technologies
Distributed Computing
DotNetNuke
DSL
Dynamic Programming
Editorials
Enterprise Services ("COM+")
Entity Framework
Events
Expression Blend
F#
Fox to Fox
Frameworks
Functional Programming
Git
Graphics
Internet Explorer 8.0
Interviews
iPhone
Iron Ruby
Java
Java Script
jQuery
LINQ
Linux
Mac OS X
MDX
Microsoft Application Blocks
Microsoft Business Rules Framework
Microsoft Dynamics
Microsoft Expression
Microsoft Office
Mobile Development
Mobile PC
Mono
MsBuild
Network
NHibernate
Object Oriented Development
Odata
Open Source
Opinion
Opinions
Oracle
ORM
Other Languages
Parallel Programming
Patterns
Podcasts
Post Mortem
PowerPoint
Print/Output
Prism
Product News
Product Reviews
Project Management
Python
Q&A
Rails
Rake
Reporting Services
REST
RIA Services
Ruby
Ruby on Rails
Search
Security
Services
SharePoint
Silverlight
SOA
Social Networks
Software & Law
Software Business
Source Control
Speech-Enabled Applications
SQL Server
SQL Server 2000
SQL Server 2005
SQL Server 2008
SQL Server CE/AnyWhere/Mobile/Compact
SSIS
Subversion
Sync Framework
Tablet PC
TDD
Team System
Techniques
Testing and Quality Control
Tips
UI Design
UML
User Groups
VB Script
VB.NET
Version Control
VFP and .NET
VFP and SQL Server
Virtual Earth
Vista
Visual Basic
Visual Basic 6 (and older)
Visual FoxPro
Visual Studio .NET
Visual Studio 2005
Visual Studio 2008
Visual Studio 2010
Visual Studio Tools for Office
VSX
WCF
Web Development (general)
Web Services
WF
Whitepapers
Windows 7
Windows Azure
Windows Live
Windows Server
Windows Vista
WinForms
Workflow
WPF
XAML
XML
XNA
XSLT



Devscovery


 


Free Webinar


Reader rating:
Click here to read 5 comments about this article.
Article source: CoDe (2007 - Mar/Apr)


Article Pages:  1  2 3 - Next >


Everyday Use of Generics

You may think of generics as a Ferrari that you only take out for special occasions; but they are better compared to your trusty pickup, perfectly suited for everyday use.

It would be nice to begin by saying in simple terms what generic are … but it is hard to explain exactly what generics are. Generics are not really a single thing but rather a set of techniques with a single purpose: to work with generalized code in a data type-specific way.

"
With the built-in generic collection classes you may never need to dimension an array again!
"

This somewhat complex-sounding purpose is why it may appear that generics are a Ferrari-style technique. But getting past the definition to actual examples will demonstrate how you can use generics every day to minimize the amount of code you write and improve the performance of your applications.

The two most fundamental and potentially “everyday” generics techniques involve the built-in generics collections and generic methods.

If you ever use arrays or ArrayLists in your applications, consider using the built-in generics collections instead. The built-in generics collections are not only easier to use than arrays, but they allow you to limit the data type of the items that are in the collection. This provides type-safety, meaning that a compile-time error is generated if the code attempts to put something in the collection that is not of the correct type. It can also improve the performance of the application, limiting conversion of data types.

Generic methods provide a way for you to write code that can work with any data type. You then specify the data type that you want to use when you call the code. This minimizes repetitive code and maximizes type safety.

For both techniques, generics provide for code (either that you write or that is in the Framework) that will work with any data type, such as strings, integers, business objects, etc. You then specify the data type that the code should use when you call that code. That allows you to reuse that code for any number of data types.

This article demonstrates how to use the built-in generic collections instead of arrays. It then details other uses of generic collections, such as for data binding and sorting. Finally, it describes how to build your own generic methods to take advantage of generics every day.

Using Generics Instead of Arrays

Arrays are a common mechanism for storing data in an application. You may currently use them to store internal data or user-entered values. But working with arrays is somewhat complex. First you need to set up their dimension, and then you need to keep track of how many items you are adding to the array so you don’t exceed their dimension.

For example, the following code takes user-entered names and adds them to an array:

Private NameArray(5) As String
Private NameArrayIndex As Integer = 0



If NameArrayIndex Then
    ReDim Preserve NameArray(NameArray.Length + 5)
End If
NameArray(NameArrayIndex) = NameTextBox.Text
NameArrayIndex += 1

If you instead use one of the built-in generic collections, you can replace the two declarations with one and replace the five lines of code to manage the array with one line of code:

Private NameList As New List(Of String)



NameList.Add(NameTextBox.Text)

Note: If Visual Studio does not recognize the List keyword, examine your project imports (My Project, References Tab, Imported Namespaces section). Ensure that System.Collections.Generic is checked. Or prefix the List keyword with System.Collections.Generic.

The declaration in this example creates a new instance of the List built-in generic collection. The “Of String” syntax is used to identify the type parameter and defines the specific data type to use with the generic collection. In this case, only strings can be added to the collection.

Note: You will often see generics documented using “Of T” such as List(Of T). The T is the placeholder for the type parameter and can be replaced with any data type when using the generics collection or method.

If the code attempts to put something other than a string into the collection, the code generates a compile-time error. For example:

NameList.Add(1)

This line will generate the error: “Option Strict On disallows implicit conversions from 'Integer' to 'String'”. (Assuming of course that you have Option Strict On.)

If you want to retain key and value pairs, such as U.S. states along with their abbreviations, you can use a generic Dictionary. Generic Dictionaries have two type parameters, a unique key and a value.

Note: Do not confuse these generic Dictionaries with the old scripting Dictionaries sometimes used in Visual Basic 6.0 applications.

The following code creates a new generic Dictionary and adds the abbreviation as the key and the long name as the value:

Private StateDictionary As New Dictionary(Of 
StringString)



StateDictionary.Add("CA", "California")
StateDictionary.Add("NY", "New York")
StateDictionary.Add("WI", "Wisconsin")

Even though the code examples so far showed Strings as the type parameters, you can use any data type as the key or as the value.

For example, if you had a Person business object with a unique numeric ID, you could define a PersonDictionary as follows:

Private PersonDictionary As New Dictionary(Of 
IntegerPerson)

The .NET Framework provides for several different types of generic collections. The ones that you may use most often include:

  • Dictionary: Provides a list of key and value pairs where the key must be unique. For example PersonDictionary(Of Integer, Of Person) represents a collection of Person objects keyed by a unique integer value.
  • List: Provides a list of values that can be accessed by index. For example PersonList(Of Person) represents a list of Person objects. The List provides methods to search, sort, and manipulate lists.
  • SortedDictionary: Provides a generic Dictionary that is sorted by the unique key.
  • SortedList: Provides a generic List that is sorted by a unique key.

Each of these generic collections provides better type safety and performance than non-generic collections and is much easier to use than arrays. With the built-in generic collection classes you may never need to dimension an array again!

&

By: Deborah Kurata

Deborah Kurata is cofounder of InStep Technologies Inc., a professional consulting firm that focuses on turning your business vision into reality using Microsoft .NET technologies. She has over 15 years of experience in architecting, designing and developing successful applications.

Deborah is the author of several books, including Best Kept Secrets in .NET (Apress), Doing Objects in Visual Basic 6.0 (SAMS) and Doing Web Development: Client-Side Techniques (Apress). She is on the INETA Speaker’s Bureau, is a well-known speaker at technical conferences, and is a Microsoft Most Valuable Professional (MVP). After a hard day of coding and taking care of her family, Deborah enjoys blowing stuff up (on her XBox of course).

Some of the information in this article was obtained from her upcoming book, Doing Objects in VB 2005.

deborahk@insteptech.com

Fast Facts

The .NET 2.0 Framework now supports a new style of strongly typed collections called generics. This article demonstrates how to use generics in your .NET code.



Article Pages:  1  2 3 - Next Page: 'Data Binding With Generic Collections' >>

Page 1: Everyday Use of Generics
Page 2: Data Binding With Generic Collections
Page 3: Writing Generic Methods

How would you rate the quality of this article?
1 2 3 4 5
Poor      Outstanding

Tell us why you rated the content this way. (optional)

Average rating:
3.9 out of 5

20 people have rated this article.

      INSTANTLY dtSearch® TERABYTES OF TEXT

 

INSTANTLY dtSearch® TERABYTES OF TEXT