asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search





Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Generics In-Depth
By J. Ambrose Little
Rating: 3.3 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction


    One of the most talked-about features of the next version of the .NET Framework is generics capability. The funny thing is that although generics are extremely useful, they also seem to have a certain mystique about them that cannot be readily explained. Perhaps the fact that VB never supported anything like them, C++ did (templates), and that the C# team seems to have led the way in pushing the addition of this feature has led to the perception that they are an advanced feature that only the elite can understand.

    This author hopes to dispel, as much as possible, that aura of mystery by digging into generic support in .NET v2 and showing just how easy it can be used and how useful it can be in many common situations. As a result, the reader should come away with, at a minimum, an idea of when and how to use generics, the terminology surrounding them, and perhaps even a feeling of confidence in creating his or her own generic types and methods.

    What's in a Name?

    Before moving on, you need to be clear on just what a "type" is in .NET because there still seems to be some confusion surrounding this point. "Type" is simply short hand for "type of data" or "data type"; a type tells the computer how to store information (data) and what will be done with that information.

    There are different ways to store data and different ways that data can be acted upon, so we need to have ways to tell the computer that this particular information should be stored in this way and that particular information should be used in that way. This is where data types come in handy.

    There are different kinds of data types in the .NET Framework. There are classes, enums, delegates, structs, and events. Classes are by far the most common kind of type, so much so that many folks often forget or neglect the others. We even say "class library" when in fact many, if not most, "class libraries" contain all different kinds of types.

    So when we say "type," we mean a blueprint that instructs the computer how to store and act on a particular set of information. And when we say "strongly typed," we mean that the computer has enough information-a clear blueprint-on how to deal with particular data that it can tell you up front (i.e., at design and/or compile time) if you are using the type correctly ("type checking") and even, such as in the case of Visual Studio, help you use it by helping you remember what features are available for a given type (e.g., Intellisense). Further, the computer can help itself by optimizing how it handles the data, giving you better performance and reliability. Both of these concepts are prerequisites for understanding why generics are beneficial to computer users.

    Problems Solved

    Now that we are clear on the fundamental terminology, we can move on to the issue at hand. Just what is it that generics do? Why are they important? What problems do they solve? How will they make life easier? Ultimately, why should you care?

    The truth is that I don't think there will be a .NET developer out there who will not benefit from generic features, whether it's simply by using the types in the System.Collections.Generic namespace or by taking advantage of the technology to write better types themselves. The reasons for this assertion should become clear as this article unfolds.

    The most obvious benefit, and the one that will likely provide the most widespread benefit, is in the area of type collections. The most basic type of a collection is an array; however, arrays can be difficult to use, particularly when the number of items in the array varies and when the actual items in the array vary or move around. To address these limitations, we have collections, which are more or less friendly wrappers around arrays. More important, they enable us to interact with collections of types in a familiar way, just as we might interact with a collection of items in the real world.

    The problem with collections in the first version of .NET is that in order for them to be strongly typed, the developer would have to write custom collections for each and every type, overriding or implementing methods (such as Add, Remove, Contains, etc.) and indexers on each one, which is basically just a bunch of keystrokes of repetitive code. So life was hard for the developer.

    Life was also hard for the computer because in order to generalize collection types enough, it had to use the Framework base class, Object, in order to provide the needed flexibility. Value types, such as Int16, Int32, Boolean, etc. caused the computer the most headache because it had to put them into a special package known as a box (the operation is called "boxing") in order to store them in the collection (because the collection was of the Object type, which is a reference type). In fact, this applied for any method that wanted to be so flexible as to allow any type to be used.

    When life is hard for the computer, performance suffers, and when performance suffers, so do you.

    Enter generic types and methods. Generic types allow developers to have strongly-typed collections without having to rewrite the same code (e.g., Add, Remove, Insert, etc. methods) over and over again and without bloating class libraries with type-specific collection classes that all do the same thing (only on different types).

    Indeed, they are so useful that a great many scenarios will be taken care of by the generic types in the System.Collections.Generic namespace-unless your type collection needs custom functionality, you won't even have to define a single collection type in your class library!

    The same benefits can be extended to any situation in which the developer wants to allow consumers (meaning other developers using his or her types and methods) to specify the type to be used. In other words, generics enable us to have type variables, so we can write one method, for instance, that can return the type that the consumer specifies or take an input parameter of the type that the consumer specifies or expose a property of the type that the consumer specifies.

    Generics not only make life easier, they also enable developers to do what they could not without them. An illustration of this is in the case of polymorphism. For instance, if the developer wants to write a base class that has a method that returns an instance or collection of the derived type, he or she could create a generic method that returns the type specified by the consumer, that is, any type derived from the base type.

    In addition to making life easier and enabling developers, generics can also help increase performance by eliminating the need for boxing of value types and by eliminating the need for downcasting, as in the case mentioned with polymorphism, where the parameters have to be cast to a type that they are derived from. This applies both in the example in the previous paragraph as well as in the Version 1.x collections classes that use Object as the type of members, return values, and method parameters.

    Generic Terminology and Syntax

    The first term that one needs to be familiar with is "type parameter." A type parameter is the core of enabling generic functionality. It is just like any other parameter in the sense that you pass an argument to it when you use the type or method. For types, it is kind of like a constructor parameter. For methods, it's like other parameters except that it can often be inferred, which we will cover later. Listing 1 shows the syntax for defining type parameters in your types and methods.

    Listing 1 – Type Parameters

    [C#]

    public class MySample<T>

    {

          public void DoSometing<K,V>()

          {}

    }

    [VB .NET]

    Public Class MySample(Of T)

          Public Sub DoSomething(Of K, V)()

          End Sub

    End Class

    This leads us to the second set of terms to get familiar with: "generic type" and "generic method." A generic type is a type (class, struct, delegate, or event) that defines one or more type parameters, as in the MySample class in Listing 1. A generic method is any method that defines one or more type parameters, as in the DoSomething method in Listing 1. It is important to note that generic methods do not have to be declared within generic types. These three terms-type parameter, generic type, and generic method-provide us with the terms we need to define generics.

    The next set of terms cover the usage of generic types and methods. First, consider the term "constructed type." This means a type that is created (constructed) as a result of the usage of a generic type. So, for instance, if I were to use the MySample generic type in Listing 1, I would declare an identifier of that type as in Listing 2.

    Listing 2 – Constructed Type

    [C#]

              MySample<string> someSample;

    [VB .NET]

              someSample As MySample(Of String)

    Notice that we are passing an argument (a "type argument") to the type parameter for the MySample generic type. The result of this declaration will be the creation of a constructed type at runtime.

    At this point, a further distinction needs to be made between different kinds of constructed types. This distinction is between what are called "closed constructed types" and "open constructed types." The example above in Listing 2 is of a closed constructed type. What makes it "closed" is that at design-time we know the type that is being passed to it, a System.String.

    However, if we examine the example in Listing 3, we see that the type argument being passed to the MySample type parameter is itself a type parameter; therefore, we do not know what type will be used while we are designing our class in Listing 3. This is known as an "open" constructed type because the type used is open to any types passed to it.

    Listing 3 – Open Constructed Type

    [C#]

          public class MyExample<V>

          {

                private MySample<V> someSample;

          }

    [VB .NET]

          Public Class MyExample(Of V)

                Private someSample As MySample(Of V)

          End Class

    Constraints >>

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Other Articles
    Feb 23, 2005 - My Feature in Visual Basic 2005
    In this article, Thiru Thangarathinam demonstrates the different classes and features available through the My namespace. By providing a speed-dial that allows you to more quickly and effectively utilize .NET framework functionalities in your application, the My feature provides huge productivity improvements for .NET developers.
    [Read This Article]  [Top]
    Oct 6, 2004 - Creating Triggers Using Managed Code in SQL Server 2005
    Thiru Thangarathinam discusses taking advantage of the integation between the .NET CLR and SQL Server 2005 in order to do things like create triggers using managed code.
    [Read This Article]  [Top]
    Sep 8, 2004 - Custom Object Data Binding with .NET
    Developers often use brute force coding to marshal data between the GUI and application objects. In this article, Luther Stanton explains how to use .NET's out-of-the box data-binding functionality to make this job much easier.
    [Read This Article]  [Top]
    Aug 17, 2004 - The Perfect Service - Part 2
    Ambrose Little provides the complete source code for his 'Perfect Service' and explains how the .NET Service Manager enables features such as drag-n-drop deployment.
    [Read This Article]  [Top]
    Aug 12, 2004 - Middle-Tier Hosting: Enterprise Services, IIS, DCOM, Web Services, and Remoting
    There is broad-reaching debate about remoting, Web services, Enterprise Services, and DCOM. In short, it is a debate about the best technology to use when implementing client/server communication in .NET. Rocky Lhotka shares his thoughts on the issue while offering clear explanations of basic application architecture terminology.
    [Read This Article]  [Top]
    Jul 21, 2004 - COM Interop Exposed
    This article provides and excellent foundation for COM Interop. It reviews COM's background, explains how VB6 interacts with COM, and then shows how to design .NET components to smoothly interact with COM.
    [Read This Article]  [Top]
    Jun 24, 2004 - The Perfect Service - Part 1
    The first article in this two-part series shows how to get Ambrose Little's .NET Service Manager running and then how to add plug-n-play services to it using drag-n-drop or XCOPY.
    [Read This Article]  [Top]
    May 11, 2004 - SharePoint Security and .NET Impersonation
    When implementing custom components that require access to restricted resources, implicit impersonation must be used. Jay Nathan shows how to create a class that makes using .NET Impersonation a snap.
    [Read This Article]  [Top]
    Mar 23, 2004 - Exploiting .NET's Advanced Deployment Features
    Tony Arslan shows how to use VS .NET's custom deployment feature to create configuration files on the target machine during installation.
    [Read This Article]  [Top]
    Mar 18, 2004 - DevDays 2004 Round-Up
    Adnan Masood just returned from DevDays 2004 in Los Angeles. Here he provides some thoughts and insights into the Web application security-focused conference.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry

    internet.commediabistro.comJusttechjobs.comGraphics.com

    Search:

    WebMediaBrands Corporate Info

    Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
    Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs