
Beginning ASP.NET 2
.0.pdf
9
Code
You’re now at the stage where the site is getting more features, and you need to start learning more about code. Some of the code used in previous chapters might not have been explained fully — that’s because what the code was doing was more important than the actual code itself. It’s not that the code wasn’t important, but rather that the technique being taught was the key; understanding how the actual code worked would come later. Now it’s time to learn about the basics of writing code, what makes good code, and how you put all that code together.
This chapter looks at the following topics:
What data types and variables are and how they are used
How you make decisions in your code
How you repeat lines of code
What object-oriented programming means and why it’s important
How to think about structuring your code so it’s well organized and easy to maintain
How one of the new language features in ASP.NET 2.0 eases working with collections of objects
There’s a lot to cover, and although some of it might sound difficult, it’s actually quite easy. The first section discusses data types.
Variables and Data Types
When you use applications, you don’t really care how the application stores your data, just that it does. As a programmer, however, you have to think about this. What sort of data is the user entering? Is it text, numbers, dates, or something else? This matters because how you store data internally in your application affects not only how you deal with the data, but also what you can do with that data. To store data internally, variables are used (variables are simply names, used to store information during code), and variables have types; there is a type for each type of data. For example, there is a data type called String, unsurprisingly used for strings, or text data. There is a data

Chapter 9
type called Date for dates and times, an Integer data type for whole numbers, and a Decimal or Double data type for floating-point numbers. Each has different characteristics; the Integer type can only store integer numbers, and trying to store any other type of data into an Integer will raise an exception. Likewise, the Date data type can only store dates and times. The full list of data types is as follows:
Boolean is used to store either True or False. The default value is False.
Byte is used for a single byte of data. This can be a single character or a number from 0 to 255. The default value is 0.
Char is used for two bytes of data. This can be a character or a number from 0 to 65,535. Because it is bigger than a Byte, Char can store double-byte characters like those used by foreign characters sets such as Chinese. The default value is 0.
Date is used to store a date and time. The default value is 0:00:00 (midnight) on January 1, 0001.
Decimal is used for decimal values. It supports up to 29 significant digits and is therefore the most accurate type for financial numbers. The default value is 0.
Double is used for floating-point numbers. Unlike the Decimal data type, Double has a smaller range and is less accurate. However, it is also faster in use, so it is the preferred data type for floating-point numbers unless a great depth of precision is required. The default value is 0.
Integer is used for whole numbers between –2,147,483,648 and 2,147,483,647. The default value is 0.
Long is used for whole numbers between –9,223,372,036,854,775,808 and 9,223,372,036,854,775,807. The default value is 0.
Object is used to represent objects. In VB, the default value is Nothing. In C#, the default value is null.
SByte is used to hold whole numbers between –128 and 127. The default value is 0.
Short is used for whole numbers between –32,768 and 32,767. The default value is 0.
Single is used for floating-point numbers that don’t require the full size of a Double. The default value is 0.
String is used for storing text (or string) data. The default value is Nothing in VB and null in C#.
UInteger is the unsigned equivalent of an Integer. Because it is unsigned it can only store positive numbers, giving a range of 0 to 4,294,967,295. The default value is 0.
ULong is the unsigned equivalent of a Long. Because it is unsigned it can only store positive numbers, giving a range of 0 to 18,446,774,073,709,551,615. The default value is 0.
UShort is the unsigned equivalent of a Short. Because it is unsigned it can only store positive numbers, giving a range of 0 to 65,535. The default value is 0.
Having different data types allows the type to provide features that only that type requires. For example, the DateTime type allows dates to be manipulated, the individual parts of the date or time to be extracted, and so on. Also, data types allow you to choose the most efficient way of storing data, so if you need to store a really long number, you would use a Long. A Long takes up more room in memory than a Short,
290

Code
so if you only ever needed to store numbers between 1 and 100, you wouldn’t use a Long. In essence the data type you choose depends not only on the type of data, but also its size.
Common Language Runtime Types
This may seem confusing, but there are different names for the same data types. This is because there are data types that the language uses, and data types that the Common Language Runtime (CLR) uses. Simply put, the CLR is the system that actually makes .NET run. You don’t need to know much about it now, although it’s definitely worth learning about as you become more experienced. The reason that the CLR has data types and the language has data types is that the CLR is common to all languages in
.NET. Whether you use Visual Basic .NET, C#, or even COBOL .NET, underneath you are using the CLR. However, languages have history (apart from C#, which was new for .NET, but C# has a C and C++ base in terms of the language syntax), and so have data types of their own. For compatibility reasons it makes sense to keep these specific language types. This enables users of the language to work with familiar data types, and the compiler takes care of using the actual CLR data type.
For much of what you do you’ll use the language data types, but there are times when you need to know what CLR data type a language data type maps onto, and the following table shows this:
CLR Type |
Visual Basic Type |
C# Type |
|
|
|
Boolean |
Boolean |
bool |
Byte |
Byte |
byte |
Char |
Char |
char |
DateTime |
Date |
DateTime |
Decimal |
Decimal |
decimal |
Double |
Double |
double |
Int32 |
Integer |
int |
Int64 |
Long |
long |
Object |
Object |
Object |
SByte |
SByte |
sbyte |
Int16 |
Short |
short |
Single |
Single |
float |
String |
String |
string |
UInt32 |
UInteger |
uint |
UInt64 |
ULong |
ulong |
UInt16 |
UShort |
ushort |
|
|
|
When you look at converting between data types you’ll see why it might be important to know the underlying data type.
291

