microsoft visual basic 2005: new language features

36
Microsoft Visual Basic Microsoft Visual Basic 2005: 2005: New Language Features New Language Features Stan Schultes Stan Schultes Architect, Developer, Author Architect, Developer, Author Microsoft MVP Visual Basic Microsoft MVP Visual Basic www.VBNetExpert.com www.VBNetExpert.com [email protected] [email protected]

Upload: danae

Post on 17-Jan-2016

45 views

Category:

Documents


3 download

DESCRIPTION

Microsoft Visual Basic 2005: New Language Features. Stan Schultes Architect, Developer, Author Microsoft MVP Visual Basic www.VBNetExpert.com [email protected]. Agenda. Major Additions: My, XML Comments, Generics New Language Statements: Using, Continue, TryCast, Global, IsNot - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Microsoft Visual Basic 2005: New Language Features

Microsoft Visual Basic 2005:Microsoft Visual Basic 2005:New Language FeaturesNew Language Features

Stan SchultesStan SchultesArchitect, Developer, AuthorArchitect, Developer, Author

Microsoft MVP Visual BasicMicrosoft MVP Visual Basicwww.VBNetExpert.comwww.VBNetExpert.com

[email protected]@vbnetexpert.com

Page 2: Microsoft Visual Basic 2005: New Language Features

AgendaAgenda Major Additions:Major Additions:

My, XML Comments, GenericsMy, XML Comments, Generics

New Language Statements:New Language Statements: Using, Continue, TryCast, Global, IsNotUsing, Continue, TryCast, Global, IsNot

Operator OverloadingOperator Overloading Conversion Operators, Unsigned TypesConversion Operators, Unsigned Types

Other Features:Other Features: Property Accessor AccessibilityProperty Accessor Accessibility Custom Event AccessorsCustom Event Accessors Partial TypesPartial Types Application Level EventsApplication Level Events Compiler WarningsCompiler Warnings Explicit Array BoundsExplicit Array Bounds Form Default InstancesForm Default Instances RefactoringRefactoring

Page 3: Microsoft Visual Basic 2005: New Language Features

MyMy

ApplicationApplication

ComputerComputer

UserUser

ResourcesResources

SettingsSettings

WebServicesWebServices

FormsForms

— — Application title, version, logs, description, …Application title, version, logs, description, …

— — Registry, audio, file system, …Registry, audio, file system, …

— — User name, group, domain, …User name, group, domain, …

— — Access resources for the application: Access resources for the application: icons, images,…icons, images,…

— — User and application settingsUser and application settings

— — Collection of project formsCollection of project forms

— — Collection of Web services referenced in projectCollection of Web services referenced in project

My HierarchyMy Hierarchy“Speed Dial” & Dynamic Types“Speed Dial” & Dynamic Types

Page 4: Microsoft Visual Basic 2005: New Language Features

My.ApplicationMy.Application

My.Application is My.Application is designed to:designed to: Make application-related Make application-related

properties more accessibleproperties more accessible Allow commonly referenced Allow commonly referenced

services and classes to be services and classes to be enabled easilyenabled easily

Provide a more manageable Provide a more manageable framework for application framework for application startup and shutdownstartup and shutdown

My.ApplicationMy.Application

TitleTitle

VersionVersion

DescriptionDescription

LogLog

WorkingDirectoryWorkingDirectory

… …

Exit()Exit()

Page 5: Microsoft Visual Basic 2005: New Language Features

My.ComputerMy.Computer

MouseMouse

AudioAudio

NetworkNetwork

RegistryRegistry

… …

FileSystemFileSystem

ClipboardClipboard

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

My.ComputerMy.Computer

Page 6: Microsoft Visual Basic 2005: New Language Features

My.UserMy.User

Login NameLogin Name

DomainDomain

AuthenticationAuthentication

RolesRoles

……

Custom PrincipalCustom Principal

My.User provides My.User provides access to properties for access to properties for the currently logged-on the currently logged-on user of the application.user of the application.

Also allows the Also allows the developer to implement developer to implement IPrincipal and IIdentity IPrincipal and IIdentity to interface with other to interface with other authentication schemes authentication schemes such as SQL databases.such as SQL databases.

My.UserMy.User

Page 7: Microsoft Visual Basic 2005: New Language Features

Application level version of “Me”Application level version of “Me” My.ResourcesMy.Resources

PictureBox1.Image = My.Resources.LogoPictureBox1.Image = My.Resources.Logo My.SettingsMy.Settings

My.Settings.FormLocation = Me.LocationMy.Settings.FormLocation = Me.Location My.FormsMy.Forms

My.Forms.Form1.Show My.Forms.Form1.Show My.WebServicesMy.WebServices

My.WebServices.MSDN.Search(“VB”)My.WebServices.MSDN.Search(“VB”)

My (Dynamic Types)My (Dynamic Types)Provided Automatically by CompilerProvided Automatically by Compiler

Page 8: Microsoft Visual Basic 2005: New Language Features

My.ResourcesMy.Resources

Strongly-typed interface to resources added Strongly-typed interface to resources added with the Resources Editorwith the Resources Editor

Manipulate image & media filesManipulate image & media files Manage strings in resource files by cultureManage strings in resource files by culture

'MVPLogo.png added with Resources Editor Button1.BackgroundImage = My.Resources.MVPLogo

Page 9: Microsoft Visual Basic 2005: New Language Features

Settings ArchitectureSettings ArchitectureSettings BaseSettings Base

Application Settings BaseApplication Settings Base

Windows App SettingsWindows App Settings

My SettingsMy Settings

Provider InterfaceProvider Interface

LocalLocalSettingsSettings RemoteRemote CustomCustom SQLSQL AccessAccess CustomCustom

Page 10: Microsoft Visual Basic 2005: New Language Features

Settings in ActionSettings in Action

App settingsApp settings User SettingsUser Settings

App.exe.configApp.exe.configRead Only

(app directory)

<applicationSettings<applicationSettings>…

</applicationSettings</applicationSettings>

user.configuser.configRead/Write

(local settings directory)

<userSettings><userSettings>……

</userSettings></userSettings>

Page 11: Microsoft Visual Basic 2005: New Language Features

Handling events for validationHandling events for validation

Settings in ActionSettings in Action

Load Load

My.Settings.WorkOffline = True‘ Settings automatically loaded on first access

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 IfEnd Sub

My.Settings.WorkOffline = TrueMy.Settings.Save() SaveSave

Page 12: Microsoft Visual Basic 2005: New Language Features

My.FormsMy.FormsMy.WebServicesMy.WebServices

Dynamically generated by the compilerDynamically generated by the compiler Default form instance is back:Default form instance is back:

My.Forms.Form1.ShowMy.Forms.Form1.Show Web service proxy goop handled for you:Web service proxy goop handled for you:

Dim CompanyDataSet As New ServiceDataSet = Dim CompanyDataSet As New ServiceDataSet = My.WebServices.CompanyData.LoadDataSetMy.WebServices.CompanyData.LoadDataSet

Page 13: Microsoft Visual Basic 2005: New Language Features

Type Type three single-quotes above a class, field, method or enum to insert an XML Comment n XML Comment templatetemplate.

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.

XML CommentsXML CommentsNo More C# EnvyNo More C# Envy

Page 14: Microsoft Visual Basic 2005: New Language Features

New namespace: New namespace: System.Collections.GenericSystem.Collections.Generic

Create the equivalent of a custom Create the equivalent of a custom collection in one line of codecollection in one line of code Huge time saver when handling collections of Huge time saver when handling collections of

specific types.specific types. Create your own generic typesCreate your own generic types

GenericsGenericsSpecify Type at Declaration TimeSpecify Type at Declaration Time

Page 15: Microsoft Visual Basic 2005: New Language Features

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 PropertyEnd Class

Dim intList As New ArrayList()

intList.Add(1) ‘ Argument is boxedintList.Add(2) ‘ Argument is boxedintList.Add("Three") ‘ Should be an error

Dim i As Integer = CInt(intList(0)) ‘ Cast

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 PropertyEnd Class

Generics (Example)Generics (Example)

Dim intList As New List(Of Integer)

intList.Add(1) ‘ No boxingintList.Add(2) ‘ No boxingintList.Add("Three") ‘ Compile-time error

Dim i As Integer = intList(0) ‘ No cast

Page 16: Microsoft Visual Basic 2005: New Language Features

Generics (Specifics)Generics (Specifics)

Compile-time checkingCompile-time checking Eliminates runtime errorsEliminates runtime errors

Better performanceBetter performance No casting or boxing overheadNo casting or boxing overhead

Code re-useCode re-use Easy to create strongly typed collectionsEasy to create strongly typed collections

Common data structures in frameworkCommon data structures in framework Dictionary, HashTable, List, Stack, etc.Dictionary, HashTable, List, Stack, etc.

Page 17: Microsoft Visual Basic 2005: New Language Features

IsNot – logical counterpart to Is statement IsNot – logical counterpart to Is statement Using – acquire, execute, release resourcesUsing – acquire, execute, release resources Continue – skips to next iteration of loopContinue – skips to next iteration of loop TryCast – returns Nothing if cast fails TryCast – returns Nothing if cast fails Global – access to root (empty) namespaceGlobal – access to root (empty) namespace

New Language StatementsNew Language StatementsMaking the Language CompleteMaking the Language Complete

Page 18: Microsoft Visual Basic 2005: New Language Features

Clearer way of determining if an object has Clearer way of determining if an object has a value or is equivalent to another objecta value or is equivalent to another object

IsNotIsNotLogical counterpart to IsLogical counterpart to Is

'prior VB syntax If Not prd Is Nothing Then 'use prd... End If

'IsNot is cleaner If prd IsNot Nothing Then 'use prd... End If

Page 19: Microsoft Visual Basic 2005: New Language Features

Using StatementUsing StatementAcquire, Execute, ReleaseAcquire, Execute, Release

Fast way correctly release resources Fast way correctly release resources Easier to read than Try, Catch, FinallyEasier to read than Try, Catch, Finally

‘Using block disposes of resourceUsing fStr As New FileStream(path, FileMode.Append) For i As Integer = 0 To fStr.Length fStr.ReadByte() Next

‘End of block closes streamEnd Using

Page 20: Microsoft Visual Basic 2005: New Language Features

Continue StatementContinue StatementSkips to next iteration of loopSkips to next iteration of loop

Works with Do, For, While loopsWorks with Do, For, While loops Loop logic is concise, easier to read 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 jContinue For

End If

Graph(j) End WhileNext j

Page 21: Microsoft Visual Basic 2005: New Language Features

Using CType or DirectCast requires Try – Using CType or DirectCast requires Try – Catch logic in case conversion fails.Catch logic in case conversion fails.

Using TryCast results in cleaner code.Using TryCast results in cleaner code.

TryCastTryCastReturns Nothing if cast failsReturns Nothing if cast fails

'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

Page 22: Microsoft Visual Basic 2005: New Language Features

Global KeywordGlobal KeywordAccess to Root (empty) namespaceAccess to Root (empty) namespace

Complete name disambiguation Complete name disambiguation Better choice for code generationBetter 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

Page 23: Microsoft Visual Basic 2005: New Language Features

Create your own TypesCreate your own Types Conversion OperatorsConversion Operators Unsigned TypesUnsigned Types

Operator OverloadingOperator OverloadingOne Mark of a True OO LanguageOne Mark of a True OO Language

Page 24: Microsoft Visual Basic 2005: New Language Features

Operator OverloadingOperator OverloadingCreate your own base typesCreate 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 OperatorEnd Class

'new Complex + operator works intuitively'new Complex + operator works intuitively Dim lhs As Complex = New Complex(2.1, 3.3)Dim lhs As Complex = New Complex(2.1, 3.3) Dim rhs As Complex = New Complex(2.5, 4.6)Dim rhs As Complex = New Complex(2.5, 4.6) Dim res As Complex = lhs + rhsDim res As Complex = lhs + rhs 'res.real = 4.6, res.imag = 7.9'res.real = 4.6, res.imag = 7.9

Page 25: Microsoft Visual Basic 2005: New Language Features

Shared Narrowing Operator CType(ByVal Value As Complex)_ As String Return Value.Real.ToString & "i" & Value.Imag.ToStringEnd Operator

Overrides Function ToString(ByVal Value As Complex) _ As String Return Value.Real.ToString & "i" & Value.Imag.ToStringEnd Function

