Home > Articles > Programming > Windows Programming

Using Generics in Visual Basic 2005

  • Print
  • + Share This
Tired of writing the same class code over and over to meet specific datatype requirements? John Mueller recommends generics.
Like this article? We recommend

Like this article? We recommend

Generics is a new Visual Basic 2005 feature that many developers will likely miss on the first pass, but find they can't do without once they know about it. The term doesn't really tell you what this feature can do. Imagine writing a class that performs math tasks. Using standard code-writing techniques, you'd have to write separate methods for integers (in all their forms) and reals (in all their forms). Using generics, you can write the methods one time and let the .NET Framework handle the type issues for you. Generics can make your programming experience a lot more enjoyable. You receive the benefits of code reuse without all of the work.

What's the Big Deal?

You might wonder what generics have to offer, besides reduced typing; after all, you still have to create the class to process information. The best feature is that a properly constructed generic class can actually reduce security problems in your code. Because you define the class as using several datatypes, you don't have to rely on the generic Object type. A generic class relies on the same strong datatyping that other classes do when they work with a specific datatype. In short, although you've gained a lot of flexibility, the resulting code is actually better.

Using generic classes can also improve performance. One of the biggest improvements is that the .NET Framework won't use boxing for value types. Although a generic class can work with more than one datatype, it handles each datatype individually behind the scenes. This technique ensures that your application provides the best performance with the least amount of work on your part.

One of the amazing features of using a generic class is that IntelliSense can actually track the strong datatyping for you. Unlike using an object to create a generic method of handling multiple datatypes, your code relies on strong datatyping, which means that IntelliSense provides more information to you. This feature not only makes the code easier to work with; it reduces errors and debugging time as well.

  • + Share This
  • 🔖 Save To Your Account