Visual Basic Keywords And Syntax

Those with previous experience with Visual Basic are already familiar with many of the language keywords and syntax. However, not all readers will fall into this category so this introductory section is for those new to Visual Basic. A glossary of keywords is provided after which this section will use many of these keywords in context.

Although they're not the focus of the chapter, with so many keywords, a glossary follows. Table 1-2 briefly summarizes most of the keywords discussed in the preceding section, and provides a short description of their meaning in Visual Basic. Keep in mind there are two commonly used terms that aren't Visual Basic keywords that you will read repeatedly including in the glossary:

V Method — A generic name for a named set of commands. In Visual Basic, both subs and functions are types of methods.

V Instance — When a class is created, the resulting object is an instance of the class's definition.

TABLE 1-2: Commonly Used Keywords in Visual Basle 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.

Sub A method that contains a set of commands, allows data to be transferred as parameters, and provides scope around local variables and commands, but does not return a value

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 continues

Table 1-2 (continued)

keyword description




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

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

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

A code block that isn't a class but which can contain Sub and Function methods. Used when only a single copy of code or data is needed in memory.

Even though the focus of this chapter is on Visual Studio, during this introduction a few basic elements of Visual Basic will be referenced and need to be spelled out. This way as you read, you can understand the examples. Chapter 4, for instance, covers working with namespaces, but some examples and other code are introduced in this chapter that will mention the term, so it is defined here.

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 both your custom application's classes, whether it be a small or large collection, and that of the .NET Framework's thousands of classes. As noted earlier, namespaces are covered in detail in Chapter 4.

Next is the keyword Class. Chapters 2 and 3 provide details on object-oriented syntax and the related keywords for objects and types, 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 use the New command to assign that instance of an object to a variable. A variable is quite literally something which can hold a reference to that class's instance.

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, which preceded Visual Basic as a language. The idea is that you are telling the system to allocate or dimension a section of memory to hold data. As discussed in subsequent chapters on objects, the Dim statement may be replaced by another keyword such as Public or Private that not only dimensions the new value, but also limits the accessibility of that 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()

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.

A class consists of both state and behavior. State is a fancy way of referring to the fact that the class has one or more values also known as properties associated with it. Embedded in the class definition are zero 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 Visual Basic's days as a procedural language. The first is Sub. Sub, 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 without returning a value. The following snippet shows the declaration of a Sub:

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

The preceding example shows the start of a Sub 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. Thus, in other languages this might be considered and written explicitly as a function that returns Nothing.

The preceding method declaration for Sub Load also includes a single parameter, object, which is declared as being of type System.Object. The meaning of the ByVal qualifier is explained in chapter 2, but is related to how that value is passed to this method. The code that actually loads the object would be written between the line declaring this method and the End Sub line.

Alternatively, a method can return a value; Visual Basic uses the keyword Function to describe this behavior. In Visual Basic, the only difference between a Sub and the method type Function is the return type.

The Function declaration shown in the following sample code specifies the return type of the function as a Long value. A Function works just like a Sub with the exception that a Function returns a value, which can be Nothing. This is an important distinction, because when you declare a function the compiler expects 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, and if it is in a function, the return value should be returned. To declare a Function, you write code similar to the following:

Public Function Add(ByVal ParamArray values() As Integer) As Long Dim result As Long = 0 'TODO: Implement this function Return result

'What if there is more code Return result End Function

In the preceding example, note that after the function initializes the second line of code, there is a Return statement. 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:

The preceding example demonstrates a call to a function. The value returned by the function Add is a Long, 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 how, within an object, that you can reference the current instance of that object.

You may have noticed that in all the sample code presented thus far, 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.

Visual Basic doesn't use visible punctuation to end each line. Traditionally, the BASIC family of languages viewed source files more like a list, whereby each item on the list is placed on its own line. At one point the term was source listing. By default, Visual Basic ends each source list item with the carriage-return linefeed, and treats it as a command line. 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. Thus previously, in Visual Basic, that entire statement would be found on a single line unless the user explicitly indicates that it is to continue onto another line.

To explicitly indicate that a command line spans more than one physical line, you'll see the use of the underscore at the end of the line to be continued. However, one of the new features of Visual Basic 10, which ships with Visual Studio 2010, is support for an implicit underscore when extending a line past the carriage-return linefeed. However, this new feature is limited as there are still places where underscores are needed.

When a line ends with the underscore character, this explicitly tells Visual Basic that the code on that line does not constitute a completed set of commands. The compiler will then continue to the next line to find the continuation of the command, and will end when a carriage-return linefeed is found without an accompanying underscore.

In other words, 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 Message Box Title", _ MessageBoxButtons.OK, MessageBoxIcon.Information)

Prior to Visual Basic 10 the preceding example illustrated the only way to extend a single command line beyond one physical line in your source code. The preceding line of code can now be written as follows:

MessageBox.Show("Hello World", "A Message Box Title", MessageBoxButtons.OK, MessageBoxIcon.Information)

The compiler now recognizes certain key characters like the "," or the "=" as the type of statement where a line isn't going to end. The compiler doesn't account for every situation and won't just look for a line extension anytime a line doesn't compile. That would be a performance nightmare; however, there are several logical places where you, as a developer, can choose to break a command across lines and do so without needing to insert an underscore to give the compiler a hint about the extended line.

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

Was this article helpful?

0 0

Post a comment