Você está na página 1de 56

Language Fundamentals

VB.NET .NET Programming


Contents

VB.NET Source File Structure


VB.NET Keywords
Identifiers
Literals
Variables and Data Types
Variable Declaration and Initialization
Operators
Casting
Flow Controls

2
Objectives

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


Recognize and create properly constructed source code
Recognize and create properly constructed declarations
Distinguish between legal and illegal identifiers
Describe all value data types and their range
Recognize properly formatted data types
Declare and initialize variables
Understand the contents of the argument list of an applications Main()
method
Recognize and properly use operators
Identify object, shift and bitwise operators
Identify the order of evaluation and change its precedence
Cast primitive data types
Recognize the syntax and correct use of flow controls
Describe the concept of return statement

3
Agenda

Fundamentals
Operators
Flow Controls

4
VB.NET Source File Structure
Declaration order
1. Imports statement '
Used to reference namespace. ' * Created on Feb 22, 2006
When class names are to be referred in the ' * First VB.NET Program
imports directive, aliases for the classes can '
be used.
Imports System
using alias-name = namespace.class-name
Imports A = System.Console

2. Namespace declaration Namespace VBNETSchool


Public Class VBNetOne
Used to logically group similar classes that
''' <summary>
have related functionality. In VB.NET you need
''' </summary>
to declare each class in a namespace. By
''' <param name="args"></param>
default namespace is automatically created with
Public Shared Sub Main(ByVal args As
the same name as that of the project. String())
VBNETSchool is the namespace and ' print a message
VBNETOne class is contained in the A.WriteLine("Welcome to VB.NET!")
namespace. End Sub
3. Class declaration End Class
A VB.NET source file can have several
End Namespace
classes but only one class can have the Main
method
5
VB.NET Source File Structure (Continued)
Comments '
' * Created on Feb 22, 2006
1. Single-line Comment ' * First VB.NET Program
'
' insert comments here
Imports System
2. Documentation Comment Imports A = System.Console
''' <summary>
''' </summary> Namespace VBNETSchool
''' <param Public Class VBNetOne
name="args"></param> ''' <summary>
''' </summary>
''' <param name="args"></param>
Public Shared Sub Main(ByVal args As
String())
' print a message
A.WriteLine("Welcome to VB.NET!")
End Sub
Whitespaces End Class

Tabs and spaces are ignored by End Namespace


the compiler. They are used to
improve the readability of code.

6
VB.NET Source File Structure (Continued)

'
Class ' * Created on Feb 22, 2006
' * First VB.NET Program
Every VB.NET program '
includes at least one class
definition. The class is the Imports System
fundamental component of all Imports A = System.Console
VB.NET programs. Class is a
keyword Namespace VBNETSchool
Public Class VBNetOne
VBNetOne is a VB.NET
''' <summary>
identifier that specifies the
''' </summary>
name of the class to be
''' <param name="args"></param>
defined
Public Shared Sub Main(ByVal args As String())
' print a message
A class definition contains all A.WriteLine("Welcome to VB.NET!")
the variables and methods End Sub
that make the program work. End Class
This is contained in the class
body indicated by the opening End Namespace
and closing braces.

7
VB.NET Source File Structure (Continued)
'
' * Created on Feb 22, 2006
Main() method ' * First VB.NET Program
'
This line begins the Main() Imports System
method. This is the line at which Imports A = System.Console
the program will begin executing.
Namespace VBNETSchool
Public Class VBNetOne
''' <summary>
''' </summary>
''' <param name="args"></param>
Public Shared Sub Main(ByVal args As String())
ByVal args As ' print a message
String() A.WriteLine("Welcome to VB.NET!")
Declares a parameter named End Sub
args, which is an array of string. End Class
It represents command-line
arguments. End Namespace

8
VB.NET Source File Structure (Continued)
'
' * Created on Feb 22, 2006
' * First VB.NET Program
VB.NET
'
statement
A complete unit of work in a Imports System
VB.NET program. Imports A = System.Console
A statement is always
terminated with a line break. Namespace VBNETSchool
Except when the _ character is Public Class VBNetOne
used. ''' <summary>
''' </summary>
Console.WriteLine(); ''' <param name="args"></param>
Public Shared Sub Main(ByVal args As String())
' print a message
This line outputs the string A.WriteLine _
Welcome to VB.NET! followed ("Welcome to VB.NET!")
by a new line on the screen. End Sub
End Class