Chapter 9
Declaring Variables
There is a specific syntax for creating variables, which requires the name and data type. The name is up to you, but it’s always best to use a sensible name, something that represents what the variable holds. To define a variable you use the Dim statement, like so:
Dim VariableName As DataType
Replace the VariableName and DataType with your requirements:
Dim FirstName As String
Dim LastName As String
Dim Age As Integer
Dim Birthday as Date
You’ve used sensible names for the variables: two String types to hold the first and last names, an Integer to hold the age, and a Date to hold the birthday. In some documents and books you might see a prefix on the variable name, giving an indication of its data type. For example, the names and ages might be declared like so:
Dim strFirstName As String
Dim sLastName As String
Dim iAge As Integer
Dim dBirthday as Date
Here str or s has been used as a prefix for String types, i for Integer types, and d for Date data types. You may find this technique useful when learning how to use variables and data types, although it isn’t generally recommended and has dropped out of favor. A correctly named variable should give a good indication of its data type. Having said that, there are times when some form of prefix is useful, and you’ll see this when you look at classes a little later in the chapter.
Assigning Values
Once you declare a variable, you can assign values to it, and this is simply a matter of setting the variable equal to the required value. The syntax for this is as follows:
variable = value
This says give the variable named on the left of the equals sign the value on the right of the equals sign. For example:
FirstName = “Arthur”
LastName = “Arbuthnot”
Age = 24
Birthday = #10/25/1980#
As you can see, string values are enclosed in quotation marks, whereas numeric values aren’t. Notice that the date value is enclosed within hash marks (#), and the format is MM/DD/YYYY. This is a fixed format when assigning dates like this, and takes no account of the regional settings of your machine. You can also assign a time part, like so:
292

Code
Appointment = #10/25/1980 11:10 PM #
Alternatively, you can assign a time like this:
Appointment = #10/25/1980 23:10 #
Variables can also be initialized when they are declared, like so:
Dim FirstName As String = “Arthur”
Dim LastName As String = “Arbuthnot”
Dim Age As Integer = 24
Dim Birthday As Date = #10/25/1980#
These examples show the assignment using literal values, but you can also assign values to other variables or objects. For example, in ASP.NET pages it’s very common to assign values from user-entered data, perhaps from a text box:
FirstName = FirstNameTextBox.Text
LastName = LastNameTextBox.Text
Or vice versa:
FirstNameTextBox.Text = FirstName
LastNameTextBox.Text = LastName
The TextBox control has a property called Text that contains the text value, so you are simply copying that value into the String variable, or copying the string value into the property. This is fine for String types, but extra work needs to be done if the variable isn’t a String type; for example, allowing users to enter their age would require a text box and an Integer type variable. However, you can’t assign the values of differing types — you need to convert them.
Data Conversion
Visual Basic .NET does provide some automatic conversion of data types, but it’s best not to rely on this, otherwise you tend to forget that conversion is actually happening. Explicit conversion makes it clear exactly what your code does, a useful point when you (or others) look at your code later. There isn’t a single syntax for converting between types, but there is a lot of commonality in the different methods.
Converting to string values is the simplest, because every data type has a ToString method. For example, to convert the age to a TextBox you could use:
AgeTextBox.Text = Age.ToString()
For the Boolean type the conversion method is the same, but the string value will be either True or
False.
Converting from a string value to another type is slightly different, because no methods on the String type do this automatically. Instead you have to use a separate class to perform the conversion.
293

Chapter 9
Converting Data Types Using the Framework Classes
Two ways exist to convert from string values to other types using the framework classes, and it’s worth mentioning both in case you see them in code. The first is to use the Parse method that most data types supply. For example, to convert a number held in a TextBox control into an Integer data type, you could do this:
Dim Age As Integer
Age = Integer.Parse(AgeTextBox.Text)
What’s happening here is that the Parse method parses the value passed to it — that is, it reads the value, checks that it is an integer value, and converts it into an integer. The value to be converted is the value from the Text property of the AgeTextBox control, which is a string. So the string is passed into the Parse method, which converts it into an integer and returns the integer, which in turn is assigned to the Age variable.
All of the data types, apart from Object, support the Parse method, which means that even though you may be using a different data type the syntax is the same. For example:
Dim ANumber As Double
ANumber = Double.Parse(NumberTextBox.Text)
The second way to perform data conversion is to use the Convert class, which converts between types. It’s a very flexible class in that it can convert between all types, but it does require knowledge of the CLR type. For example, the preceding example using an integer could be written as follows:
Dim Age As Integer
Age = Convert.ToInt32(AgeTextBox.Text)
For the double example this would be:
Dim ANumber As Double
ANumber = Convert.ToDouble((NumberTextBox.Text)
In use there is no difference between the Convert class and the data type class when converting types. The only reason for using the Convert class is that it makes code easier to convert to another language. This was important when writing the Wrox United web site, but may not be important to you if you intend to stick with one language.
Converting Data Types with Casting
Another way of converting between types is by casting. Instead of explicitly converting the type, the value is forced into another type. Casting doesn’t work in the same way as converting, and isn’t always suitable. For example, you can’t use casting to convert from strings to numbers. You can, however,
use casting to convert between similar types. For example, you could cast between a Double and an Integer by using the following code:
Dim MyDouble As Double = 123.456
Dim MyInteger As Integer
MyInteger = CType(MyDouble, Integer)
294



