Variables
Variable is a generic term for some data in the computer's memory that has a name. For example, if you put the string "Hello World!" in a variable and called it x, it would be placed in memory and take up 10 (or so) bytes. This information can now be referenced by that name.
Since a variable is just a location in memory, you can manipulate it by changing it, deleting it, moving it, and so on. The important part of a variable, however, is what's inside the memory location.
Data Types
You can store many different types of information inside a variable, such as strings, numbers, and dates. Each type has a set of rules that govern its usage, which you'll discover as you develop your ASP.NET pages. There are 10 basic data types in Visual Basic.NET, called primitive types. These are the basic building blocks for using variables, hence the term primitives. These 10 are divided into five different categories: integers, floating-point numbers, strings, dates, and Booleans. Table 3.1 summarizes these types.
Table 3.1 VB.NET and C# Primitives
VB.NET Type |
C# Type |
Category |
Description |
Byte |
byte |
Integers |
A 1-byte integral number (also known as System.Int) |
Short |
short |
Integers |
A 2-byte integral number (also known as System.Int16) |
Integer |
int |
Integers |
A 4-byte integral number (also known as System.Int32) |
Long |
long |
Integers |
An 8-byte integral number (also known as System.Int64) |
Single |
float |
Floating-points |
4-byte number with decimal point (also known as System.Single) |
Double |
double |
Floating-points |
8-byte number with decimal point (also known as System.Double) |
Decimal |
decimal |
Floating-points |
12-byte number with decimal point (also known as System.Decimal) |
Char |
char |
Strings |
A single Unicode character (also known as System.Char) |
Date |
Dates |
A date and/or a time value (also known as System.DateTime) |
|
Boolean |
bool |
Booleans |
A true or false value (also known as System.Boolean) |
In addition to these, C# has other data types that are similar. For example, uint has the same size and range as int, but doesn't cover negative numbers. Most of the time, though, you'll use the standard ones defined in Table 3.1.
Integers
An integer is a whole numbera number without a fraction or decimal part. For instance, 3, 6767, and 1 are all integers, whereas 3.4 and 3 1/2 are not.
Although integers are a general type of variable, there are also subtypes that you may use depending on how much memory you need. An integer (or int) technically uses 32 bits of memory4 bytes. This means that it can store any number from 2,147,483,648 to 2,147,483,647. Usually this will be more than enough for your needs. There are also bytes (8 bits), chars (16 bits), shorts (16 bits), and longs (64 bits). You won't have to worry much about these, but they're there in case you need to use them.
Floating-Point Numbers
Floating-point numbers are numbers with a fractional part, such as 4.5, 1.956445, or even 3.0.
There are also subtypes for these, depending on how many decimal places you need: single, double, and decimal. Again, you won't have to worry much about these because the default memory size will usually work.
Strings
Strings are groups of characters, such as "hello", "my name is", "@$@#$!", and even "234". You've already used these in the first two lessons. They're among the most common data types that you'll be using in ASP.NET. Strings in VB.NET and C# are enclosed with double quotes, such as "hello".
Dates
Dates are, well, date and time values. The actual data type is called DateTime. (Note that VB.NET has its own DateTime data type, but C# doesn'tthis means you'll have to use the built-in .NET System.DateTime data type instead. They work exactly the same.) It can be stored in many different forms, such as "1/2/2001", "Wednesday January 5th, 2001 8:09:30PM", and so on. These are all dates to VB.NET and C#, and it's easy to convert from one to the other.
You can represent dates as strings, but the DateTime data type allows these programming languages to perform special operations on dates that wouldn't be possible with a string, such as adding hours, minutes, or even days. The .NET Framework has a large number of date functions that you'll be using throughout your ASP.NET pages.
Booleans
A Boolean is a general term for a true/false values, such as 1/0, yes/no, and on/off. In VB.NET and C#, the Boolean data type can only be true or false.
Object
The Object data type is a general term for a variable that isn't specified as another type. It has a special purpose in the .NET Framework that you'll learn about later.
Declaring Variables
So how do you use a variable or a data type? First, you have to tell the system that you want to set aside a piece of memory, and you have to give it a name. This is done in VB.NET with the following line:
Dim MyVariable
The word Dim tells VB.NET to create a location in memory called MyVariable. You can now use this name in other places in your code. However, since you didn't tell VB.NET what kind of variable (data type) you want, it created an Object type. To declare the variable as a specific type, use the following:
Dim MyVariable As String
This is known as explicit declaration. Now VB.NET knows that you want to store a String in that memory location. The code in C# would look like the following:
string MyVariable;
The difference is that you put the data type before the name in C#, and don't require the dim keyword. Don't forget the semicolon at the end of the line!
TIP
It's strongly recommended that you always explicitly declare your variables. If you tell VB.NET or C# how much memory to set aside, it won't have to bother changing this amount later. It also allows you to perform operations on that variable that are inherent to that data type.
You can now assign values to this variable:
MyVariable = "Hello World!"
Or in C#:
MyVariable = "Hello World!";
You can even combine the declaration with the assignment or declare multiple variables on one line:
'VB.NET Dim MyVariable As String = "Hello World!" Dim MyIntA, MyIntB, MyIntC as Integer Dim MyIntA as Integer = 9, MyIntB as Integer = 7 //C# string MyVariable = "Hello World!"; int MyIntA, MyIntB, MyIntC; int MyIntA = 9, MyIntB = 7;
The first line of either code snippet declares a variable named MyVariable as a String data type and assigns it the value "Hello World!" The second line declares three variables, MyIntA, MyIntB, and MyIntC, all as Integer (or int) data types. Finally, the third statement creates an Integer MyIntA and assigns it a value of 9, and it also creates an Integer named MyIntB with a value of 7. These are all valid ways to declare your variables.
Listing 3.1 shows an example.
Listing 3.1 Declaring Variables in ASP.NET
1: <%@ Page Language="VB" %> 2: 3: <script runat="server"> 4: dim MyIntA as integer = 8, MyIntB as Integer = 7 5: 6: sub Page_Load(Sender as object, e as eventargs) 7: Response.Write(MyIntA * MyIntB) 8: end sub 9: </script> 10: 11: <html><body> 12: </body></html>
The C# version is slightly different. Listing 3.2 shows the code.
Listing 3.2 Declaring Variables in ASP.NET Using C#
1: <%@ Page Language="C#" %> 2: 3: <script runat="server"> 4: int MyIntA = 8, MyIntB = 7; 5: 6: void Page_Load(Object Sender, EventArgs e) { 7: Response.Write(MyIntA * MyIntB); 8: } 9: </script> 10: 11: <html><body> 12: </body></html>
You'll learn about the syntax of these listings as you move through today's lesson. All you need to know now is that line 4 in the code declaration block declares two variables, MyIntA and MyIntB. Then you simply print out their product on line 7. This produces the output in Figure 3.1.
Figure 3.1 The page produced by Listing 3.1.
Naming Variables
Naming your variables properly is an important part of programming. If you've been experimenting, you may have noticed some restrictions on variable names. The following list summarizes the rules for naming variables:
Do not use spaces, dashes, or periods, which will cause errors in your applications. Underscores are fine, however.
Names must begin with a letter or underscore.
Names cannot be existing VB.NET or C# keywords.
Names should not be longer than 255 characters.
There are also some well-known styles that you should apply when creating names. These styles make it much easier to read your code:
-
Use an abbreviation of the variable's data type as a prefix. This helps you keep track of which variable is used for which purpose:
Dim intMyInteger as Integer 'int for integer Dim strName as String 'str for string bool blnGo 'bln for Boolean
This doesn't take much effort, and it helps tremendously later on, by allowing you to easily see what kind of data you're dealing with.
Use names that make sense. Giving variables names like I or temp may make sense to you now, but if you return to the code in a week, you'll have no idea what those variables were used for.
Don't go overboard and use something like intUsedToKeepTrackofMyLoopInThePage. This is overkill and will only slow you down. Instead, use something like intLoop or intIterator.
Try to declare all variables in one location, generally at the top of the page. This will save you a lot of hassle trying to find things later on.
TIP
Do use names that are adequately descriptive!
Don't use temporary variable names, or reuse namesit only makes code confusing!
Data Type Conversions
Type conversions change a variable's type from one data type to another. This process is also known as casting. Both VB.NET and C# can convert some types automatically (implicit conversions), but others have to be specified explicitly (explicit conversions).
VB.NET provides you with several functions to cast one type to another, as shown in Table 3.2.
Table 3.2 Conversion Functions
Cbool |
CByte |
CChar |
CDate |
CDec |
CDbl |
CInt |
CLng |
CObj |
CShort |
CSng |
CStr |
CType |
Asc |
|
|
For example, CByte transforms one data type into a byte, and CStr converts into a String. These functions are very helpful in ASP.NET pages, and you'll see them quite often. Listing 3.3 shows an example of converting data types.
Listing 3.3 Converting Data Types Without Casting
1: <%@ Page Language="VB" %> 2: 3: <script runat="server"> 4: dim strName as String = "a" 5: dim intNumber as integer = 4 6: 7: sub Page_Load(Sender as object, e as eventargs) 8: Response.Write("The value of strName is: ") 9: Response.Write(strName & "<p>") 10: 11: Response.Write("The value of intNumber is: ") 12: Response.Write(intNumber & "<p>") 13: 14: Response.Write("Their product is: ") 15: Response.Write(intNumber * strName & "<p>") 16: end sub 17: </script> 18: 19: <html><body> 20: 21: </body></html>
You declare two variables on lines 4 and 5, one with the value "a" and one with the value 4. The first is a String value and the second is an Integer. When you try to multiply them on line 15, you receive the error shown in Figure 3.2 because you cannot multiply a String and an Integer.
This is a very common situation in ASP.NET. Here, you must cast the String value to an Integer with Asc, which turns a character into its corresponding ASCII numeric value. Let's modify line 15:
Response.Write(intNumber * Asc(strName) & "<p>")
Figure 3.2 An error caused by incorrect data type manipulation.
Now your page will work as expected.
CAUTION
Be aware that some conversions will cause you to lose data. For instance, if you convert from a floating-point number to an integer, you'll lose all of the decimal values.
There's another way to convert data types in VB.NET. Many data types have a method that allows you to convert to another specified type. These methods always begin with To and end with the data type to convert to. (We'll discuss methods later in "Branching Logic.")
For example, to convert an Integer to a String, we can use ToString:
dim MyIntA as Integer = 4 dim MyString as String MyString = MyIntA.ToString
Be careful with these functions, however, because some conversions aren't allowed. For instance, you can't convert from a String to an Integer with the ToInt32 method. You'll see these methods throughout the code examples.
Casting in C# is a bit different than in VB.NET. Rather than having a method to do so, you use what is known as a casting operator. This operator is simply the type of data you want to convert to, surrounded by parentheses and placed in front of the variable to convert. For example, the following code snippet creates an integer, and then casts it to a double:
int intA = 10; double dblA; dblA = (double)intA;
This will work for simple conversionsthose that cast one data type to a similar one. For example, an integer to a double. It will not work, however, for other casts like an integer to a string.
The final method to cast data types works in both C# and VB.NET, and involves the Convert class. This class has numerous methods that take one data type and convert it to another. To convert an integer to a string and then back again, for instance, use the following code:
int intA = 10; string strA; strA = Convert.ToString(intA); intA = Convert.ToInt32(strA);