Dotnet - Unit 1 Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

DOTNET PROGRAMMING

UNIT - I
Introduction
.NET technology was introduced by Microsoft, to catch the market from the SUN's Java.
Few years back, Microsoft had only VC++ and VB to compete with Java, but Java was catching
the market very fast. With the world depending more and more on the Internet/Web and java
related tools becoming the best choice for the web applications, Microsoft seemed to be losing
the battle. Thousands of programmers moved to java from VC++ and VB. To recover the
market, Microsoft announced .NET. The .NET is the technology, on which all other Microsoft
technologies will be depending on in future. It is a new framework platform for developing web-
based and windows-based applications within the Microsoft environment. .NET is not a
language. (runtime and a library for execution .net application)

.NET Environment/Platform
Visual studio .NET is an Integrated Development Environment(IDE) from Microsoft.
It provides the tools to design, develop, compiling and debugging the all .net applications.

.NET Framework
.NET Framework is a computing model that makes things easier for application
development for the distributed environment of the internet. .NET Framework is an environment
for building, deploying and running web services and others applications. The first version of the
.Net framework was released in the year 2002. The version was called .Net framework 1.0.
The .Netframework has come a long way since then, and the current version is 4.8. .NET
framework comes with a single class library. Whether write the code in C# or VB.NET or J# just
use the .NET class library. There is no classes specific to any language. Because it is support
multiple
programming languages.

1
.NET Components/ Features of the .Net Framework:
The .NET Framework is composed of five main components:
 Common Language Runtime (CLR)
 Common Language Specification(CLS)
 Common Type System(CTS)
 Base Class Library(BCL)/Framework Class Library(FCL)
 Microsoft Intermediate language(MSIL or IL)

CLR-stands for Common Language Runtime is a managed execution environment that is part of
Microsoft’s .NET framework. CLR manages the execution of programs written in different
supported languages. CLR transforms source code into a form of bytecode known as Common
Intermediate Language (CIL). At run time, CLR handles the execution of the CIL code.

CLS- stands for Common Language Specification and it is a subset of CTS. It defines a set of
rules and restrictions that every language must follow which runs under .NET framework. The
languages which follows these set of rules are said to be CLS Compliant. It enables cross-
language interoperability between various programming languages.

2
CTS-stands for Common Type System Common The language interoperability, and .NET Class
Framework, are not possible without all the language sharing the same data types. What this
means is that an "int" should mean the same in VB, VC++, C# and all other .NET compliant
languages. Same idea follows for all the other data types. It is an important part of the runtimes
support for cross language integration.

BCL - stands for Base Class Library ( Unified Classes) is a subset of Framework class library
(FCL). Class library is the collection of reusable types that are closely integrated with CLR.
All .NET-based languages also access the same libraries. The .NET Framework has an extensive
set of class libraries.
This includes classes for:
 Data Access: High Performance data· access classes for connecting to SQL Server or any
other OLEDB provider.
 XML Supports: Next generation XML support that goes far beyond the functionality of
MSXML.
 Directory Services: Support for accessing Active directory/LDPA using ADSI.
 Regular Expression: Support for above and beyond that found in Perl 5.
 Queuing Supports: Provides a clean object-oriented set of classes for working with
MSMQ.

MSIL-stands for Microsoft Intermediate Language A .NET programming language (C#,


VB.NET, J# etc.) does not compile into executable code; instead it compiles into an intermediate
code called MSIL or IL. A source code in automatically converted to MSIL. The MSIL code is
then send to the CLR that converts the code to machine language which is then run on the host
machine.

3
Just In Time Compiler – JIT
The .Net languages , which is conforms to the Common Language Specification (CLS),
uses its corresponding runtime to run the application on different Operating Systems .
During the code execution time, the Managed Code compiled only when it is needed, that is it
converts the appropriate instructions to the native code for execution just before when each
function is called. This process is called Just In Time (JIT) compilation, also known as Dynamic
Translation . With the help of Just In Time Compiler (JIT) the Common Language Runtime
(CLR) doing these tasks.

Garbage Collection (GC)


The Garbage collection is the important technique in the .Net framework to free the
unused managed code objects in the memory and free the space to the process. The garbage
collection (GC) is new feature in Microsoft .net framework. When a class that represents an
object in the runtime that allocates a memory space in the heap memory. All the behavior of that
objects can be done in the allotted memory in the heap. Microsoft was planning to introduce a
method that should automate the cleaning of unused memory space in the heap after the life time
of that object. Eventually they have introduced a new technique "Garbage collection". It is very
important part in the .Net framework. Now it handles this object clear in the memory implicitly.
It overcomes the existing explicit unused memory space clearance.

Assemblies
Assemblies form the fundamental units of deployment, version control, reuse, activation
scoping, and security permissions for .NET-based applications. An assembly is a collection of
types and resources that are built to work together and form a logical unit of functionality.
Assemblies take the form of executable (.exe) or dynamic link library (.dll) files, and are the
building blocks of .NET applications. They provide the common language runtime with the
information it needs to be aware of type implementations.
Every Assembly create contains one or more program files and a Manifest. There are two
types program files : Process Assemblies (EXE) and Library Assemblies (DLL). Each Assembly
can have only one entry point (that is, DllMain, WinMain, or Main).
+There are two types:
1. Private Assembly
2. Shared Assembly
1. Private Assembly It is used only by a single application, and usually it is stored in that
application's install directory. Private Assembly cannot be references outside the scope of the
folder.

2. Shared Assembly Shared Assembly is a public assembly that is shared by multiple


applications.
Shared Assembly is one that can be referenced by more than one application.

.Net Assembly Manifest


An Assembly Manifest is a file that containing Metadata about .NET Assemblies.
Assembly Manifest contains a collection of data that describes how the elements in the assembly
relate to each other. It describes the relationship and dependencies of the components in the
Assembly, versioning information, scope information and the security permissions required by
the Assembly.

4
Difference between VB.NET and Visual Basic

VB.NET is also known as Visual Basic.NET. It stands for Visual Basic .Network
Enabled Technologies. It is a simple, high-level, object-oriented programming language
developed by Microsoft in 2002. It is a successor of Visual Basic 6.0, which is implemented on
the Microsoft .NET Framework.

VB .NET Visual Basic

It stands for Visual Basic. Network Enables It is a programming language developed by


Technology. It is also developed by Microsoft for the fastest development of a
Microsoft, and this language was based on window-based operating system as well as
the .Net Framework. Furthermore, it is applications.
specially designed for VB developers.

It is a modern, fully object-oriented language VB is the predecessor of VB.NET and was not an
that replaced VB6. object-oriented language. So, it is not actively
maintained.

A VB.NET uses the Common Language Visual Basic uses the VB-Runtime environment.
Runtime (CLR) component of .Net
Framework at runtime. It has better features
and design implementation as compared to
VB-Runtime.

It is a compiled language It is an Interpreter based language

It does not support backward compatibility. It supports backward compatibility.

It is a type-safe language. It is not a type-safe language.

In VB.NET, data is handled using the Data Connectivity and handling are done through
ADO.net protocol. DAO, RDO, and ADO (ActiveX Data Object)
protocol,

Object does not support default property. The Object support default property of virtual
basic.

In the VB.Net parameter are passed by a In VB, most of the parameters are passed by
default value. reference.

A Multithreaded application can be It does not support the multithread concept.


developed in VB.NET.

5
Object Oriented Programming in Vb.Net
OOP can be defines as Object-oriented programming is a programming technique that
involves structuring a program around special, user-defined data types called classes. Classes are
used to break a problem up into a set of objects that interact with each other. A class consists of
both the data that define an object and subprograms, called methods, which describe the object's
behavior. A language that is to be called a true OOP language must implement three concepts –
encapsulation, polymorphism, and inheritance. Without all three of these features, a
programming language can be considered object-based, but all three must be present for the
language to be considered a true object-oriented language.

Polymorphism: The method can be implemented for more number of times we call this
as
Write once and use it for many times.

Encapsulation: Hiding data structure and the mechanism of a component behind the interface,
helps the user to know only about “what the component does rather how it does”.

Inheritance: Helps in reusability, supports existing interface inheritance but not the
implementation. Visual Basic .NET provides for true implementation inheritance whereby
you
Encapsulation
Encapsulation is the exposure of properties and methods of an object while hiding the
actual implementation from the outside world. In other words, the object is treated as a black box
—developers who use the object should have no need to understand how it actually works.

Encapsulation allows developers to build objects that can be changed without affecting
the client code that uses them. The key is that the interface of the object, the set of exposed
properties and methods of the object, doesn't change even if the internal implementation does.

Public Class Person


Private m_sFirstName as String
Private m_sLastName as String
Private m_sFullName as String
Public Property FirstName() as String
Get
FirstName = m_sFirstName
End Get

6
Set(ByVal Value as String)
m_sFirstName = Value
m_sFullName = m_sLastName & ", " & m_sFirstName
End Set
End Property
Public Property LastName() as String
Get
LastName = m_sLastName
End Get
Set(ByVal Value as String)
m_sLastName = Value
m_sFullName = m_sLastName & ", " & m_sFirstName
End Set
End Property
ReadOnly Property FullName() as String
Get
FullName = m_sFirstName
End Get
End Property
End Class

Inheritance
Inheritance is the idea that one class, called a subclass, can be based on another class,
called a base class. Inheritance provides a mechanism for creating hierarchies of objects.

Table 3.1 New Language Elements for Implementation Inheritance

Element Context Description

Inherits Class Statement Indicates the class from which the new class
inherits

7
Element Context Description

NotInheritable Class Statement Indicates that a class that cannot be inherited from

MustInherit Class Statement Indicates a class that must be inherited by another


class

Overridable Procedure Indicates a procedure that can be overridden by a


subclass

NotOverridable Procedure Indicates a procedure that cannot be overridden in a


subclass

MustOverride Procedure Indicates a procedure that must be overridden in a


subclass

Overrides Procedure Indicates that a procedure is overriding a procedure


in a base class

This is the example of inheritance.

Public Class Person


Protected c_sFirstName as String
Protected c_sLastName as String
MustOverride ReadOnly Property ClassName() as String
Get
ClassName = "Person"
End Get
End Property
NotOverridable ReadOnly Property BaseClassName() as String
Get
BaseClassName = "Person"
End Get
End Property
Overidable Public Property FirstName() as String
Get
FirstName = c_sFirstName
End Get
Set(ByVal Value as string)
c_sFirstName = Value
End Set
End Property

8
Overidable Public Property LastName() as String
Get
LastName = c_sLastName
End Get
Set(ByVal Value as string)
c_sLastName = Value
End Set
End Property
Overridable Sub Speak()
Console.WriteLine("I am " & c_sFirstName & " " & c_sLastName)
Console.WriteLine(" and I am a Person.")
End Sub
End Class

Polymorphism
Polymorphism is the next fundamental principle of Object-Oriented Programming (OOP).
Polymorphism is a Greek word that means many-shaped. One object has many forms or has one
name with multiple functionalities.

 Polymorphism allows treating objects of a derived class as objects of its base class.
 It provides the ability for a class to have multiple implementations with the same name.

Overriding members
By default, a derived class inherits all members from its base class. If we want to change
the behavior of the inherited member, you need to override it. That is, we can define a new
implementation of the method, property, or event in the derived class.

The following modifiers are used to control how properties and methods are overridden.

Modifier Description

Overridable Allows a class member to be overridden in a derived class.

Overrides Overrides a virtual (overridable) member defined in the base class.

NotOverridable Prevents a member from being overridden in an inheriting class.

MustOverride Requires that a class member be overridden in the derived class.

Shadows Hides a member inherited from a base class

Example program of polymorphism

Public Class Shape


9
Public Overridable Function CalculateArea() As Double
Return 0
End Function
End Class

Public Class Circle


Inherits Shape

Public Property Radius As Double

Public Sub New(ByVal rad As Double)


Radius = rad
End Sub

Public Overrides Function CalculateArea() As Double


Return (3.14) * Math.Pow(Radius, 2)
End Function
End Class

Public Class Rectangle


Inherits Shape

Public Property Height As Double


Public Property Width As Double

Public Sub New(ByVal h As Double, ByVal w As Double)


Height = h
Width = w
End Sub

Public Overrides Function CalculateArea() As Double


Return Height * Width
End Function
End Class

DATA TYPES, VARIABLES, AND OPERATORS

Data Types
A Data Type refers to which type of data or value is assigning to a variable or function so
that a variable can hold a defined data type value.
Syntax
Dim Variable_Name as DataType

Data Types Required Space Value Range

10
Boolean A Boolean type depends on the True or False
implementing platform

Byte 1 byte Byte Range start from 0 to 255 (unsigned)

Char 2 bytes Char Range start from 0 to 65535


(unsigned)

Date 8 bytes Date range can be 0:00:0 (midnight)


January 1, 0001 to 11:5959 PM of
December 31, 9999.

Decimal 16 bytes Range from 0 to +/-


79,228,162,514,264,337,593,543,950,335
(+/-7.9…E+28) without any decimal
point;
And 0 to +/-
7.92281625142264337593543950335
with 28 position to the right of the decimal

Double 8 bytes -1.79769313486231570E+308 to -4.94-


65645841246544E-324 for negative
values;
4.94065645841246544E-324 to
1.79769313486231570E+308, for positive
values

Integer 4 bytes -2,147,483,648 to 2,147,483,647 (signed)

Long 8 bytes -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807 (9.2…E + 18)
(signed)

Object Object size based on the platform It can store any type of data defined in a
such as 4 bytes in 32-bit and 8 variable of type Object
bytes in 64-bit platform

SByte 1 byte -128 to 127 (signed)

Short 2 bytes -32,768 to 32,767 (signed)

Single 4 bytes -3.4028235E + 38 to -1.401298E-45 for


negative values;
And for positive value: 1.401298E-45 to
3.4028235E + 38.

String String Datatype depend on the It accepts Unicode character from 0 to

11
implementing platform approximately 2 billion characters.

User-Defined A user-defined data type depends Each member of the structure has its own
(structure) on the implementing platform data type and limits independent of the
other members' ranges.

Reference Type Vs Value Type


The data working on its own memory space. Its simply a pointer or reference to another
area of memory holding the value of the data.

Value type Reference type


Numeric, Boolean, char, and date data types String data types
Structures Arrays
Enumerations classes

Type as Classes
Data type are actually derived from the system namespace
Syntax:
Dim x as System.Object
All the objects are derived from class, and that the class can have methods, properties, fields, and
events. In .net this include all data types
Dim x as Single=123.45
Msgbox(x.ToString)

Variable
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.

Declaration variables:
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]

Dim x As Integer

Creates an Integer variable named x. We can also write:

Dim x As Integer = New Integer( )

12
When multiple variables are declared on the same line, if a variable is not declared with
an explicit type declaration, then its type is that of the next variable with an explicit type
declaration. Thus, in the line:

Dim x As Long, i, j, k As Integer, s As String

The variables i, j, and k have type Integer. (In VB 6, the variables i and j would have type
Variant, which is VB 6’s default data type.). VB.NET permits the initialization of variables in
the same line as their declaration.

Dim x As Integer = 5

To declare an Integer variable and initialize it to 5. Similarly, we can declare and


initialize more than one variable on a single line:

Dim x As Integer = 6, y As Integer = 9

To declare must explicitly be assigned a data type. You cannot assign each variable an
explicit value without explicitly declaring the data type of each variable.

Variable Default

Variable of a type without assigned a value to it, the variables has a default value based
on the type of variable have assigned as that type.

Numbers : 0 (zero)

Boolean : False

String : Nothing

Object : Nothing

Date : 12:00:00 AM

Constants

13
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

[ public | private | friend | protected | protected friend ] const constname


[as type]=expression
To Const num As Integer = 10
Static name As String
Public Const name As String = "JavaTopoint"
Private Const PI As Double = 3.14

To declare more than one variable in the same line, we must separate each variable with a
comma, as shown below.

The Syntax for defining the multiple variables as constant is:


Dim Variable_name1 As DataType1, variable_name2 As DataType2, Variable_name3
As DataType3
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

Operators

In VB.NET, operator is a special symbol that tells the compiler to perform the specific
logical or mathematical operation on the data values. The data value itself (which can be either a
variable or a constant) is called an operand, and the Operator performs various operations on the
operand.

14
For example: In the expression,
3+2-1. The symbol + and - are the Operators, and the 3, 2, and 1 are operands.

Types of Operators

o Arithmetic Operators

o Comparison Operators

o Logical and Bitwise Operators

o Bit Shift Operators

o Assignment Operators

o Concatenation Operators

Arithmetic Operators

The Arithmetic Operators in VB.NET, used to perform mathematical operations such


as subtraction, addition, multiplication, division, etc. on the operands in VB.NET. These are as
follows:

Operators Description Example

^ It is an exponentiation Operator that is used to raises one Y^X


operand to the power of another operand. (X to the
power Y)

+ The addition Operator is used to add numeric data, as well X+Y


as concatenate two string variables.

- It is a subtraction Operator, which is used to subtract the X-Y


second operand from the first operand.

* The multiplication Operator is used to multiply the X*Y


operands

/ It is a division Operator used to divide one operand by X/Y


another operand and returns a floating-point result.

15
\ It is an integer division Operator, which is similar to X\Y
division Operator, except that it returns an integer result
while dividing one operand to another operand.

Mod It is a modulo (Modulus) Operator, which is used to divide X Mod Y


two operands and returns only a remainder.

Comparison Operators

As the name suggests, the Comparison Operator is used to compare the value of two
variables or operands for the various condition such as greater, less than or equal, etc. and returns
a Boolean value either true or false based on the condition.

Operato Description Example


r

= It checks whether the value of the two operands is equal; If yes, (A = B)


it returns a true value, otherwise it shows False.

<> It is a Non-Equality Operator that checks whether the value of (A <> B),
the two operands is not equal; it returns true; otherwise, it check Non-
shows false. Equality

> A greater than symbol or Operator is used to determine whether (A > B); if
the value of the left operand is greater than the value of the yes, TRUE,
right operand; If the condition is true, it returns TRUE;
otherwise, it shows FALSE value. Else FALSE

< It is a less than symbol which checks whether the value of the (A < B); if the
left operand is less than the value of the right operand; If the condition is
condition is true, it returns TRUE; otherwise, it shows FALSE true, returns
value. TRUE else
FALSE

>= It is greater than equal to which checks two conditions whether A >= B
the first operand is greater than or equal to the second operand;
if yes, it returns TRUE; otherwise, it shows False.

<= This symbol represents less than equal to which determines the A <= B
first operand is less than or equal to the second operand, and if
the condition is true, it returns TRUE; otherwise, it shows
FALSE.

16
Is The Is Operator is used to validate whether the two objects result = obj1
reference the same variable or object; If the test is true, it Is obj2
returns True; otherwise, the result is False. In short, it checks
the equality of the objects. An Is Operator is also used to
determine whether the object refers to a valid object.

IsNot The IsNot Operator is similar to Is Operator, except that the Result = obj1
two object references the different object; if yes, the result is IsNot obj2
True; otherwise, the result is False.

Like The Like Operator is used to check the pattern expression of result = string
string variable; And if the pattern matched, the result is True; Like the
otherwise, it returns False. pattern, the
pattern
represents the
series of
characters
used by Like
Operator.

Logical and Bitwise Operators

logical and bitwise Operators work with Boolean (true or false) conditions, and if the
conditions become true, it returns a Boolean value. The following are the logical and bitwise
Operators used to perform the various logical operations such as And, Or, Not, etc. on the
operands (variables). Suppose there are two operand A and B, where A is True, and B is False.

Operator Description Example

And The And Operator represents, whether both the (A And B), result = False
operands are true; the result is True.

Or It is an Or Operator that returns a true value; if (A Or B), result = True


anyone operand is true from both the operands.

Not The Not Operator is used to reverse the logical Not A


condition. For example, if the operand's logic is
True, it reveres the condition and makes it False. Or

Not(A And B) is True

Xor It is an Exclusive OR Operator that represents, A Xor B is True


whether both the expression is true or false, the
result is True; otherwise, the result is False.

17
AndAlso It is a logical AND Operator that performs short- A AndAlso B = False
circuit operation on the variables, and if both the
operands are true, the result is True else the result is
False.

OrElse It is a logical OR Operator that perform short-circuit A OrElse B = True


operation on Boolean data. If anyone of the operand
is true, the result is True else the result is False.

IsFalse The IsFalse Operator is used to determine whether


an expression is False.

IsTrue The IsTrue Operator is used to determine whether an


expression is True.

Bit Shift Operators

The Bit Shit Operators are used to perform the bit shift operations on binary values either
to the right or to the left.

Bit Shift operations in VB.NET

Operator Description

AND The Binary AND Operator are used to copy the common binary bit in the
result if the bit exists in both operands.

OR The Binary OR Operator is used to copy a common binary bit in the result if
the bit found in either operand.

XOR The Binary XOR Operator in VB.NET, used to determine whether a bit is
available to copy in one operand instead of both.

Not The binary NOT Operator is also known as the binary Ones' Compliment
Operator, which is used to flip binary bits. This means it converts the bits from
0 to 1 or 1 to 0 binary bits.

<< The Binary Left Shift Operator is used to shift the bit to the left side.

>> The Binary Right Shift Operator is used to shift the bit to the right side.

Assignment Operators

The Assignment Operators are used to assign the value to variables in VB.NET.

18
Operato Description Example
r

= It is a simple assignment Operator used to assign a right- X = 5, X assign a value 5


side operand or value to a left side operand. X = P + Q, (P + Q)
variables or value assign
to X.

+= An Add AND assignment Operator is used to add the value X += 5, which means
of the right operand to the left operand. And the result is X= X+5 ( 5 will add and
assigned to the left operand. assign to X and then
result saved to Left X
operand)

-= It is a Subtract AND assignment Operator, which subtracts X -= P, which is same as


the right operand or value from the left operand. And then, X=X-P
the result will be assigned to the left operand.

*= It is a Multiply AND assignment Operator, which X *= P, which is same as


multiplies the right operand or value with the left operand. X=X-P
And then, the result will be assigned to the left operand.

/= It is a Divide AND assignment Operator, which divides the X /= P, which is same as


left operand or value with the right operand. And then, the X=X-P
result will be assigned to the left operand (in floating-
point).

\= It is a Divide AND assignment Operator, which divides the X \= P, which is same as


left operand or value with the right operand. And then, the X=X-P
result will be assigned to the left operand (in integer-point
division).

^= It is an expression AND assignment Operator, which raises X ^= P, which is same as


the left operand or value to the right operand's power. And X=X^P
then, the result will be assigned to the left operand.

&= It is a concatenate string assignment Operator used to bind Str &= name, which is
the right-hand string or variable with the left-hand string or same as Str = Str &
variable. And then, the result will be assigned to the left name
operand.

Concatenation Operators

In VB.NET, there are two concatenation Operators to bind the operands:

19
Operato Description Example
r

& It is an ampersand symbol that is used to bind two Result = Wel & come,
or more operand together. Furthermore, a nonstring Result = Welcome
operand can also be concatenated with a string
variable ( but in that case, Option Strict is on).

+ It is also used to add or concatenate two number or Result = Wel + come,


string. Result = Welcome

Operator Precedence in VB.NET

Operator precedence is used to determine the order in which different Operators in a


complex expression are evaluated. There are distinct levels of precedence, and an Operator may
belong to one of the levels. The Operators at a higher level of precedence are evaluated first.
Operators of similar precedents are evaluated at either the left-to-right or the right-to-left level.

The Following table shows the operations, Operators and their precedence -

Operations Operators Precedence

Await Highest

Exponential ^

Unary identity and negation +, -

Multiplication and floating-point *, /


division

Integer division \

Modulus arithmetic Mod

Addition and Subtraction +, -

Arithmetic bit shift <<, >>

All comparison Operators =, <>, <, <=, >,


>=, Is, IsNot,
Like, TypeOf …is

Negation Not

20
Conjunction And, AndAlso

Inclusive disjunction Or, Else

Exclusive disjunction Xor Lowest

Example Program of Operator Precedence in VB.NET.

Module Operator_Precedence
Sub Main()
'Declare and Initialize p, q, r, s variables
Dim p As Integer = 30
Dim q As Integer = 15
Dim r As Integer = 10
Dim s As Integer = 5
Dim result As Integer
Console.WriteLine("Check Operator Precedence in VB.NET")
'Check Operator Precedence
result = (p + q) * r / s ' 45 * 10 / 5
Console.WriteLine("Output of (p + q) * r / s is : {0}", result)
result = (p + q) * (r / s) ' (45) * (10/5)
Console.WriteLine("Output of (p + q) * (r / s) is : {0}", result)
result = ((p + q) * r) / s ' (45 * 10 ) / 5
Console.WriteLine("Output of ((p + q) * r) / s is : {0}", result)
result = p + (q * r) / s ' 30 + (150/5)
Console.WriteLine("Output of p + (q * r) / s is : {0}", result)
result = ((p + q * r) / s) ' ((30 + 150) /5)
Console.WriteLine("Output of ((p + q * r) / s) is : {0}", result)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module

ARRAY

21
An array is a linear data structure that is a collection of data elements of the same type
stored on a contiguous memory location. Each data item is called an element of the array. It is a
fixed size of sequentially arranged elements in computer memory with the first element being
at index 0 and the last element at index n - 1, where n represents the total number of elements in
the array.

The following is an illustrated representation of similar data type elements defined in the
VB.NET array data structure.

In the above diagram, we store the Integer type data elements in an array starting at index 0. It
will continue to store data elements up to a defined number of elements.

Declaration of VB.NET Array

Syntax:

Dim array_name As [Data_Type] ()

In the above declaration, array_name is the name of an array, and the Data_Type represents the
type of element (Integer, char, String, Decimal) that will to store contiguous data elements in the
VB.NET array.

'Store only Integer values

Dim num As Integer() or Dim num(5) As Integer

Initialization of VB.NET Array

In VB.NET, we can initialize an array with New keyword at the time of declaration. For
example,

1. 'Declaration and Initialization of an array elements with size 6


1. Dim num As Integer() = New Integer(5) { }
2. Dim num As Integer() = New Integer(5) {1, 2, 3, 4, 5, 6}
3. Initialize an array with 5 elements that indicates the size of an array
4. Dim arr_name As Integer() = New Integer() {5, 10, 5, 20, 15}

22
5. Declare an array
6. Dim array1 As Char()
7. array1 = New Char() {'A', 'B', 'C', 'D', 'E'}

We can also initialize and declare an array using the following ways, as shown below.

1. Dim intData() As Integer = {1, 2, 3, 4, 5}


2. Dim intData(5) As Integer
3. Dim array_name() As String = {"Peter", "John", "Brock", "James", "Maria"}
4. Dim misc() as Object = {"Hello friends", 16c, 12ui, "A"c}
5. Dim Emp(0 to 2) As String
6. Emp{0} = "Mathew"
7. Emp(1) = " Anthony"
8. Emp(2) = "Prince"

9. Module num_Array
10. Sub Main()
11. Dim i As Integer, Sum As Integer = 0
12. 'In VB.NET the size of an array is n+1
13. 'Declaration and Initialization of marks() array
14. Dim marks() As Integer = {58, 68, 95, 50, 23, 89}
15. Console.WriteLine(" Marks in 6 Subjects")
16. For i = 0 To marks.Length - 1
17. Console.WriteLine(" Marks {0}", marks(i))
18. Sum = Sum + marks(i)
19. Next
20. Console.WriteLine(" Grand total is {0}", Sum)
21.
22. Console.WriteLine(" Press any key to exit...")
23. Console.ReadKey()
24. End Sub
23
25. End Module

Multidimensional Array

In VB.NET, a multidimensional array is useful for storing more than one dimension in a
tabular form, such as rows and columns. The multidimensional array support two or three
dimensional in VB.NET.

Declaration of Multidimensional Array

1. Declaration of two-dimensional array


2. Dim twoDimenArray As Integer( , ) = New Integer(3, 2) {}
3. Or Dim arr(5, 3) As Integer
4. Representation of Three Dimensional array
5. Dim arrThree(2, 4, 3) As Integer
6. Or Dim arr1 As Integer( , , ) = New Integer(5, 5, 5) { }

Fixed Size Array

In VB.NET, a fixed- size array is used to hold a fixed number of elements in memory. It
means that we have defined the number of elements in the array declaration that will remain the
same during the definition of the elements, and its size cannot be changed. For example, we need
to hold only 5 names in an array; it can be defined and initialized in the array such as,

1. Dim names( 0 to 4) As String


2. names(0) = "Robert"
3. names(1) = "Henry"
4. names(2) = "Rock"
5. names(3) = "James"
6. names(4) = "John"

The above representation of the fixed array is that we have defined a string array names 0 to 4,
which stores all the elements in the array from 0 to index 4.

Dynamic Arrays

Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the need of
the program. To declare a dynamic array using the ReDim statement.

24
Syntax for ReDim statement −

ReDim [Preserve] arrayname(subscripts)

Where,

 The Preserve keyword helps to preserve the data in an existing array, when you resize it.
 arrayname is the name of the array to re-dimension.
 subscripts specifies the new dimension.

