Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
505 views

Computer Programming 2

The document provides an overview of Visual Basic .NET (VB.NET) programming, explaining that VB.NET is an object-oriented language that combines the power of the .NET framework, and it discusses key features of VB.NET like object-oriented principles, strong programming features, and the .NET Framework which VB.NET programs run within. The document also outlines the integrated development environments for VB.NET programming and mentions that Mono provides a way to write VB.NET programs on non-Windows operating systems.

Uploaded by

Javan Domanico
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
505 views

Computer Programming 2

The document provides an overview of Visual Basic .NET (VB.NET) programming, explaining that VB.NET is an object-oriented language that combines the power of the .NET framework, and it discusses key features of VB.NET like object-oriented principles, strong programming features, and the .NET Framework which VB.NET programs run within. The document also outlines the integrated development environments for VB.NET programming and mentions that Mono provides a way to write VB.NET programs on non-Windows operating systems.

Uploaded by

Javan Domanico
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

COMPUTER PROGRAMMING 2

Khryss Leanne B. Omnes


LAGUNA UNIVERSITY

Vision

Laguna University shall be a socially responsive educational institution of


choice providing holistically developed individuals in the Asia-Pacific Region.

Mission

Laguna University is committed to produce academically prepared and


technically skilled individuals who are socially and morally upright.

ii
Table of Contents

Module 1: Introduction To Visual Basic.Net Programming


Introduction 1
Learning Outcomes 1
Lesson 1. VB.Net – Overview 1
Lesson 2. The .Net Framework 3
Lesson 3. Program Structure 4

Assessment Task 10
Summary 10

Module 2: Visual Basic.Net Fundamentals (Part 1) 12


Introduction 12
Learning Outcomes 12
Lesson 1. VB.NET Data Types 12
Lesson 2. VB.NET Variables 15
Lesson 3. Declaring Constants 18

Assessment Task 19
Summary 20

Module 3: Visual Basic.Net Fundamentals (Part 2) 21


Introduction 21
Learning Outcomes 21
Lesson 1. Declaring Enumerations 21
Lesson 2. Modifiers 23
Lesson 3. Statements 24

Assessment Task 27
Summary 28

iii
Module 4: Visual Basic.Net Operators 29
Introduction 29
Learning Outcomes 29
Lesson 1. Arithmetic Operators 29
Lesson 2. Comparison Operators 31
Lesson 3. Logical Operators 33
Lesson 4. Assignment Operators 35

Assessment Task 37
Summary 38

iv
Course Code: CS2109

Course Description: This course is a continuation of CS 1103 – Computer


Programming 1. The emphasis is to train student to design, implement test,
and debug programs intended to solve computing problems using Visual
Basic or Visual Basic.Net. It introduces the different concepts that are
commonly associated with object programming.
The course introduces the student to Visual Basic application development
with database connectivity using ADODB component. This course prepares
the students for more advanced programming in database management with
the use of SQL Programming. It also prepares the students to high level
programming such as Advance Microsoft VB.Net with RDLC and Crystal
Reporting.

Course Intended Learning Outcomes (CILO):


At the end of this course, the students should be able to:
 Demonstrate the basic concepts and methods of object-oriented
programming and the fundamentals of Visual basic programming.
 Acquaint students with the three-step process of building Windows
application using Visual Basic.
 Manifest and apply graphical user interface design principles using
Microsoft Visual Basic 2012
 Demonstrate how to implement logic solving sequence, selection and
repetition using Visual basic 2012
 Produce sophisticated, professional programs by using arrays and files
that handle data and make programs more robust by defining classes
and using the power of inheritance.

Course Requirements:
 Assessment Tasks - 60%
 Major Exams - 40%
_________
Periodic Grade 100%

Final Grade = Total CS + Final Exam x 70% + 30% of the


Midterm

v
MODULE 1
INTRODUCTION TO VISUAL BASIC.NET
PROGRAMMING

Introduction

VB.Net is a simple, modern, object-oriented, Microsoft-created computer programming


language that combines the power of the. NET framework with the common runtime language,
with the usability benefits of Visual Basic (VB.Net, n.d.).

Learning Outcomes

At the end of this module, students should be able to:


1. Understand and familiarize the programming language VB.NET
2. Understand the different programming features of VB.NET

Lesson 1. VB.Net – Overview

What Is Visual Basic .NET?

VB.Net is a simple, modern, object-oriented, Microsoft-created computer programming


language that combines the power of the. NET framework with the common runtime language,
with the usability benefits of Visual Basic. The Visual Basic 6 code can not be compiled without
a major shift from the Visual Basic .Net Compiler. The good news is that Microsoft has
developed a migration system for handling the job. Visual Basic .NET (VB.NET) is an object-
oriented computer programming language based on the .NET Interface. While it is a classic
implementation of the Visual Basic language, it is not backwards compatible with VB6, and
any code written in the old version is not compiled under VB .NET (VB.Net, n.d.).

Like with all other NET languages, VB.NET supports object-oriented principles in full.
Everything in VB.NET is an object, with all the basic types (Short, Integer, Long, String,
Boolean, etc.) and the user-defined classes, events and even assemblies. The base Object
class inherits all properties. VB.NET is implemented through Microsoft's. NET Framework.
Therefore it has complete access to all libraries inside the Net Network. It is also possible to

1
run VB.NET programs on Mono, an open-source alternative to NET, not only under Windows
but also under Linux or Mac OSX (VB.Net, n.d.).

The following explanations make VB.Net a commonly used language of the profession
(VB.Net Environment Setup, n.d.) –

 Generalized, modern intent.


 Object Oriented
 Oriented Element
 Kind of thinking
 Language built in
 Makes effective services
 Compilable on a range of computer platforms
 Member of the .Net Framework

Strong Programming Features VB.Net

VB.Net has many strong programming features that make it endearing to many
programmers around the world (VB.Net Basic Syntax, n.d.).

 Boolean Conditions
 Automated Garbage Collection
 Standard Library
 Versioning Assembly
 Properties and Events
 Delegates and Events Management
 Generics Facile to Use
 Indexers
 Conditional Compilation
 Fast Multithreading

The Visual Basic language has undergone drastic changes, with its release for the NET
platform.

For example:
 The language as such is now fully object-oriented
 Visual Basic .Net programs and modules have full access to .Net
 Framework, a robust level class library offering system and application services.
 All applications built using Visual Basic .Net run the .Net common language
runtime within a controlled runtime environment.

2
Lesson 2. The .Net Framework

.Net framework is a pioneering platform that lets you write the following types of
applications (VB.Net Environment Setup, n.d.):
 Windows applications
 Web applications
 Web services

Software are multi-platform software within the Net system. The program was
designed for use in any of the following languages: Visual Basic, C #, C++, Jscript, and
COBOL etc. All these languages can both access and communicate with the device. Net
database is an comprehensive collection of codes used by client languages like VB.Net. Such
languages use artefact-oriented processes (VB.Net Environment Setup, n.d.).

All of. Net system components below are:


 Common Language Runtime (CLR)
 The .Net Framework Class Library
 Common Language Specification
 Common Type System
 Metadata and Assemblies
 Windows Forms
 ASP.Net and ASP.Net AJAX
 ADO.Net
 Windows Workflow Foundation (WF)
 Windows Presentation Foundation
 Windows Communication Foundation (WCF)
 LINQ (VB.Net Environment Setup, n.d.)

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. With these tools, all sorts of VB.Net programs can be written to
more complex applications, including simple command-line applications. Visual Basic Express
and Visual Web Developer Express edition have the same look and feel and Visual Studio
versions are stripped off (VB.Net Environment Setup, n.d.).

Writing VB.Net Programs on Linux or Mac OS

3
Although the NET Architecture runs on Windows OS, some alternative
implementations operate on other operating systems. Mono is a NET Platform open source
version that offers a Visual Basic compiler and runs on many operating systems including
various Linux and Mac OS flavors (VB.Net Environment Setup, n.d.).
The stated goal of Mono is not only to be able to run Microsoft NET cross-platform
applications but also to enhance development tools for Linux developers. Numerous operating
systems can run Mono, including Android, BSD, iOS, Linux , OS X, Windows, Solaris, and
UNIX (VB.Net Environment Setup, n.d.).

Lesson 3. Program Structure

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 (VB.Net Basic Syntax, n.d.)
Let us look at a simple code that would print the words "Hello World":

Imports System
Module Module1
'This program will display Hello World
Sub Main()
Console.WriteLine("Welcome to Laguna University!")
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:

Welcome to Laguna University!

Let us look various parts of the above program:

 The first line of the program Imports System is used to include the System namespace
in the program.
 Totally object oriented, so every program needs to have a class module containing
the data and procedures the program uses.

4
 Modules or classes will usually include more than one procedure. Procedures
include the executable code, or in other words, they describe the class behavior.
A procedure could be any of the following:
o Function
o Sub
o Operator
o Get
o Set
o AddHandler
o RemoveHandler
o RaiseEvent

 The next line ('This program') is ignored by the compiler, and additional comments
have been added to the program.
 The next line specifies the Main Procedure, the entry point for all VB.Net programs.
The Main procedure sets out what the module or class will do when it is run.
 The Main procedure specifies its behavior with the statement Console.WriteLine
("Welcome to Laguna University!”) WriteLine is a method of the Console class defined
in the System namespace. This statement causes the message "Welcome to Laguna
University!" to be displayed on the screen.
 The last line Console.ReadKey() is for the VS.NET Users. It would prevent the
computer from quickly running and closing when Visual Studio. NET begins the
program (VB.Net Basic Syntax, n.d.).

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 Basic Syntax, n.d.).

You can compile a VB.Net program by using the command line instead of the Visual Studio
IDE:
 Open a text editor and add the above mentioned code.
 Save the file as welcometoLU.vb

5
 Open the command prompt tool and go to the directory where you saved the file.
 Type vbc welcometoLU.vb and press enter to compile your code.
 If there are no errors in your code the command prompt will take you to the next
line and would generate helloworld.exe executable file.
 Next, type welcometoLU to execute your program.
 You will be able to see "Welcome To Laguna Univesrsity" printed on the screen
(VB.Net Basic Syntax, n.d.)

Basic Syntax

VB.Net is an object oriented programming language. In object-oriented programming


philosophy a program consists of different objects which communicate via actions with each
other. The actions which an person can take are called methods. It is said that the same kind
of objects have the same type, or are said to be more often of the same class (VB.Net Basic
Syntax, n.d.).

If we consider a VB.Net program, it can be described as a set of objects which


communicate by invoking methods of each other. Now let's look briefly at what class, object,
methods, and instant variables mean. (VB.Net Basic Syntax, n.d.)

 Object - Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behaviors - wagging, barking, eating, etc. An object is an
instance of a class.
 Class - A class can be defined as a template/blueprint that describes the
behaviors/states that object of its type support.
 Methods - A method is basically a behavior. A class can contain many methods. It
is in methods where the logics are written, data is manipulated and all the actions
are executed.
 Instant Variables - Each object has its unique set of instant variables. An object's
state is created by the values assigned to these instant variables (VB.Net Basic
Syntax, n.d.).

A Rectangle Class in VB.Net

For example, let us consider a Rectangle object. It does have characteristics such as
length and width. Depending on the architecture, it will need ways to recognize these attribute
values, measure area and display data (VB.Net Basic Syntax, n.d.).

Imports System
Public Class Rectangle
Private length As Double
Private width As Double

6
'Public methods
Public Sub AcceptDetails

7
length = 4.5
width = 3.5

End Sub

Public Function GetArea() As Double


GetArea = length * width
End Function

Public Sub Display()

Console.WriteLine("Length: {0}", length)


Console.WriteLine("Width: {0}", width)
Console.WriteLine("Area: {0}", GetArea())

End Sub

Shared Sub Main()


Dim r As New Rectangle()
r.Acceptdetails()
r.Display()
Console.ReadLine()
End Sub
End Class

Let's look at the implementation of a rectangle class and discuss the basic syntax of VB.Net
on the basis of our observations: when the above code is compiled and executed, the
following results are produced:

The VB.Net system entry point is indicated by Sub Main. Here we use Class which includes
both code and data. Classes are used for object construction. For instance, r is a Rectangle
object in the code (VB.Net Basic Syntax, n.d.).

An object is an instance of a class:


Dim r As New Rectangle()

A class can have members, if defined, which can be accessed from outside class. Data
members are called fields and processes are called process members.

One can invoke shared methods or static methods without creating a class object. Methods
of instance are invoked via class object:

Shared Sub Main()


Dim r As New Rectangle()

8
r.Acceptdetails()
r.Display()
Console.ReadLine()
End Sub

Identifiers

An identifier is a name used to identify a user-defined object, class, variable, function or any
other. The basic rules for naming classes in VB.Net are as follows:
 A name must begin with a letter that could be followed by a sequence of letters,
digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.
 It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ;
: " ' / and \. However, an underscore ( _ ) can be used.
 It should not be a reserved keyword (VB.Net Basic Syntax, n.d.).

VB.Net Keywords
The following table lists the VB.Net reserved keywords:

Table 1.1 VB.NET Keyword (VB.Net Basic Syntax, n.d.)

AddHandler CStr GetType Next Resume


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

9
Assessment Task

I. Write a VB.NET program that outputs the following:

My Name is Juan dela Cruz.


I am 18 years old.
I am currently in 2nd year College taking BS in Computer Science.

II. Answer the following question:


a. Discuss the difference between Objects, Classes and Methods

Summary

 VB.Net is a plain, modern, object-oriented, Microsoft-developed computer


programming language
 Features of VB.Net are Boolean Conditions, Automatic Garbage Collection, Standard
Library, Assembly Versioning, Properties and Events, Delegates and Events
Management, Easy-to-use Generics, Indexers, Conditional Compilation, Simple
Multithreading
 An integrated development environment (IDE) is a software application which provides
comprehensive software development facilities for computer programmers. An IDE
usually consists of at least one source code editor, a debugger, and automation
software.
 A VB.Net program basically consists of the following parts:
a) Namespace declaration
b) A class or module
c) One or more procedures
d) Variables
e) The Main procedure
f) Statements & Expressions
g) Comments
 Some VB.Net Keywords are: if, IsNot, And, Catch, CBool, and ByRef (VB.Net
Environment Setup, n.d.; VB.Net Basic Syntax, n.d.).

10
References

 VB.Net. (n.d.). Retrieved from Tutorials Point:


https://www.tutorialspoint.com/vb.net/vb.net_overview.htm
 VB.Net Basic Syntax. (n.d.). Retrieved from Tutorials Point:
https://www.tutorialspoint.com/vb.net/vb.net_basic_syntax.htm
 VB.Net Environment Setup. (n.d.). Retrieved from Tutorials Point:
https://www.tutorialspoint.com/vb.net/vb.net_environment_setup.htm

11
MODULE 2
VISUAL BASIC.NET FUNDAMENTALS (PART 1)

Introduction

Data types refer to a large system used to define variables or functions of different
types. A variable type defines how much storage space it occupies, and how it interprets the
stored bit pattern (VB.Net Operators, n.d.).

Learning Outcomes

At the end of this module, students should be able to:


1. Understand the different data types in VB.Net;
2. Understand the variables and variable declaration in VB.net.
3. Understand the constants and variables of VB.Net;

Lesson 1. VB.NET Data Types

What are Data Types?

Data types determine what type of data any individual can hold. Variables belonging to
various data types are given varying amount of space in the memory. VB.NET is composed
of various types of data. (VB.Net Operators, n.d.)

Including:

 Boolean: the allocated storage depends on the platform of implementation. Its value
can be either True or False.
 Byte: allocated storage space of 1 byte. Values range from 0 to 255 (unsigned).

12
 Char: allocated a space of 2 bytes. Values range from 0 to 65535 (unsigned).
 Date: allocated storage space of 8 bytes. Values range from 0:00:00 (midnight)
January 1, 0001 to 11:59:59 PM of December 31, 9999.
 Integer: has a storage space of 4 bytes. Values range between -2,147,483,648 to
2,147,483,647 (signed).
 Long: has a storage space of 8 bytes. Numbers range from -
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807(signed).
 String: The storage space allocated depends on the platform of implementation.
Values range from 0 to about 2 billion Unicode characters (VB.Net Operators, n.d.).

The following example demonstrates use of some of the types:

Module DataTypes
Sub Main()
Dim b As Byte
Dim n As Integer
Dim si As Single
Dim d As Double
Dim da As Date
Dim c As Char
Dim s As String
Dim bl As Boolean

b = 1
n = 1234567
si = 0.12345678901234566
d = 0.12345678901234566
da = Today
c = "U"c
s = "Me"

If ScriptEngine = "VB" Then


bl = True

Else
bl = False
End If
If bl Then
'the oath taking

Console.Write(c & " and," & s & vbCrLf)


Console.WriteLine("declaring on the day of: {0}", da)
Console.WriteLine("We will learn VB.Net seriously")
Console.WriteLine
("Let us see what happens to the floating point variables:")
Console.WriteLine("The Single: {0}, The Double: {1}", si, d)
End If
Console.ReadKey()

End Sub
End Module

When the above code is compiled and executed, it produces the following result:

U and, Me
declaring on the day of: 12/4/2012 12:00:00 PM
We will learn VB.Net seriously

13
Let us see what happens to the floating point variables:
The Single:0.1234568, The Double: 0.123456789012346

The Type Conversion Functions in VB.Net

Table 2.1 Functions in VB.Net (VB.Net Datatypes, n.d.)

Functions & Description


CBool(expression)
Converts the expression to Boolean data type.
CByte(expression)
Converts the expression to Byte data type.
CChar(expression)
Converts the expression to Char data type.
CDate(expression)
Converts the expression to Date data type
CDbl(expression)
Converts the expression to Double data type.
CDec(expression)
Converts the expression to Decimal data type.
CInt(expression)
Converts the expression to Integer data type.
CLng(expression)
Converts the expression to Long data type.
CObj(expression)
Converts the expression to Object type.
CSByte(expression)
Converts the expression to SByte data type.
CShort(expression)
Converts the expression to Short data type.
CSng(expression)
Converts the expression to Single data type.
CStr(expression)
Converts the expression to String data type.
CUInt(expression)
Converts the expression to UInt data type.
CULng(expression)
Converts the expression to ULng data type.
CUShort(expression)

14
Converts the expression to UShort data type.

Lesson 2. VB.NET Variables

A variable is nothing other than a name given to a storage area which our programs
can control. Every variable in VB.Net has a different type, specifying the size and configuration
of the variable 's memory; the number of values that can be stored in that memory; and the
set of operations that can be applied to the variable (VB.Net Variables, n.d.).

Table 2.1 The basic value types provided in VB.Net can be categorized as (VB.Net Variables,
n.d.):

Type Example
Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long,
ULong and Char
Floating point types Single and Double
Decimal types Decimal
Boolean types True or False values, as assigned
Date types Date

Variable Declaration in VB.Net (VB.Net Variables, n.d.)

The statement Dim is used to declare variable and to assign storage for one or more
variables. The word Dim is used at the element, class, structure, method, or block stage.

Syntax for variable declaration in VB.Net is:

[< attributelist>] [accessmodifier] [[ Shared ] [ Shadows ] | [ Static ]]


[ ReadOnly ] Dim [ WithEvents ] variablelist

Where,
 Attributelist is a list of the attributes used by the variable. Optional.
 accessmodifier defines the access levels of the variables, it has values as - Public,
Protected, Friend, Protected Friend and Private. Optional.
 Shared declares a shared variable not associated with any particular instance of a
class or structure, but instead open to all class or structure instances.
 Shadows mean that the variable re-declares and conceals an identically named
element or group of overloaded elements in a base class. Optional.

15
 Static indicates that the variable will retain its value, even when the after termination
of the procedure in which it is declared. Optional.
 ReadOnly means that the attribute is readable, but not writable. Optional.
 WithEvents specifies that the variable is used by the instance assigned to the variable
to respond to the events posed. Optional.
 Variablelist provides a list of the declared variables (VB.Net Variables, n.d.).

Each variable in the variable list has the following syntax and parts (VB.Net Variables,
n.d.):
variablename[([boundslist])][As [ New ] datatype ] [ = initializer ]

Where,

 variablename: is the variable’s name


 boundslist: optional. It provides a list of the boundaries of an array variable for each
dimension.
 New: optional. When the Dim statement runs it generates a new instance of the class.
 datatype: Supported if Strict Option is On. It defines variable data sort.
 initializer: Optional if New is not specified. An expression that is evaluated when it is
generated and allocated to the variable.

Some valid variable declarations along with their definition are shown here:

Dim StudentID As Integer


Dim StudentName As String
Dim Salary As Double

Dim count1, count2 As Integer


Dim status As Boolean
Dim exitButton As New System.Windows.Forms.Button
Dim lastTime, nextTime As Date

Variable Initialization in VB.Net (VB.Net Variables, n.d.)

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

16
pi = 3.14159

You can initialize a variable at the time of declaration as follows:

Dim StudentID As Integer = 100


Dim StudentName As String = "Bill Smith"

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("a = {0}, b = {1}, c = {2}", a, b, c)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:

a = 10, b = 20, c = 30

Accepting Values from User (VB.Net Variables, n.d.)

The Console class in System namespace provides a ReadLine function to accept


user input and store it in a variable. For example,

Dim message As String


message = Console.ReadLine
The following example demonstrates it:
Module variablesNdataypes

Sub Main()
Dim message As String
Console.Write("Enter message: ")

message = Console.ReadLine

Console.WriteLine()
Console.WriteLine("Your Message: {0}", message)
Console.ReadLine()
End Sub
End Module

(VB.Net Variables, n.d.)

When the above code is compiled and executed, it produces the following result (assume
the user inputs Hello World):

17
Enter message: Hello World
Your Message: Hello World

Lvalues and Rvalues


There are two kinds of expressions:

 lvalue : An expression which is a lvalue can appear as the left or right side of an
assignment.
 rvalue : An expression that is a rvalue can appear on a given assignment's right but
not left side.
Variables are lvalues, and can thus appear on the left side of an assignment. Numeric
literals are rvalues and may therefore not be delegated and do not appear on the left side.
Following is a valid statement:
Dim g As Integer = 20
But following is not a valid statement and would generate compile-time error:
20 = g

Lesson 3. Declaring Constants

Constants are described using Const statement in VB.Net. The Const statement is
used at entity, class, structure, process or block level for use instead of literal values (Vb.net
Constants, n.d.).

The syntax for the Const statement is (Vb.net Constants, n.d.):

[ < attributelist> ] [ accessmodifier ] [ Shadows ]


Const constantlist

Where,

 attributelist: specifies the list of attributes applied to the constants; you can provide
multiple attributes separated by commas. Optional.
 Shadows: That makes the constant hide an identical name programming feature in a
base class.
 Constantlist: Gives a list of names of the declared constants. Where, each constant
name has the syntax and sections below: constantname [ As datatype ] = initializer
 constantname: specifies constant name
 datatype: specifies constant data type
 initializer: specifies the assigned value to the constant (Vb.net Constants, n.d.)

For example,

' The following statements declare constants.


Const maxval As Long = 4999
Public Const message As String = "HELLO"

18
Private Const piValue As Double = 3.1415

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

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

When the above code is compiled and executed, it produces the following result:
Area = 153.933

Print and Display Constants in VB.Net


VB.Net provides the following print and display constants:

Table 2.3 VB.NET Constraints (Vb.net Constants, n.d.)

Constant Description
vbCrLf Carriage return/linefeed character combination.
vbCr Carriage return character.
vbLf Linefeed character.
vbNewLine Newline character.
vbNullChar Null character.
vbNullString Not the same as a zero-length string (""); used for
calling external procedures.
vbObjectError Error number. User-defined error numbers should
be greater than this value. For example:
Err.Raise(Number) = vbObjectError + 1000
vbTab Tab character.
vbBack Backspace character.

Assessment Task

I. Write VB.NET code to declare two integer variables, one float variable, and one
string variable and assign 10, 15, 12.5, and "VB.NET programming" to them
respectively.
II. Write a program that declare the following constants:

19
a. Declare a constant named “Pi” and place a floating point value
3.141592653589.
b. Declare a constant named “Square root of 2” and place a value of
1.41421356237
c. Declare a public constant named “message” and place a string value of
“WELCOME TO LAGUNA UNIVERSITY!”

Summary

 Types of data apply to a broad scheme used to describe variables or functions of


different types; A type of variable determines how much storage space it occupies,
and how the stored bit pattern is interpreted.
 In VB.Net some basic data types are Integer, Double, Char, Boolean and String.
 A variable is nothing but a name given to a storage area which can be controlled by
our programs. Every variable in VB.Net has a specific form, which specifies the size
and configuration of the memory of the variable; the number of values that can be
stored in that memory; and the collection of operations that can be applied to the
variable.
 The basic value types provided in VB.Net can be categorized as – Integral types,
Floating point types, decimal types, Boolean types and date types.
 The term Dim is used to declare the variable and to assign storage to one or more
variables.
 The constants refer to fixed values which the program cannot change during its
execution. These fixed values are often called literals.
 For all common data types, constants may be an integral constant, a floating constant,
a constant character or a string literal. Only the enumeration has constants.
 The constants are treated much like normal variables except that after their creation,
their values cannot be changed.

References

 Vb.Net Data Types. (n.d.). Retrieved from Tutorials Point:


