360 likes | 486 Views
Microsoft Visual Basic 2005: New Language Features. Stan Schultes Architect, Developer, Author Microsoft MVP Visual Basic www.VBNetExpert.com stan@vbnetexpert.com. Agenda. Major Additions: My, XML Comments, Generics New Language Statements: Using, Continue, TryCast, Global, IsNot
E N D
Microsoft Visual Basic 2005:New Language Features Stan Schultes Architect, Developer, Author Microsoft MVP Visual Basic www.VBNetExpert.com stan@vbnetexpert.com
Agenda • Major Additions: • 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
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
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
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
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.
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”)
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
Settings Architecture Settings Base Application Settings Base Windows App Settings My Settings Provider Interface LocalSettings Remote Custom SQL Access Custom
App settings User Settings Settings in Action App.exe.config Read Only (app directory) <applicationSettings> … </applicationSettings> user.config Read/Write (local settings directory) <userSettings> … </userSettings>
Settings in Action My.Settings.WorkOffline = True‘ Settings automatically loaded on first access • Load My.Settings.WorkOffline = TrueMy.Settings.Save() • Save Private Sub Settings_SettingChanging(ByVal sender AsObject, _ ByVal e As SettingsArg) HandlesMyBase.SettingChanging If e.SettingName = “DataCache”Then If Not My.Computer.FileSystem.FileExists(e.Setting.Value)Then ‘ Cancel event End If End If End Sub • Handling events for validation
My.FormsMy.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
XML CommentsNo 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.
GenericsSpecify 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
Generics (Example) 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 Property 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 Property 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
Generics (Specifics) • Compile-time checking • 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.
New Language StatementsMaking 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
IsNotLogical 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 'use prd... End If
Using StatementAcquire, 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
Continue StatementSkips 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
TryCastReturns 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
Global KeywordAccess 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
Operator OverloadingOne Mark of a True OO Language • Create your own Types • Conversion Operators • Unsigned Types
Operator OverloadingCreate 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
Conversion OperatorsYou 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) _ As String Return Value.Real.ToString & "i" & Value.Imag.ToString End Function
Unsigned TypesFull support in the language • Full platform parity • Easier Win32 API calls and translation • Memory and performance win Dim sb As SByte = -4 ‘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
Other FeaturesRounding out Framework Support • Property Accessor Accessibility • Custom Event Accessors • Partial Types • Application Level Events • Compiler Warnings • Explicit Array Bounds
Accessor AccessibilityGranular 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
Custom Event AccessorsDefine 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
Partial TypesSingle 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 End Class
Application Level EventsSimilar to ASP.NET Global.asax • Events exposed: • Startup • Shutdown • StartupNextInstance • NetworkAvailabilityChanged • UnhandledException • Found in ApplicationEvents.vb file
Visual Basic WarningsEarly 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.
Explicit Array BoundsLower 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
SummaryThe Best Visual Basic Ever • VB Language complete, full OO support • Feature parity between all .NET languages • IDE support for language productivity
Visual Basic development center: http://msdn.microsoft.com/vbasic/ Product feedback center: http://lab.msdn.microsoft.com/productfeedback E-mail: Stan Schultes stan@vbnetexpert.com Resources
Acknowlegements • Some slides and content borrowed from Amanda Silver and Steven Lees of the VB Team at Microsoft.