# Writing Code with Visual Basic .NET

• Print
This chapter is from the book

## Simple Calculations

Just having some values lying around does not make a program. You need to do something with the values. You can perform math on the values, or you can do something more substantial. Similarly, to make your programs more understandable, you will often need to use or create procedures. Visual Basic .NET will provide some of these procedures; you will write others. These procedures range from the operators, which provide many of the common mathematical calculations, to more complex functions that could affect strings or numbers.

### Using Operators

In Visual Basic .NET, operators perform simple calculations and similar "functions." Most of the operators in Visual Basic .NET should be familiar to you as common algebraic symbols. However, some of them are unique to programming. Table 3.6 lists the most commonly used operators.

#### Table 3.6 Common Operators in Visual Basic .NET

 Operator Use Example = Assigns one value to another X = 6 + Adds two values Y = X + 7 (Y holds 13) - Subtracts one value from another Y = X – 4 (Y holds 2) * Multiplies two values Y = X * 2 (Y holds 12) / Divides one value by another Y = X / 2 (Y holds 3) \ Divides one value by another, but only returns a whole number Y = X \ 3 (Y holds 1) Mod Short for modulus; returns the remainder for a division Y = X Mod 3 (Y holds 2) & Combines two strings S = "Hello " & "World" (S holds "Hello World") += Shorthand for adds a value and assigns the result X += 2 (X holds 8) -= Shorthand for subtracts a value and assigns the result X –= 3 (X holds 5) *= Shorthand for multiplies a value and assigns the result X *= 6 (X holds 30) /= Shorthand for divides by a value and assigns the result X /= 5 (X holds 6) &= Shorthand for combines with a string and assigns the result S &= ", John" (S holds "Hello World, John") ^ Raises one value to the power of an exponent 3^4 (3 to the power of 4, returns 81)

### Built-In Functions

In addition to the functions provided by the .NET Framework, Visual Basic .NET has many built-in functions. These functions provide many useful capabilities, including conversion from one data type to another, mathematical calculations, string manipulation, and so on. You should know about some of these functions to be able to get around in Visual Basic .NET.

#### Conversion Functions

Some of the most important functions available to you in Visual Basic are the conversion functions. They enable you to take one type of data and convert it to another. With Visual Basic .NET, conversion functions have become even more important because this version of Visual Basic is much stricter about data types, and it does not automatically convert one type into another as previous versions did.

CAUTION

If you want Visual Basic .NET to automatically convert data types for you, you can turn off the strict type checking by adding Option Strict Off to the top of your files. You should know, however, that this could lead to unexpected results in your code (that is, bugs) if Visual Basic .NET converts a variable when you don't expect it to.

The conversion functions in Visual Basic .NET all begin with the letter "C" (as in conversion), and end with an abbreviated form of the new type. In addition, there is a generic conversion function, CType, which can convert to any type. Table 3.7 describes the main conversion functions.

#### Table 3.7 Conversion Functions

 Function Description CBool Converts to a Boolean. Anything that evaluates to False or 0 will be set to False; otherwise, it will be True. CByte Converts to a Byte. Any value greater than 255, or any fractional information, will be lost. CChar Converts to a single character. If the value is greater than 65,535, it will be lost. If you convert a String, only the first character is converted. CDate Converts to a Date. One of the more powerful conversion functions, CDate can recognize some of the more common formats for entering a date. CDbl Converts to a Double. CInt Converts to an Integer. Fractions are rounded to the nearest value. CLng Converts to a Long. Fractions are rounded to the nearest value. CSht Converts to a Short. Fractions are rounded to the nearest value. CStr Converts to a String. If the value is a Date, this will contain the Short Date format. CType Converts to any type. This is a powerful function that enables you to convert any data type into any other type. Therefore, the syntax for this function is slightly different than the others.

The syntax for CType is

`oNewVariable = CType(oOldVariable, NewType)`

