Visual Basic.NET
  Home arrow Visual Basic.NET arrow Page 5 - Learning the Visual Basic .NET Language
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Moblin 
JMSL Numerical Library 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
VISUAL BASIC.NET

Learning the Visual Basic .NET Language
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 23
    2005-11-17

    Table of Contents:
  • Learning the Visual Basic .NET Language
  • The Evolution of VB .NET
  • Variables and Data Types
  • Arrays
  • Variable Operations
  • The String Class
  • Conditional Structures
  • Loop Structures
  • Functions and Subroutines

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Learning the Visual Basic .NET Language - Variable Operations


    (Page 5 of 9 )

    You can use all the standard type of variable operations in VB .NET. When working with numbers, you can use various math symbols, as listed in Table 3-2. Visual Basic .NET follows the conventional order of operations, performing exponentiation first, followed by multiplication and division, and then addition and subtraction. You can also control order by grouping subexpressions with parentheses.

    Dim Number As Integer
    Number = 4 + 2 * 3
    ' Number will be 10.
    Number = (4 + 2) * 3
    ' Number will be 18.

    Table 3-2. Arithmetic Operations

    Operator

    Description

     

    +

    Addition.

    1 +1 = 2.

    -

    Subtraction (and to indicate negative numbers).

    5 - 2 = 3.

    *

    Multiplication.

    2 * 5 = 10.

    /

    Division.

    5 / 2 = 2.5.

    ^

    Exponentiation.

    3 ^ 2 = 9.

    \

    Integer division (any remainder is discarded).

    7 \ 3 = 2.

    Mod

    Gets the remainder left after integer division.

    7 Mod 3 = 1.

    When dealing with strings, you can use the concatenation operator (&), which joins together two strings.

    ' Join two strings together. Could also use the + operator.
    MyName = FirstName & " " & LastName

    The addition operator (+) can also be used to join strings, but it’s generally clearer to use the concatenation operator. The concatenation operator automatically attempts to convert both variables in the expression to the string data type, if they are not already strings.

    In addition, Visual Basic .NET now provides special shorthand assignment operators. A few examples are shown here:

    ' Add 10 to MyValue (the same as MyValue = MyValue + 10).
    MyValue += 10
    ' Multiple MyValue by 3 (the same as MyValue = MyValue * 3).
    MyValue *= 3
    ' Divide MyValue by 12 (the same as MyValue = MyValue / 12).
    MyValue /= 12

    ............................................................................................................................

    Line Termination

    Sometimes, code statements are too long to efficiently fit on a single line. In Visual Basic, you can break a code statement over multiple lines by adding a space followed by the line-continuation character (an underscore) to the end of the line. Here’s an example:

    ' A long line of code.
    MyValue = MyValue1 + MyValue2 + MyValue3
    ' A code statement split over several lines in VB.
    MyValue = MyValue1 + MyValue2 + _
              MyValue3

    .............................................................................................................................

    Advanced Math

    In the past, every language has had its own set of keywords for common math operations such as rounding and trigonometry. In .NET languages, many of these keywords remain. However, you can also use a centralized Math class that’s part of the .NET Framework. This has the pleasant side effect of ensuring that the code you use to perform mathematical operations can easily be translated into equivalent statements in any .NET language with minimal fuss.

    To use the math operations, you invoke the methods of the System.Math class. These methods are shared, which means that they are always available and ready to use. (The next chapter explores the difference between shared and instance members in more detail.)

    The following code snippet shows some sample calculations that you can perform with the Math class.

    Dim MyValue As Integer
    MyValue = Math.Sqrt(81)          ' MyValue = 9
    MyValue = Math.Round(42.889, 2)  ' MyValue = 42.89
    MyValue = Math.Abs(-10)          ' MyValue = 10
    MyValue = Math.Log(24.212)       ' MyValue = 3.18.. (and so on)
    MyValue = Math.PI                ' MyValue = 3.14159265358979323846

    The features of the Math class are too numerous to list here in their entirety. The preceding examples show some common numeric operations. For more information about the trigonometric and logarithmic functions that are available, refer to the MSDN reference for the Math class.

    Type Conversions

    Converting information from one data type to another is a fairly common programming task. For example, you might retrieve text input for a user that contains the number you want to use for a calculation. Or, you might need take a calculated value and transform it into text you can display in a web page.

    The Visual Basic .NET rules for type conversion are slightly less strict than some other languages, like C#. For example, VB .NET will automatically allow the conversions shown here:

    Dim BigValue As Integer = 100
    Dim SmallValue As Short
    Dim MyText As String = "100"
    ' Convert your 32-bit BigValue number into a 16-bit number.
    SmallValue = BigValue
    ' Convert your MyText into a number. BigValue = MyText

    The problem with code like this, is that it isn’t guaranteed to work. Conversions are of two types: narrowing and widening. Widening conversions always succeed. For example, you can always convert a number into a string, or a 16-bit integer into a 32-bit integer. On the other hand, narrowing conversions may or may not succeed, depending on the data. If you’re converting a 32-bit integer to a 16-bit integer (as in the previous code snippet), you’ll encounter an error if the 32-bit number is larger than the maximum value that can be stored in a 16-bit data type. Similarly, some strings can’t be converted to numbers. A failed narrowing conversion will lead to an unexpected runtime error.

    It’s possible to tighten up Visual Basic’s type conversion habits by adding an Option Strict instruction to the beginning of your code files.

    Option Strict On

    In this case, VB .NET will not allow automatic or implicit data type conversions if they could cause an error or lose data. Instead, you’ll need to explicitly indicate that you want to perform a conversion.

    To perform an explicit data type conversion in VB .NET, you use the CType() function. This function takes two arguments. The first specifies the variable you want to convert, and the second specifies the data type you’re converting it to. Here’s how you would rewrite the earlier example with explicit conversions:

     Dim BigValue As Integer = 100
    Dim SmallValue As Short
    Dim MyText As String = "100"
    ' Explicitly convert your 32-bit number into a 16-bit number.
    SmallValue = CType(BigValue, Short)
    ' Explicitly convert your string into a number.
    BigValue = CType(MyText, Integer)

    Just like implicit conversions, explicit conversions can still fail and produce a runtime error. The difference is that when you add the CType() function, you clearly indicate that you’re aware that a conversion is taking place. At the same time that you use CType(), you should add code that either validates your data before you attempt to convert it, or catches any errors using the error-handling techniques described in Chapter 11.

    You can also use the classic Visual Basic keywords such as Val(), CStr(), CInt(), CBool(), and so on to perform data type conversions with the standard data types. However, the CType() function is a nice generic solution that works for all scenarios. The examples in this book almost always use explicit conversion with the CType() function. A few exceptions apply. For example, Visual Basic’s built-in Val() function is more convenient than CType() in some scenarios because it just returns a zero if it fails to convert a string to a number.

    Dim TextString As String = "Hello"
    Dim Number As Integer
    Number = Val(TextString)
    ' Number is now 0, because TextString contains no numeric information.

    You’ll also find that you can use object methods to perform some conversions a little more elegantly. The next section demonstrates this approach.

    Object-Based Manipulation

    .NET is object-oriented to the core. In fact, even ordinary variables are really full-fledged objects in disguise. That means that common data types have the built-in smarts to handle basic operations (like counting the number of letters in a string). Even better, it means that you can manipulate strings, dates, and numbers in exactly the same way in C# and in VB .NET. This wouldn’t be true if developers used special keywords that were built into the C# or VB .NET language.

    As an example, every type in the .NET class library includes a ToString() method. The default implementation of this method returns the class name. In simple variables, a more useful result is returned: the string representation of the given variable. The following code snippet demonstrates the use of the ToString() method with an integer.

    Dim MyString As String
    Dim MyInteger As Integer = 100
    ' Convert a number to a string. MyString will have the contents "100".
    MyString = MyInteger.ToString()

    To understand this example, you need to remember that all integers are based on the Int32 class in the .NET class library. The ToString() method is built in to the Int32 class, so it’s available when you use an integer in any language. You should also notice that the line of code that uses the ToString() method is virtually identical in both languages.

    The next few sections explore the object-oriented underpinnings of the .NET data types in more detail.


    NOTE  
    Object-based code isn’t just easier to translate from one language to another, it’s also more elegant. From an object-oriented perspective, it makes more sense when the functionality you use to manipulate a data type originates from the data type itself.

    More Visual Basic.NET Articles
    More By Apress Publishing


       · This article is an excerpt from the book "Beginning ASP.NET in VB.NET: From Novice...
     

    Buy this book now. This article is excerpted from chapter three of the book Beginning ASP.NET in VB.NET: From Novice to Professional, written by Matthew MacDonald (Apress, 2004; ISBN: 1590592786). Check it out at your favorite bookstore today. Buy this book now.

    VISUAL BASIC.NET ARTICLES

    - Create a Sudoku Puzzle Generator using VB.NET
    - Entity Creation and Messaging in a VB.NET Te...
    - Movement and Player Statistics in a VB.NET T...
    - Creating and Drawing a Game Map in VB.NET (F...
    - Working with Classes and Properties for Game...
    - Working with Loops, Arrays, and Collections ...
    - Learning Loops in VB.NET for Game Development
    - Learning VB.NET: Working with Variables, Con...
    - The Basics of VB.NET Through Text Game Devel...
    - Learning VB.NET Through Text Game Development
    - Types of Operators in Visual Basic
    - Operators
    - Understanding Custom Events using Visual Bas...
    - Polymorphism using Abstract Classes in Visua...
    - Shadowing using Shadows in Visual Basic.NET ...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway