Professional Documents
Culture Documents
Unit 2
Unit 2
Structure: 2.1 Introduction Objectives 2.2 2.3 2.4 2.5 First Application
Namespaces in VB.Net A more interactive Hello World Application Basic Data Types and their mapping to the CTS (Common Type System)
Variables VB.Net Option Strict and Option Explicit Settings Operators in VB.Net Constant or Symbols Summary Terminal Questions Answers
2.1 Introduction
This unit is an introduction to the Language fundamentals of Visual Basic.Net. It explains a sample application along with various components involved in it. It describes the concept of namespaces in VB.Net. It also describes the concept of developing Interactive windows based applications. It explains the variables, data types, constants and Symbols in Visual basic.Net environment.
Page No. 33
Unit 2
Objectives: At the end of the unit you will be able to: Introduce the basic concepts of Visual basic.net and its language features Demonstrate simple and interactive applications Describe namespaces in Visual Basic.Net Describe variables, data types in Visual Basic. Net
Page No. 34
Unit 2
This will show you the initial default code for your Hello World application.
Change the name of module from Module1 to "MyHelloWorldApplication" and type Console.WriteLine("Hello World") inside the Sub Main() functions' body like whats shown below: Module MyHelloWorldApplication Sub Main() Console.WriteLine("Hello World") End Sub End Module To compile and execute your application, select "Start" from the "Debug" menu or to run the application without Debug press Ctrl+F5. A new console window containing the words Hello World will now be displayed. Press any key to terminate the program and close the console window. Modify the code as below that includes some more VB.NET features: Imports System Namespace MyHelloWorldApplication Module MyHelloWorldModule Sub Main() Console.WriteLine("Hello World") End Sub End Module End Namespace
Page No. 35
Unit 2
The first line of the above program (Imports System) usually appears in all VB.Net programs. It gives us access to the core functionality of programming. The second line (Namespace MyHelloWorldApplication) will be discussed.
MyHelloWorldApplication namespace. Namespace MyHelloWorldApplication ... End Namespace The VB.Net namespaces have no physical mapping. The namespace may contain modules, classes, interfaces, events, exceptions, delegates and even other namespaces which are known as "Internal namespace". These internal namespaces can be defined like this:
Sikkim Manipal University Page No. 36
Unit 2
Namespace Parent Namespace Child ... End Namespace End Namespace The Imports Keyword The first line of the above program is Imports System. The "Imports" keyword in the code sample above enables us to use classes in the "System" namespace. For example, It is possible to access the Console class from the Main(). One point to remember here is that "Imports" allows access to classes in the referenced namespace only and not in its internal/child namespaces. Hence it might be needed to write Imports System.Collections in order to access the classes defined in Collection namespace which is a sub/internal namespace of the System namespace. The Module Keyword A VB.Net program may contain one or more modules. The Main() subprocedure usually resides in one of these modules. Modules in VB.Net are a combination of general data (fields) and general functions (methods) that are accessible to any code that can access the namespace of a module. All the members (fields, methods, properties) defined inside a module are shared by default. Modules in VB.Net are defined using the Module statement, followed by the name of the module. The end of a module is marked with the End Module statement. Module MyHelloWorldModule ... End Module
Page No. 37
Unit 2
The Main() Sub-Procedure In the next line, the Main() sub-procedure of our program is defined: Sub Main() ... End Sub This is the standard layout of a Main sub-procedure within a VB.Net module. The Main() sub-procedure is the entry point of a program,that is, a VB.Net program starts its execution from the first line in the Main sub-procedure and exists with the termination of the Main sub-procedure. We can also define the Main method inside a class as in the example given below. Imports System Namespace MyHelloWorldApplication Class MyHelloWorldClass Public Shared Sub Main() Console.WriteLine("Hello World") End Sub End Class End Namespace The main sub-procedure is designated as "Shared" as it can be called by the Common Language Runtime (CLR) without creating any objects from our MyHelloWorldClass (this is the definition of Shared methods, fields and properties). The sub-procedure is also declared as "Public" so that classes outside its namespace and assembly may call this method. Main is the (standard) name of this method. More evidence of this shall be shown later. One interesting point is that it is legitimate to have multiple Main() methods in VB.Net program. However, you have to explicitly identify which Main method is the entry point for the program.
Page No. 38
Unit 2
Printing on the Console The next line of code prints "Hello World" on the Console screen: Console.WriteLine("Hello World") In the code, WriteLine() is called. It is a "Shared" method of the Console class that is defined in the System namespace. This method takes a string (enclosed in double quotes) as its parameter and prints it on the Console window. VB.Net, like other Object Oriented languages, uses the dot (.) operator to access the member variables (fields) and methods of a class. Also, parentheses () are used to identify methods in the code. String literals are enclosed in double quotation marks ("). Lastly, it must be noted that VB.Net is a case-insensitive language; hence Console and conSole are the same words (identifiers) in VB.Net. Comments Comments are created by programmers who wish to explain the code. Comments are ignored by the compiler and are not included in the executable code. VB.Net uses similar syntax for comments as used in VB and assembly language. The text following a single quotation mark (' any comment) is a line comment. The ending is the end of the line. This is the main method Public Shared Sub Main() Console.WriteLine("Hello World") ' It will print Hello World End Sub Important points to remember VB.Net executable program resides in a class or module. The entry point to a program is the Shared sub-procedure Main() VB.Net is not a case sensitive language so SMU and Smu mean the same thing.
Sikkim Manipal University Page No. 39
Unit 2
Horizontal whitespaces (tabs and spaces) are ignored by the compiler between the code. Hence, the following is also a valid declaration of the Main() method (although not recommended): Public Shared Console.WriteLine End Sub Sub Main() )
( "Hello World"
VB.Net programs need not be saved with the same file name as that of the class or module containing the Main() method. There can be multiple Main() methods in a program, but it has to be specified which one is the entry point. The boundaries of a namespace, class, module and method are defined by their respective statements and closed with an End statement. A namespace is only a logical collection of classes with no physical mapping on disk. The "Imports" keyword is used to inform the compiler where to look for the definition of the classes (namespaces) that is to be used. Comments are ignored by the VB.Net compiler and are used only to enhance the readability and understandability of the program for developers only.
Enclosing your classes or modules in a namespace is optional. It is possible to write a program where any classes or modules are not enclosed in a namespace
It is not mandatory that the Main method of a program does not take any argument. It may take arguments, such as: Public Sub Main(ByVal CmdArgs() As String) Console.WriteLine("Hello World") End Sub
Page No. 40
Unit 2
Unit 2
line of text where the data from the variable "name" should be written after the WriteLine() method is called. Console.WriteLine("Hello {0}, Good Luck in VB.Net", name); When the compiler finds a substitution parameter {n} it replaces it with the (n+1) variables following the string in double quotation marks separated by comma. Hence, when the compiler finds {0}, it replaces it with (0+1), that is, 1st variable "name" following the double quotes separated by comma. At run-time, the CLR will read it as: Console.WriteLine("Hello Ram, Good Luck in VB.Net"); if the value of the variable "name" is "Ram" at run-time. Alternatively, it can also be written as Console.WriteLine("Hello " + name + ", Good Luck in VB.Net"); without the substitution parameter altogether. Here we concatenate (add) the strings together to form a message. (The first approach is similar to C's printf() function while the second is similar to Java's System.out.println() method) When we compile and run this program the output will be as follows: "Please, write your good name: Ram Hello Ram, Good Luck in VB.Net"
2.5 Basic Data Types and their mapping to the CTS (Common Type System)
There are two kinds of data types in VB.Net 1. Value type (implicit data types, Structure and Enumeration) 2. Reference Type (objects, delegates) Value types are passed to methods by passing an exact copy while Reference types are passed to methods by passing only their reference (handle). Implicit data types are defined in the language core by the language vendor, while explicit data types are types that are made by using or composing implicit data types.
Sikkim Manipal University Page No. 42
Unit 2
As seen in the first unit, implicit data types in .net compliant languages are mapped to types in Common Type System (CTS) and CLS (Common Language Specification). Hence, each implicit data type in VB.Net has its corresponding .Net type. The implicit data types in VB.Net are:
VB.Net type Boolean Char Corresponding .Net type Boolean Char Size in bytes 1 2 Description Contains either True or False Contains any single Unicode character enclosed in double quotation marks followed by a c, for example "x"c
Integral types Byte Short Integer(default) Long Byte Int16 Int32 Int64 1 2 4 8 May contain integers from 0-255 Ranges from -32,768 to 32,767 Ranges from -2,147,483,648 to 2,147,483,647 Ranges from 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Ranges from 1.5 10-45 to 3.4 1038 with 7 digits precision. Requires the suffix 'f' or 'F' Ranges from 5.0 10-324 to 1.7 10308 with 15-16 digits precision. Ranges from 1.0 10-28 to 7.9 1028 with 28-29 digits precision. Requires the suffix 'm' or 'M'
Double(default)
Double
Decimal
Decimal
12
Implicit data types are represented in language using 'keywords'; so each of above is a keyword in VB.Net (Keyword are the words defined by the language and can not be used as identifiers). It is worth-noting that string is also an implicit data type in VB.Net, so String is a keyword in VB.Net. Last point about implicit data types is that they are value types and thus stored at
Sikkim Manipal University Page No. 43
Unit 2
the stack, while user defined types or referenced types are stored at heap. Stack is a data structure that store items in last in first out (LIFO) fashion. It is an area of memory supported by the processor and its size is determined at the compile time. Heap is the total memory available at run time. Reference types are allocated at heap dynamically (during the execution of program). Garbage collector searches for non-referenced data in heap during the execution of program and returns that space to Operating System.
2.6 Variables
During the execution of program, data is temporarily stored in memory. A variable is the name given to a memory location holding particular type of data. So, each variable has associated with it a data type and value. In VB.Net, a variable is declared as: Dim <variable> as <data type> Example: Dim i As Integer The above line will reserve an area of 4 bytes in memory to store integer type values, which will be referred in the rest of program by identifier 'i'. You can initialize the variable as you declare it (on the fly) and can also declare/initialize multiple variables of same type in a single statement. Examples: Dim isReady As Boolean = True Dim percentage = 87.88, average = 43.9 As Single Dim digit As Char = "7"c
Unit 2
You can declare a variable without specifying its type. VB.Net, in this case, assumes the type of the variable as System.Object class. You can convert values (or objects) to incompatible types, for example String to Integer.
The use of these two features results in quite a number of bugs and makes the overall design of application bad, complex and difficult to follow. With incompatible type conversion, the program does compile without any error but throws a runtime error (exception). But these two features can be turned off by using the Option Explicit and Option Strict statements. Option Explicit Statement Option Explicit, when turned on, does not allow the use of any variable without proper declaration. There are two methods to apply the Option Explicit Statement. To apply the Option Explicit settings to the complete project in Visual Studio.Net, right click the project name in the solution explorer and select Properties. It will open the Property Pages window. Now in the Common Properties tree at left, select Build, it will show the following window
Page No. 45
Unit 2
From here, you can turn the Option Explicit (as well as Option Strict) on or off. To apply the Option Explicit settings to the current file, use the Option Explicit statement before any statement as, Option Explicit On. When Option Explicit is on, it will cause the compile time error to write myName = "Ram" ' compile time error with Option Explicit On
Rather, it has to be written as, Dim myName As String = "Ram" Option Strict Statement When the Option Strict statement is turned on, incompatible type conversion are not allowed. Option Strict can be turned on or off in the similar fashion as Option Explicit. You can either use Option Strict Statement as Option Strict On or you can set it from the project properties. When Option Strict is On, the following program will cause a compile time error Sub Main() Dim strNum As String = "1" Dim intNum As Integer = strNum Console.WriteLine(intNum) End Sub But if the Option Strict is turned off, the above program will actually compile and run without error to print 1 on the Console. It is important to remember that Option Strict also does not allow using undeclared types and hence there is no use turning the Option Explicit on if you are already using Option Strict. It is strongly advised to turn on Option Explicit and Option Strict. Throughout the book, it is assumed that the Option Strict is turned On.
Page No. 46
Unit 2
The program below uses these operators Imports System Module Arithmetic Operators ' The program shows the use of arithmetic operators ' + - * / Mod Sub Main() ' result of addition, subtraction, multiplication and modulus operator Dim sum, difference, product, modulo As Integer sum = 0 difference = 0 product = 0 modulo = 0 Dim quotient As Double = 0 ' result of division Dim num1 As Integer = 10 Dim num2 As Integer = 2 sum = num1 + num2 difference = num1 - num2 product = num1 * num2 quotient = num1 / num2
Sikkim Manipal University Page No. 47
Unit 2
Console.WriteLine("num1 = {0}, num2 = {1}", num1, num2) Console.WriteLine() Console.WriteLine("Sum of {0} and {1} is {2}", num1, num2, sum)
Console.WriteLine("Difference of {0} and {1} is {2}", num1, num2, difference) Console.WriteLine("Product product) Console.WriteLine("Quotient quotient) Console.WriteLine() Console.WriteLine("Remainder when 3 is divided by {0} is {1}", num2, modulo) End Sub End Module Assignment Operators Assignment operators are used to assign values to variables. Common assignment operators in VB.Net are:
Assignment Operator = += -= *= /= Meaning Simple assignment Additive assignment Subtractive assignment Multiplicative assignment Division assignment
The Equal operator is used to assign a value to a variable or a reference. For example, the instruction, Dim isPaid As Boolean = false
Page No. 48
Unit 2
assigns the value 'False' to the isPaid variable of Boolean type. The Left and right hand side of the equal or any other assignment operator must be compatible otherwise the compiler will complain of a syntax error. Sometimes casting is used for type conversion, e.g., to convert and store values in a variable of type Double to a variable of type Integer. We need to apply integer cast using VB.Net's CType() built-in method. Dim doubleValue As Double = 4.67 Dim intValue As Integer would be equal to 4 The method CType() is used for compatible type conversions. It takes two arguments; the first being the source variable to convert to, while the second argument is the target type of conversion. Hence, the above call to the method CType() will convert the value in the variable 'doubleValue' of type Double to a variable of type Integer and will return the converted Integer type value that will be stored in the Integer variable 'intValue'. Of course, with narrow casting (from bigger type to smaller type) there is always a danger of some loss of precision; as in the case above, we only got 4 of the original 4.67. Sometimes, the casting may result in a runtime error. Dim intValue As Integer Dim shortValue As Short = 32800 = CType(intValue, Short) = CType(doubleValue, Integer) ' intValue
When the second of these lines is run an error will be given, stating that "Arithmetic operation resulted in an overflow." Why is it so? Variables of type Short can only take a maximum value of 32767. The cast above cannot assign 32800 to a shortValue. This is detected at runtime and an error is given.
Page No. 49
Unit 2
If you try to do an invalid cast of incompatible types like below Dim strValue As String = "Ram" Dim intValue As Integer = CType(strValue, Integer) Then again it will get compiled but will crash the program at runtime. Relational Operators Relational operators are used for comparison purposes in conditional statements. The common relational operators in VB.Net are:
Relational Operator = <> > < <= >= Meaning Equality check Un-equality check Greater than Less than Less than or equal to Greater than or equal to
Relational operators always result in a Boolean statement; either True or False. For example if we have two variables Dim num1 = 5, num2 = 6 As Integer then, num1 = num2 num1 <> num2 num1 > num2 num1 < num2 num1 <= num2 num1 >= num2 will result in false will result in true will result in false will result in true will result in true will result in false
Only compatible data types can be compared. It is invalid to compare a Boolean with an Integer, if Dim i = 1 As Integer Dim b = True As Boolean then it is a syntax error to compare i and b for equality (i=b)
Sikkim Manipal University Page No. 50
Unit 2
Logical and Bitwise Operators These operators are used for logical and bitwise calculations. The common logical and bitwise operators in VB.NET are:
Logical and Bitwise Operators AND OR XOR NOT ANDALSO Meaning bitwise AND bitwise OR bitwise XOR bitwise NOT (Logical or short circuit AND) OrElse (Logical or short circuit OR)
The operators And, Or and Xor are rarely used in usual programming practice. The Not operator is used to negate a Boolean or bitwise expression like: Dim b = False As Boolean Dim bb As Boolean = Not b ' bb would be true Logical Operators And, Or, AndAlso and OrElse are also used to combine comparisons like Dim i=6, j=12 As Integer Dim firstVar As Boolean = i>3 And j < 10 ' firstVar would be false Dim secondVar As Boolean = i>3 Or j < 10 ' secondVar would be true. In the first comparison case: i>3 And j<10 will result in true only if both the conditions i>3 and j<10 result in true. While in the second comparison: i>3 Or j<10 will result in true if any of the conditions i>3 and j<10 result in true. You can of course use the combination of And, Or, AndAlso and OrElse in a single statement like: bool firstVar = (i>3 And j<10) OrElse (i<7 And j>10)
Unit 2
In the above statement, conditional expressions are grouped to avoid any ambiguity. You can also use And and Or operators in place of AndAlso and OrElse respectively; but for combining conditional expressions, AndAlso and OrElse are more efficient as they use "short circuit evaluation", i.e., if in (i>3 AndAlso j<10) expression, i>3 evaluates to false, it would not check the second expression j<10 and will return false (as in AND, if one of the participant operand is false, the whole operation will result in false). Hence, one should be very careful to use assignment expressions with AndAlso and OrElse operators. The And and Or operators don't do short circuit evaluation and do execute all the comparisons before returning the result. Operator Precedence When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence. Precedence Rules o When expressions contain operators from more than one category, they are evaluated according to the following rules: o The arithmetic and concatenation operators have the order of precedence described in the following section, and all have greater precedence than the comparison, logical, and bitwise operators. o All comparison operators have equal precedence, and all have greater precedence than the logical and bitwise operators, but lower precedence than the arithmetic and concatenation operators. o The logical and bitwise operators have the order of precedence described in the following section, and all have lower precedence than the arithmetic, concatenation, and comparison operators. o Operators with equal precedence are evaluated left to right in the order in which they appear in the expression.
Sikkim Manipal University Page No. 52
Unit 2
Arithmetic and Concatenation Operators Exponentiation (^) Unary identity and negation (+, ) Multiplication and floating-point division (*, /) Integer division (\) Modulus arithmetic (Mod) Addition and subtraction (+, ), string concatenation (+) String concatenation (&) Arithmetic bit shift (<<, >>) Comparison Operators All comparison operators (=, <>, <, <=, >, >=, Is, IsNot, Like, TypeOf...Is) Logical and Bitwise Operators Negation (Not) Conjunction (And, AndAlso) Inclusive disjunction (Or, OrElse) Exclusive disjunction (Xor) Comments The = operator is only the equality comparison operator, not the assignment operator. The string concatenation operator (&) is not an arithmetic operator, but in precedence it is grouped with the arithmetic operators. The Is and IsNot operators are object reference comparison operators. They do not compare the values of two objects; they check only to determine whether two object variables refer to the same object instance.
Sikkim Manipal University Page No. 53
Unit 2
Associativity When operators of equal precedence appear together in an expression, for example multiplication and division, the compiler evaluates each operation as it encounters it from left to right. The following example illustrates this. Dim n1 As Integer = 96 / 8 / 4 Dim n2 As Integer = (96 / 8) / 4 Dim n3 As Integer = 96 / (8 / 4) The first expression evaluates the division 96 / 8 (which results in 12) and then the division 12 / 4, which results in three. Because the compiler evaluates the operations for n1 from left to right, the evaluation is the same when that order is explicitly indicated for n2. Both n1 and n2 have a result of three. By contrast, n3 has a result of 48, because the parentheses force the compiler to evaluate 8 / 4 first. Because of this behavior, operators are said to be left associative in Visual Basic. Overriding Precedence and Associativity You can use parentheses to force some parts of an expression to be evaluated before others. This can override both the order of precedence and the left associativity. Visual Basic always performs operations that are enclosed in parentheses before those outside. However, within parentheses, it maintains ordinary precedence and associativity, unless you use parentheses within the parentheses. The following example illustrates this. Dim a, b, c, d, e, f, g As Double a = 8.0 b = 3.0 c = 4.0 d = 2.0 e = 1.0
Sikkim Manipal University Page No. 54
Unit 2
f=a-b+c/d*e 'The preceding line sets f to 7.0. Because of natural operator precedence and associativity, it is exactly equivalent to the following line. f = (a - b) + ((c / d) * e) 'The following line overrides the natural operator precedence and left associativity. g = (a - (b + c)) / (d * e) ' The preceding line sets g to 0.5.
2.10 Summary
This unit starts with basic to interactive application development using Visual Basic. It then demonstrates various variables, constants and data types and various other concepts used in Visual Basic.
2.12 Answers
1. Refer to section 2.2 2. Refer to sections 2.5 & 2.6 3. Refer to sections 2.8 & 2.9
Sikkim Manipal University Page No. 55