Popular Posts

Showing posts with label VB Language. Show all posts
Showing posts with label VB Language. Show all posts

Saturday, March 21, 2009

Loops in VB.NET

Loops

For Loop

The For loop is the most popular loop. For loops enable us to execute a series of expressions multiple numbers of times. The For loop in VB .NET needs a loop index which counts the number of loop iterations as the loop executes. The syntax for the For loop looks like this:

For index=start to end[Step step]
[statements]
[Exit For]
[statements]
Next[index]


The index variable is set to start automatically when the loop starts. Each time in the loop, index is incremented by step and when index equals end, the loop ends.

Example on For loop

Module Module1

Sub Main()
Dim d As Integer
For d = 0 To 2
System.Console.WriteLine("In the For Loop")
Next d
End Sub

End Module

The image below displays output from above code.



While loop

While loop keeps executing until the condition against which it tests remain true. The syntax of while loop looks like this:

While condition
[statements]
End While


Example on While loop

Module Module1

Sub Main()
Dim d, e As Integer
d = 0
e = 6
While e > 4
e -= 1
d += 1
End While
System.Console.WriteLine("The Loop ran " & e & "times")
End Sub

End Module

The image below displays output from above code.



Do Loop

The Do loop can be used to execute a fixed block of statements indefinite number of times. The Do loop keeps executing it's statements while or until the condition is true. Two keywords, while and until can be used with the do loop. The Do loop also supports an Exit Do statement which makes the loop to exit at any moment. The syntax of Do loop looks like this:

Do[{while | Until} condition]
[statements]
[Exit Do]
[statements]
Loop


Example on Do loop

Module Module1

Sub Main()
Dim str As String
Do Until str = "Cool"
System.Console.WriteLine("What to do?")
str = System.Console.ReadLine()
Loop
End Sub

End Module

The image below displays output from above code.

Conditional Statements in VB.NET

Conditional Statements

If....Else statement

If conditional expression is one of the most useful control structures which allows us to execute a expression if a condition is true and execute a different expression if it is False. The syntax looks like this:

If condition Then
[statements]
Else If condition Then
[statements]
-
-
Else
[statements]
End If

Understanding the Syntax

If the condition is true, the statements following the Then keyword will be executed, else, the statements following the ElseIf will be checked and if true, will be executed, else, the statements in the else part will be executed.

Example

Imports System.Console
Module Module1

Sub Main()
Dim i As Integer
WriteLine("Enter an integer, 1 or 2 or 3")
i = Val(ReadLine())
'ReadLine() method is used to read from console

If i = 1 Then
WriteLine("One")
ElseIf i = 2 Then
WriteLine("Two")
ElseIf i = 3 Then
WriteLine("Three")
Else
WriteLine("Number not 1,2,3")
End If

End Sub

End Module

The image below displays output from above code.



Select....Case Statement

The Select Case statement executes one of several groups of statements depending on the value of an expression. If your code has the capability to handle different values of a particular variable then you can use a Select Case statement. You use Select Case to test an expression, determine which of the given cases it matches and execute the code in that matched case.

The syntax of the Select Case statement looks like this:

Select Case testexpression
[Case expressionlist-n
[statements-n]] . . .
[Case Else elsestatements]
End Select

Example

Imports System.Console
Module Module1

Sub Main()
Dim keyIn As Integer
WriteLine("Enter a number between 1 and 4")
keyIn = Val(ReadLine())

Select Case keyIn
Case 1
WriteLine("You entered 1")
Case 2
WriteLine("You entered 2")
Case 3
WriteLine("You entered 3")
Case 4
WriteLine("You entered 4")
End Select

End Sub

End Module

The image below displays output from above code.

Methods,Sub Procedures

Methods

A Method is a procedure built into the class. They are a series of statements that are executed when called. Methods allow us to handle code in a simple and organized fashion. There are two types of methods in VB .NET: those that return a value (Functions) and those that do not return a value (Sub Procedures). Both of them are discussed below.

Sub Procedures

Sub procedures are methods which do not return a value. Each time when the Sub procedure is called the statements within it are executed until the matching End Sub is encountered. Sub Main(), the starting point of the program itself is a sub procedure. When the application starts execution, control is transferred to Main Sub procedure automatically which is called by default.

Example of a Sub Procedure

Module Module1