https://www.tutorialspoint.com/vb.net/vb.net_data_types.htm
 Vb.net Variables. (n.d.). Retrieved from Tutorials Point:
https://www.tutorialspoint.com/vb.net/vb.net_variables.htm
 Vb.net Constants. (n.d.). Retrieved from Tutorials Point:
https://www.tutorialspoint.com/vb.net/vb.net_constants.htm

20
MODULE 3
VISUAL BASIC.NET FUNDAMENTALS (PART 2)

Introduction

The constants apply to fixed values which cannot be changed by the program during
its execution. Even certain set values are called literals. Constants may be an integral
constant, a floating constant, a character constant or a string literal in all of the basic data
types. Also there are constants in enumeration. The constants are treated much like normal
variables, except that after their creation, their values cannot be changed. An enumeration is
a set of constants called by integer (Vb.net Constants, n.d.).

Learning Outcomes

At the end of this module, students should be able to:


1. Understand how to declare enumerations
2. Describe VB.Net modifiers;
3. Understand VB.Net Statements.

Lesson 1. Declaring Enumerations

An enumerated type is specified through the declaration Enum. Enum 's declaration sets an
enumeration, which defines the principles of its leaders. The Enum statement may be used
on node, class, structure, process or block point (Vb.net Constants, n.d.).

The syntax for the Enum statement is as follows (Vb.net Constants, n.d.):

[ < attributelist > ] [ accessmodifier ] [ Shadows ]


Enum enumerationname [ As datatype ]
memberlist
End Enum

Where,
 enumerationname: name of the enumeration. Required
 datatype: specifies the data type of the enumeration and all its members.

21
 memberlist: specifies the list of member constants being declared in this statement
required.

Each member in the memberlist has the following syntax and parts (Vb.net Constants, n.d.):
[< attribute list>] member name [ = initializer ]

Where,
 name: specifies the name of the member. Required.
 initializer: value assigned to the enumeration member. Optional.

For example,

Enum Colors
red = 1
orange = 2
yellow = 3
green = 4
azure = 5
blue = 6
violet = 7
End Enum

The following example demonstrates declaration and use of the Enum variable Colors:

Module constantsNenum
Enum Colors
red = 5
orange = 4
yellow = 3
green = 2
azure = 1
blue = 0
violet = 10
End Enum
Sub Main()
Console.WriteLine("The Color Red is : " & Colors.red)
Console.WriteLine("The Color Yellow is : " & Colors.yellow)
Console.WriteLine("The Color Blue is : " & Colors.blue)
Console.WriteLine("The Color Azure is : " & Colors.azure)
Console.ReadKey()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:

The Color Red is: 5


The Color Yellow is: 3
The Color Blue is: 0
The Color Azure is: 1

22
Lesson 2. Modifiers

The modifiers are keywords associated with each programming element to illustrate
how to act or access the programming element in the program. The access modifiers, for
example: Public, Private, Protected, Friend, Protected Friend, etc., signify the level of access
of a programming feature like a variable, constant, enumeration, or class (VB.Net Modifiers,
n.d.).

Table 3.1 List of Available Modifiers in VB.Net (VB.Net Modifiers, n.d.)

Modifier Description
Ansi Specifies that Visual Basic should marshal all strings to American National Standards Institute
(ANSI) values regardless of the name of the external procedure being declared.
Assembly Specifies that an attribute at the beginning of a source file applies to the entire assembly.
Async Indicates that the method or lambda expression that it modifies is asynchronous. Such methods
are referred to as async methods. The caller of an async method can resume its work without
waiting for the async method to finish.
Auto The charsetmodifier part in the Declare statement supplies the character set information for
marshaling strings during a call to the external procedure. It also affects how Visual Basic searches
the external file for the external procedure name. The Auto modifier specifies that Visual Basic
should marshal strings according to .NET Framework rules.
ByRef Specifies that an argument is passed by reference, i.e., the called procedure can change the value
of a variable underlying the argument in the calling code. It is used under the contexts of:
Declare Statement
Function Statement
Sub Statement
ByVal Specifies that an argument is passed in such a way that the called procedure or property cannot
change the value of a variable underlying the argument in the calling code. It is used under the
contexts of:
Declare Statement
Function Statement
Operator Statement
Property Statement
Sub Statement
Default Identifies a property as the default property of its class, structure, or interface.
Friend Specifies that one or more declared programming elements are accessible from within the
assembly that contains their declaration, not only by the component that declares them.
Friend access is often the preferred level for an application's programming elements, and Friend is
the default access level of an interface, a module, a class, or a structure.
In It is used in generic interfaces and delegates.
Iterator Specifies that a function or Get accessor is an iterator. Aniterator performs a custom iteration over
a collection.
Key The Key keyword enables you to specify behavior for properties of anonymous types.
Module Specifies that an attribute at the beginning of a source file applies to the current assembly module.
It is not same as the Module statement.
MustInherit Specifies that a class can be used only as a base class and that you cannot create an object
directly from it.

23
MustOverride Specifies that a property or procedure is not implemented in this class and must be overridden in a
derived class before it can be used.
Narrowing Indicates that a conversion operator (CType) converts a class or structure to a type that might not
be able to hold some of the possible values of the original class or structure.
NotInheritable Specifies that a class cannot be used as a base class.
NotOverridable Specifies that a property or procedure cannot be overridden in a derived class.
Optional Specifies that a procedure argument can be omitted when the procedure is called.
Out For generic type parameters, the Out keyword specifies that the type is covariant.
Overloads Specifies that a property or procedure redeclares one or more existing properties or procedures
with the same name.
Overridable Specifies that a property or procedure can be overridden by an identically named property or
procedure in a derived class.
Overrides Specifies that a property or procedure overrides an identically named property or procedure
inherited from a base class.
ParamArray ParamArray allows you to pass an arbitrary number of arguments to the procedure. A ParamArray
parameter is always declared using ByVal.
Partial Indicates that a class or structure declaration is a partial definition of the class or structure.
Private Specifies that one or more declared programming elements are accessible only from within their
declaration context, including from within any contained types.
Protected Specifies that one or more declared programming elements are accessible only from within their
own class or from a derived class.
Public Specifies that one or more declared programming elements have no access restrictions.
ReadOnly Specifies that a variable or property can be read but not written.
Shadows Specifies that a declared programming element redeclares and hides an identically named
element, or set of overloaded elements, in a base class.
Shared Specifies that one or more declared programming elements are associated with a class or
structure at large, and not with a specific instance of the class or structure.
Static Specifies that one or more declared local variables are to continue to exist and retain their latest
values after termination of the procedure in which they are declared.
Unicode Specifies that Visual Basic should marshal all strings to Unicode values regardless of the name of
the external procedure being declared.
Widening Indicates that a conversion operator (CType) converts a class or structure to a type that can hold
all possible values of the original class or structure.
WithEvents Specifies that one or more declared member variables refer to an instance of a class that can raise
events.
WriteOnly Specifies that a property can be written but not read.

Lesson 3. Statements

A statement is a complete instruction in the Visual Basic programs. Keywords, operators,


variables, literal values, constants and expressions can be included (VB.NET Statements,
n.d.).

Could categorize statements as:


 Declaration statements - These are statements in which you name a variable, constant
or procedure and you can also specify the type of data.

24
 Executable statements - These are the declarations that trigger actions. Those
statements may call a method or function, loop or branch to a variable or constant
through blocks of code or assign values or expression. For the last case it is called a
Declaration of Assignment (VB.NET Statements, n.d.).

Declaration Statements
The declaration statements are used for naming and defining processes, variables,
resources, arrays, and constants. Also, when you declare a programming element you can
specify their data type, access level and scope (VB.NET Statements, n.d.).
The programming elements that you may declare include variables, constants,
enumerations, classes, structures, modules, interfaces, method parameters, function returns,
references to external procedures, operators, properties, events, and delegates (VB.NET
Statements, n.d.).

Table 3.2 Following are the declaration statements in VB.Net (VB.NET Statements, n.d.):

Statements and Description Example


Dim Statement Dim number As Integer
Declares and allocates storage space for one or more variables. Dim age As Integer = 24
Dim message As String = "I love you!"

Const Statement Declares and defines one or more constants. Const high As Long = 1000
Const naturalLogBase As Object
= CDec(2.7182818284)
Enum Statement Declares an enumeration and defines the values of its Enum ShirtSize
members. ExtraLarge
Large
Medium
Small
End Enum
Class Statement Class Box
Declares the name of a class and introduces the definition of the variables, Public length As Double
properties, events, and procedures that the class comprises. Public breadth As Double
Public height As Double
End Class
Structure Statement Structure Box
Declares the name of a structure and introduces the definition of the Public length As Double
variables, properties, events, and procedures that the structure comprises. Public breadth As Double
Public height As Double
End Structure
Module Statement Public Module myModule
Declares the name of a module and introduces the definition of the variables, Sub Main()
properties, events, and procedures that the module comprises. Dim user As String =
InputBox("What is your real name?")
MsgBox("Real name is" & user)
End Sub
End Module

25
Interface Statement Public Interface MyInterface
Declares the name of an interface and introduces the definitions of the Sub doSomething()
members that the interface comprises. End Interface
Function Statement Function myFunction
Declares the name, parameters, and code that define a Function procedure. (ByVal n As Integer) As Double
Return 5.87 * n
End Function
Sub Statement Sub mySub(ByVal s As String)
Declares the name, parameters, and code that define a Sub procedure. Return
End Sub
Declare Statement Declare Function getUserName
Declares a reference to a procedure implemented in an external file. Lib "advapi32.dll"
Alias "GetUserNameA"
(ByVal lpBuffer As String,
ByRef nSize As Integer) As Integer
Operator Statement Public Shared Operator +
Declares the operator symbol, operands, and code that define an operator (ByVal x As obj, ByVal y As obj) As obj
procedure on a class or structure. Dim r As New obj
' implemention code for r = x + y
Return r
End Operator

Property Statement ReadOnly Property quote() As String


Declares the name of a property, and the property procedures used to store Get
and retrieve the value of the property. Return quoteString
End Get
End Property
Event Statement Public Event Finished()
Declares a user-defined event.
Delegate Statement Delegate Function MathOperator(
Used to declare a delegate. ByVal x As Double,
ByVal y As Double
) As Double

Executable Statements
An action is executed by an executable sentence. Executable statements are
statements that call a process, branch to a specific location in the code, loop through several
statements or evaluate an expression. An assignment statement is a particular case of an
executable declaration (VB.NET Statements, n.d.).

The following example demonstrates a decision making statement:

Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 10
' check the boolean condition using if statement '
If (a < 20) Then
' if condition is true then print the following '
Console.WriteLine("a is less than 20")

26
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()
End Sub
End Module

When the above code is compiled and executed, it produces the following result:

a is less than 20;


value of a is : 10

Assessment Task

I. Identification
a. It specifies the data type of the enumeration and all its members.
b. It specifies that one or more declared member variables refer to an instance
of a class that can raise events.
c. It specifies that a property or procedure redeclares one or more existing
properties or procedures with the same name.
d. It declares a reference to a procedure implemented in an external file.
e. It associated on each programming element to illustrate how to act or access
the programming element in the program.
f. It specifies that one or more declared programming elements are associated
with a class or structure at large, and not with a specific instance of the class
or structure.
g. What is the meaning of the abbreviation ANSI?
h. Those statements may call a method or function, loop or branch to a variable
or constant through blocks of code or assign values or expression.
i. It is optional and the value assigned to the enumeration member.
j. It declares and defines one or more constants.
k. It specifies that one or more declared programming elements are accessible
only from within their declaration context, including from within any contained
types.
l. These are statements in which you name a variable, constant or procedure
and you can also specify the type of data.
m. It specifies the list of member constants being declared in this statement
required.
n. It indicates that a conversion operator (CType) converts a class or structure
to a type that can hold all possible values of the original class or structure.
o. Declares the name of a module and introduces the definition of the variables,
properties, events, and procedures.

27
II. Create a program that will declare and allocate storage space. Use the following
variables and data types.
a. Employee Name – String
b. Employee Salary – Integer
c. Sex – String
d. Employment Status -String

Summary

 Using the statement Enum is considered an enumerated form. The declaration of


Enum establishes an enumeration, and describes its members' principles. The
statement Enum may be used at the level of module, class, structure, procedure or
block.
 For Visual Basic programs a sentence is a complete instruction. Keywords, operators,
variables, logical values, constants and expressions can be included.
 Statements from the declaration are used to name and describe processes, variables,
properties, arrays, and constants. You may also describe their data type, access level,
and scope when you declare a programming element.
 Contains variables, constants, enumerations, classes, frameworks, modules,
interfaces, protocols, method parameters, function returns, references to external
processes, operators, resources, events and delegates.

References

