Chapter 9
you had a collection to store the CartItem objects you could in fact store strings, numbers, dates, and so forth in the same collection. For example you could do this:
Dim _items As New List()
Dim item As New CartItem( . . .)
_items.Add(item)
_items.Add(“this isn’t a cart item”) _items.Add(“65”)
When taking items out of the collection you’d have no idea what data type it was unless you tracked which objects you put into the list.
To get around this problem you use generics, or more specifically generic collections. These are stored in the System.Collections.Generic namespace, and the one the shopping cart uses is the List:
Private _items As List(Of CartItem)
This simply states that _items is a List, but a list only of CartItem objects. So now you do this:
Dim _items As New List(Of CartItem)
Dim item As New CartItem( . . .)
_items.Add(item)
But because the list is of a specific data type you can’t do this:
_items.Add(“this isn’t a cart item”)
_items.Add(“65”)
Both of these lines would generate compile time errors. Whenever you need a collection of custom classes, it’s always a good idea to use generic collections, because they improve the readability of your code, reduce the potential for errors, as well as provide performance improvements over the standard collections.
Summar y
This chapter has covered a lot of ground, but it was necessary. Although the rich controls in ASP.NET 2.0 provide a way to create web applications with less code than previous versions, you can’t get away without coding completely. So you’ve learned the fundamentals of coding and what you need to control your program. Specifically, this chapter covered the following topics:
Variables and data types, and how to work with the different data types, seeing that data types have different features. You also looked at arrays and collections, as a way of storing groups of variables.
The control of programs is by way of decisions and loops, which use expressions and operators as part of the decision process. You saw how there are different ways to perform both decisions and loops, depending on the requirements.