Visual Basic .NET
Program Organization & .NET Discussion
A Visual Basic program has standard building blocks. For example, the VB .NET code will follow this sequence: Option statements, Imports statements, the Sub Main procedure, Class and Module statements, etc.
An Imports statement permits a class to be referred to by its class name alone, rather than through dot notation that includes the namespace, i.e. import system.windows.forms to allow you to access the "system.windows.forms.form" class simply by "form"
All VB .NET programs must contain at least one module or class.
In VB .NET, a method consists of either a Function or Sub defined within the class. A Sub does some task and returns no value. The Function does some task and returns a value.
Refer to the current object with "me" (same as "this" in java). Refer to the inherited class and its methods/events/variables with "mybase".
A Generic Windows Application
The generic Windows Application consists of a class that inherits from system.windows.forms.form. Upon execution of the program, a single instance of that class is created. The program continues to run until that instance of the class is disposed of. This means that after the constructor is done, the program sits there waiting for events to occur until one of them disposes the initial class.
Namespaces
In VB .NET, related classes are grouped into namespaces. Namespaces avoid naming conflicts by organizing classes, interfaces, and methods into hierarchies. The fully qualified name of a class is indicated by the namespace, followed by a dot followed, by a class name (referred to as "dot notation"). For example: System.Console
Visual Basic .NET programs may or may not be explicitly declared to be part of a namespace.
To declare a module or class a part of a namespace, enclose it in
namespace
end namespace
Classes
Visual Basic .NET conforms to Object Oriented style in its handling of classes and objects.
Modules
Modules are a reference type similar to classes, but with some important distinctions. The members of a module are implicitly Shared and scoped to the declaration space of the standard module's containing namespace, rather than just to the module itself. Unlike classes, modules can never be instantiated, do not support inheritance, and cannot implement interfaces. A module can only be declared in a namespace and cannot be nested in another type.
You can have multiple modules in a project, but members with the same name defined in two or more modules must be qualified with their module name when accessed outside of their module.
Control Statements
IF
The conditional IF statement is structured similarly to that of other computer languages. The following is the syntax for an IF statement:
if (condition) then
Statement(s)
end if
As in any conditional IF statement, we may want the format of an IF ELSE, which has the following syntax: (note reserved words and & or)
if (condition1 and condition2) or condition3 then
Statement(s)
elseIf (condition2) then
statement(s)
else
statement(s)
end if
In a nested IF statement, the same format is followed, with each IF requiring an END IF to match up with it (the closest END IF within the code to the IF).
Select
Another way to test conditions is to use a SELECT CASE, which is similar to a SWITCH CASE in some other languages. The SELECT CASE has the following syntax:
select case expression
case possible value {or case range of values}
statement(s)
case another possible value or range of values
statement(s)
case else
statement(s)
end select
Case can be listed as 'case "first", "second",' meaning if "first" or "second" then this action is performed. Another possible example is to use a value ('case 1'), or a range of values ('case 0 to 30' or 'case is < 0').
For
As usual, a FOR loop is used when there is a specific initial value that is either incremented or decremented by a certain amount until the value has reached the terminating value. The syntax for this loop in Visual Basic .NET is:
for counter = initialValue to terminatingValue {step amount}
statement(s)
next
The STEP part is optional - the default value is +1.
Do
There are four forms of a DO statement in Visual Basic .NET. The first two are pretest and the last two posttest. The first form tests if a condition is true before executing any statements included within the loop body and continues to execute them while the condition is true. This syntax format is:
do while (condition)
program statement(s)
loop
The second form is used when you wish to execute the loop until a given condition is true. Its syntax is:
do until (condition)
program statement(s)
loop
The third form is used to execute the statements at least once and continue to do so while the condition is true. Its syntax is:
do
statement(s)
loop while (condition)
And the last form is used to execute the statements within the loop body at least once until the given condition is true. The syntax for this form is:
do
statement(s)
loop until (condition)
Identifiers
Must Begin with a Letter
Be a Maximum of 255 Letters
Contain only letters, numbers, or underscore
Can not be a reserved word
Reserved Words
If using the Visual Studio IDE for Visual Basic .NET, key words will stand out by being highlighted in blue text. (In addition, it will immediately inform you if you have violated any grammar rules if you are doing something such as declaring a variable and you accidentally use a reserved word. The text will be underlined, and when the mouse pointer is dragged over it, a pop-up message will appear showing you what rule you have violated.) Another way you can test what is key words is to take your code and input it into the test box at http://www.vbcity.com/encoder/default.asp?lang=vbnet (make sure VB.NET is selected).
Data Types & Variables
Declaring Variables
To declare a variable you must specify a name and data type.
Example: Dim Variable as DataType.
Multiple Declarations can be made on one line.
Example: Dim Var1, Var2, as DataType
Option Explicit statement forces one to declare variables before using them in code.
The data types are as follows
Numbers:
Integer - -10 (4 bytes)
Byte - 0 to 255 (1 byte)
Double - 456 (8 bytes)
Decimal - 1.2 (16 bytes)
Long - 12345 (8 bytes)
Short - -32,768 to 32,768 (2 bytes)
Single - 85858 (4 bytes)
Char - 0 to 65,535 (2 bytes)
String:
String - "Hello World" (Varies)
Boolean:
Boolean - True or False (4 bytes)
Date:
Date - Jan 1,1 to Dec 31, 9999 (8 bytes)
Object:
Object - Can hold any variable type (4 bytes)
It is also possible to declare the type of the variable by using type declaration characters
Data Type Character Identifier
Decimal @ D
Double # R
Integer % I
Long & L
Single ! F
String $ S
Example:
Dim Age as Integer could also be written as Dim Age%
Scope:
The Scope of a variable is where it can be accessed in the code relevant to its declaration
Private:
Only available to module, class, or structure in which they are declared.
Dim:
Same as Private except can be used with functions or subprocedures
Public:
Available to all procedures in all classes, modules, and structures. By default all declarations Public.
Static:
Only contain value within scope of method or class in which they are declared.
Shared:
Properties, Procedures, or Fields shared by all instances of a class.
Protected:
Only available to class in which they are declared.
Friend:
Accessible from any class or module within assembly that they are declared.
Variable Defaults:
When variable are initialized they are by default initialized to the value below
Numbers: 0
Boolean: False
String: Nothing
Object: Nothing
Date: 12:00 AM
Data Structures
Arrays
NOTE: Arrays are done with parenthesis, NOT brackets, so it gets a little confusing
Creation:
You must define the array name, size, and type
Example : Dim ArrayName(Size) as DataType
You can also declare multidimensional arrays
Example: Dim MultiArray( X, Y ) as DataType
Inserting Data:
Arrays always begin at position zero, therefore to insert data into the 2nd position in the array ArrayExample. You would say:
ArrayExample(1) = "Hello"
Resizing Arrays:
You can change the size of your array to grow and shrink as you please with the ReDim command. Suppose SmallArray is of size 2. To make it bigger just:
ReDim SmallArray(22) as Integer.
Structure
These are also known as user defined variable types. Because in a sense you are creating a variable that holds what you want it to hold. You can use a structure to store what you want in one variable.
Creation:
Example:
Structure NameofStructure
Variable declaration1
Variable declaration2
End Structure
Referencing:
Once a structure has been created you can initialize variables to this structure.
Example: Variable as StructureName
Inserting Data:
Inserting data is done as follows
Example: VariableName.StructureVariable = New Value
Example of creation and insertion.
Structure Person
Public Name as String
Public Phone as Integer
End Structure
Dim Josh as Person
Josh.Name = "Josh"
Josh.Phone = 123-4567
type conversions:
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. This recognizes some of the more common forms of 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 by calling toString() on the object
Ctype converts to any type. Allows you to convert any type to another type. The syntax For this function is slightly different than others.
(newVar = ctype(oldvar, newType)
Double d = ctype("10354", Double)
NOTE: Explicit conversions are NOT neccesary.
Assignment Statements
Math symbols:
= assigns one value to another
+ adds two values
- subtracts one value from another
* multiplies two values
/ divides one value by another
mod returns the remainder for a division
& concatenates two strings ("hello " & "world" = "hello world")
+= adds a value and assigns the result
-= subtracts a value and assigns the result
*= multiplies a value and assigns the result
/= divides by a value and assigns the result
&= concatenates with a string and assigns the result
^ raises one value to the power of an exponent
Declarations:
dim <variableName> as <type>
ex: dim dateOfMagnaCarta as Date = #June 15, 1215#
Instantiation
Variable_name = new ClassName(parameter_1, parameter_2)
Variable_name = "hello world"
Combine the two
Dim <var_name> as ClassName = new ClassName(parameter_1, parameter_2)
Dim <var_name> as string = "Hello_World"
Shorter Version:
Dim <var_name> as new ClassName(parameter_1, parameter_2)
Modualrity
Routines
There are two types of routines used in VB.NET. One type is a routine that does something, but doesn't return any value. These are called subroutines (sub). The other type of procedure does something, but returns a value. These are called functions. Related to subroutines and functions is the idea of scope. We will discuss the importance of this as well.
Subroutines
Any time that you wish to perform some piece of code that you know you will probably perform exactly the same later on, it is probably a good idea to create a subroutine. There are plenty of predefined subroutines for VB such as the console subroutines write() and readLine(). Subroutines are started with the word "sub" and ended with the phrase "end sub". They can have parameters passed in as well. This is of the form parameter as type such as "message as String".
Example:
Sub showMessage(ByVal Message As String)
msgbox("someMessage")
End Sub
Functions
Functions are very similar to subroutines in vb.net. The basic difference in use is that functions return some sort of type, usually a Boolean answer or some number value. However it can return virtually any type.
Example:
Function Square(value1 as Integer) as Integer
Return value1*value1
End Function
Scope
Scope basically answers the question "who else can see me?" It refers to the visibility of variables within a program. These settings restrict which routines can access which variables. The two settings one can use are public and private. Public variables are available throughout the application and are otherwise known as global variables. Make sure that use of public variables is used only when necessary to protect against unauthorized or accidental change throughout the program. Private variables are only available within the module or class that they are declared. That is, any function within a class can access that variable, but not other classes in the application.
Gui & IO
Visual Basic .NET is Event Driven. Events occur all the time. Any time a button is clicked, or the mouse moves, or menu is selected, an event is raised. Look at how many events a Button or a Textbox can raise (scroll down to the events section).
To "handle" an event, you need to declare a sub that has the following form:
sub <sub-name>(<event parameters>) handles <instance>.<event-name>
statements
end sub
<event-parameters> always has 2 parameters. the first is "sender as object" (a reference to the object that raised the event), and the second is a type of event arguments. Each event has a different event argument type, which can be found in the Framework Class Documentation on that event (see "event data" section here)
Here is an example of a method that handles a button being clicked:
sub button_clicked(sender as object, e as eventargs) handles mybutton.click
msgbox("you clicked me")
end sub
If you want to handle events from a class, you must declare that class "withevents":
Public Withevents myButton as button
.NET Framework Class Library
http://msdn.microsoft.com/library/en-us/cpref/html/cpref_start.asp
Example Programs:
Image Viewer
Source Code
Executable (rename to .exe and run on a pc with .net framework)
This program is a clone of the microsoft image viewer found in windows xp.
Reversi
Source Code Class 1
Source Code Class 2
Executable(same instructions as above)
This is a version of the game "reversi". It is not complete, the AI shows what it is thinking.