Sub Main()
'sub procedure Main() is called by default
Display()
'sub procedure display() which we are creating
End Sub

Sub Display()
System.Console.WriteLine("Using Sub Procedures")
'executing sub procedure Display()
End Sub
End Module

The image below displays output from above code.



Functions

Function is a method which returns a value. Functions are used to evaluate data, make calculations or to transform data. Declaring a Function is similar to declaring a Sub procedure. Functions are declared with the Function keyword. The following code is an example on Functions:

Imports System.Console
Module Module1

Sub Main()
Write("Sum is" & " " & Add())
'calling the function
End Sub

Public Function Add() As Integer
'declaring a function add
Dim i, j As Integer
'declaring two integers and assigning values to them
i = 10
j = 20
Return (i + j)
'performing the sum of two integers and returning it's value
End Function

End Module

The image below displays output from above code.



Calling Methods

A method is not executed until it is called. A method is called by referencing it's name along with any required parameters. For example, the above code called the Add method in Sub main like this:
Write("Sum is" & " " & Add()).

Method Variables

Variables declared within methods are called method variables. They have method scope which means that once the method is executed they are destroyed and their memory is reclaimed. For example, from the above code (Functions) the Add method declared two integer variables i, j. Those two variables are accessible only within the method and not from outside the method.

Parameters

A parameter is an argument that is passed to the method by the method that calls it. Parameters are enclosed in parentheses after the method name in the method declaration. You must specify types for these parameters. The general form of a method with parameters looks like this:

Public Function Add(ByVal x1 as Integer, ByVal y1 as Integer)
------------
Implementation
------------
End Function

Statements and Scope

Statements and Scope

Statements

A statement is a complete instruction. It can contain keywords, operators, variables, literals, expressions and constants. Each statement in Visual Basic should be either a declaration statement or a executable statement. A declaration statement is a statement that can create a variable, constant, data type. They are the one's we generally use to declare our variables. On the other hand, executable statements are the statements that perform an action. They execute a series of statements. They can execute a function, method, loop, etc.

Option Statement

The Option statement is used to set a number of options for the code to prevent syntax and logical errors. This statement is normally the first line of the code. The Option values in Visual Basic are as follows.

Option Compare: You can set it's value to Text or Binary. This specifies if the strings are compared using binary or text comparison operators.
Option Explicit: Default is On. You can set it to Off as well. This requires to declare all the variables before they are used.
Option Strict: Default is Off. You can set it to On as well. Used normally when working with conversions in code. If you want to assign a value of one type to another then you should set it to On and use the conversion functions else Visual Basic will consider that as an error.

Example of Option Statement

The following code demonstrates where to place the Option statement.

Option Strict Off
Imports System
Module Module 1

Sub Main ()
Console.WriteLine (“Using Option”)
End Sub

End Module

The following code throws an error because Option Strict is On and the code attempts to convert a value of type double to integer.

Option Strict On
Imports System.Console
Module Module2

Sub Main()
Dim i As Integer
Dim d As Double = 20.12
i = d
WriteLine(i)
End Sub

End Module

We always should program with Option Strict On. Doing so allows us to catch many errors at compile time that would otherwise be difficult to track at run time.

Imports Statement

The Imports statement is used to import namespaces. Using this statement prevents you to list the entire namespace when you refer to them.

Example of Imports Statement

The following code imports the namespace System.Console and uses the methods of that namespace preventing us to refer to it every time we need a method of this namespace.

Imports System.Console
Module Module1

Sub Main()
Write("Imports Statement")
WriteLine("Using Import")
End Sub

End Module

The above two methods without an imports statement would look like this: System.Console.Write("Imports Statement") and System.Console.WriteLine("Using Import")

With Statement

With statemnt is used to execute statements using a particular object. The syntax looks like this:

With object
[statements]
End With

Sample Code

The following code sets text and width for a button using the With Statement.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Load
With Button1
.Text = "With Statement"
.Width = 150
End With
End Sub

Boxing

Boxing is implicit conversion of value types to reference types. Recall that all classes and types are derived from the Object class. Because they are derived from Object class they can be implicitly converted to that type. The following sample shows that:

Dim x as Integer=20
'declaring an integer x
Dim o as Object
'declaring an object
o=x
converting integer to object

Unboxing is the conversion of a boxed value back to a value type.

Scope

