Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Serializing, Consuming, and Binding Generics in .NET 2.0

Generics are a powerful new feature in .NET 2.0, but it's not so obvious how to use them as return values from Web services, or how to bind them to controls. Find out how to serialize, data bind, and consume generic collections in ASP.NET 2.0


advertisement
enerics, a new feature introduced with .NET 2.0, provides type safety at compile time. Generics let you create data structures without committing to a specific data types in your code at design time. At compile time, the compiler ensures that the types used with the data structure are consistent with type safety. In other words, generics provide type safety, but without any loss of performance or code bloat. While they are similar to templates in C++ in this regard, their implementation is very different.

This article discusses the application of generics in .NET development and different ways in which you can leverage generic types and collections within a .NET application.

What are Generics?
Generics are code templates generalized to use the same code repeatedly with different data types without needing to rewrite any of the internal code, and thus increasing the reusability of your software components. Within the data structure, member or argument usage adapts to different data types. Generics let you avoid those all-too-common, messy, and resource-intensive conversions from reference types to native types, creating routines that are much more type-safe.

You define a generic using a slightly different notation than you're used to with non-generic types. For example, here's the basic code for a generic class named Compare that can compare two items of the same type and return the larger or smaller value, depending on which method is invoked:

public class Compare<ItemType, ItemType> { public ItemType ReturnLarger (ItemType data, ItemType data2) { //logic... } public ItemType ReturnSmaller (ItemType data, ItemType data2) { //logic... } }


You've probably written similar code, but you've also probably written it many times, once for each type you want to compare. In contrast, you can use this generic class with any data type, ranging from basic data types such as integers to complex classes and structures. When you use the generic, you identify what data type you're planning to use with it. For example, to compare Integers with the Compare generic class, you would write code similar to the following:

Compare<int, int> compare = new Compare<int, int>; int result = compare.ReturnLarger(3,5);




Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap