8. Basics
Before exploring the depths of
the Visual Basic language, let us first focus on some core issues. The first
version of Visual Basic was 1.0. We have intentionally mentioned this fact
here, because the software giant Microsoft is not always known to begin all its
product versions with the Version Number 1.0.
Visual Basic was not initially
conceived as a language. It was designed mainly as a product that used the
language. Actually, the language was developed as an afterthought, since
Microsoft's main focus was on building the Visual Basic product. Ever since its
inception, Visual Basic has donned the mantle of the most popular language
amongst Windows programmers.
At that stage, the only other
competitors in the market were Power Builder and Delphi. Incidentally, the
designer of the above two products has also designed the .Net programming
language named C#. When Microsoft released COM, i.e. the Component Object
Model, it used Visual Basic 4.0 to showcase its efficacy. However, in the
current scenario, Visual Basic has been replaced by Visual Studio.Net.
According to the big boys at Microsoft, Visual Basic is considered to be the
easiest entry-point into the Microsoft.Net platform. We are not going to argue
on issue, since we could but not agree with them anymore!
The designers of Visual Basic
did not merely extract random ideas out of their hats to develop this product.
They sat down and designed it with a specific target audience in mind. The fact
that the largest number of programmers the world over are Visual Basic
programmers is indeed a tribute to their genius.
To retain the loyalty of this
large posse of Visual Basic programmers, Microsoft has very little choice but
to design Visual Basic.Net in such a manner that a Visual Basic programmer
would feel as comfortable using it as a fish in water. If they had not done so,
there was imminent danger of the trillions of Visual Basic programmers jumping
ship to some other language ;). Visual Basic.Net is thus a descendant of Visual
Basic.
The syntax and the semantics of
the language are easy to understand and the counter-intuitive features have
been circumvented. The language is also designed to be an integral part of the
.Net framework.
All .Net languages compile to IL
or Intermediate Language. We are aware of this conversion since we have written
a book on IL. This concept has been introduced to ensure that the classes
created in one language can be used in another language with ease. As a result
of this, there is no way of ascertaining whether the Console class has been
written in C# or in Visual Basic.Net or in some other .Net language.
In order to implement this
concept, and to make it fit into the overall framework of the .Net world, the
features of Visual Basic.Net are quite divergent from those of the older Visual
Basic. Thus, Visual Basic.Net is considered to be a reasonable upgrade of
Visual Basic. This fact is also ratified by what is stated in the
documentation.
The original designers of Visual
Basic had intended it to be a quick and easy language that people could use,
without having any formal training. The emphasis of Visual Basic always was to
facilitate users to build applications with ease. It has succeeded remarkably
in its original intention, a fact that is vindicated from the exceptional success
of the product.
However, the language
disconcerts the purists, since it infringes the cardinal rules of the
programming world. But hey, who cares? Why fix a thing that already works well?
In Visual Basic.Net, the Enter
key signals the end of a line. Most languages such as C, C++, C# and Java use
the semi-colon to signal the end of a statement. The ABAP/4 programming
language from SAP uses the dot, like we do in the English language. However,
the designers of Visual Basic.Net mutually decided to use the Enter key for
this purpose.
a.vb
public class zzz
shared sub Main()
System.Console.WriteLine("This line is" &
"broken over two line")
end sub
end class
Error
c:\il\a.vb(3) : error BC30201: Expression expected.
The above program is bound to
generate an error, since we are not permitted to press Enter midway through a
line. We unwittingly pressed Enter, since the line was becoming too protracted.
However, this is unacceptable. There is a very simple remedy to this malady,
which is, to use the _ underscore character.
System.Console.WriteLine("This line is" & _
"broken over two line")
Thus, whenever the Visual
Basic.Net compiler bumps into the underscore character, it is aware that the
string is incomplete, and continues its search to the next line. Furthermore,
we cannot break up a string enclosed within double quotes. Even an underscore
character would not be able to help in such cases.
The program given below is
distinct from those we have encountered so far. It substantiates the fact that,
if and when the reserved words like string and class are used in any other
context, they need to be placed within square brackets.
a.vb
public class zzz
shared sub Main()
System.Console.WriteLine([class].[string])
end sub
end class
class [class]
public shared [string] as integer = 10
end class
Output
10
The program has two classes, zzz
and class. String is a shared variable of type integer in the class. Now, to
access the variable in the main subroutine, the syntax to be used is
'class.variable'. Hence, the WriteLine function has a string variable, which is
accessed by using [class].[string].
Mark the use of square brackets.
The use of square brackets with the identifier, is also known as 'escaping' the
identifiers.
We would advise you to refrain
from using keywords as identifiers, although they are legally valid, as
depicted above. There are only about a hundred such keywords in Visual
Basic.Net. The keywords conform to the Unicode 3.0 Standard Report 15 Annex 5.
Languages such as Chinese and
Japanese are extremely visual, and hence, the ASCII character set, which is
used for representing the English language, becomes too restrictive in their
case. The Unicode standard is an approach, by means of which, characters from
all languages of the world can be represented. Unicode, which is an
international standard, uses 16 bits, instead of the regular 8 bits used by the
ASCII set.
Another rule for an identifier
to adhere to is that, if it begins with an underscore character, it must have
at least one more character following it.
The identifiers have a
constraint in the form of their length, i.e. their maximum size can only be
1633 characters. This infuriates us, since only a programmer bereft of all
reason, would create a variable exceeding 100 characters in lengths. Yet, the
documentation says that the identifier length is restricted to the above.
Perhaps, in the next version, the limit may be eked out to 32000 characters!
Note that the identifiers in Visual Basic.Net are case-insensitive.
a.vb
public class zzz
shared sub Main()
dim a as string
a$ = "hi"
System.Console.WriteLine(a$)
end sub
end class
Output
hi
An identifier or a variable name
may be followed by some special characters, such as $ or @. These special characters
are called 'type characters' and they work with non-escaped identifiers. The
variable name mentioned above remains as 'a'. However, the $ sign ensuing it,
indicates that the variable type is a string.
Therefore, the variable is
declared in the normal way. The use of 'type' character is optional. It serves
the purpose of visually revealing the data type of the variable.
a@ = "hi"
Error
c:\il\a.vb(4) : error BC30277: Type character '@' does not
match declared data type 'String'.
Change the $ sign to @. Its
outcome is an error, because the $ denotes a string, whereas, the @ denotes a
number or a long. Thus, in spite of the type character being optional, we are
not authorized to use it in inappropriate contexts.
We cannot lodge spaces or white
space characters between the variable and the type identifier. Also, the type
characters cannot be placed on entities that do not have a type, such as a
namespace or a classname. Therefore, the example given below, leads to an
error, since the type identifier $ has been positioned in front of the class
name.
public class zzz$
Error
c:\il\a.vb(1) : error BC30468: Type declaration characters
are not valid in this context.
The keyword mentioned above
signifies something special, and has certain rules associated with it, which
need to be followed meticulously. In order to learn any language, we have to
master the use its keywords.
A 'literal' is a constant or a
textual representation of some value. We have six different types of literals.
The 'boolean literal' can take one of the two values, True or False.
a.vb
public class zzz
shared sub Main()
System.Console.WriteLine(&Hf)
System.Console.WriteLine(&o12)
end sub
end class
Output
15
10
The integer literal can
represent numbers in three different bases. By default, we humans are
habituated into using numbers that are in the decimal notation or numbers with
the base 10.
The above example displays
numbers in hex. Hence, the number starts with &h. A hex number is
represented, not merely by the digits from 0 to 9, but also by the characters
from A to F. Thus, the digit A stands for 10 and F stands for 15. In the decimal
numbering system, each digit is multiplied with an order of 10, while in hex,
it is multiplied by an order of 16.
A number beginning with &o
represents an octal number that uses the base of 8. Thus, all numbers in octal
consist of digits from 0 to 7 only. Every individual digit is multiplied by a
order of 8.
While working with computers at
the bit level, it is relatively easier to work with the hex and octal numbering
systems, rather than with the decimal system. However, you could spend a
lifetime in the computer world, and yet, never chance upon a number in octal or
hex!
a.vb
public class zzz
shared sub Main()
dim i as integer
i = 10000000000000
System.Console.WriteLine(i)
end sub
end class
Error
c:\il\a.vb(4) : error BC30439: Constant expression not representable
in type 'Integer'.
You and I may snooze off at the
wheel, but the Visual Basic.Net complier does not suffer from any such malady.
It is hawk-eyed. The literal integer has a specific range of values, and if we
exceed it, the above error would get generated.
a.vb
public class zzz
shared sub Main()
System.Console.WriteLine("Hi
""Vijay""")
end sub
end class
Output
Hi "Vijay"
A string 'literal' consists of
anything enclosed within double inverted commas, as we had explained earlier.
However, when a double inverted comma is to be inserted in the string, an
additional set of double inverted commas is required to be positioned back to
back. The following characters are used as separators: ( | ) | ! | # | , | . | :.
When the Visual Basic.Net
compiler is executed, it first scans the code. This process is known as
'lexical analysis'. Then, it has an option of including specific code of ours,
in the output files generated. This process is known as 'conditional
compilation'. It is demonstrated in the next example.
a.vb
#const z = true
public class zzz
shared sub Main()
abc
end sub
shared sub abc
#if z then
System.Console.WriteLine("z true")
#else
System.Console.WriteLine("z false")
#end if
end sub
end class
Output
z true
The preprocessor is a program
that normally is part of the Visual Basic.Net compiler. It scrutinizes the code
at a very early stage in the whole process. It only looks at lines beginning
with a # symbol, also known as a preprocessor directive.
The preprocessor directive,
along with the word 'const', is part of the syntax, which is set to a value of
True. Any value, including numbers, can be assigned here, as long as it is not
a string, since string values cannot be converted into boolean values.
The sub called abc has an 'if'
statement, which begins with a # sign, followed by the 'if' statement. This is
the preprocessor equivalent of the 'if' statement. The syntax remains the same.
This directive checks for the value in the 'const'.
The value of z is checked to
determine if it is true or false. If it is true, then all the code between the
'if' and 'else' gets included in the resultant code. But, if the value
evaluates to false, the code between the 'else' and 'end if' gets included. In
the above case, the Visual Basic.Net compiler ignores the 'else' block, thereby
totally sidelining the second WriteLine function.
a.vb
#const z = true
public class zzz
shared sub Main()
abc
end sub
shared sub abc
#if z then
dim i as integer
#else
dim j as integer
#end if
System.Console.WriteLine(i+j)
end sub
end class
Output
c:\il\a.vb(12) : error BC30451: Name 'j' is not declared.
The above example lucidly
explains the concept described above. The directive of 'if-else-end if' is used
to create either of the variables i or j, depending upon the value stored in
the const z. Since z holds the value of
true, only the variable i is created.
The DIM statement for j gets
knocked out of the code, since the 'else' block is snubbed completely. When the
Visual Basic.Net compiler kicks in, the only variable visible to it is i, and
not j. Resultantly, it hurls the error message at us, stating that j has not
been declared.
Rewrite the above const
statement as :
#const z = nothing
The error message now reads as :
c:\il\a.vb(12) : error BC30451: Name 'i' is not declared.
When the const variable is
initialized to nothing, a default value of false is assigned to the variable.
Also, the const variable assumes a default value of false, when the variable
has not been created in the program. If a variable is created, it must be
assigned some value, or else, the following error will be thrown:
c:\il\a.vb(1) : error
BC30249: '=' expected.
There are two ways of creating a
preprocessor variable; one is by using the const directive, and the other is by
employing an option of the command line compiler. Eliminate the line in the
above program that creates a const variable z, and then, run the Visual
Basic.Net compiler using the command:
vbc /d:z=true a.vb
c:\il\a.vb(11) : error BC30451: Name 'j' is not declared.
The /d option with the Visual
Basic.Net compiler creates a preprocessor constant. Thus, a constant z is
created, with its value set to true. The variable j is not defined anywhere,
since the 'else' block has been ignored. Hence, the above error message gets
displayed. Had we set the value of the variable z to false, an error message
would have been generated, informing us that the variable i has not been
created.
This method demonstrates the
most common use of preprocessor variables. Under normal circumstances, the
program code has a large number of debugging statements sprinkled all over the
program. The example given below delineates this.
a.vb
public class zzz
shared sub Main()
abc
end sub
shared sub abc
#if DEBUG then
System.Console.WriteLine("Debug")
#end if
end sub
end class
There are many things that may
go awry while developing programs. Therefore, at every stage, checks need to be
implemented. For this very reason, the code is infused with plenty of
statements, which reveal the activities to the program, while it is running.
The WriteLine function may also
be used for this purpose. However, the only failing of this approach is that,
millions of WriteLine functions will have to be deleted, after they have served
their utility.
So, the best solution is to
place all the debugging code in a '#if' statement using the variable DEBUG. At
compile time, the DEBUG variable is set to True. On seeing the value of true,
all the WriteLine statements will get executed, thus providing a trace of the
events. If the debugging facility needs to be switched off, i.e. when the
program is to be switched to the Release mode, the DEBUG variable can be
deleted or set to False. This would result in all the WriteLine functions being
ignored in the program.
This is just one example of the
myriad uses of the preprocessor variables that can be created at the command
line.