Presentation is loading. Please wait.

Presentation is loading. Please wait.

Microsoft Visual Basic 2005: New Language Features

Similar presentations


Presentation on theme: "Microsoft Visual Basic 2005: New Language Features"— Presentation transcript:

1 Microsoft Visual Basic 2005: New Language Features
Stan Schultes Architect, Developer, Author Microsoft MVP Visual Basic

2 Agenda Major Additions: New Language Statements: Operator Overloading
My, XML Comments, Generics New Language Statements: Using, Continue, TryCast, Global, IsNot Operator Overloading Conversion Operators, Unsigned Types Other Features: Property Accessor Accessibility Custom Event Accessors Partial Types Application Level Events Compiler Warnings Explicit Array Bounds Form Default Instances Refactoring

3 My Hierarchy “Speed Dial” & Dynamic Types
— Application title, version, logs, description, … — Registry, audio, file system, … — User name, group, domain, … — Access resources for the application: icons, images,… — User and application settings — Collection of project forms — Collection of Web services referenced in project

4 My.Application My.Application is designed to:
Make application-related properties more accessible Allow commonly referenced services and classes to be enabled easily Provide a more manageable framework for application startup and shutdown

5 My.Computer My.Computer provides straightforward access to the host computer’s properties and hardware resources, allowing devices to be enabled easily and their services integrated seamlessly into applications

6 My.User My.User provides access to properties for the currently logged-on user of the application. Also allows the developer to implement IPrincipal and IIdentity to interface with other authentication schemes such as SQL databases.

7 My (Dynamic Types) Provided Automatically by Compiler
Application level version of “Me” My.Resources PictureBox1.Image = My.Resources.Logo My.Settings My.Settings.FormLocation = Me.Location My.Forms My.Forms.Form1.Show My.WebServices My.WebServices.MSDN.Search(“VB”)

8 My.Resources Strongly-typed interface to resources added with the Resources Editor Manipulate image & media files Manage strings in resource files by culture 'MVPLogo.png added with Resources Editor Button1.BackgroundImage = My.Resources.MVPLogo

9 Settings Architecture
Settings Base Application Settings Base Windows App Settings My Settings Provider Interface Local Settings Remote Custom SQL Access Custom

10 Settings in Action App settings User Settings Myapp.exe.config
<applicationSettings> </applicationSettings> fred.config ethel.config gladys.config <userSettings> </userSettings>

11 Settings in Action Load Save Handling events for validation
My.Settings.WorkOffline = True ‘ Settings automatically loaded on first access Load My.Settings.WorkOffline = True My.Settings.Save() Save Private Sub Settings_SettingChanging(ByVal sender As Object, _ ByVal e As SettingsArg) Handles MyBase.SettingChanging If e.SettingName = “DataCache” Then If Not My.Computer.FileSystem.FileExists(e.Setting.Value)Then ‘ Cancel event End If End Sub Handling events for validation

12 My.Forms My.WebServices
Dynamically generated by the compiler Default form instance is back: My.Forms.Form1.Show Web service proxy goop handled for you: Dim CompanyDataSet As New ServiceDataSet = My.WebServices.CompanyData.LoadDataSet

13 XML Comments No More C# Envy
Type three single-quotes above a class, field, method or enum to insert an XML Comment template. The template is like a form you can tab through and enter details. Intellisense immediately includes comment strings you enter. Considered by the compiler an integral part of your code (colorizes & syntax checks). XML documentation file automatically created when you build the project.

14 Generics Specify Type at Declaration Time
New namespace: System.Collections.Generic Create the equivalent of a custom collection in one line of code Huge time saver when handling collections of specific types. Create your own generic types

15 Generics (Example) Dim intList As New List(Of Integer)
Public Class List Private elements() As Object Private mCount As Integer Public Sub Add(element As Object) If (mCount = elements.Length) Then _ Resize(mCount * 2) mCount += 1 elements(mCount) = element End Sub Default Public Property Indexer(index As Integer) As Object Get : Return elements(index) : End Get Set : elements(index) = value : End Set End Property Public Property Count() As Integer Get : Return mCount : End Get End Class Public Class List(Of ItemType) Private elements() As ItemType Private count As Integer Public Sub Add(element As ItemType) If (count = elements.Length) Then _ Resize(count * 2) count += 1 elements(count) = element End Sub Default Public Property Indexer(index As Integer) As ItemType Get : Return elements(index) : End Get Set : elements(index) = value : End Set End Property Public Property Count As Integer Get : Return count : End Get End Class Dim intList As New List(Of Integer) intList.Add(1) ‘ No boxing intList.Add(2) ‘ No boxing intList.Add("Three") ‘ Compile-time error Dim i As Integer = intList(0) ‘ No cast Dim intList As New ArrayList() intList.Add(1) ‘ Argument is boxed intList.Add(2) ‘ Argument is boxed intList.Add("Three") ‘ Should be an error Dim i As Integer = CInt(intList(0)) ‘ Cast

16 Generics (Specifics) Compile-time checking Better performance
Eliminates runtime errors Better performance No casting or boxing overhead Code re-use Easy to create strongly typed collections Common data structures in framework Dictionary, HashTable, List, Stack, etc.

17 New Language Statements Making the Language Complete
IsNot – logical counterpart to Is statement Using – acquire, execute, release resources Continue – skips to next iteration of loop TryCast – returns Nothing if cast fails Global – access to root (empty) namespace