1. VB.Net Modifiers. (n.d.). Retrieved from Tutorials Point:


https://www.tutorialspoint.com/vb.net/vb.net_modifiers.htm
2. VB.NET Statements. (n.d.). Retrieved from Tutorials Point:
https://www.tutorialspoint.com/vb.net/vb.net_statements.htm

28
MODULE 4
VISUAL BASIC.NET OPERATORS

Introduction

An operator is a symbol that tells the compiler to perform specific mathematical or


logical manipulations. VB.Net is rich in built-in operators and provides following types of
commonly used operators − (VB.Net Operators, n.d.).

Learning Outcomes

At the end of this module, students should be able to:


1. Understand the functions of arithmetic operators.
2. Understand the how to use the comparison operator.
3. Understand the logical operator and assignment operator

Lesson 1. Arithmetic Operators

Following table shows all the arithmetic operators supported by VB.Net. Assume
variable A holds 2 and variable B holds 7, then (VB.Net Operators, n.d.) –

Table 4.1 Arithmetic Operators (VB.Net Operators, n.d.)


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

29
MOD Modulus Operator and B MOD A will give 1
remainder of after an integer
division
Try the following example to understand all the arithmetic operators available in
VB.Net (VB.Net Operators, n.d.):
Module operators
Sub Main()
Dim a As Integer = 21
Dim b As Integer = 10
Dim p As Integer = 2
Dim c As Integer
Dim d As Single
c=a+b
Console.WriteLine("Line 1 - Value of c is {0}", c)
c=a-b
Console.WriteLine("Line 2 - Value of c is {0}", c)
c=a*b
Console.WriteLine("Line 3 - Value of c is {0}", c)
d=a/b
Console.WriteLine("Line 4 - Value of d is {0}", d)
c=a \b
Console.WriteLine("Line 5 - Value of c is {0}", c)
c = a Mod b
Console.WriteLine("Line 6 - Value of c is {0}", c)
c=b^p
Console.WriteLine("Line 7 - Value of c is {0}", c)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result
(VB.Net Operators, n.d.)
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of d is 2.1
Line 5 - Value of c is 2
Line 6 - Value of c is 1
Line 7 - Value of c is 100

30
Lesson 2. Comparison Operators

Following table shows all the comparison operators supported by VB.Net. Assume
variable A holds 10 and variable B holds 20, then (VB.Net Operators, n.d.):

Table 4.2 Comparison Operators (VB.Net Operators, n.d.)


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

Try the following example to understand all the relational operators available in
VB.Net (VB.Net Operators, n.d.)
Module operators
Sub Main()
Dim a As Integer = 21
Dim b As Integer = 10
If (a = b) Then

31
Console.WriteLine("Line 1 - a is equal to b")
Else
Console.WriteLine("Line 1 - a is not equal to b")
End If

If (a < b) Then
Console.WriteLine("Line 2 - a is less than b")
Else
Console.WriteLine("Line 2 - a is not less than b")
End If
If (a > b) Then
Console.WriteLine("Line 3 - a is greater than b")
Else
Console.WriteLine("Line 3 - a is not greater than b")
End If
' Lets change value of a and b
a=5
b = 20
If (a <= b) Then
Console.WriteLine("Line 4 - a is either less than or equal to b")
End If
If (b >= a) Then
Console.WriteLine("Line 5 - b is either greater than or equal to b")
End If
Console.ReadLine()
End Sub
End Module

When the above code is compiled and executed, it produces the following result
(VB.Net Operators, n.d.)–
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b
Apart from the above, VB.Net provides three more comparison operators, which we
will be using in forthcoming chapters; however, we give a brief description here (VB.Net
Operators, n.d.).
 Is Operator − It compares two object reference variables and determines if two
object references refer to the same object without performing value comparisons. If

32
object1 and object2 both refer to the exact same object instance, result is True;
otherwise, result is False.
 IsNot Operator − It also compares two object reference variables and determines if
two object references refer to different objects. If object1 and object2 both refer to
the exact same object instance, result is False; otherwise, result is True.
 Like Operator − It compares a string against a pattern.

Lesson 3. Logical Operators

Following table shows all the logical operators supported by VB.Net. Assume
variable A holds Boolean value True and variable B holds Boolean value False, then
(VB.Net Operators, n.d.)−

Table 4.3 Logical Operators (VB.Net Operators, n.d.)


Operator Description Example
And It is the logical as well as bitwise AND operator. (A And B) is False.
If both the operands are true, then condition
becomes true. This operator does not perform
short-circuiting, i.e., it evaluates both the
expressions.
Or It is the logical as well as bitwise OR operator. If (A Or B) is True.
any of the two operands is true, then condition
becomes true. This operator does not perform
short-circuiting, i.e., it evaluates both the
expressions.
Not It is the logical as well as bitwise NOT operator. Not(A And B) is True.
Use to reverses the logical state of its operand.
If a condition is true, then Logical NOT operator
will make false.
Xor It is the logical as well as bitwise Logical A Xor B is True.
Exclusive OR operator. It returns True if both
expressions are True or both expressions are
False; otherwise it returns False. This operator
does not perform short-circuiting, it always
evaluates both expressions and there is no
short-circuiting counterpart of this operator.
AndAlso It is the logical AND operator. It works only on (A AndAlso B) is
Boolean data. It performs short-circuiting. False.
OrElse It is the logical OR operator. It works only on (A OrElse B) is True.
Boolean data. It performs short-circuiting.
IsFalse It determines whether an expression is False.
IsTrue It determines whether an expression is True.

33
Try the following example on next page to understand all the logical/bitwise
operators available in VB.Net (VB.Net Operators, n.d.)−
Module logicalOp
Sub Main()
Dim a As Boolean = True
Dim b As Boolean = True
Dim c As Integer = 5
Dim d As Integer = 20
'logical And, Or and Xor Checking
If (a And b) Then
Console.WriteLine("Line 1 - Condition is true")
End If
If (a Or b) Then
Console.WriteLine("Line 2 - Condition is true")
End If
If (a Xor b) Then
Console.WriteLine("Line 3 - Condition is true")
End If
'bitwise And, Or and Xor Checking
If (c And d) Then
Console.WriteLine("Line 4 - Condition is true")
End If
If (c Or d) Then
Console.WriteLine("Line 5 - Condition is true")
End If
If (c Or d) Then
Console.WriteLine("Line 6 - Condition is true")
End If
'Only logical operators
If (a AndAlso b) Then
Console.WriteLine("Line 7 - Condition is true")
End If
If (a OrElse b) Then
Console.WriteLine("Line 8 - Condition is true")
End If
' lets change the value of a and b
a = False
b = True
If (a And b) Then
Console.WriteLine("Line 9 - Condition is true")
Else
Console.WriteLine("Line 9 - Condition is not true")
End If
If (Not (a And b)) Then

34
Console.WriteLine("Line 10 - Condition is true")
End If
Console.ReadLine()
End Sub
End Module

When the above code is compiled and executed, it produces the following result
(VB.Net Operators, n.d.)−

Line 1 - Condition is true


Line 2 - Condition is true
Line 3 - Condition is true
Line 4 - Condition is true
Line 5 - Condition is true
Line 6 - Condition is true
Line 7 - Condition is true
Line 8 - Condition is true
Line 9 - Condition is not true
Line 10 - Condition is true

Lesson 4. Assignment Operators

There are following assignment operators supported by VB.Net (VB.Net Operators,


n.d.)−

Table 4.4 Assignment Operator (VB.Net Operators, n.d.)


Operator Description Example
= Simple assignment operator, Assigns values from right C = A + B will assign
side operands to left side operand value of A + B into C
+= Add AND assignment operator, It adds right operand to C += A is equivalent to C
the left operand and assigns the result to left operand =C+A
-= Subtract AND assignment operator, It subtracts right C -= A is equivalent to C
operand from the left operand and assigns the result to =C-A
left operand
*= Multiply AND assignment operator, It multiplies right C *= A is equivalent to C
operand with the left operand and assigns the result to =C*A
left operand
/= Divide AND assignment operator, It divides left operand C /= A is equivalent to C
with the right operand and assigns the result to left =C/A
operand (floating point division)
\= Divide AND assignment operator, It divides left operand C \= A is equivalent to C
with the right operand and assigns the result to left = C \A
operand (Integer division)

35
^= Exponentiation and assignment operator. It raises the left C^=A is equivalent to C =
operand to the power of the right operand and assigns C^A
the result to left operand.
<<= Left shift AND assignment operator C <<= 2 is same as C =
C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C =
C >> 2
&= Concatenates a String expression to a String variable or Str1 &= Str2 is same as
property and assigns the result to the variable or property. Str1 = Str1 & Str2
Try the following example to understand all the assignment operators available in VB.Net
(VB.Net Operators, n.d.)−
Module assignment
Sub Main()
Dim a As Integer = 21
Dim pow As Integer = 2
Dim str1 As String = "Hello! "
Dim str2 As String = "VB Programmers"
Dim c As Integer
c=a
Console.WriteLine("Line 1 - = Operator Example, _
Value of c = {0}", c)
c += a
Console.WriteLine("Line 2 - += Operator Example, _
Value of c = {0}", c)
c -= a
Console.WriteLine("Line 3 - -= Operator Example, _
Value of c = {0}", c)
c *= a
Console.WriteLine("Line 4 - *= Operator Example, _
Value of c = {0}", c)
c /= a
Console.WriteLine("Line 5 - /= Operator Example, _
Value of c = {0}", c)
c = 20
c ^= pow
Console.WriteLine("Line 6 - ^= Operator Example, _
Value of c = {0}", c)
c <<= 2
Console.WriteLine("Line 7 - <<= Operator Example,_
Value of c = {0}", c)
c >>= 2

36
Console.WriteLine("Line 8 - >>= Operator Example,_
Value of c = {0}", c)
str1 &= str2
Console.WriteLine("Line 9 - &= Operator Example,_
Value of str1 = {0}", str1)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result (VB.Net
Operators, n.d.)−
Line 1 - = Operator Example, Value of c = 21
Line 2 - += Operator Example, Value of c = 42
xLine 3 - -= Operator Example, Value of c = 21
Line 4 - *= Operator Example, Value of c = 441
Line 5 - /= Operator Example, Value of c = 21
Line 6 - ^= Operator Example, Value of c = 400
Line 7 - <<= Operator Example, Value of c = 1600
Line 8 - >>= Operator Example, Value of c = 400
Line 9 - &= Operator Example, Value of str1 = Hello! VB Programmers

Assessment Task

I. Code in VB.NET program to allow the user to input two integer values and then the
program print the results of adding, subtracting, multiplying, and dividing among
the two values. See the output below:
a. Enter value a:30
b. Enter value b:10
c. The result of adding is 40.
d. The result of subtracting is 20;
e. The result of multiplying is 300.
f. The result of dividing is 3.
II. Code in VB.NET program to allow the user to input the amount of deposit, yearly
interest rate (percentage), and income tax(percentage). Then the program will
calculate the amount of interest that the person earns in the year. See the output
below:
a. The amount of deposit: 1000
b. Yearly interest rate: 7.5%
c. Income tax rate: 4%
d. The amount of interest earned in the year:71.0

37
III. Code in VB.NET program to allow the user to input two float values and then the
program adds the two values together.
The result will be assigned to the first variable.
a. Enter value a:12.5
b. The value of a before adding is 12.5.
c. Enter value b:34.9
d. The value of a after adding is 47.4

Summary

 An operator is a symbol that tells the compiler to perform specific mathematical or


logical manipulations. VB.Net is rich in built-in operators and provides following types
of commonly used operators − (VB.Net Operators, n.d.).

References

1. VB.NET Operators. (n.d.). Retrieved from Tutorials Point:


https://www.tutorialspoint.com/vb.net/vb.net_operators.htm
2. VB.NET Operators. (n.d.). Retrieved from Tutorials Point:
https://www.tutorialspoint.com/vb.net/vb.net_arithmetic_operators.htm
3. VB.Net Operators. (n.d.). Retrieved from Tutorials Point:
https://www.tutorialspoint.com/vb.net/vb.net_comparison_operators.htm
4. VB.Net Operators. (n.d.). Retrieved from Tutorials Point:
https://www.tutorialspoint.com/vb.net/vb.net_arithmetic_operators.htm
5. VB.Net Operators. (n.d.). Retrieved from Tutorials Point:
https://www.tutorialspoint.com/vb.net/vb.net_assignment_operators.htm

- END OF MODULE FOR PRELIMINARY TERM PERIOD –


SUBMISSION OF ASSESSMENT TASKS AND EXAMINATION FOR PRELIM
PERIOD WILL BE ANNOUNCED VIA iLearnU LMS or GC
MAKE SURE TO CHECK THE DATES AND DO NOT FORGET TO TAKE IT AS
SCHEDULED.

38

You might also like