The scope of an element in code is all the code that can refer to it without qualifying it's name. Stated other way, an element's scope is it's accessibility in code. Scope is normally used when writing large programs as large programs divide code into different classes, modules, etc. Also, scope prevents the chance of code referring to the wrong item. The different kinds of scope available in VB .NET are as follows:

Block Scope: The element declared is available only within the code block in which it is declared.
Procedure Scope: The element declared is available only within the procedure in which it is declared.
Module Scope: The element is available to all code within the module and class in which it is declared.
Namespace Scope: The element declared is available to all code in the namespace.

Data Types, Access Specifiers

Data Types in VB .NET

The Data types available in VB .NET, their size, type, description are summarized in the table below.














Data TypeSize in BytesDescriptionType
Byte18-bit unsigned integerSystem.Byte
Char216-bit Unicode charactersSystem.Char
Integer432-bit signed integerSystem.Int32
double864-bit floating point variableSystem.Double
Long864-bit signed integerSystem.Int64
Short216-bit signed integerSystem.Int16
Single432-bit floating point variableSystem.Single
StringvariesNon-Numeric TypeSystem.String
Date8/td>System.Date
Boolean2Non-Numeric TypeSystem.Boolean
Object4Non-Numeric TypeSystem.Object
Decimal16128-bit floating point variableSystem.Decimal


Access Specifiers

Access specifiers let's us specify how a variable, method or a class can be used. The following are the most commonly used one's:

Public: Gives variable public access which means that there is no restriction on their accessibility
Private: Gives variable private access which means that they are accessible only within their declaration content
Protected: Protected access gives a variable accessibility within their own class or a class derived from that class
Friend: Gives variable friend access which means that they are accessible within the program that contains their declaration
Protected Friend: Gives a variable both protected and friend access
Static: Makes a variable static which means that the variable will hold the value even the procedure in which they are declared ends
Shared: Declares a variable that can be shared across many instances and which is not associated with a specific instance of a class or structure
ReadOnly: Makes a variable only to be read and cannot be written

Variables

Variables are used to store data. A variable has a name to which we refer and the data type, the type of data the variable holds. VB .NET now needs variables to be declared before using them. Variables are declared with the Dim keyword. Dim stands for Dimension.

Example

Imports System.Console
Module Module1

Sub Main()
Dim a,b,c as Integer
'declaring three variables of type integer
a=10
b=20
c=a+b
Write("Sum of a and b is" & c)
End Sub

End Module

Console Applications

Console Applications

Console Applications are command-line oriented applications that allow us to read characters from the console, write characters to the console and are executed in the DOS version. Console Applications are written in code and are supported by the System.Console namespace.

Example on a Console Application

Create a folder in C: drive with any name (say, examples) and make sure the console applications which you open are saved there. That's for your convenience. The default location where all the .NET applications are saved is C:\Documents and Settings\Administrator\My Documents\Visual Studio Projects. The new project dialogue looks like the image below.



The following code is example of a console application:

Module Module1

Sub Main()
System.Console.Write("Welcome to Console Applications")
End Sub

End Module

You run the code by selecting Debug->Start from the main menu or by pressing F5 on the keyboard. The result "Welcome to Console Applications" displayed on a DOS window. Alternatively, you can run the program using the VB compiler (vbc). To do that, go to the Visual Studio. NET command prompt selecting from
Start->Programs->Visual Studio.NET->Visual Studio.NET Tools->Visual Studio.NET Command Prompt and type:
c:\examples>vbc example1.vb.

The result, "Welcome to Console Applications" is displayed on a DOS window as shown in the image below.



Breaking the Code to understand it

Note the first line, we're creating a Visual Basic Module and Modules are designed to hold code. All the code which we write should be within the Module.
Next line starts with Sub Main(), the entry point of the program.
The third line indicates that we are using the Write method of the System.Console class to write to the console.

Commenting the Code