18 IsNot Logical counterpart to Is
Clearer way of determining if an object has a value or is equivalent to another object 'prior VB syntax If Not prd Is Nothing Then 'use prd... End If 'IsNot is cleaner If prd IsNot Nothing Then

19 Using Statement Acquire, Execute, Release
Fast way correctly release resources Easier to read than Try, Catch, Finally ‘Using block disposes of resource Using fStr As New FileStream(path, FileMode.Append) For i As Integer = 0 To fStr.Length fStr.ReadByte() Next ‘End of block closes stream End Using

20 Continue Statement Skips to next iteration of loop
Works with Do, For, While loops Loop logic is concise, easier to read For j As Integer = 0 to 5000 While matrix(j) IsNot thisValue If matrix(j) Is thatValue ‘ Continue to next j Continue For End If Graph(j) End While Next j

21 TryCast Returns Nothing if cast fails
Using CType or DirectCast requires Try – Catch logic in case conversion fails. Using TryCast results in cleaner code. 'runtime exception if obj <> Product type p = CType(obj, Product) p = DirectCast(obj, Product) 'TryCast returns Nothing if obj <> Product p = TryCast(obj, Product) If p IsNot Nothing Then 'use p... End If

22 Global Keyword Access to Root (empty) namespace
Complete name disambiguation Better choice for code generation 'fails if current Namespace contains type named System Dim sb1 As New System.Text.StringBuilder 'disambiguate framework namespaces Dim sb2 As New Global.System.Text.StringBuilder

23 Operator Overloading One Mark of a True OO Language
Create your own Types Conversion Operators Unsigned Types

24 Operator Overloading Create your own base types
Public Class Complex Public Real As Double Public Imag As Double Public Sub New(ByVal rp As Double, ByVal ip As Double) Real = rp Imag = ip End Sub Shared Operator +(ByVal lhs As Complex, ByVal rhs As Complex)_ As Complex Return New Complex(lhs.Real + rhs.Real, lhs.Imag + rhs.Imag) End Operator End Class 'new Complex + operator works intuitively Dim lhs As Complex = New Complex(2.1, 3.3) Dim rhs As Complex = New Complex(2.5, 4.6) Dim res As Complex = lhs + rhs 'res.real = 4.6, res.imag = 7.9

25 Conversion Operators You Control Type Conversions
Shared Narrowing Operator CType(ByVal Value As Complex)_ As String Return Value.Real.ToString & "i" & Value.Imag.ToString End Operator Overrides Function ToString(ByVal Value As Complex) _ End Function

26 Unsigned Types Full support in the language
Full platform parity Easier Win32 API calls and translation Memory and performance win Dim sb As SByte = ‘Error:negative Dim us As UShort Dim ui As UInteger Dim ul As ULong ‘Full support in VisualBasic modules If IsNumeric(uInt) Then ‘ Will now return true End If

27 Other Features Rounding out Framework Support
Property Accessor Accessibility Custom Event Accessors Partial Types Application Level Events Compiler Warnings Explicit Array Bounds

28 Accessor Accessibility Granular accessibility on Get and Set
Forces calls to always use get, set Easy way to enforce validation Property Salary() As Integer Get Return mSalary End Get Private Set( value As Integer) If value < 0 Then Throw New Exception(“Not Available”) End If End Set End Property

29 Custom Event Accessors Define and Control Custom Events
Code gen when you type Custom keyword Public Custom Event NameChanged As EventHandler AddHandler(ByVal value As EventHandler) 'hook handler to backing store End AddHandler RemoveHandler(ByVal value As EventHandler) 'remove handler from backing store End RemoveHandler RaiseEvent(ByVal sender As Object, _ ByVal e As System.EventArgs) 'invoke listeners End RaiseEvent End Event

30 Partial Types Single structure, class in multiple files
Separates designer gen into another file Team dev / factor implementation Public Class Form1 Inherits Windows.Forms.Form ‘ Your Code End Class Partial Class Form1 ‘ Designer code Sub InitializeComponent() ‘ Form controls End Sub

31 Application Level Events Similar to ASP.NET Global.asax
Events exposed: Startup Shutdown StartupNextInstance NetworkAvailabilityChanged UnhandledException Found in ApplicationEvents.vb file

32 Visual Basic Warnings Early warning of runtime behavior
Overlapping catch blocks or cases Recursive property access Unused Imports statement Unused local variable Function, operator without return Reference on possible null reference Option Strict broken down “Late binding” Visual Basic Style Conversions Etc.

33 Explicit Array Bounds Lower Bound Must Still be 0
More precise array declarations Dim a(10) As Integer 'old way Dim b(0 To 10) As Integer 'new way

34 Summary The Best Visual Basic Ever
VB Language complete, full OO support Feature parity between all .NET languages IDE support for language productivity GoLive licenses available for Beta 2 now from Microsoft

35 Resources Session: VS 2005 Development Environment Keith Kabza – 1:50 to 2:50 in this room Visual Basic development center: Product feedback center: Stan Schultes

36 Acknowlegements Some slides and content borrowed from Amanda Silver and Steven Lees of the VB Team at Microsoft.


Download ppt "Microsoft Visual Basic 2005: New Language Features"

Similar presentations


Ads by Google