End Namespace

9
VB.NET Keywords
Keywords are an essential part of language definition as they implement
specific features of the language.

AddHandler AddressOf Alias And As Assembly

Auto Boolean ByRef Byte AndAlso Ansi

ByVal Call Case Catch While Unicode

CBool CByte CChar CDate With Until

CDec CDbl Char CInt WithEvents Variant

Class CLng CObj Const WriteOnly When

CShort CSng CStr CType To Sub

Date Decimal Declare Default True SyncLock

Delegate Dim DirectCast Do Try Then

Double Each Else ElseIf TypeOf Throw

10
VB.NET Keywords

Event Exit False Finally Stop Short

End Enum Erase Error Step Shared

For Friend Function Get String Single

GetType GoSub GoTo Handles Structure Static

If Implements Imports In Return ReDim

Inherits Integer Interface Is Select REM

Let Lib Like Long Set RemoveHandler

Loop Me Mod Module Shadows Resume

MustInherit MustOverride MyBase MyClass Protected ParamArray

Namespace New Next Not Public Preserve

Nothing NotInheritable NotOverridable Object RaiseEvent Private

On Option Optional Or ReadOnly Property

OrElse Overloads Overridable Overrides

11
Identifiers

An identifier is the name given by a programmer to a variable, statement


label, method, class, and interface.
An identifier must begin with a letter
Subsequent characters must be letters, digits or _ (underscore)
An identifier must not be a VB.NET keyword
Identifiers are case-insensitive
Keywords can be used as identifiers when they are enclosed in the [ ]
characters
Incorrect Correct
3strikes strikes3
Write&Print Write_Print

printMe is the same as PrintMe

12
Literals

Literals are the way in which the values that are stored in variables are
represented.
VB.NET Literals

Numeric Literals Boolean Literals Character Literals

Integer Literals Real Literals Single character Literals String Literals

13
Variable and Data Types

A variable is a named storage location used to represent data that


can be changed while the program is running.
A data type determines the values that a variable can contain and the
operations that can be performed on it.
Categories of data types include:
Value types
Reference types
pointers (used only in unsafe code)

14
Data Types

VB.NET Data Types

Value Types Reference Types


Pointers

Predefined User-defined Predefined User-defined


Types Types Types Types

Integers Enumerations Objects Classes


Real Integers Structures Strings Arrays
Booleans Delegates
Characters Interfaces
15
Value Data Types

Predefined value types are also known as simple types (or primitive types).

SimpleTypes

Boolean Types Numeric Types Character Types

Integral Decimal
Floating Point
Types Types
Types

Signed Unsigned

Types Types

16
Data Types

Signed Integers UnSigned Integers

sbyte byte

short ushort

int uint

long ulong

17
Value Data Types

FloatingPoint Floatingpoint types


Are used to hold numbers containing fractional parts.
Types
There are two types:
float (single precision numbers)
double (double precision numbers)

float double

Floatingpoint types support a special value known as Not-a-


Number(NaN). NaN is used to represent results of operations such as
dividing zero by zero, where an actual number is not produced.

18
Value Data Types (Continued)

Decimal Type
Is a high precision 128-byte data type that is designed for use in financial and
monetary calculations.
It can store values in the range 1.0 10e28 to 7.9 10e28.
To specify a number to be decimal type, append the character M (or m) to the
value e.g 123.45M.
Boolean Types
Are declared using the keyword, bool.
They have two values: true or false. In languages, such as C and C++, boolean
conditions can be satisfied where 0 means false and anything else means true.
In VB.NET the only values that satisfy a boolean condition is true and false,
which are official keywords.
Character Types
Are declared using the keyword char.
char type assumes a size of two bytes but can hold only a single character.
It is designed to hold a 16bit Unicode character.

19
Value Data Types (Continued)

Structures Syntax: Structure struct-name

Are similar to classes. member1 as data


member2 as data
Are used for simple composite data types.
Structure keyword is used to declare
End Structure
structures.
E.g.. Structure Student
Variables are known as members or fields or Public Name As String
elements. Public ID As Integer
Public TotalMark As Double
s1 is a variable type of structure Student. End Structure

Member variables can be accessed using dot


notation. Dim s1 as Student declare a student

s1.Name = John
S1.RollNumber = 0200789

20
Value Data Types (continued)

Enumerations
Are a user-defined integer type which provides a way to attach names to
numbers.
Help increase comprehensibility of the code.
The enum keyword is used to define an enumeration.
A list of words in an enum is automatically assigned values of 0,1,2, etc.
The default value of the first enum member is set to 0 while each subsequent
member is incremented by one
Can be changed by assigning specific values to the members.

Syntax: Enum enum-name E.g. Enum Color


word1 Red = 10
word2 Blue = 20
word3 Green = 100
End Enum
End Enum

21
Reference Data Types

Reference data types represent objects.


A reference serves as a handle to the object, it is a way to get to the
object.
VB.NET reference data types are divided into two types:
User-defined (or complex) types
Class
Interfaces
Delegates
Arrays
Predefined (or simple) types
Object type
String type

22
Variables

Default Values
Variables are either explicitly assigned a value or automatically assigned a
default value.

23
Constant Variables

Variables whose values do not change during execution of a program.


Use the Const keyword to initialize
Constants must be declared and initialized simultaneously
Constants can be initialized using an expression
Constants cannot use non-const values in an expression
Const age As Integer = 21

Const age As Integer Is illegal


age = 21

Const m As Integer = 10
Const age As Integer = m * 5
Is illegal
Dim m As Itneger= 10
Const age as Integer = m * 5
24
Variable Declaration & Initialization

To declare a variable with value data type:

Dim age As Integer = 21

identifier primitive initial


name type value

To declare a variable with reference data type:

Dim b1 As Box = new Box();


Dim name As String = Jason;

identifier reference initial


name type value

25
Value Type Declaration

declaration allot space to memory MEMORY


Dim age As Integer

Identifier type
name age 07
1

initialization/assignment
age = 17

Identifier value
name stack

26
Reference Type Declaration

allot space to memory


Dim myCar As Car; memory address
myCar
location

type Identifier reference


name
The heap

myCar = new Car(Bumble Bee);


Bumble Bee
Values
Identifier
name
Car object

27
Scope of Variable

Member Variables ..
Declared inside the class but Public Class TestClass
outside of all methods.
Accessible by all methods of Dim x as Integer =0
the class. Public Sub TestSub
Dim n As Integer =5 Ok
Block2
Dim x As Integer =0 Ok
Local Variables .
Available only within the End Sub
Block1
method where they were
declared. Method parameters Public Sub Sub2
have local scope. n = n+1 wrong, n not available here


Block3
Dim m As Integer = 20 ok
x = m ok
End Sub

End Class

28
Boxing and UnBoxing

Boxing Public Shared Sub Main()


Is a data type conversion technique that is used Dim x As Integer = 10
implicitly to convert a value type to either an Dim obj1 As Object = x
object type or a reference type. x = 456
Console.WriteLine(x)
Console.WriteLine(obj1)
UnBoxing End Sub
Is the opposite of boxing. It is a data type
conversion technique that is used explicitly to
convert an object type to a value type.
Public Shared Sub Main()
Dim x As Integer = 10
Dim obj1 As Object = x
Dim y As Integer = CType(obj1,
Integer)
Console.WriteLine(y)
End Sub

29
Agenda

Fundamentals
Operators
Flow Controls

30
Operators and Assignments

Unary operators
Arithmetic operators
String operators
Relational operators
Conditional operators
Logical operators
Assignment operators
Shift operators
Bitwise operators
Primitive Casting

31
Unary Operators

Unary operators use only one operand.


+ Positive sign

- Negative sign

Sample code: Sample output:


Dim num as Integer =10 setting signs...
10
System.Console.WriteLine("setting signs) -10
System.Console.WriteLine(+num)
System.Console.WriteLine(-num)

32
Arithmetic Operators

Arithmetic operators are used for basic mathematical operations.


+ Add

- Subtract

* Multiply

/ Divide

Mod Modulo, remainder

Sample code: Sample output:


Dim num1 as Integer =15 calculating...
Dim num2 as Integer =10 25
5
System.Console.WriteLine("calculating...") 150
System.Console.WriteLine(num1 + num2) 1
System.Console.WriteLine(num1 - num2) 5
System.Console.WriteLine(num1 * num2)
System.Console.WriteLine(num1 / num2)
System.Console.WriteLine(num1 Mod num2)

33
String Operators

The string operator (+, &) is used to concatenate operands.


If one operand is string, the other operands are converted to string.
The & operand can also be used to concatenate strings.

Sample code:

Dim fname As String = Henry


Dim lname As String = Ford
Dim mi As String = D"
Dim fullName as String = lname + ", " + fname + " " + mi + "."
Dim nickName As String = Henry"
Dim age as Integer = 21

System.Console.WriteLine("My full name is: " + fullName)


System.Console.WriteLine("You can call me " + nickName + "!")
System.Console.WriteLine("I'm " + age + " years old.")

Sample output:
My full name is: Ford, Henry D.
You can call me Henry!
I'm 21 years old.
34
Relational Operators

Relational operators are used to compare values.


boolean values cannot be compared with non-boolean values.
Only object references are checked for equality, and not their states.
Objects cannot be compared with null.
null is not the same as .

< Less than

<= Less than or equal to

> Greater than

>= Greater than or equal to

= Equals

<> Not equals

35
Relational Operators
Sample code:
Dim name1 As String = "Marlon"
Dim weight1 As Integer = 140, height1 As Integer = 74
Dim name2 As String = "Katie"
Dim weight2 As Integer = 124, height2 As Integer = 78
Dim isLight As Boolean = weight1 < weight2, isLightEq As Boolean = weight1 <= weight2
System.Console.WriteLine("Is " + name1 + " lighter than " + name2 + "? " + isLight)
System.Console.WriteLine("Is " + name1 + " lighter or same weight as " + name2 + "? " +
isLightEq)
Dim isTall As Boolean = height1 > height2, isTallEq As Boolean = height1 >= height2
System.Console.WriteLine("Is " + name1 + " taller than " + name2 + "? " + isTall)
System.Console.WriteLine("Is " + name1 + " taller or same height as " + name2 + "? " +
isTallEq)
Dim isWeighEq As Boolean = weight1 = weight2, isTallNotEq As Boolean = height1 <> height2
System.Console.WriteLine("Is " + name1 + " same weight as " + name2 + "? " + isWeighEq)
System.Console.WriteLine("Is " + name1 + " not as tall as " + name2 + "? " + isTallNotEq)
System.Console.WriteLine("So who is heavier?")
System.Console.WriteLine("And who is taller?") Is Marlon lighter than Katie? false

Sample output: Is Marlon lighter or same weight as Katie? false


Is Marlon taller than Katie? false
Is Marlon taller or same height as Katie? false
Is Marlon same weight as Katie? false
Is Marlon not as tall as Katie? true
So who is heavier?
And who is taller? 36
Logical Operators
Not logical NOT
Logical operators are used to compare
boolean expressions. AND logical AND

Not inverts a boolean value. OR logical OR

AND and OR evaluate both operands. AndAlso Same as And except


that once a false is
found it will not
continue checking the
succeeding
conditions.
Truth Table OrElse Same as Or except
that once a false is
Op1 And Op1 Or
Op1 Op2 Not Op1 found it will not
Op2 Op2
continue checking the
false false true false false succeeding
conditions.
false true true false true

true false false false true

true true false true true

37
Logical Operators

Sample output: Are you a candidate for promotion? true


Sample code: Will you be promoted as a regular employee? false
Will you be promoted as a supervisor? false
Dim yrsService As Integer = 8 Will you be promoted as a manager? true
Dim perfRate As Double = 86 Will you be paid more and work less? false
Dim salary As Double = 23000 I hope you won't be demoted, are you? false
Dim position As Char = "S"C
' P-probationary R-regular, S-supervisor, M-manager, E-executive, T-top executive
Dim forRegular As Boolean, forSupervisor As Boolean, forManager As Boolean, forExecutive As
Boolean, forTopExecutive As Boolean
forRegular = yrsService > 1 And perfRate > 80 And position = "P"C And salary < 10000
forSupervisor = yrsService > 5 And perfRate > 85 And position = "R"C And salary < 15000
forManager = yrsService > 7 And perfRate > 85 And position = "S"C And salary < 25000
forExecutive = yrsService > 10 And perfRate > 80 And position = "M"C And salary < 50000
forTopExecutive = yrsService > 10 And perfRate > 80 And position = "E"C And salary < 75000
Dim isPromoted As Boolean = forRegular OrElse forSupervisor OrElse forManager OrElse
forExecutive OrElse forTopExecutive
Dim isLuckyGuy As Boolean = forExecutive Xor forTopExecutive
System.Console.WriteLine("Will you be promoted as a regular employee? " + forRegular)
System.Console.WriteLine("Are you a candidate for promotion? " + isPromoted)
System.Console.WriteLine("Will you be promoted as a supervisor? " + forSupervisor)
System.Console.WriteLine("Will you be promoted as a manager? " + forManager)
System.Console.WriteLine("Will you be paid more and work less? " + isLuckyGuy)
System.Console.WriteLine("I hope you won't be demoted, are you? " + Not isPromoted)
38
Assignment Operators
Sample code:
Assignment operators Dim unitPrice As Double = 120, qty As Double = 2,
salesAmount As Double
are used to set the Dim discRate As Double = 15, discAmount As Double,
value of a variable. vatRate As Double = 10, vatAmount As Double
' compute gross sales
= Assign salesAmount = unitPrice * qty
System.Console.WriteLine("Gross Sales: " + salesAmount)
+= Add and assign ' compute tax
vatRate /= 100
-= Subtract and assign vatAmount = salesAmount * vatRate
salesAmount += vatAmount
*= Multiply and assign
System.Console.WriteLine("Tax: " + vatAmount)
/= ' compute discount
Divide and assign
discRate /= 100
discAmount = salesAmount * discRate
salesAmount -= discAmount
&= AND and assign System.Console.WriteLine("Discount: " + discAmount)
System.Console.WriteLine("Please pay: " + salesAmount)
|= OR and assign

^= XOR and assign Sample output:


Gross Sales: 240.0
Tax: 24.0
Discount: 39.6
Please pay: 224.4 39
Casting (Type Conversion)

Casting is conversion from one data type to another which include:


Implicit casting
Explicit casting
Implicit Conversion is the conversion of one data type to another data
type without any loss of data.

40
Casting (Type Conversion)

Explicit Conversion is the conversion of one data type to another


data type with loss of data.

Explicit conversions can be carried out using the Ctype function.


Syntax: E.g.. Dim amount As Single = 50
Type variable1 = Dim totAmount As Long =
Ctype(variable2,type); CType(amount, Long)

41
Summary of Operators

Evaluation order of operators in VB.NET is as follows:


Unary
Arithmetic
Comparison
Bitwise
Logical Operators
Assignment

42
Agenda

Fundamentals
Operators
Flow Controls

43
Flow Controls

If-Else statement
Select statement
While statement
Do-While statement
For statement
For Each statement
Exit statement
Continue statement

44
If-Else

If-Else performs Syntax:


statements based on two If condition1 Then

conditions. ElseIf condition2 Then


Condition should result
Else
to a boolean expression.
End If
If condition is true, the
statements following if are Dim age As Integer = 10
executed. If age < 10 Then
System.Console.WriteLine("You're just a kid.")
If condition is false, the ElseIf age < 20 Then
statements following else System.Console.WriteLine("You're a teenager.")
Else
are executed. System.Console.WriteLine("You're probably
If-Else can be nested to old...")
End If
allow more conditions.
Output:
You're a teenager.

45
Select
Syntax:
Select performs Select Case exp
statements based on Case val
'Do something
multiple conditions. Case val
exp can be char byte 'do something
Case Else
short int, val should be 'If no match it will pass here
a unique constant of exp. End Select

Case statements falls Example:


through the next case Dim sex As Char = "M"
Select Case sex
unless a exit is Case "M"
encountered. System.Console.WriteLine("I'm a male.")
Case "F"
Case Else is executed if System.Console.WriteLine("I'm a
none of the other cases female.")
Case Else
match the exp. System.Console.WriteLine("I am what I
am!")
End Select

Output:
I'm a male.
46
While

While performs statements repeatedly while condition remains true.

Syntax: While condition


'Do something
End While

Example: Dim ctr As Integer = 10


While ctr > 0
System.Console.WriteLine("Timer: " + ctr.ToString)
ctr -= 1
End While

Output: Timer: 10
Timer: 9
Timer: 8
Timer: 7
Timer: 6
Timer: 5
Timer: 4
Timer: 3
Timer: 2
Timer: 1
47
Do- Loop While

Do-While performs statements repeatedly (at least once) while


condition remains true.
Syntax: Do
'this will run at least once
Loop While condition

Example: Dim ctr As Integer = 0


Do
System.Console.WriteLine("Timer: " + ctr)
ctr += 1
Loop While ctr < 10

Output: Timer: 0
Timer: 1
Timer: 2
Timer: 3
Timer: 4
Timer: 5
Timer: 6
Timer: 7
Timer: 8
Timer: 9
48
For Next

For enable us to execute Syntax:


For init To final Step inc
a series of expressions 'do something
multiple numbers of times Next

Example:
For age As Integer = 18 To 29
System.Console.WriteLine("Enjoy life while you're
" + age)
Next

Output:
Enjoy life while you're 18
Enjoy life while you're 19
Enjoy life while you're 20
Enjoy life while you're 21
Enjoy life while you're 22
Enjoy life while you're 23
Enjoy life while you're 24
Enjoy life while you're 25
Enjoy life while you're 26
Enjoy life while you're 27
Enjoy life while you're 28
Enjoy life while you're 29
49
For Each

For Each() is similar to for statement Syntax:


but implemented differently. For Each variable In collection
type and variable declare the 'Statement here
Next
iteration variable. During execution,
the iteration variable represents the
array element (or collection element Example:
in case of collections) for which an Dim arrayint As Integer() = {11, 22,
33, 44}
iteration is currently being performed. For Each m As Integer In arrayint
In is a keyword. System.Console.WriteLine(" " + m)
collection must be an array or Next
collection type and an explicit System.Console.WriteLine()

conversion must exist from the


Output:
element type of the collection to the
11
type of the iteration variable. 22
33
44

50
Exit

Exit exits loops and other conditional statements.

Syntax: Exit [conditonal operator]

Example: Exit For


Exit Sub
Exit Function
Exit While
Exit Do
Exit Select

51
Continue

Continue is used inside loops to start a new iteration.


Same syntax as Exit
Syntax: Continue [conditional operator];

Example: For time As Integer = 7 To 11


If time < 10 Then
System.Console.WriteLine("Don't disturb! I'm studying...")
Continue For
End If
System.Console.WriteLine("zzzZZZ...")
Next

Output: Don't disturb! I'm studying...


Don't disturb! I'm studying...
Don't disturb! I'm studying...
zzzZZZ...
zzzZZZ...

52
return

The return branching statement is used to exit from the current method.
There are two forms: Example 1:
return <value>; Public Function sum(ByVal x As Integer, ByVal y As
return; Integer) As Integer
Return x + y
End Function
Example 2:
Public Function sum(ByVal x As Integer, ByVal y As
Integer) As Integer
x=x+y
If x < 100 Then
Return x
Else
Return x + 5
End If
End Function
Public Sub getSum(ByVal x As Integer)
System.Console.WriteLine(x)
Return
53
End Sub
Key Points

A VB.NET source file can include using, Namespace and class


declarations in that order
Identifiers are case-sensitive
VB.NET keywords cannot be used as identifiers
Each variable must be declared with a data type
There are 13 primitive data types: sbyte, short, int, long,
byte, ushort, uint, ulong, float, double, decimal,
char, boolean
There are 4 reference data types: classes, interfaces, delegates, and
arrays
Use unary, arithmetic operators for basic mathematical operations
Use string operator to concatenate strings

54
Key Points (Continued)

Use relational operators to compare objects


Use conditional operator as alternative to If- Else statement
Use logical operators to compare Boolean values
Use assignment operators to assign values to variables
VB.NET evaluates operators in order of precedence
Casting is converting one data type to another
If and Select are used for branching statements
While, Do While, For and For Each are used for iterating
statements
Exit, Continue are used to branch inside loops

55
Questions and Comments

56

Você também pode gostar