vb.net professor corinne hoisington central virginia community college
TRANSCRIPT
VB.NET
Professor Corinne Hoisington
Central Virginia Community College
Programming Curricular Changes
• Why should we implement this new software developer’s tool?
• What language will be “THE” most used language?
• Is this simply another upgrade?
• What classes could incorporate the content of .NET?
Visual Basic.NET
• Easier to Use• Streamlined and Modernized • More Powerful than VB 6.0• Higher level of access to system
resources that in the past required the use of languages like C++
• True Object Inheritance• Garbage Collection for better
memory management
Visual Studio .NET 2003
• Released April 27, 2003• J#• Mobile Web Applications: using the
integrated ASP.NET Web Forms and the Visual Studio .NET Web Forms Designer, Visual Basic and C# developers can easily build thin-client Web-based applications that render intelligently on more than 200 devices, including wireless application protocol (WAP) phones, wireless personal digital assistants (PDAs), and pagers.
New Web Development
• Programming for the Web vs. Windows
• New set of controls• Web page layout• ASP.NET• ADO.NET• Mobile Applications• Convert Projects
Just an Upgrade???
• NO!• VB.NET omits quite a few forms of
syntax• VB.NET requires a total rewrite rather
than a simple port of code• VB.NET is not dependent on older
libraries such as VBA runtime and ADO (ActiveX Database Object)
A new Forms Engine
• The forms engine has been replaced by the forms engine built into .NET
• This new forms engine is called Windows Forms (or Win Forms for short)
• Win Forms add such features as docking and opacity
Forms are now Classes
• In VB6, forms were classes, but you rarely treated them that way
• VB .NET shows the code that instantiates the form
• To show additional forms, you must first instantiate them
Form Changes
• Forms have undergone a number of changes. These include:• The Forms engine is now
WinForms• Forms are classes• A Component Tray holds non-
visual controls at design-time
VB.NET or C#.NET• C# is a new language that
was designed to be friendly to programmers who are already proficient in C or C++
• Either language can be used to write software that takes full advantage of the CLR and .NET framework
NEW IDE
New Tools
• Calendar Tool• Date Picker Calendar• Opacity Control• Timer does not lay on form• Command Buttons are now called
Buttons • Use “btn” for prefix
Great New Menu Tool
More Changes
• The Editor window (formerly the Code window)• Lots more IntelliSense help;
can be confusing• Declarations section replaces
General Declarations• Collapsible Regions in code
(Plus signs)
Collapsed Regions
CollapsedRegion
CollapsedProcedure
ClassList
Method ListTabs
General Changes
• There have been a number of changes in VB .NET. General changes include:• Form changes• Option Strict• Event Handler changes• Default Properties• Calling Subs and Functions• Boolean operators• Using CTRL + Space to finish variables
The Component Tray
• In VB6, controls that were only visible at design-time still appeared on the form in the IDE• Such as the Timer control
• VS .NET places controls that are invisible at runtime in a small area below the form• This area is the Component Tray
A new Forms Engine
• The forms engine has been replaced by the forms engine built into .NET
• This new forms engine is called Windows Forms (or Win Forms for short)
• Win Forms add such features as docking and opacity
Forms are now Classes
• In VB6, forms were classes, but you rarely treated them that way
• VB .NET shows the code that instantiates the form
• To show additional forms, you must first instantiate them
The Component Tray
• In VB6, controls that were only visible at design-time still appeared on the form in the IDE• Such as the Timer control
• VS .NET places controls that are invisible at runtime in a small area below the form• This area is the Component Tray
Calls to Subs and Functions Require Parentheses
• In VB6, you called a Sub without parenthesesAddOrder OrderNum, OrderDate
• You could use the Call statement, which required parentheseCall AddOrder(OrderNum, OrderDate)
• .NET always requires parentheses for a Sub, as well as with Functions
New Boolean Operators
• The And and Or keywords do not short-circuit in VB and VB .NET• Both sides of an operator are evaluated, even
if the first option invalidates the statement
• VB .NET adds two short-circuiting Boolean operators:• AndAlso• OrElse
Boolean Operators Example
Dim x As Integerx = 0If x>2 And 5\x > 1 Then ...
• This If statement is already false on the x>2 part, but 5\x is still checked because And does not short-circuit
• In this case, 5\x causes a “divide by zero” error
Boolean Operators Example cont.
Dim x As Integer
x = 0
If x>2 AndAlso 5\x > 1 Then ...
• This If statement is already false on the x>2 part, so the AndAlso does not check the 5\x portion
• The key result: No Error!
The Value of True
• The value of True has not changed• Originally, the value of True was going
to change, but it did not
• The value of True in VB .NET is still negative one (-1)
• Your code should not check for -1, but for True
Common Language Runtime
• VB.NET has undergone a significant overhaul to accommodate the CLR• New object oriented design features
• Much higher levels of type safety
• Universal type system allows for greater inoperability
Changes in Properties
• The Alignment property becomes TextAlign
• The maximum length of identifiers is 16,383
• All new Help — MSDN• OptionButton becomes RadioButton• Frame becomes GroupBox
• New component tray holds non-visible controls
More Property Changes
• Text boxes have a Clear methodtxtName.Clear()txtName.Text = “”
• Focus method replaces SetFocustxtName.Focus()
• Many colors available through the Color class• lblMessage.ForeColor = Color.Blue
Color.AquamarineColor.BisqueColor.ChocolateColor.Cadetblue
Tab Order
This is neat! Click on View and Tab Order
Caption / Text Property• VB 6.0 - Some controls, such as
Label, have a Caption property that determines the text displayed in or next to the control. Other controls, such as TextBox, have a Text property that determines the text contained in the control
• VB.NET - In Windows Forms, the property that displays text in a control is consistently called Text on all controls. This simplifies the use of controls.
Data Types
byte 1 byte Range
0 to 255
Unsigned
byte
sbyte 1 byte Range
-128 to 127
Signed
byte
Short
(sho)
2 bytes
Range
-32768 to 32767
Signed
short
ushort 2 bytes
Range
0 to 65535
Unsigned
short
int
(int)
4 bytes Range-2,147,483,647 to 2,147,483,647
Signed
integer
uint 4 bytes Range0 to 4,294,967,295
Unsigned
integer
long
(lng)
8 bytes Greater than
±900,000 trillion
Signed long int
ulong 8 bytes Greater than 18 million trillion
Unsigned
long int
More Integer Data Types
Other Data Types
single
(sng)
4 bytes
RangeA number 6 digits past the decimal
Float
number
double
(dbl)
8
bytes
RangeA number 14 digits past the decimal
Double
precision
decimal 8
bytes
RangeA number 28 zeros long
Fixed
precision
string (str) N/A Range N/A Unicode
char 2
bytes
Range0x0000 to 0xFFFF
Unicode
character
Bool (bln) True or False Boolean
Block-Level Scope
• VB .NET introduces variables that only exist within blocks of code• Blocks are items such as For…Next,
Do…Loop, and If Then…End If
• Variables are only visible within the block, but their lifetime is that of the whole procedure
Changes in Syntax• Firstly the ‘Currency’ data type is no
longer used in VB 6.0• Currency has been replaced with Decimal
in VB.NET• The Currency data type (64 bit) does not
provide sufficient accuracy to avoid rounding errors, so Decimal (96 bit) was created as its own data type.
• Dim x As Currency is upgraded to: Dim x As Decimal
Long and Integer Data Types
• VB 6.0 - Long variables were stored as 32-bit numbers and Integer variables as 16-bit numbers
• VB.NET - Long variables are stored as 64-bit numbers, Integer variables are stored as 32-bit numbers, and Short variables are stored as 16-bit numbers.
No More Variant Data Type
• Variant data types are changed to Object due
to keeping all the languages more similar. This
is no longer the same as a pointer to an object.
• Dim x As Variant
is upgraded to:
Dim x As Object
Option Explicit
• In VB.BET the option is turned on by default for all new projects.
• When Option Explicit Off is used (not a good programming style), you can use any variable without first declaring it.
Option Strict On• New Option in VB.NET• When Option Strict is turned on, the
compiler/editor does not allow implicit conversions from a wider data type to a narrower one, or between String and numeric data types
• CInt and CDec convert• Limits erroneous numbers or run-time
errors • Place the line Option Strict On before the
first line of code
Converting Data Types• Initialize a variable at declaration
Dim intMax As Integer = 100IDim decRate As Decimal = 0.08D
• Declare multiple variables at onceDim intCount, intNum As Integer
• Convert all input to correct data type(Do not use Val function) decSale = CDec(txtSale.Text)
• CInt (still rounds to even #)• CDec• CStr
** CInt and CDec parse some characters like $, commas,()
Format
• VB 6.0 –
Format(variable, “Currency”)• VB.NET – FormatCurrency(variable)
FormatPercent(variable)
FormatNumber(variable)
FormatNumber(variable,3)
FormatDateTime(variable)
New Compound Operators
• New assignment Operators• += –= *= /= \= &=• decTotal += decSale same as
decTotal=decTotal + decSale
Case Conversions
• String ToUpper and ToLower methods• Replace UCase and LCase functions• If txtInput.Text.ToUpper = “YES”
Arrays• VB 6.0 - Arrays can be defined with lower
and upper bounds of any whole number. The Option Base statement is used to determine the default lower bound if a range is not specified in the declaration.
• VB.NET- To enable interoperability with other languages, all arrays must have a lower bound of zero. This makes the Option Base statement no longer necessary.
• Dim a(1 To 10) As String is upgraded to:
Dim a(10) As String
Array Size
• This is one area that was going to change, but did not• When you declare an array, it starts at
zero, and the element number you use is the Upper Bound of the array
• This means that arrays will always be one larger than the size declared
• Dim x(2) As Integer has three elements
Arrays Continued
• Arrays in VB.NET are classes supporting properties and methods, making them quite flexible.• .Sort• .Reverse
• You can sort an array in one line of code!
Garbage Collection• The garbage collector
periodically checks for unreferenced objects and releases all memory and system resources used by the objects
• VB’s garbage collection reclaims object space automatically behind the scenes
• For efficiency, VB only runs the garbage collection feature when:• There are objects to recycle• There is a need to recycle them
While Loops
• VB 6.0 - While statements are ended with
a WEND statement.
• VB.NET - WEND statements are changed
to End While. This improves language
consistency and readability.
• While
End While
Parameter Passing
• VB 6.0 - Parameters that do not specify either ByVal or ByRef default to ByRef
• VB.NET - Parameters that do not specify either ByVal or ByRef default to ByVal. Defaulting to ByVal rather than ByRef eliminates the problem of having a procedure mistakenly modify a variable passed in by the caller.
GoSub, On Goto
• VB 6.0 - The GoSub line ... Return statement branches to and returns from a subroutine within a procedure.
• VB.NET - GoSub...Return is a nonstructured programming construct. Its use makes programs harder to read and understand. Creating separate procedures that you can call may provide a more structured alternative or use case statements.
Structures Replace UDTs
• User Defined Types (UDTs) have been replaced with Structures
• Structures are far more powerful than UDTs• They support the equivalent of
properties and methods• They are not as powerful as classes
File I/O Changes
• VB .NET supports such built-in functions as FileOpen and Write• These functions are found in the
Microsoft.VisualBasic namespace• VB6 code that is upgraded to
VB .NET will use these functions• The Framework includes a rich
namespace called System.IO
The System.IO Namespace
• System.IO contains a large number of classes for handling all types of I/O
• There are a variety of major categories of objects in System.IO• These include objects to manage files
and directories, read and write text files, and read and write binary streams
Working with Files
• FileInfo and DirectoryInfo classes are for such operations as creating, moving, and deleting files and directories
• If you use the Open method of FileInfo to open a file, the returned object is a FileStream
Reading and Writing Files
• The StreamReader and StreamWriter classes are common ways to perform file I/O• This can read binary and text data
• The StringReader and StringWriter are designed to read text data
Structured Error Handling
• VB .NET now supports Structured Exception Handling (SEH)• On Error Goto is still supported
• SEH uses the Try…Catch…Finally syntax
• Should help reduce spaghetti code
Overloading
• Overloading is the ability to have the same method, but with different arguments• You could fake this in VB6 using
ParamArrays
• For example, a FindCustomer method could accept a customer ID, a customer name, or a contact name
Constructors and Destructors
• Constructors are blocks of code that run when a class is instantiated
• Destructors are blocks of code that run when a class drops out of memory
• Constructors can be overloaded to make them more powerful
• Due to garbage collection, you cannot be assured of when destructors will execute
Dispose and Finalize
• Finalize will run when the object is cleaned up by the GC
• You might want to release resources explicitly, since you cannot determine when Finalize will be called
• Use the Dispose design pattern to explicitly free resources
Multithreading
• VB .NET allows you to create truly multithreaded (or free threaded) applications
• The Framework includes a System.Threading namespace to make working with threads easier
• You will learn more in Chapter 11, “Multithreaded Applications”
Windows VB.NET Example