in which oNewVariable and oOldVariable are placeholders for the variables that you're converting to and from, respectively. NewType is the type you are converting to. This can be any variable that you could put after the As in a declaration, so you can use this function to convert to enumerations, structures, and object types as well as simple types.

#### String Manipulation Functions

Most of Visual Basic's earlier string-related functions have been replaced in Visual Basic .NET with the functionality internal to the String class (we'll look at the String class in detail on Day 7). However, you might see some of the functions listed in Table 3.8 in older code, so you should be familiar with these functions.

#### Table 3.8 String-Handling Functions

 Function Description Example Len Returns the length of a string. iValue = Len("Hello") ('iValue holds 5.) Chr Returns the character based on the entered ASCII or Unicode value. sValue = Chr(56) ('s Value holds the letter A.) Asc Returns the ASCII or Unicode value. iValue = Asc("A") ('iValue holds 56.) Left Returns characters from a string, beginning with the leftmost character. Also requires the number of characters to return. sValue = Left("Hello World", 2) ('sValue holds He.) Right Returns characters from a string beginning with the rightmost character (the opposite of Left). Also requires the number of characters to return. sValue = Right("Hello World",4) ('sValue holds orld.) Mid Returns characters not at either end of a string. Mid returns any number of characters. The syntax for Mid is sReturn = Mid(String, Start, Length) in which Start is the character to begin returning from, and Length is the number of characters (including Start) to return. One nice feature is that if you omit Length, you will return all the characters from Start on. sValue = Mid("Hello World", 4, 5)) ('sValue holds lo Wo.) sValue = Mid("Hello World", 7) ('sValue holds World.) Instr Finds one string within another. This is useful when searching a file for some string. The syntax for the Instr function is iReturn = Instr(StartAtCharacter, SearchString, SearchFor, ComparisonType) iValue = Instr(1,"Hello World","l")) ('iValue holds 3.) Keep in mind that the string you are searching for could be multiple characters, so a search for "World", as in iValue = Instr(1, "Hello World", "World")) 'iValue holds 7.) StartAtCharacter is the position within the search string, SearchString, where the program begins searching (counting begins at 1). SearchString is the string to search in, and SearchFor is the string being sought. ComparisonType determines the case sensitivity of the search. If ComparisonType is set to 0 (Binary Compare), the search will be case sensitive. If it is ignored, or set to 1 (Text Compare), it will not be case sensitive. iReturn would then hold the position within the SearchString where the SearchFor begins. If the search for string is not found, iReturn will be 0. InstrRev searches from the right side of the string; otherwise, InstrRev is identical to Instr. InstrRev is useful when you are searching a string containing a directory path, and you want to view the lower directories first. iValue = InstrRev("Hello World", "o") 'iValue holds 8. LCase Converts a string to all lowercase. sValue = LCase("Hello World") 'sValue holds hello world UCase Converts a string to all uppercase. sValue = UCase("Hello World") 'sValue holds HELLO WORLD LTrim Removes all leading spaces from a string sValue = LTrim(" Hello World ") 'sValue holds "Hello World " RTrim Removes all trailing spaces from a string sValue = RTrim(" Hello World ") 'sValue holds " Hello World" Trim Removes all leading and trailing spaces from a string. sValue = Trim(" Hello World ") sValue holds "Hello World"

#### Other Useful Functions

Finally, some generally useful functions don't fit into the other categories. These include functions that enable you to determine the type of a variable, as well as Date manipulation functions. Table 3.9 describes some of these functions.

#### Table 3.9 Miscellaneous Built-In Functions

 Function Description IsArray Returns True if the parameter is an array. IsDate Returns True if the parameter is recognizable as a date. IsNumeric Returns True if the parameter is recognizable as a number. IsObject Returns True if the parameter is some object type. TypeName Returns the name of the data type of the parameter, for example, TypeName(sName) would return "String". Now Returns the current date and time. Today Returns the current date, with the time set to 0:00:00 a.m. (midnight).
• 🔖 Save To Your Account

### 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.

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.

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.

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.