Conversion OperatorsConversion OperatorsYou Control Type ConversionsYou Control Type Conversions

Page 26: Microsoft Visual Basic 2005: New Language Features

Unsigned TypesUnsigned TypesFull support in the languageFull support in the language

Full platform parityFull platform parity Easier Win32 API calls and translationEasier Win32 API calls and translation Memory and performance winMemory and performance win

Dim sb As SByte = -4 ‘Error:negativeDim us As UShortDim ui As UIntegerDim ul As ULong

‘Full support in VisualBasic modulesIf IsNumeric(uInt) Then

‘ Will now return true End If

Page 27: Microsoft Visual Basic 2005: New Language Features

Property Accessor AccessibilityProperty Accessor Accessibility Custom Event AccessorsCustom Event Accessors Partial TypesPartial Types Application Level EventsApplication Level Events Compiler WarningsCompiler Warnings Explicit Array BoundsExplicit Array Bounds

Other FeaturesOther FeaturesRounding out Framework SupportRounding out Framework Support

Page 28: Microsoft Visual Basic 2005: New Language Features

Accessor AccessibilityAccessor AccessibilityGranular accessibility on Get and SetGranular accessibility on Get and Set

Forces calls to always use get, setForces calls to always use get, set Easy way to enforce validationEasy 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 SetEnd Property

Page 29: Microsoft Visual Basic 2005: New Language Features

Code gen when you type Custom keywordCode 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 RaiseEventEnd Event

Custom Event AccessorsCustom Event AccessorsDefine and Control Custom EventsDefine and Control Custom Events

Page 30: Microsoft Visual Basic 2005: New Language Features

Partial TypesPartial TypesSingle structure, class in multiple filesSingle structure, class in multiple files

Separates designer gen into another fileSeparates designer gen into another file Team dev / factor implementationTeam dev / factor implementation

Public Class Form1 Inherits Windows.Forms.Form

‘ Your CodeEnd Class

Partial Class Form1‘ Designer codeSub InitializeComponent() ‘ Form controlsEnd Sub

End Class

Page 31: Microsoft Visual Basic 2005: New Language Features

Events exposed:Events exposed: StartupStartup ShutdownShutdown StartupNextInstanceStartupNextInstance NetworkAvailabilityChangedNetworkAvailabilityChanged UnhandledExceptionUnhandledException

Found in ApplicationEvents.vb fileFound in ApplicationEvents.vb file

Application Level EventsApplication Level EventsSimilar to ASP.NET Global.asaxSimilar to ASP.NET Global.asax

Page 32: Microsoft Visual Basic 2005: New Language Features

Visual Basic WarningsVisual Basic WarningsEarly warning of runtime behaviorEarly warning of runtime behavior

Overlapping catch blocks or cases Overlapping catch blocks or cases Recursive property accessRecursive property access Unused Imports statementUnused Imports statement Unused local variableUnused local variable Function, operator without returnFunction, operator without return Reference on possible null referenceReference on possible null reference Option Strict broken downOption Strict broken down

““Late binding”Late binding” Visual Basic Style ConversionsVisual Basic Style Conversions Etc.Etc.

Page 33: Microsoft Visual Basic 2005: New Language Features

More precise array declarationsMore precise array declarations

Dim a(10) As Integer 'old wayDim b(0 To 10) As Integer 'new way

Explicit Array BoundsExplicit Array BoundsLower Bound Must Still be 0Lower Bound Must Still be 0

Page 34: Microsoft Visual Basic 2005: New Language Features

VB Language complete, full OO supportVB Language complete, full OO support Feature parity between all .NET languagesFeature parity between all .NET languages IDE support for language productivityIDE support for language productivity

SummarySummaryThe Best Visual Basic EverThe Best Visual Basic Ever

Page 35: Microsoft Visual Basic 2005: New Language Features

Visual Basic development center: Visual Basic development center: http://msdn.microsoft.com/vbasic/

Product feedback center: Product feedback center: http://lab.msdn.microsoft.com/productfeedback

E-mail: Stan Schultes E-mail: Stan Schultes [email protected]

ResourcesResources

Page 36: Microsoft Visual Basic 2005: New Language Features

AcknowlegementsAcknowlegements

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