Comments in VB.NET begin with a single quote (') character and the statements following that are ignored by the compiler. Comments are generally used to specify what is going on in the program and also gives an idea about the flow of the program. The general form looks like this:

Dim I as Integer
'declaring an integer

Code

VB Language

VB Language

Visual Basic, the name makes me feel that it is something special. In the History of Computing world no other product sold more copies than Visual Basic did. Such is the importance of that language which clearly states how widely it is used for developing applications. Visual Basic is very popular for it's friendly working (graphical) environment. Visual Basic. NET is an extension of Visual Basic programming language with many new features in it. The changes from VB to VB .NET are huge, ranging from the change in syntax of the language to the types of projects we can create now and the way we design applications. Visual Basic .NET was designed to take advantage of the .NET Framework base classes and runtime environment. It comes with power packed features that simplify application development.

Briefly on some changes:

The biggest change from VB to VB .NET is, VB .NET is Object-Oriented now. VB .NET now supports all the key OOP features like Inheritance, Polymorphism, Abstraction and Encapsulation. We can now create classes and objects, derive classes from other classes and so on. The major advantage of OOP is code reusability
The Command Button now is Button and the TextBox is TextBox instead of Text as in VB6
Many new controls have been added to the toolbar to make application development more efficient
VB .NET now adds Console Applications to it apart from Windows and Web Applications. Console applications are console oriented applications that run in the DOS version
All the built-in VB functionality now is encapsulated in a Namespace (collection of different classes) called System
New keywords are added and old one's are either removed or renamed
VB .NET is strongly typed which means that we need to declare all the variables by default before using them
VB .NET now supports structured exception handling using Try...Catch...Finally syntax
The syntax for procedures is changed. Get and Let are replaced by Get and Set
Event handling procedures are now passed only two parameters
The way we handle data with databases is changed as well. VB .NET now uses ADO .NET, a new data handling model to communicate with databases on local machines or on a network and also it makes handling of data on the Internet easy. All the data in ADO .NET is represented in XML format and is exchanged in the same format. Representing data in XML format allows us for sending large amounts of data on the Internet and it also reduces network traffic when communicating with the database
VB .NET now supports Multithreading. A threaded application allows to do number of different things at once, running different execution threads allowing to use system resources
Web Development is now an integral part of VB .NET making Web Forms and Web Services two major types of applications

Namespaces

A namespace is a collection of different classes. All VB applications are developed using classes from the .NET System namespace. The namespace with all the built-in VB functionality is the System namespace. All other namespaces are based on this System namespace.

Some Namespaces and their use:

System: Includes essential classes and base classes for commonly used data types, events, exceptions and so on
System.Collections: Includes classes and interfaces
that define various collection of objects such as list, queues,
hash tables, arrays, etc
System.Data: Includes classes which lets us handle data from data sources
System.Data.OleDb: Includes classes that support the OLEDB .NET provider
System.Data.SqlClient: Includes classes that support the SQL Server .NET provider
System.Diagnostics: Includes classes that allow to debug our application and to step through our code
System.Drawing: Provides access to drawing methods
System.Globalization: Includes classes that specify culture-related information
System.IO: Includes classes for data access with Files
System.Net: Provides interface to protocols used on the internet
System.Reflection: Includes classes and interfaces that return information about types, methods and fields
System.Security: Includes classes to support the structure of common language runtime security system
System.Threading: Includes classes and interfaces to support multithreaded applications
System.Web: Includes classes and interfaces that support browser-server communication
System.Web.Services: Includes classes that let us build and use Web Services
System.Windows.Forms: Includes classes for creating Windows based forms
System.XML: Includes classes for XML support

Assemblies

An assembly is the building block of a .NET application. It is a self describing collection of code, resources, and metadata (data about data, example, name, size, version of a file is metadata about that file). An Assembly is a complied and versioned collection of code and metadata that forms an atomic functional unit. Assemblies take the form of a dynamic link library (.dll) file or executable program file (.exe) but they differ as they contain the information found in a type library and the information about everything else needed to use an application or component. All .NET programs are constructed from these Assemblies. Assemblies are made of two parts: manifest, contains information about what is contained within the assembly and modules, internal files of IL code which are ready to run. When programming, we don't directly deal with assemblies as the CLR and the .NET framework takes care of that behind the scenes. The assembly file is visible in the Solution Explorer window of the project.

An assembly includes:

* Information for each public class or type used in the assembly – information includes class or type names, the classes from which an individual class is derived, etc
* Information on all public methods in each class, like, the method name and return values (if any)
* Information on every public parameter for each method like the parameter's name and type
* Information on public enumerations including names and values
* Information on the assembly version (each assembly has a specific version number)
* Intermediate language code to execute
* A list of types exposed by the assembly and list of other assemblies required by the assembly

Image of a Assembly file is displayed below.