The Array Class

The Array class is the base class for all the arrays in VB.Net. It is defined in the System
namespace. The Array class provides various properties and methods to work with arrays.

Properties of the Array Class

The following table provides some of the most commonly used properties of the Array class
Sr.No Property Name & Description

1 IsFixedSize
Gets a value indicating whether the Array has a fixed size.

2 IsReadOnly
Gets a value indicating whether the Array is read-only.

Length
3 Gets a 32-bit integer that represents the total number of elements in all the dimensions of the
Array.

LongLength
4 Gets a 64-bit integer that represents the total number of elements in all the dimensions of the
Array.

5 Rank
Gets the rank (number of dimensions) of the Array.

Methods of the Array Class

The following table provides some of the most commonly used methods of the Array class
Sr.No Method Name & Description

1 Public Shared Sub Clear (array As Array, index As Integer, length As Integer)
Sets a range of elements in the Array to zero, to false, or to null, depending on the element

25
type.

Public Shared Sub Copy (sourceArray As Array, destinationArray As Array, length As


2 Integer)
Copies a range of elements from an Array starting at the first element and pastes them into
another Array starting at the first element. The length is specified as a 32-bit integer.

Public Sub CopyTo (array As Array, index As Integer)


3 Copies all the elements of the current one-dimensional Array to the specified one-dimensional
Array starting at the specified destination Array index. The index is specified as a 32-bit
integer.

Public Function GetLength (dimension As Integer) As Integer


4 Gets a 32-bit integer that represents the number of elements in the specified dimension of the
Array.

Public Function GetLongLength (dimension As Integer) As Long


5 Gets a 64-bit integer that represents the number of elements in the specified dimension of the
Array.

6 Public Function GetLowerBound (dimension As Integer) As Integer


Gets the lower bound of the specified dimension in the Array.

7 Public Function GetType As Type


Gets the Type of the current instance (Inherited from Object).

8 Public Function GetUpperBound (dimension As Integer) As Integer


Gets the upper bound of the specified dimension in the Array.

Public Function GetValue (index As Integer) As Object


9 Gets the value at the specified position in the one-dimensional Array. The index is specified
as a 32-bit integer.

Public Shared Function IndexOf (array As Array,value As Object) As Integer


10 Searches for the specified object and returns the index of the first occurrence within the entire
one-dimensional Array.

11 Public Shared Sub Reverse (array As Array)


Reverses the sequence of the elements in the entire one-dimensional Array.

Public Sub SetValue (value As Object, index As Integer)


12 Sets a value to the element at the specified position in the one-dimensional Array. The index
is specified as a 32-bit integer.

Public Shared Sub Sort (array As Array)


13 Sorts the elements in an entire one-dimensional Array using the IComparable implementation
of each element of the Array.

26
14 Public Overridable Function ToString As String
Returns a string that represents the current object (Inherited from Object).

Control Statements

In VB.NET, the control statements are the statements that controls the execution of the
program on the basis of the specified condition. It is useful for determining whether a condition
is true or not. If the condition is true, a single or block of statement is executed. In the control
statement, we will use if- Then, if Then Else, if Then ElseIf and the Select case statement.

If the defined condition is true, the statement or block executes according to the
condition, and if the condition is false, another statement is executed.

VB.NET provides the following conditional or decision-making statements.

o If-Then Statement

o If-Then Else Statement

o If-Then ElseIf Statement

o Select Case Statement

o Nested Select Case Statements

If-Then Statement

The If-Then Statement is a control statement that defines one or more conditions, and if
the particular condition is satisfied, it executes a piece of information or statements.

Syntax:

If condition Then
[Statement or block of Statement]
End If

In If-Then Statement, the condition can be a Boolean, logical, or relational condition, and the
statement can be single or group of statements that will be executed when the condition is true.

If-Then-Else Statement

27
The If-Then Statement can execute single or multiple statements when the condition is
true, but when the expression evaluates to false, it does nothing. So, here comes the If-Then-
Else Statement. The IF-Then-Else Statement is telling what If condition to do when if the
statement is false, it executes the Else statement. Following is the If-Then-Else statement syntax
in VB.NET as follows:

Syntax:

If (Boolean_expression) Then
[This statemen]t will execute if the Boolean condition is true
Else
[Optional statement] will execute if the Boolean condition is false
End If

VB.NET If-Then-ElseIf statement

The If-Then-ElseIf Statement provides a choice to execute only one condition or


statement from multiple statements. Execution starts from the top to bottom, and it checked for
each If condition. And if the condition is met, the block of If the statement is executed. And if
none of the conditions are true, the last block is executed. Following is the syntax of If-Then-
ElseIf Statement in VB.NET as follows:

Syntax

If(condition 1)Then
' Executes when condition 1 is true
ElseIf( condition 2)Then
' Executes when condition 2 is true
ElseIf( boolean_expression 3)Then
' Executes when the condition 3 is true
Else
' executes the default statement when none of the above conditions is true. End If

Select Case Statement

In VB.NET, the Select Case statement is a collection of multiple case statements, which
allows executing a single case statement from the list of statements. Using the select case
statement in VB.NET programming, you can replace the uses of multiple If-Then-Else If
statement from the program for better readability and easy to use.
28
Syntax

Select Case [variable or expression]


Case value1 'defines the item or value that you want to match.
// Define a statement to execute
Case value2 'defines the item or value that you want to match.
// Define a statement to execute
Case Else
// Define the default statement if none of the conditions is true.
End Select

VB.NET Nested Select Case statements

When a Select Case statement is written inside the body of another Select Case
statement is called a nested Select Case statement.

Syntax:

Select Case "num"


' code to be executed if num = 1
Case 1
' nested Select case
Select Case n
' code to be executed if n = 5
Case 5
Statement 1
' code to be executed if n = 10
Case 10
Statement 2
' code to be executed if n = 15
Case 15
Statement 3
' code to be executed if n doesn't match with any cases.
Case Else
Statement
29
' code to be executed if num = 2
Case 2
Statement 2

' code to be executed if num = 3


Case 3
Statement 3
' code to be executed if num doesn't match with any cases.
Case Else
Statement

VB.NET Do Loop

A Loop is used to repeat the same process multiple times until it meets the specified
condition in a program. By using a loop in a program, a programmer can repeat any number of
statements up to the desired number of repetitions. A loop also provides the suitability to a
programmer to repeat the statement in a program according to the requirement. A loop is also
used to reduce the program complexity, easy to understand, and easy to debug.

Advantages of VB.NET loop

o It provides code iteration functionality in a program.

o It executes the statement until the specified condition is true.

o It helps in reducing the size of the code.

o It reduces compile time.

Types of Loops

There are five types of loops available in VB.NET:

o Do While Loop

o For Next Loop

o For Each Loop

o While End Loop

o With End Loop

30
Do While Loop

In VB.NET, Do While loop is used to execute blocks of statements in the program, as


long as the condition remains true. It is similar to the While End Loop, but there is slight
difference between them. The while loop initially checks the defined condition.

If the condition becomes true, the while loop's statement is executed. Whereas in
the Do loop, is opposite of the while loop, it means that it executes the Do statements, and then it
checks the condition.

Syntax:

Do
[ Statements to be executed]
Loop While Boolean_expression
// or
Do
[Statement to be executed]
Loop Until Boolean_expression

For Next Loop

A For Next loop is used to repeatedly execute a sequence of code or a block of code until
a given condition is satisfied. A For loop is useful in such a case when we know how many times
a block of code has to be executed. In VB.NET, the For loop is also known as For Next Loop.

Syntax

For variable_name As [ DataType ] = start To end [ Step step ]


[ Statements to be executed ]
Next
o For: It is the keyword that is present at the beginning of the definition.

o variable_name: It is a variable name, which is required in the For loop Statement. The
value of the variable determines when to exit from the For-Next loop, and the value
should only be a numeric.
o [Data Type]: It represents the Data Type of the variable_name.

o start To end: The start and end are the two important parameters representing the initial
and final values of the variable_name. These parameters are helpful while the execution

31
begins, the initial value of the variable is set by the start. Before the completion of each
repetition, the variable's current value is compared with the end value. And if the value of
the variable is less than the end value, the execution continues until the variable's current
value is greater than the end value. And if the value is exceeded, the loop is terminated.
o Step: A step parameter is used to determine by which the counter value of a variable is
increased or decreased after each iteration in a program. If the counter value is not
specified; It uses 1 as the default value.
o Statements: A statement can be a single statement or group of statements that execute
during the completion of each iteration in a loop.
o Next: In VB.NET a Next is a keyword that represents the end of the For loop's

VB.NET For Each Loop

In the VB.NET, For Each loop is used to iterate block of statements in an array or
collection objects. Using For Each loop, we can easily work with collection objects such as lists,
arrays, etc., to execute each element of an array or in a collection. And when iteration through
each element in the array or collection is complete, the control transferred to the next statement
to end the loop.

Syntax:

For Each var_name As [ DataType ] In Collection_Object


[ Statements to be executed]
Next

For Each loop is used to read each element from the collection object or an array.
The Data Type represents the type of the variable, and var_name is the name of the variable to
access elements from the array or collection object so that it can be used in the body of For
Each loop.

VB.NET With End With Statement

In VB.NET, the With End statement is not the same as a loop structure. It is used to
access and execute statements on a specified object without specifying the name of the objects
with each statement. Within a With statement block, you can specify a member of an object that
begins with a period (.) to define multiple statements.

Syntax:

With objExpression
32
[ Statements to be Executed]
End With

objExpression: It defines the data type of objExpression. It may be any class or structure type
or basic data type such as Integer. It can be executed once in the With End statement.

Statement: It defines one or more executed statements within the With block. The statement
refers to the member of the object that links with objectExpression to execute the With
statement block.

End With: It is used to end the With block.

33

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy