CSC 102 VB - Net, Data Types, Variables, Operators-2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

.

Net Framework

.Net stands for Network Enables Technology. Framework is a collection of all technologies
integrated together to develop application that can be executed anywhere.

Net Framework is a software development platform developed by Microsoft for building and
running Windows applications. The .Net framework consists of developer tools, programming
languages, and libraries to build desktop and web applications. It is also used to build websites,
web services, and games.
The .Net framework was meant to create applications, which would run on the Windows Platform.
The first version of the .Net framework was released in the year 2002. The version was called .Net
framework 1.0. The Microsoft .Net framework has come a long way since then, and the current
version is .Net Framework 4.7.2. The Microsoft .Net framework can be used to create both
– Form-based and Web-based applications. Web services can also be developed using the .Net
framework.
The .Net Framework supports more than 60 programming languages such as C#, F#, VB.NET, J#,
VC++, JScript.NET, APL, COBOL, Perl, Oberon, ML, Pascal, Eiffel, Smalltalk, Python, Cobra,
ADA, etc, so developers can choose and select the language to develop the required application.
The .Net framework application are multiplatform application (they can run on various platforms
– Linux, Windows or Mac OSX). It is used to build application for Windows, Phone, Web etc.

Visual Basic .NET (VB.Net)


VB.NET is known as Visual Basic.NET. VB.NET is a simple, object-oriented programming
language developed by Microsoft in 2002, and it is the successor of Visual Basic 6 (VB6) language,
that implement on the .NET Framework. One of the best features of the VB.NET language is that
its program can also run on mono (multi-platform), which means that it is not restricted to run on
the Windows operating system; moreover, it can also run on Linux and Mac OS. The Application
built using the VB.NET is much secure, robust, high-performance, and easy to develop.
There is some VB.NET application:
o Console Application
o Mobile application
o Windows forms Application
o Window control library
o .Net website

VB.NET Features
VB.NET comes loaded with numerous features that have made it a popular programming
language amongst programmers worldwide. These features include the following:

 VB.NET is not case sensitive like other languages such as C++ and Java.
 It is an object-oriented programming language. It treats everything as an object.
 Automatic code formatting, XML designer, improved object browser etc.
 Support for Boolean conditions for decision making.
 Simple multithreading, allowing your apps to deal with multiple tasks simultaneously.
 A standard library.
 References. You should reference an external object that is to be used in a VB.NET
application.
1
 Attributes, which are tags for providing additional information regarding elements that
have been defined within a program.
 Windows Forms- you can inherit your form from an already existing form.

VB.Net - Environment Setup


Integrated Development Environment (IDE) For VB.Net
Microsoft provides the following development tools for VB.Net programming −
 Visual Studio 2010 (VS)
 Visual Basic 2010 Express (VBE)
 Visual Web Developer
The last two are free. Using these tools, you can write all kinds of VB.Net programs from simple
command-line applications to more complex applications. Visual Basic Express and Visual Web
Developer Express edition are trimmed down versions of Visual Studio and has the same look and
feel. They retain most features of Visual Studio. In this tutorial, we have used Visual Basic 2010
Express and Visual Web Developer (for the web programming chapter).
Compile & Execute VB.Net Program
If you are using Visual Studio.Net IDE, take the following steps −
 Start Visual Studio.
 On the menu bar, choose File → New → Project.
 Choose Visual Basic from templates
 Choose Console Application.
 Specify a name and location for your project using the Browse button, and then choose the
OK button.
 The new project appears in Solution Explorer.
 Write code in the Code Editor.
 Click the Run button or the F5 key to run the project. A Command Prompt window appears
that contains the line Hello World.

VB.Net Hello World Example:


A VB.Net program basically consists of the following parts −
 Namespace declaration
 A class or module
 One or more procedures
 Variables
 The Main procedure
 Statements & Expressions
 Comments

Let us look at a simple code that would print the words "Hello World”
Imports System
Module Module1
Sub Main()
'This program will display Hello World
Console.WriteLine("Hello World")
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result −
Hello World 2
Let us look various parts of the above program −
 Line 1: This is called the namespace declaration. We are including a namespace with the
name system to our programming structure. After that, we will be able to access all the
methods that have been defined in that namespace without getting an error.
 Line 2: Module declaration.here a module namesd Module 1 has been declared. We must
have a class module inn every program because VB.NET is an object oriented language. It
is inside the module that you will be able to define the data and the methods to be used in
the program.
 Line 3: Sub Main(). The line defines the Main procedure, which is the entry point for all
VB.Net programs. It what the module or class will do when executed.
 Line 4: This line (“This program…..) is the comment line and will be ignored by the
compiler and it has been put to add additional comments in the program.
 Line 5: Console.WriteLine("Hello World") WriteLine is a method of the Console class
defined in the System namespace. This statement causes the message "Hello, World!" to be
displayed on the screen.
 Line 6: The line Console.ReadKey() will prevent the screen from running and closing or
exiting the screen after the program has been executed. The screen will pause and wait for
the user to perform an action to close it.
 Line 7: Closing the Main Sub Procedure
 Line 8: Ending Module

Compile & Execute VB.Net Program


If you are using Visual Studio.Net IDE, take the following steps −
 Start Visual Studio.
 On the menu bar, choose File → New → Project.
 Choose Visual Basic from templates
 Choose Console Application.
 Specify a name and location for your project using the Browse button, and then choose
the OK button.
 The new project appears in Solution Explorer.
 Write code in the Code Editor.
 Click the Run button or the Ctrl+F5 key to run the project. A Command Prompt window
appears that contains the line Hello World.
Visual Basic Comments
In Visual Basic, Comments are the self-explanatory notes to provide detailed information about
the code which we wrote in our applications.
By using comment symbol ('), we can comment on the code in our Visual Basic programming.
The comment symbol (') will tell the Visual Basic compiler to ignore the text following it, or the
comment.
It’s always a good practice to include the comments in your Visual Basic code to provide
detailed information about the functionality like what the specific block or line of code can do
and it will be a benefit for anyone else who examines the code.

VB.NET Identifiers
As the name defines, an identifier is used to identify the name of variable, function, class, or any
other user-defined elements in the program. An identifier should be the combination of letter,
digit, and underscore. Still, the first character of the identifier or variable name should start with
alphabet letter or underscore (_) of any length.
There are various rules for identifier in VB.NET, as follows:

3
1. The first character of an identifier must start with an alphabet or underscore that could be
followed by any sequence of digits (0-9), letter or underscore.
2. An identifier should not contain any reserved keyword.
3. It should not start with any digit.
4. It should not more than 51 characters.
5. An identifier can contain two underscores, but should not be consecutive.
6. It should not include any commas or white spaces in-between characters.
Generally, identifiers are meaningful names. Some valid identifiers are:
Value, a, rec1, my_data, Marks, num, etc.
Some invalid identifiers are:
5be : First character should be alphabets or underscore (_)
Class, Shared : Keyword are not allowed as identifier name.
A# - : Identifier does not contain any special symbol.
Avg marks : It should not contain any blank space.

VB.Net Keywords
A keyword is a reserved word with special meanings in the compiler, whose meaning cannot be
changed. Therefore, these keywords cannot be used as an identifier in VB.NET programming
such as class name, variable, function, module, etc.
The following table lists the VB.Net reserved keywords –

AddHandler AddressOf Alias And AndAlso As Boolean


ByRef Byte ByVal Call Case Catch CBool
CByte CChar CDate CDec CDbl Char CInt
Class CLng CObj Const Continue CSByte CShort
CSng CStr CType CUInt CULng CUShort Date
Decimal Declare Default Delegate Dim DirectCast Do
Double Each Else ElseIf End End If Enum
Erase Error Event Exit False Finally For
GetXML
Friend Function Get GetType Global GoTo
Namespace
Handles If Implements Imports In Inherits Integer
Interface Is IsNot Let Lib Like Long
Loop Me Mod Module MustInherit MustOverride MyBase
MyClass Namespace Narrowing New Next Not Nothing
Not Not
Object Of On Operator Option
Inheritable Overridable
Optional Or OrElse Overloads Overridable Overrides ParamArray
Partial Private Property Protected Public RaiseEvent ReadOnly
Remove
ReDim REM Resume Return SByte Select
Handler
Set Shadows Shared Short Single Static Step
Stop String Structure Sub SyncLock Then Throw
To True Try TryCast TypeOf UInteger While
Widening With WithEvents WriteOnly Xor

4
Data Types Available in VB.Net
In VB.NET, data type is used to define the type of a variable or function in a program.
Furthermore, the conversion of one data type to another type using the data conversion function.
A Data Type refers to which type of data or value is assigning to a variable or function so that a
Data Storage Allocation Value Range
Type
Boolean Depends on platform True or False
Byte 1 byte 0 through 255 (unsigned)
Char 2 bytes 0 through 65535 (unsigned)
Date 8 bytes 0:00:00 (midnight) on January 1, 0001 through 11:59:59 PM on December 31, 9999
0 through +/-79,228,162,514,264,337,593,543,950,335 (+/-7.9...E+28) with no decimal
Decimal 16 bytes point; 0 through +/-7.9228162514264337593543950335 with 28 places to the right of
the decimal
-1.79769313486231570E+308 through -4.94065645841246544E-324, for negative
Double 8 bytes values
4.94065645841246544E-324 through 1.79769313486231570E+308, for positive values
Integer 4 bytes -2,147,483,648 through 2,147,483,647 (signed)
Long 8 bytes -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807(signed)
4 bytes on 32-bit
platform
Object Any type can be stored in a variable of type Object
8 bytes on 64-bit
platform
SByte 1 byte -128 through 127 (signed)
Short 2 bytes -32,768 through 32,767 (signed)
-3.4028235E+38 through -1.401298E-45 for negative values;
Single 4 bytes
1.401298E-45 through 3.4028235E+38 for positive values
Depends on
String 0 to approximately 2 billion Unicode characters
implementing platform
UInteger 4 bytes 0 through 4,294,967,295 (unsigned)
ULong 8 bytes 0 through 18,446,744,073,709,551,615 (unsigned)
User- Depends on Each member of the structure has a range determined by its data type and independent of
Defined implementing platform the ranges of the other members
UShort 2 bytes 0 through 65,535 (unsigned)
variable can hold a defined data type value. The type of a variable determines how much space it
occupies in storage and how the bit pattern stored is interpreted. For example, when we declare a
variable, we have to tell the compiler what type of data or value is allocated to different kinds of
variables to hold different amounts of space in computer memory..
Syntax:
Dim Variable_Name as DataType
Variable_Name: It defines the name of the variable that you assign to store values.
DataType: It represents the name of the data type that you assign to a variable.

VB.NET Variable
In VB.NET, a variable is used to hold the value that can be used further in the programming.
A variable is a simple name used to store the value of a specific data type in computer memory.
In VB.NET, each variable has a particular data type that determines the size, range, and fixed
space in computer memory. With the help of variable, we can perform several operations and
manipulate data values in any programming language.
VB.NET Variables Declaration
The declaration of a variable is simple that requires a variable name and data type followed by a
Dim. A Dim is used in Class, Module, structure, Sub, procedure.
Syntax:
Dim [Variable_Name] As [Defined Data Type]

5
Name Descriptions
It is used to declare and allocate the space for one or more variables in
Dim
memory.
Variable_Name It defines the name of the variable to store the values.
It is a keyword that allows you to define the data type in the declaration
As
statement.
It defines a data type that allows variables to store data types such as Char,
Data Type
String, Integer, Decimal, Long, etc.
Value Assign a value to the variable.
Here are some valid declarations of variables along with their data type definition, as shown
below:
Dim StudentID As Integer
Dim StudentName As String
Dim Emp_name As String
Dim Salary As Double
Dim Emp_id, Stud_id As Integer
Dim result_status As Boolean
Further, if we want to declare more than one variable in the same line, we must separate each
variable with a comma.
Syntax
Dim Variable_name1 As DataType1, variable_name2 As DataType2, Variable_name3 As DataT
ype3
Example: Dim Num1, Num2, Sum as Integer
VB.NET Variable Initialization
Variable Initialization in VB.Net
Variables are initialized (assigned a value) with an equal sign followed by a constant expression.
The general form of initialization is −
variable_name = value;
for example,
Dim pi As Double
Pi= 3.14159
You can initialize a variable at the time of declaration as follows –
Dim Roll_no As Integer = 101
Dim Emp_name As String = " Stephen Robert "

Example: Try the following example which makes use of various types of variables

Module variablesNdataypes
Sub Main()
Dim a As Short
Dim b As Integer
Dim c As Double
a = 10
b = 20
c = a + b
Console.WriteLine(“c=” & c)
Console.ReadLine()
End Sub
End Module

When the above code is compiled and executed, it produces the following result − 6
c = 30
VB.NET Constants
As the name suggests, the name constant refers to a fixed value that cannot be changed during the
execution of a program. It is also known as literals. These constants can be of any data type, such
as Integer, Double, String, Decimal, Single, character, enum, etc.
Declaration of Constants
In VB.NET, const is a keyword that is used to declare a variable as constant. The Const statement
can be used with module, structure, procedure, form, and class.

Syntax:
Const constname As datatype = value

The following example demonstrates declaration and use of a constant value −


Module constantsNenum
Sub Main()
Const PI As Double = 3.14149
Dim radius, area As Single
Console.WriteLine("Enter radius”)
radius=Console.ReadLine()
area = PI * radius * radius
Console.WriteLine("Area = " & area)
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result –
Enter radius
15
Area = 706.83525

Input and Output Statement


To enter data into the system, input statements are used. Input commands used in VB Console
applications are:
 Console.Read
 Console.ReadLine
 Console.ReadKey
To Display information to the user, output statements are used. Output commands in VB Console
application are
 Console.Write
 Console.WriteLine

Console.Read() : In Console.Read(), input terminates as user presses space or tab. It is better for
Single value input

Console.ReadLine() It allows multiple word input including space, tabs as part of the input. Input
terminates as return key is pressed.

7
Console.ReadKey() Reads a single keystroke from the keyboard and terminates the input.
Readkey is used to prevent the screen from running and closing quickly when the program is
executed until you press the Enter Key.

The Console.Write() method is identical to the Console.WriteLine() method except that it prints
the given argument(s) without a newline attached at the end. This method can be made
functionally identical to WriteLine by adding a newline string to the end of any arguments
provided:

The Console.WriteLine() method will print the given argument(s) with a newline attached at the
end. This will print any object supplied, including, but not limited to, strings, integers, variables,
floating-point numbers.
In summary, Console.Write() does not shift cursor on the next line while Console.WriteLine()
shifts the cursor to the next line
Example
Module 1
Sub Main()
Dim Name as String
Console.Write("Please Enter your Name:")
Name=Console.ReadLine( )
Console.WriteLine("Hello ” +Name)
Console.ReadLine( )
End Sub
End Module

The output will be:


Please Enter your name: John Okoye
Hello John Okoye

Concatenation Operators in Visual Basic


Concatenation operators join multiple strings into a single string. There are two concatenation
operators, + and &.
The ampersand symbol (&) is the recommended concatenation operator. It is used to bind a
number of string variables together, creating one string from two or more individual strings. Any
nonstring variable or expression is converted to a string prior to concatenation (even if Option
Strict is on).
Its syntax is:
result = expression1 & expression2...
The Plus Sign (+ ): Although in principle the + sign is identical to the & concatenation operator,
it also doubles as the addition operator. Hence, as Microsoft states: When you use the + operator,
you may not be able to determine whether addition or string concatenation will occur. Use the &
operator for concatenation to eliminate ambiguity and provide self-documenting code.

8
Program to Show Concatenation of Strings
Module Module1
Sub Main()
Dim w, x, y, z As String
w = "anu"
x = "nchi"
y=w&x
z=x+w
Console.WriteLine("y is " & y)
Console.WriteLine("z is " & z)
Console.ReadKey()
End Sub
End Module

The output will be:


y is anunchi
z is nchianu

Arithmetic Operators
Following table shows all the arithmetic operators supported by VB.Net. Assume variable A
holds 2 and variable B holds 7, then :

Operator Description Example


^ Raises one operand to the power of another B^A will give 49
+ Adds two operands A + B will give 9
- Subtracts second operand from the first A - B will give -5
* Multiplies both operands A * B will give 14
Divides one operand by another and returns
/ B / A will give 3.5
a floating point result
Divides one operand by another and returns
\ B \ A will give 3
an integer result
Modulus Operator and remainder of after an
MOD B MOD A will give 1
integer division

9
Program for Arithmetic Operators
Module Module1
Sub Main()
Dim a As Integer
Dim b As Integer
Dim sum As Integer
Dim subtraction As Integer
Dim multiplication As Integer
Dim division As Double
Console.WriteLine("Enter the Value for a")
a = Console.ReadLine()
Console.WriteLine("Enter the value for b")
b = Console.ReadLine()
sum = a + b
Subtraction = a - b
Multiplication = a * b
Division = a / b
Console.WriteLine("The Sum is = " & sum)
Console.WriteLine("The Subtraction is = " & subtraction)
Console.WriteLine("The Division is = " & division)
Console.WriteLine("The Multiplication is = " & multiplication)
Console.ReadLine()
End Sub
End Module

The output will be:


Enter the Value for a
10
Enter the value for b
3
The Sum is = 13
The Subtraction is = 7
The Division is = 3.33333333333333
The Multiplication is = 30

10
Relational Operators: Compares two expression and returns a Boolean Value that represents
the result of the Comparison

Example: Assume variable A holds 10 and variable B holds 20, then −


Operator Description Example
= Checks if the values of two operands are equal or not; if yes, then (A = B) is not true
condition becomes true.
<> Checks if the values of two operands are equal or not; if values are (A <> B) is true.
not equal, then condition becomes true.
> Checks if the value of left operand is greater than the value of (A > B) is not true.
right operand; if yes, then condition becomes true.
< Checks if the value of left operand is less than the value of right (A < B) is true
operand; if yes, then condition becomes true
>= Checks if the value of left operand is greater than or equal to the (A >= B) is not
value of right operand; if yes, then condition becomes true. true.
<= Checks if the value of left operand is less than or equal to the (A <= B) is true
value of right operand; if yes, then condition becomes true.

Program for Relational Operators


Module Module1
Sub Main()
Dim x As Integer = 11
Dim y As Integer = 5
If (x = y) Then
Console.WriteLine("11=5 is True")
Else
Console.WriteLine(" 11=5 is False")
End If

If (x < y) Then
Console.WriteLine(" 11<5 is True")
Else
Console.WriteLine(" 11<5 is False")
End If

If (x > y) Then
Console.WriteLine(" 11>5 is True")
Else
Console.WriteLine(" 11>5 is False")
End If
Console.ReadLine()
End Sub
End Module

The output will be:


11=5 is False
11<5 is False
11>5 is True

11
Program for Relational Operators
Module Module1
Sub Main()
Dim x As Integer = 3
Dim y As Integer = 7
If (x <= y) Then
Console.WriteLine(" 3<=7 is True")
End If
If (y >= x) Then
Console.WriteLine(" 7>=3 is True")
End If
Console.ReadLine()
End Sub
End Module

The output will be:


3<=7 is True
7>=3 is True

Assignment Statement
An assignment statement assigns a value to a variable.
For example, x = 5; gives x the value of 5.
The value of the variable may be changed. For example, if x has the value of 5, then the expression
x=x+1 will give x the value of 6.
The general syntax for Assignment Statement is:
variableName = expression ;
 The equal sign = is the assignment operator.
 variableName is the name of a variable that has been declared previously in the program.
 expression is a collection of characters that calls for a value to be calculated. Expression
can be a constant and or a variable connected with the operators such as +,-,8, /

Example of Assignment Statement


i. x= 42 Assigns the value of 42 to the variable “x”
ii. name = “Cindy” Assigns the string Cindy to the variable “name”
iii. x= x+1 Takes the value of the variable and add 1 to it and stores the result
into x. it will eliminate the old value and replace it with the new value.
iv. Dim b as string
b = “Con” & “cat” & “enation” This assigns the value Concatenation to” b”
v. Dim S,T as Boolean
S=45>1003
T= 45<117
The statement assigns False to S and True to T.

Consider the following Sequence of Statements

i. x=4 Location x now contains 4


ii. y=7 Location y now contains 7
iii. x=x+y location x now contains 11
iv. y=3 Location y now contains 3
v. z=x+y Location z now contains 14

The value of expression x+y in Line (v) changed when we changed y in line (iv)
12
Examples of invalid Assignment Statements:
i. Somebody @ = aroma+eke awka The variable contains special character @
ii. Amaechi+Wike =Rivers The variable contains special character +
iii. object=Mat Object is a keyword

Compound Assignment Statement


Compound Assignment Statement first perform an operation on an expression before assigning I
to a programming element.
The following example illustrates one of the operators
Sample Explanation Assigns
Expression
Assume c=4 and d=”He”
Add AND assignment operator, It adds right operand to the
+= c+=7
left operand and assigns the result to left operand c=c+7 11 to c
Subtract AND assignment operator, It subtracts right operand
-= c-=3
from the left operand and assigns the result to left operand c=c-3 1 to c
Multiply AND assignment operator, It multiplies right
c=c*4 16 to c
*= operand with the left operand and assigns the result to left c*=4
operand
Divide AND assignment operator, It divides left operand with
/= the right operand and assigns the result to left operand c/=2 c=c/2 2 to c
(floating point division)
Divide AND assignment operator, It divides left operand with
\= the right operand and assigns the result to left operand c\=3 c=c\3 1 to c
(Integer division)
Exponentiation and assignment operator. It raises the left
^= operand to the power of the right operand and assigns the c^=2 c=c^2 16 to c
result to left operand.
&= Concatenates a String expression to a String variable or Hello to
property and assigns the result to the variable or property. d&=”llo” d=d&”llo” d

MOD= Modulus Operator and remainder of after an integer division cMOD=3 c=cMOD3 1 to c

13

You might also like