Initial Keywords and Syntax


While it would be possible to just add a giant glossary of keywords, that isn’t the focus of this chapter. Instead, a few basic elements of Visual Basic need to be spelled out, so that as you read you can understand the examples. Chapter 8, for instance, covers working with namespaces, but some examples and other code are introduced in this chapter.

Let’s begin with namespace. When .NET was being created, the developers realized that attempting to organize all of these classes required a system. A namespace is an arbitrary system that the .NET developers used to group classes containing common functionality. A namespace can have multiple levels of grouping, each separated by a period (.). Thus, the System namespace is the basis for classes that are used throughout .NET, while the Microsoft.VisualBasic namespace is used for classes in the underlying .NET Framework but specific to Visual Basic. At its most basic level, a namespace does not imply or indicate anything regarding the relationships between the class implementations in that namespace; it is just a way of managing the complexity of the .NET Framework’s thousands of classes. As noted earlier, namespaces are covered in detail in Chapter 8.

Next is the keyword Class. Chapters 3 and 4 provide details on object-oriented syntax and the related keywords for objects, but a basic definition of this keyword is needed here. The Class keyword designates a common set of data and behavior within your application. The class is the definition of an object, in the same way that your source code, when compiled, is the definition of an application. When someone runs your code, it is considered to be an instance of your application. Similarly, when your code creates or instantiates an object from your class definition, it is considered to be an instance of that class, or an instance of that object.

Creating an instance of an object has two parts. The first part is the New command, which tells the compiler to create an instance of that class. This command instructs code to call your object definition and instantiate it. In some cases you might need to run a method and get a return value, but in most cases you’ll use the New command to assign that instance of an object to a variable.

To declare a variable in Visual Basic, you use the Dim statement. Dim is short for “Dimension” and comes from the ancient past of Basic as a language. The idea is that you are telling the system to allocate or dimension a section of memory to hold data. The Dim statement is used to declare a variable, to which the system can then assign a value. Each variable declaration uses a Dim statement similar to the example that follows, which declares a new variable, winForm:

  Dim winForm As System.Windows.Forms.Form = New System.Windows.Forms.Form() 

As a best practice, always set a variable equal to something when it is declared. In the preceding example, the code declares a new variable (winForm) of the type Form. This variable is then set to an instance of a Form object. It might also be assigned to an existing instance of a Form object or alternatively to Nothing. The Nothing keyword is a way of telling the system that the variable does not currently have any value, and as such is not actually using any memory on the heap. Later in this chapter, in the discussion of Value and Reference types, keep in mind that only reference types can be set to Nothing.

What do we mean when we refer to a class consisting of data and behavior? For “data” this means that the class specifies certain variables that are within its scope. Embedded in the class definition are one or more Dim statements that create variables used to store the properties of the class. When you create an instance of this class, you create these variables; and in most cases the class contains logic to populate them. The logic used for this and to carry out other actions is the behavior. This behavior is encapsulated in what, in the object-oriented world, are known as methods.

However, Visual Basic doesn’t have a “method” keyword. Instead, it has two other keywords that are brought forward from VB’s days as a procedural language. The first is Sub. Sub is short for “Subroutine,” and it defines a block of code that carries out some action. When this block of code completes, it returns control to the code that called it. To declare a function, you write code similar to the following:

  Private Sub Load(ByVal object As System.Object) End Sub 

The preceding example shows the start of a method called Load. For now you can ignore the word Private at the start of this declaration; this is related to the object and is further explained in the next chapter. This method is implemented as a Sub because it doesn’t return a value and accepts one parameter when it is called. This parameter is declared as being of type System.Object, and the meaning of the ByVal qualifier is explained later in this chapter. The code that actually loads the object would be written between the line declaring this method and the End Sub line.

In Visual Basic, the only difference between a Sub and the second method type, a Function, is this return type. Note that the Function declaration shown in the following sample code specifies the return type of this function. A function works just like a Sub with the exception that a Function returns a value. This is an important distinction, because when you declare a function you expect it to include a Return statement. The Return statement is used to indicate that even though additional lines of code may remain within a function or sub, those lines of code should not be executed. Instead, the Function or Sub should end processing at the current line.

  Public Function Add(ByVal ParamArray values() As Integer) As Long     Dim result As Long = 0     Return result     'TODO: Implement this function     'What if user passes in only 1 value, what about 3 or more...     result = values(0) + values(1)     Return result End Function 

In the preceding example, note that after the function initializes the second line of code, there is a Return statement. Since the implementation of this function isn’t currently shown (it is shown later in this chapter in the discussion of parameters), the developer wanted the code to exist with a safe value until the code was completed. Notice that there are two Return statements in the code. However, as soon as the first Return statement is reached, none of the remaining code in this function is executed. The Return statement immediately halts execution of a method, even from within a loop. As shown in the preceding example, the function’s return value is assigned to a local variable until returned as part of the Return statement. For a Sub, there would be no value on the line with the Return statement, as a Sub does not return a value when it completes. When returned, the return value is usually assigned to something else; this is shown in the next example line of code, which calls a function to retrieve the currently active control on the executing Windows Form:

  Dim ctrl As System.Windows.Forms.Control = Me.GetContainerControl().ActiveControl() 

The preceding example demonstrates a call to a function. The value returned by the function ActiveControl is of type Control, and the code assigns this to the variable ctrl. It also demonstrates another keyword that you should be aware of: Me. The Me keyword is the way, within an object, that you can reference the current instance of that object. For example, in the preceding example, the object being referenced is the current window.

You may have noticed that in all the sample code presented above each line is a complete command. If you’re familiar with another programming language, then you may be used to seeing a specific character that indicates the end of a complete set of commands. Several popular languages use a semicolon to indicate the end of a command line. For those who are considering Visual Basic as their first programming language, consider the English language, whereby we end each complete thought with a period.

Visual Basic doesn’t use visible punctuation to end each line. Instead, it views its source files more like a list, whereby each item on the list is placed on its own line. The result is that Visual Basic ends each command line with the carriage return linefeed. In some languages, a command such as X = Y can span several lines in the source file until a semicolon or other terminating character is reached. However, in Visual Basic that entire statement would be found on a single line unless the user explicitly indicated that it was to continue onto another line.

When a line ends with the underscore character, this tells Visual Basic that the code on that line does not constitute a completed set of commands. The compiler will then continue onto the next line to find the continuation of the command, and will end as soon as a carriage return linefeed is found without an accompanying underscore. In this way, Visual Basic enables you to use exceptionally long lines and indicate that the code has been spread across multiple lines to improve readability. The following line demonstrates the use of the underscore to extend a line of code:

  MessageBox.Show("Hello World", "A First Look at VB.NET",  _                  MessageBoxButtons.OK, MessageBoxIcon.Information) 

It is also possible to place multiple different statements on a single line with Visual Basic, by separating the statements with colons. However, this is generally considered a poor coding practice because it reduces readability.

Console Applications

The simplest type of application is a console application. This application doesn’t have much of a user interface; in fact, for those old enough to remember the MS-DOS operating system, a console application looks just like an MS-DOS application. It works in a command window with no support for graphics or graphical devices such as a mouse. A console application is a text-based user interface that reads and writes characters from the screen.

The easiest way to create a console application is to use Visual Studio. However, for our purposes let’s just look at a sample source file for a console application, as shown in the following example. Notice that the console application contains a single method, a Sub called Main. However, this Sub isn’t contained in a class. Instead, the Sub is contained in a Module:

  Module Module1     Sub Main()          Dim myObject As Object = New Object()          Console.WriteLine("Hello World")     End Sub End Module 

A module is another item dating to the procedural days of Visual Basic. It isn’t a class, but a block of code that can contain methods, which are then referenced by classes - or, as in this case, it can represent the execution start for a program. The module in the preceding example contains a single method called Main. The Main method indicates the start point for running this application. Once a local variable is declared, the only other action taken by this method is to output a line of text to the console.

Note that in this usage, the Console refers to the text-based window, which hosts a command prompt from which this program is run. The console window is best thought of as a window encapsulating the older nongraphical-style user interface whereby literally everything was driven from the command prompt. The Console class is automatically created when you start your application, and it supports a variety of Read and Write methods. In the preceding example, if you were to run the code from within Visual Studio’s debugger, the console window would open and close immediately. To prevent that, you include a final line in the Main Sub, which executes a Read statement so that the program continues to run while waiting for user input.

Because so many keywords have been covered, a glossary might be of use. The following table briefly summarizes most of the keywords discussed in the preceding section, and provides a short description of their meaning in Visual Basic:

Open table as spreadsheet

Keyword

Description

Namespace

A collection of classes that provide related capabilities. For example, the System.Drawing namespace contains classes associated with graphics.

Class

A definition of an object. Includes properties (variables) and methods, which can be subs or functions.

Instance

When a class is created, the resulting object is an instance of the class’s definition. Not a keyword in Visual Basic.

Method

A generic name for a named set of commands. In Visual Basic, both subs and functions are types of methods. Not a keyword in Visual Basic.

Sub

A method that contains a set of commands, allows data to be transferred as parameters, and provides scope around local variables and commands.

Function

A method that contains a set of commands, returns a value, allows data to be transferred as parameters, and provides scope around local variables and commands.

Return

Ends the currently executing sub or function. Combined with a return value for functions.

Dim

Declares and defines a new variable

New

Creates an instance of an object

Nothing

Used to indicate that a variable has no value. Equivalent to null in other languages and databases

Me

A reference to the instance of the object within which a method is executing

Console

A type of application that relies on a command-line interface. Console applications are commonly used for simple test frames. Also refers to a command window to and from which applications can read and write text data.

Module

A code block that isn’t a class but which can contain sub and function methods. Not frequently used for application development but is part of a console application.




Professional VB 2005 with. NET 3. 0
Professional VB 2005 with .NET 3.0 (Programmer to Programmer)
ISBN: 0470124709
EAN: 2147483647
Year: 2004
Pages: 267

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net