Home > Articles > Programming > ASP .NET

This chapter is from the book

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 number—a 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 memory—4 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't—this 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 names—it 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 conversions—those 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);

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020