Sei sulla pagina 1di 5796

Visual Studio 2005 Visual Basic

Copyright© 2016 Microsoft Corporation

The content in this document is retired and is no longer updated or supported. Some links might not work. Retired content represents the
latest updated version of this content.
Visual Basic Language Concepts

Visual Basic
Microsoft Visual Basic 2005 is an evolution of the Visual Basic language that is engineered for productively building type-safe
and object-oriented applications. Visual Basic allows developers to target Windows, Web, and mobile devices. As with all
languages targeting the Microsoft .NET Framework, programs written in Visual Basic benefit from security and language
interoperability.
This generation of Visual Basic continues the tradition of giving you a fast and easy way to create .NET Framework-based
applications.
This version of Visual Basic brings back support for Edit and Continue and has new features for rapid application development.
One of these features, called My, provides quick access to common tasks provided by the .NET Framework, as well as
information and default object instances that are related to the application and its run-time environment. New language
features include loop continuation, guaranteed resource disposal, operator overloading, generic types, and custom events.
Visual Basic also fully integrates the .NET Framework and the common language runtime (CLR), which provide language
interoperability, garbage collection, enhanced security, and versioning support.
In This Section
Getting Started with Visual Basic
Helps you begin working by listing what is new and what is available in various editions of the product.
Visual Basic Guided Tour
Steps you through various aspects of programming with Visual Basic.
Help for Visual Basic 6.0 Users
Discusses the differences in Visual Basic between version 6.0 and the current version.
Upgrading Applications in Visual Basic
Demonstrates how to upgrade various kinds of Visual Basic code.
Developing Applications with Visual Basic
Discusses various aspects of development in Visual Basic, such as the code editor, security, exception handling, debugging,
and making use of the .NET Framework class library.
Visual Basic Programming Guide
Introduces the essential components of Visual Basic, an object-oriented programming language.
Reference (Visual Basic)
Contains the Visual Basic language and compiler information.
Visual Basic Sample Applications
Contains information about samples.
Related Sections
Introducing Visual Studio
Provides information about new features, a high-level overview of Visual Studio and the .NET Framework, and tips for
getting started.
Integrated Development Environment for Visual Studio
Discusses the shared tools that allow you to design, develop, debug, and deploy applications.
Windows-based Applications, Components, and Services
Discusses Windows applications, components of various kinds, XML Web services, Windows services, console applications,
and 64-bit applications.
.NET Framework Programming in Visual Studio
Discusses application development with the .NET Framework.
Visual Web Developer
Discusses how to create Web applications.
.NET Framework Class Library Reference
Provides entry to the library of classes, interfaces, and value types that are included in the Microsoft .NET Framework SDK.
Visual Studio Tools for Office
Guides you in taking advantage of the productivity enhancements in the Microsoft .NET Framework version 2.0 to extend
Microsoft Office Word 2003, Microsoft Office Excel 2003, and Microsoft Office Outlook 2003.
Smart Device Development
Discusses development of software that runs on Windows CE-based smart devices such as Pocket PCs and Smartphones.
Visual Basic Language Concepts

Getting Started with Visual Basic


This section of the documentation helps you get started with Visual Basic application development.
In This Section
What's New in Visual Basic
Covers new features for Visual Basic.
Visual Basic Editions
Describes the features that come with Visual Studio and the .NET Framework.
Visual Basic Language Walkthroughs
Provides a list of Help pages that demonstrate aspects of the Visual Basic language.
Additional Resources for Visual Basic Programmers
Provides a list of Web sites and newsgroups that can help you find answers to common problems.
How Do I in Visual Basic
Provides categorized pages of links to "how-to" Help pages on important programming subjects.
Related Sections
Deciding Which Technologies and Tools To Use
Provides an interactive guide to help you choose which approach or technology to use, as well as links to more information.
Object-Oriented Programming in Visual Basic
Provides links to pages that introduce object-oriented programming and describe how to create your own objects and how
to use objects to simplify your coding.
Visual Basic Sample Applications
Provides links to sample code in Visual Basic.
Using Help in Visual Studio
Explains how to use filters and provides links to pages about searching Help, using the index, and finding information in the
MSDN Library.
Customizing the Development Environment
Covers how to set options for the integrated development environment (IDE), such as shortcut keys and debugging
preferences.
Product Support
Covers how to receive support and give feedback.
Visual Studio
Provides links into the Visual Studio documentation.
Visual Studio Editions
Lists the features of the three editions of Visual Studio.
Visual C#
Provides links into the documentation on application development with Visual C#.
Visual C++
Provides links into the Visual C++ documentation.
Visual J#
Provides links into the documentation on application development with Visual J#.
Visual Studio Tools for Office
Provides information on using Microsoft Office and Visual Studio as part of your business application.
Visual Basic Language Concepts

What's New in Visual Basic


This page lists the new and enhanced features available with this release of Visual Basic in Visual Studio 2005. Select from the
links below to read more details about a feature.
Note
If you are moving from Visual Basic 6.0 to Visual Basic 2005, there are a number of topics that help you make the move to th
e new version. For more information, see What's New for Visual Basic 6.0 Users.

Visual Basic Compiler and Language


Language improvements in Visual Basic 2005 simplify source code and enable interaction with components that use advanced
features. For more information, see What's New in the Visual Basic Language and What's New in the Visual Basic Compiler.
Visual Basic Development with My
Visual Basic 2005 provides new features for rapid application development that aim to improve productivity and ease of use
while delivering power. One of these features, called My, provides access to commonly used functionality provided by the .NET
Framework, as well as information and default object instances that are related to the application and its run-time
environment. This information is organized in a format that is discoverable through IntelliSense and logically delineated
according to use. For more information, see Development with My.
Developing Applications
The My.Application Object provides access to an application, allowing you to easily update it and log information from it.
My.Application can also be used to access an application's command-line arguments or run code when the application starts
or ends. For more information, see Updating an Application, Logging Information from the Application, and
Accessing a Running Application in Visual Basic.
Clipboard
The My.Computer.Clipboard Object provides easy access for reading from and writing to the Clipboard, along with methods
for clearing it and determining what type of data is stored on it. For more information, see
Storing Data to and Reading From the Clipboard.
Computer Resources
Many computer resources can be accessed through My objects, including the computer's clock, keyboard, mouse, ports, and
registry. For more information, see Accessing Computer Resources.
File Input/Output
The My.Computer.FileSystem Object provides file-access methods and properties that simplify file I/O. The
TextFieldParser Object allows you to parse large delimited or fixed-width text files; methods such as WriteAllText,
WriteAllBytes, ReadAllText, and ReadAllBytes make reading and writing to files intuitive while increasing performance.
Similarly, the GetFileInfo, GetDirectoryInfo, and GetDriveInfo methods provide information about files, directories, and
drives. For more information, see Parsing Text Files with the TextFieldParser Object.
Network Operations
The My.Computer.Network Object provides methods and properties for uploading and downloading files, for checking
connection status, and for determining whether remote computers are available. For more information, see
Performing Network Operations.
Resources
The My.Resources Object allows you to access resources such as audio resources, icon resources, and localized resources. For
more information, see Accessing Application Resources.
You can add and manage resources using the Resources page of the Project Designer. For more information, see
Resources Page, Project Designer.
User Settings and Application Settings
The My.Settings Object allows you to persist and change user settings as well as read application settings. For more
information, see Accessing Application Settings.
You can also manage application settings using the Settings page of the Project Designer. For more information, see
Settings Page, Project Designer.
Data Access
Visual Basic 2005 includes several new features to assist in developing applications that access data. The
Data Source Configuration Wizard simplifies connecting your application to data in databases, Web services, and user-created
objects.
The new Data Sources Window provides a central location to view the data available to and associated with your project, and it
reduces the complexity of data binding by allowing you to drag items from the window onto forms to create data-bound
controls.
Filling datasets, running queries, and executing stored procedures can now be accomplished using the new Visual Studio-
generated TableAdapter object. The new local data feature allows you to include Microsoft Access database files and Microsoft
SQL Server Express database files directly into your application. For a complete list of new features, see What's New in Data.
Design-Time Enhancements
Edit and Continue
Edit and Continue allows you to make changes to your application while it is running under the debugger without stopping
and restarting the application. The changes you make during break mode are applied immediately when you continue
execution of your application.
For more information, see Edit and Continue (Visual Basic).
Attribute Editing in Properties Window
You can now edit common attributes that apply to your classes and methods in the Properties window instead of having to
apply them in code.
See How to: Edit Code Attributes for more information.
IntelliSense Filtering
You can now adjust the level of detail supplied by IntelliSense in the Code Editor. When the IntelliSense window is displayed,
you can filter out the less commonly used members by clicking the Common tab, or see everything that is available by clicking
the All tab. By adjusting the level, you can easily filter out uncommon or esoteric members when they are not needed, or
include them when they are.
See Filtered Completion Lists in Visual Basic for more information.
IntelliSense in Zone
IntelliSense in Zone is a Visual Basic IntelliSense feature that displays certain items in the statement completion list in a
different color if they do not have enough permission to run in the security zone specified. This design-time support allows you
to more easily develop applications that run in partial trust.
See Visual Basic-Specific IntelliSense for more information. Also see How to: Set a Security Zone for a ClickOnce Application.
IntelliSense Code Snippets
The IntelliSense code snippet library consists of 380 prewritten pieces of code. You can add these reusable routines to your
code and edit them using the pointers the code contains. The code snippets are available to you when you right-click in the
Code Editor and click Insert Snippet. They are also available through keyboard shortcuts.
Code-snippet tasks range from creating a custom exception, to sending an e-mail message, to drawing a circle. Some are
simple expansions for common programming structures. The library is extensible; you can create code tasks that suit your
business needs and add them to the library. You can also download more library tasks from third-party software vendors and
Visual Basic community sites.
For more information, see: Visual Basic IntelliSense Code Snippets and How to: Insert Snippets Into Your Code (Visual Basic).
Error Correction and Warnings
With Smart Compile Error Correction, the Code Editor can suggest solutions to common errors and warnings and allow you
to select the appropriate correction, which is then applied to your code. When an error occurs, if there is a symbol under the
right side of the squiggle, resting your mouse over the squiggle turns the symbol into a smart tag panel. Clicking the smart tag
panel opens the Error Correction Options helper window, which provides a description of the error, suggests possible ways
to fix it, and, where appropriate, allows you to preview the fix.
For more information, see Smart Compile Auto Correction and Configuring Warnings in Visual Basic.
Exception Assistant
When you are debugging an application, by default the Exception Assistant opens to assist with unhandled exceptions. If you
choose, you can change the environment so that the Assistant appears when any exception occurs within your code. The
Exception Assistant lists the type of the exception, the message specific to the exception that has been thrown, a list of
trouble-shooting tips, and possible actions to apply.
For more information, see How to: Correct Run-Time Errors with the Exception Assistant.
XML Documentation
XML code documentation allows you to document your classes in code and expose that documentation as XML. The resulting
XML documentation can be consumed and displayed in a variety of ways, allowing you to create documentation for your code
while you are writing it.
For more information, see How to: Create XML Documentation in Visual Basic.
Document Outline Window
The Document Outline window now supports outline views for Windows Forms in addition to ASP.NET Web pages and
HTML pages. You can use the Document Outline window to navigate among the controls on Windows Forms while in
Design view of the editor. To access this window, on the View menu, click Other Windows and then click Document
Outline. For more information, see Document Outline Window
Project Designer for Managing Projects, Settings, and Resources
The Project Designer provides a centralized location for managing project properties, settings, and resources. It can be
accessed with the Properties command on the Project menu.
For more information, see Introduction to the Project Designer.
Settings Designer
The Settings page of the Project Designer allows you to specify a project's application settings, which can be user-scoped or
application-scoped. This feature replaces Dynamic Properties. For information, see Settings Page, Project Designer.
Resource Designer
The Resource Designer is a user interface tool that allows you to manage resources (such as strings, images, icons, audio, and
files) that a project uses. It creates strongly-typed resources that you can access at run time using the My.Resources Object. For
information about accessing resources through the My.Resources object, see Accessing Application Resources.
The Resources page of the Project Designer hosts an instance of the Resource Designer that stores and maintains
resources in a single location (Resources.resx). For more information, see Resources Page, Project Designer.
ClickOnce Deployment
ClickOnce deployment allows you to publish self-updating Windows-based and console applications that can be installed,
updated, and run as easily as Web applications. For more information, see ClickOnce Deployment.
The new Security, Signing, and Publish tabs on the Project Designer allow you to customize your ClickOnce deployment.
Use the new Publish command on the Build menu (or the shortcut menu in Solution Explorer) to get to the Publish
Wizard, a tool to step you through publishing your application. For more information, see Publish Page, Project Designer,
Signing Page, Project Designer, and Security Page, Project Designer.
64-bit Application Deployment
Both ClickOnce and Windows Installer deployment support installation on 64-bit platforms. For more information, see
Deploying 64-bit Applications.
Expanded Samples
Visual Basic 2005 ships over 60 sample applications. The new features covered include:
ClickOnce deployment
Programming with the My object
Language enhancements, including generics and XML comments
Data access
For more information, see Visual Basic Sample Applications.
Upgrading from Visual Basic 6.0
The upgrade tools in Visual Basic 2005 feature numerous enhancements, including the ability to upgrade many Visual Basic 6.0
ActiveX controls to their Visual Basic 2005 equivalents.
For more information, see What's New in Upgrading.
See Also
Concepts
What's New in Visual Studio 2005
What's New in Windows Forms and Windows Forms Controls
What's New in ASP.NET
What's New in Web Projects
What's New in Web Development for Visual Studio
What's New in Deployment
Visual Basic Language Concepts

What's New in the Visual Basic Language


Visual Basic 2005 introduces new language features, including loop continuation, guaranteed resource disposal, mixed access
properties, unsigned and nullable data types, operator overloading, partial and generic types, custom events, and
Common Language Specification (CLS) compliance checking.
This page lists features that are new to the Visual Basic language with Visual Basic 2005. For a discussion of features and
functionality that have changed from earlier versions, see Language Changes for Visual Basic 6.0 Users.
Continue Statement
Visual Basic now supplies a Continue statement, which immediately skips to the next iteration of a Do, For, or While loop. For
more information, see How to: Skip to the Next Iteration of a Loop and Continue Statement (Visual Basic).
Visual Basic 6.0 Form Access
Visual Basic now allows you to refer to a defined form, such as Form1, by using its class name, instead of explicitly creating an
instance of it. For more information, see How to: Access a Form.
IsNot Operator
Visual Basic now furnishes an IsNot operator, with which you can avoid using the Not and Is operators in an awkward order.
For more information, see How to: Test Whether Two Objects Are the Same and IsNot Operator.
TryCast Operator
Visual Basic now provides the TryCast type conversion operator that returns Nothing if the attempted conversion fails, unlike
CType and DirectCast which both throw an InvalidCastException error. For more information, see TryCast.
Using Statement
Visual Basic now offers a Using...End Using block to ensure disposal of a system resource when your code leaves the block
for any reason. For more information, see How to: Dispose of a System Resource and Using Statement (Visual Basic).
Explicit Zero Lower Bound on an Array
Visual Basic now permits an array declaration to specify the lower bound (0) of each dimension along with the upper bound.
For more information, see How to: Specify a Zero Lower Bound on an Array.
Properties with Mixed Access Levels
Visual Basic now allows you to declare a property with different access levels on its Get and Set procedures. For more
information, see How to: Declare a Property with Mixed Access Levels.
Unsigned Types
Visual Basic now supports unsigned integer data types (UShort, UInteger, and ULong) as well as the signed type SByte. For
more information, see How to: Call a Windows Function that Takes Unsigned Types,
How to: Optimize Storage of Positive Integers With Unsigned Types, UInteger Data Type, ULong Data Type (Visual Basic),
UShort Data Type (Visual Basic), and SByte Data Type (Visual Basic).
Nullable Types
Visual Basic now supports extensions of value types that can take either their normal values or a null value. A null value is
useful for indicating that a variable has no defined value because the information is not currently available. For more
information, see Value Types and Reference Types and Value Types that Might Not Have a Defined Value.
Operator Overloading
Visual Basic now allows you to define a standard operator (such as +, &, Not, or Mod) on a class or structure you have
defined. For more information, see How to: Use a Class that Defines Operators, How to: Define an Operator, and
Operator Statement.
Code Separation using Partial Types
Visual Basic now provides a mechanism to allow the integrated development environment (IDE) to separate generated code
from your authored code into separate source files. Most of the time, you only have to deal with the code you wrote. For more
information, see Partial (Visual Basic).
Generic Types
Visual Basic now supports type parameters on generic classes, structures, interfaces, procedures, and delegates. A
corresponding type argument specifies at compilation time the data type of one of the elements in the generic type. For more
information, see Generic Types in Visual Basic.
Custom Events
Visual Basic now allows you to have greater control over the detailed behavior of events. You can declare custom events by
using the Custom keyword as a modifier for the Event statement. In a custom event, you specify exactly what happens when
code adds or removes an event handler to or from the event, or when code raises the event. For examples, see
Event Statement, How to: Declare Events That Conserve Memory Use, and How to: Declare Events That Avoid Blocking. To
maintain backward compatibility with existing code, the Custom keyword is not a reserved keyword.
Compiler Checking Options
Visual Basic 2005 introduces new compiler checking options. The /nowarn and /warnaserror (Visual Basic) options provide
more control over how warnings are handled. Each one of these compiler options now takes a list of warning IDs as an
optional parameter, to specify to which warnings the option applies.
CLS Compliance Checking
Visual Basic now generates a warning for each line of code that contains any specification or operation that the
Common Language Specification (CLS) does not support.
Uninitialized Variable Checking
Visual Basic now generates a warning for each potentially uninitialized variable. A variable has this status if there is at least one
possible execution path that does not assign any value to the variable before using it.
For more information, see Configuring Warnings in Visual Basic.
See Also
Reference
Data Types Summary
Concepts
What's New in Visual Studio 2005
Writing CLS-Compliant Code
Object Lifetime: How Objects Are Created and Destroyed
Other Resources
Visual Basic Reference
Exception and Error Handling in Visual Basic
Visual Basic Language Concepts

What's New in the Visual Basic Compiler


Visual Basic 2005 includes new compiler options and other compiler changes.
Conditional Compilation
Visual Basic introduces the following new conditional-compilation constants for all projects:
TRACE. a Boolean value you can set to specify that methods of the Trace class generate output to the Output window.
VBC_VER. the Visual Basic version, in major.minor format. For Visual Basic 2005, the value of VBC_VER is 8.0.
For more information, see Conditional Compilation Constants
Default Command-Line Options in Vbc.rsp
The Visual Basic command-line compiler now stores the default command-line options in the Vbc.rsp file, in the same directory
as the command-line compiler, Vbc.exe. You can edit Vbc.rsp to reconfigure the default command-line options.
New Command-Line Options
There are seven new command-line compiler options:
The /codepage option specifies which code page to use when opening source files.
The /doc option generates an XML documentation file based on comments within your code.
The /errorreport option provides a convenient way to report a Visual Basic internal compiler error to Microsoft.
The /filealign option specifies the size of sections in your output file.
The /noconfig option specifies that the compiler should not automatically reference the commonly used .NET Framework
assemblies or import the System and Microsoft.VisualBasic namespaces.
The /nostdlib option removes the automatic reference to the System.dll assembly and other commonly used assemblies.
The /platform option specifies the processor to be targeted by the output file, in those situations where it is necessary to
explicitly specify it.
/nowarn and /warnaserror
The /nowarn and /warnaserror options provide more control over how warnings are handled. These compiler options now
takes a list of warning IDs as an optional parameter, to specify to which warnings the option applies.
See Also
Concepts
What's New in the Visual Basic Language
Visual Basic Language Concepts

Visual Basic Editions


This topic outlines and describes the features that are included in various editions of Visual Basic.
Visual Basic Project Templates
The best way to create new projects is by using Visual Basic templates, or application wizards. Project templates work in
conjunction with application frameworks and libraries to create starter programs for you.
The following table shows which Visual Basic project templates are available in the different editions of Visual Studio.
Template Microsoft Visual Basic 2005 Exp Visual Studio 2005 S Visual Studio 2005 Professional
ress Edition tandard and above
ASP.NET Web Site X X

ASP.NET Web Service X X

ASP.NET Crystal Reports Web Si X


te

Class Library X X X

Console Application X X X

Crystal Reports Application X

Device Application X X

Empty Project X X X

Empty Web Site X X

Excel Template X

Excel Workbook X

Movie Collection Starter Kit X X X

Outlook Add-in X

Personal Web Site Starter Kit X X

Pocket PC 2003: Class Library X X

Pocket PC 2003: Class Library (1 X X


.0)

Pocket PC 2003: Console Applic X X


ation

Pocket PC 2003: Console Applic X X


ation (1.0)

Pocket PC 2003: Control Library X X


Pocket PC 2003: Device Applicat X X
ion

Pocket PC 2003: Device Applicat X X


ion (1.0)

Pocket PC 2003: Empty Project X X

Pocket PC 2003: Empty Project ( X X


1.0)

Screen Saver Starter Kit X X X

SQL Server Project X

Smartphone 2003: Class Library X X


(1.0)

Smartphone 2003: Console Appl X X


ication (1.0)

Smartphone 2003: Device Appli X X


cation (1.0)

Smartphone 2003: Empty Projec X X


t (1.0)

Test Project X

Web Control Library X X

Windows Application X X X

Windows CE 5.0: Class Library X X

Windows CE 5.0: Console Applic X X


ation

Windows CE 5.0: Control Library X X

Windows CE 5.0: Device Applicat X X


ion

Windows CE 5.0: Empty Project X X

Windows Control Library X X

Windows Service X

Word Document X

Word Template X

For more information on available project templates and items, see Default Project Templates in Visual Studio. For information
on File Types File Types and File Extensions in Visual Basic, Visual C#, and Visual J#.
Visual Tools
The following designers are included in Visual Basic.
Feature Description Microsoft Visual Visual Stu Visual Studio 20
Basic 2005 Expr dio 2005 S 05 Professional
ess Edition tandard and above
Web Forms Designer Provides a set of visual tools for worki X
ng with ASP.NET Web Forms pages an
d controls.

Windows Forms Designer Provides a set of visual tools for worki X X X


ng with Windows Forms and controls.

Component Designer Provides a set of visual tools for worki X


ng with nonvisual components.

XML Schema Designer (XML Designer) Provides a set of visual tools for worki X
ng with XML schemas, ADO.NET datas
ets, and XML documents.

Visual Database Tools Provides a set of tools for working wit X X X


h databases.

Class View Displays the symbols defined, referenc X X


ed, or called in the application you are
developing

Crystal Reports Provides tools to create reports for Wi X


ndows and Web applications.

Report Viewer Provides reporting tools for custom a X


pplications.

To see a complete listing of the features in various editions of Visual Studio, see Visual Studio Editions.
See Also
Tasks
How to: Modify Project Properties and Configuration Settings
Reference
Visual Basic Settings
Concepts
Installation and Setup Essentials
Visual Database Tools Editions
Project Types in Visual Basic Express
Other Resources
Visual Studio Editions
Visual Basic Language Concepts

Visual Basic Language Walkthroughs


Walkthroughs give step-by-step instructions for common scenarios, which makes them a good place to start learning about
the product or a particular feature area.
In This Section
Walkthrough: Declaring and Raising Events
Illustrates how events are declared and raised in Visual Basic.
Handling Events
Shows how to handle events using either the standard WithEvents keyword or the new AddHandler/RemoveHandler
keywords.
Defining Classes
Describes how to declare a class and its fields, properties, methods, and events.
Calling Windows APIs
Explains how to use Declare statements and call Windows APIs. Includes information about using attributes to control
marshaling for the API call and how to expose an API call as a method of a class.
Creating and Implementing Interfaces
Shows how interfaces are declared and implemented in Visual Basic.
Multithreading
Shows how to create a multithreaded application that searches a text file for occurrences of a word.
Structured Exception Handling
Demonstrates how to create and maintain programs with comprehensive error handling, and how to use
Try...Catch...Finally.
Creating COM Objects with Visual Basic
Demonstrates how to create COM objects in Visual Basic, both with and without the COM class template.
Implementing Inheritance with COM Objects
Demonstrates how to use Visual Basic 6.0 to create a COM object containing a class, and then use it as a base class in Visual
Basic.
Manipulating Files and Folders in Visual Basic
Demonstrates how to use Visual Basic functions to determine information about a file, search for a string in a file, and write
to a file.
Manipulating Files Using .NET Framework Methods
Demonstrates how to use .NET Framework methods to determine information about a file, search for a string in a file, and
write to a file.
Related Sections
Visual Basic Walkthroughs
Provides links to Visual Basic walkthroughs covering distributed applications, data, Web services, Windows Forms, Web
Forms, component and control authoring, Framework Services, upgrading, internationalization, and accessibility.
Visual Basic Language Concepts

Additional Resources for Visual Basic Programmers


The following Web sites and newsgroups can help you find answers to common problems.
Microsoft Resources
On the Web
Microsoft Help and Support
Provides access to Knowledge Base (KB) articles, downloads and updates, support Webcasts, and other services.
Microsoft Visual Basic Developer Center
Provides code samples, upgrade information, free downloads, and technical content.
Microsoft Visual Basic Team Blog
Provides access to the Visual Basic team blog.
Microsoft ASP.NET
Provides articles, demonstrations, tool previews, and other information for Web development in Visual Basic.
GotDotNet for Visual Basic
Contains articles, samples, and other information of interest to Visual Basic developers.
Chats, Forums and Discussion Groups
MSDN Forums
Provides Web-based discussion forums for many Microsoft technologies, including Visual Basic and the .NET Framework.
MSDN Discussion Groups
Provides a newsgroup experience, allowing you to connect as a community with experts from around the world.
MSDN Chats
Provides discussions about Microsoft products or technologies. Each chat is hosted by one or more Microsoft experts.
Transcripts are available for completed chats.
Videos and Webcasts
Visual Basic at the Movies
Showcases 101 short films aimed at delivering new Visual Basic skills to everybody from the beginner to the advanced
developer.
Channel9
Provides continuous community through videos, Wikis, and forums.
Third-Party Resources
MSDN's Web site provides information on current third-party sites and newsgroups of interest. For the most current list of
resources available, see the MSDN Visual Basic Community Web site.
On the Web
DevX Visual Basic Zone
Provides in-depth technical articles for today's Visual Basic developer moving to Visual Basic 2005.
devCity.NET
Provides access to more than 5,000 Microsoft Visual Basic and Active Server Pages (ASP) articles, source code, tutorials, and
user-submitted content when you join devCity.NET.
See Also
Other Resources
Getting Started with Visual Basic
Interacting with Other Developers
Product Support and Accessibility
Visual Basic Language Concepts

How Do I in Visual Basic


How Do I is your gateway to key task-based topics about Visual Basic programming and application development. The
essential categories of what you can do with Visual Basic are listed in this topic. The links provide pointers to important
procedure-based Help pages.
Learn the Visual Basic Language (How Do I in Visual Basic)
Object-oriented Programming … Manage Control Flow … Work with Variables … Handle Errors and Exceptions … more
Upgrade For Visual Basic 6 Users (How Do I Visual Basic)
Upgrade a Visual Basic 6 Application … Learn the .NET Framework … more
Data Access (How Do I in Visual Basic)
Getting Started … Load Data … Validate Data … more
Deployment (How Do I in Visual Basic)
Deploy with ClickOnce … Use Setup Projects … Use other Deployment Projects … more
Windows Applications (How Do I in Visual Basic)
Forms and Controls … Data … Printing … more
Web Applications (How Do I in Visual Basic)
Develop a Web Site … User Web Forms and Controls … Deploy a Web Site … more
Web Services (How Do I in Visual Basic)
Create a Web Service … Call a Web Service … Debug a Web Service ... more
Office Programming (How Do I in Visual Basic)
Excel Applications … Word Applications … more
Smart Device Applications (How Do I in Visual Basic)
Work with Data … Work with Controls … Deploy Smart Device Applications … more
Security (How Do I in Visual Basic)
Web Applications … Windows Applications …Components … more
Debug and Test (How Do I in Visual Basic)
Debug Applications … Monitor Applications … more
Visual Basic Language Concepts

Upgrade For Visual Basic 6 Users (How Do I Visual Basic)


This page links to help on getting up and running with Visual Basic .NET if you're coming from a Visual Basic 6 background. To
view other categories of popular tasks covered in Help, see How Do I in Visual Basic.
In General
Help for Visual Basic 6.0 Users
Highlights changes to various features since Visual Basic 6.0.
What's New in the Visual Basic Language
Describes new and improved language features — such as inheritance, interfaces, overriding, shared members, and
overloading.
Walkthrough: Upgrading a Visual Basic 6.0 Application to the Current Version of Visual Basic
Shows upgrading a Visual Basic graphics sample application to Visual Basic .NET. In addition to illustrating the upgrading
process, this walkthrough highlights the differences in graphics architectures between Visual Basic 6.0 and Visual Basic .NET.
Preparing a Visual Basic 6.0 Application for Upgrading
Details a number of things you can do to optimize your upgrade with a little bit of preparation.
By following the recommendations in this topic, you can minimize and, in some cases, eliminate the changes needed after
upgrading your project to Visual Basic .NET.
Things to Consider Before Upgrading
Describes areas where compatibility with previous versions is broken.
Development with My
Describes the Visual Basic feature designed to provide access to information and default object instances that are related to
the application and its run-time environment.
Additional Resources for Visual Basic Programmers
For information on the various Microsoft and third-party sites for Visual Basic.
Upgrade a Visual Basic 6 Application
Working with Both Visual Basic 6.0 and the Current Version of Visual Basic
Highlights changes to various features since Visual Basic 6.0.
Walkthrough: Upgrading a Visual Basic 6.0 Application to the Current Version of Visual Basic
Shows upgrading a Visual Basic graphics sample application to Visual Basic .NET. In addition to illustrating the upgrading
process, this walkthrough highlights the differences in graphics architectures between Visual Basic 6.0 and Visual Basic .NET.
Upgrading from Visual Basic 6.0
Provides links to help topics that show you how to upgrade your applications and quickly learn about changes in Visual Basic
2005.
How to: Upgrade a Project with the Visual Basic Upgrade Wizard
Steps you through upgrading a Visual Basic 6 project with an easy-to-use wizard.
Preparing a Visual Basic 6.0 Application for Upgrading
Details a number of things you can do to optimize your upgrade with a little bit of preparation.
By following the recommendations in this topic, you can minimize and, in some cases, eliminate the changes needed after
upgrading your project to Visual Basic .NET.
Things to Consider Before Upgrading
Describes areas where compatibility with previous versions is broken.
COM Interop
Describes COM Interop in the context of Visual Basic applications.
Additional Resources for Visual Basic Programmers
For information on the various Microsoft and third-party sites for Visual Basic.
Work with Data (for Visual Basic 6 users)
Data Access for Visual Basic 6.0 Users
Describes a number of differences both conceptually and in terms of tasks between ADO and ADO.NET.
Comparison of ADO.NET and ADO
Explains ADO.NET for those familiar with ADO.
Learn the .NET Framework
.NET Framework Conceptual Overview
Explains the features of the common language runtime and the .NET Framework class library.
Visual Basic and the .NET Framework
Explains the essentials of .NET programming from a Visual Basic perspective.
Introduction to the .NET Framework Class Library in Visual Studio
Explains how to use namespaces and assemblies.
VBRun
The Visual Basic 6.0 Resource Center. Provides links to downloads, articles, newsgroups, user groups, and other resources.
http://msdn.microsoft.com/VBRun/
Additional Resources for Visual Basic Programmers
For information on the various Microsoft and third-party sites for Visual Basic.
See Also
Concepts
How Do I in Visual Basic
Visual Basic Language Concepts

Learn the Visual Basic Language (How Do I in Visual Basic)


This page links to help on widely used Visual Basic programming tasks. To view other categories of popular tasks covered in
Help, see How Do I in Visual Basic.
In General
What's New in Visual Basic
Lists the new and enhanced features available with this release of Visual Basic in Visual Studio 2005.
Language Changes for Visual Basic 6.0 Users
Provides a list of changes, with links to details, about how the Visual Basic language has changed since Visual Basic 6.0.
Object-Oriented Programming with Visual Basic 2005
When to Use Inheritance
Discusses when to use inheritance instead of interfaces.
Inheritance Basics
Covers inheritance modifiers, overriding methods and properties, MyClass, and MyBase.
How to: Define an Operator
Shows how to define the behavior of a standard operator (such as *, <>, or And) when one or both of the operands is of the
type of your class or structure.
How to: Access Members of an Object
Explains how to read, write, or call a member of an object that you have created.
How to: Define Multiple Versions of a Procedure
Explains how to define a procedure in multiple versions by overloading it, using the same name but a different parameter list
for each version.
Work with Properties
How to: Put a Value in a Property
Demonstrates how to store a value in a property.
How to: Get a Value from a Property
Demonstrates how to retrieve the value stored in a property.
How to: Declare and Call a Default Property in Visual Basic
Demonstrates how to declare and call a property that can be accessed without using its name.
How to: Declare a Property with Mixed Access Levels
Demonstrates declaring properties with different access levels for storing and retrieving.
How to: Create a Property
Demonstrates how to create a property.
Use Inheritance
How to: Define a Class That Uses Members of an Existing Class.
Shows example code for creating a class that derives from another class.
How to: Hide an Inherited Variable
Demonstrates using the Shadows keyword to hide an inherited variable.
How to: Access a Variable Hidden by a Derived Class
Demonstrates how to access a base class variable that is hidden in a derived class.
Work with Procedures
How to: Create a Procedure
Explains how to declare a procedure to perform a task that is needed in several places in your code.
How to: Call a Procedure that Returns a Value
Shows two ways to call a Function procedure and use the value it returns.
How to: Call a Procedure that Does Not Return a Value
Discusses how to call a Sub procedure, which performs a task but does not return a value to the calling code.
How to: Define a Parameter for a Procedure
Covers defining a parameter list to accept values passed to the procedure by the calling code.
How to: Pass Arguments to a Procedure
Demonstrates how to pass a value to a procedure by supplying an argument for each of its parameters.
Manage Program Control Flow
How to: Break Large Pieces of Code into Smaller Pieces.
Explains how to use procedures to achieve structured programming in your code
How to: Break and Combine Statements in Code
Covers breaking a single statement into several source code lines and combining several statements onto one source line.
How to: Add a Comment to Your Code (Visual Basic)
Shows two ways to place explanatory comments in your source code.
Conditional Statements
How to: Run Statements Depending on One or More Conditions
Demonstrates using If...Then...Else constructions to run different blocks of statements depending on various conditions.
Functions and Subroutines
How to: Create a Procedure
Explains how to declare a procedure to perform a task that is needed in several places in your code.
How to: Call a Procedure that Returns a Value
Shows two ways to call a Function procedure and use the value it returns.
How to: Call a Procedure that Does Not Return a Value
Discusses how to call a Sub procedure, which performs a task but does not return a value to the calling code.
How to: Define a Parameter for a Procedure
Covers defining a parameter list to accept values passed to the procedure by the calling code.
How to: Pass Arguments to a Procedure
Demonstrates how to pass a value to a procedure by supplying an argument for each of its parameters.
Loop Statements
How to: Skip to the Next Iteration of a Loop
Explains how to skip out of the current iteration of a loop and proceed to the next iteration.
How to: Run Several Statements Repeatedly
Shows how to run a block of statements either a set number of times or until a condition is met.
How to: Iterate through a Collection in Visual Basic
Demonstrates a For Each...Next loop, which runs the same statements for each element of a collection.
How to: Improve the Performance of a Loop
Covers choosing the most efficient data type for the control variable of a loop.
Work with Collections, Generics, and Arrays
How to: Define Collections in Your Classes
Demonstrates defining and using a simple Visual Basic Collection object.
Managing Your Objects with Collections
Discusses criteria to consider when choosing the type of collection for grouping related objects.
How to: Add, Delete, and Retrieve Items of a Collection
Describes the fundamental operations of adding a new element, removing an existing element, and retrieving an element.
How to: Create a Collection of Objects
Covers Visual Basic collections and generic collections, how to create them, and how to iterate through them.
Collections
How to: Create an Array of Objects
Explains arrays as an alternate way to group related objects together.
Troubleshooting Collections
Lists common problems encountered with collections and shows how to deal with them.
Generics
How to: Use a Generic Class
Demonstrates how to use a class that takes one or more type parameters.
How to: Pass an Array to a Procedure or Property
Discusses how to pass an array of values to a procedure or property using the argument list.
How to: Define a Class That Can Provide Identical Functionality on Different Data Types
Shows how to define a single class that adapts to different data types to perform the same functionality.
Arrays
How to: Create an Array
Shows two ways to create an array object and assign it to an array variable.
How to: Initialize an Array Variable
Explains how to store an array in an array variable, and how to set its length and element values.
How to: Initialize a Jagged Array
Shows four ways to store an array of arrays, or jagged array, in a variable, and how to set its length and element values.
How to: Initialize a Multidimensional Array
Shows four ways to store an array of more than one dimension in a variable, and how to set its length and element values.
How to: Put a Value into an Array
Describes how to store a value in an array element.
How to: Sort An Array in Visual Basic
Explains how to sort the elements of an array alphabetically.
How to: Reverse the Contents of An Array in Visual Basic
Demonstrates how to reverse the order of the elements of an array.
How to: Specify a Zero Lower Bound on an Array
Discusses making your code easier to read by declaring the lower bound of an array as zero.
Work with Variables
How to: Create a New Variable
Covers the Dim statement and the various keywords and clauses you can use to create a variable.
How to: Create an Object
Discusses object variables and how to create an instance of a class.
How to: Move Data Into and Out of a Variable
Describes how to store and retrieve the value of a variable.
Declare and Initialize Variables
How to: Declare an Object Variable and Assign an Object to It in Visual Basic
Explains the Object data type and how to assign an object of any type to it.
How to: Hold More Than One Value in a Variable
Discusses composite data types such as structures, arrays, and classes, which can hold multiple values.
How to: Hold True and False Values in a Variable
Discusses the Boolean data type and how to declare variables to hold logical values.
How to: Lengthen a Variable's Lifetime
Describes the Static keyword and how to use it to make a variable exist after its containing element ceases to exist.
How to: Determine Whether Two Objects Are Related
Demonstrates using the GetType method to find out if one object inherits from another.
Control Variable Scope
How to: Control the Scope of a Variable
Discusses the levels of scope and how to use them to control what code can make a reference to a variable.
How to: Control the Availability of a Variable
Explains the different access levels and how to assign one to a variable to control what code can read or write it.
How to: Hide a Variable with the Same Name as Your Variable
Shows two ways to use shadowing to hide a variable with another one of the same name.
Interact with Data Types
Data Types in Visual Basic
Describes how to assign a data type to various kinds of programming elements.
Characters and Strings
How to: Hold Characters in a Variable
Discusses the Char and String data types and how to declare variables to hold character values.
How to: Match a String against a Pattern
Shows how to use the Like operator to match a character in a string against a variety of character sets.
How to: Remove Parts of a String (Visual Basic)
Demonstrates how to remove all occurrences of a substring from a string.
Numeric Values
How to: Hold Integers in a Variable
Discusses the SByte, Short, Integer, and Long data types and how to declare variables to hold signed integer values.
How to: Hold the Most Significant Digits in a Variable
Discusses the Decimal data type and how to declare variables to hold up to 29 significant digits.
How to: Hold the Largest Possible Number in a Variable
Discusses the ULong, Decimal, Single, and Double data types and how to declare variables to hold very large values.
How to: Hold Fractions in a Variable
Discusses the Single and Double data types and how to declare variables to hold fractional values.
Convert Data Types
How to: Convert an Object to Another Type in Visual Basic
Covers type conversions from the Object data type to a more specific data type.
Date and Time
How to: Hold Date and Time Values in a Variable
Discusses the Date data type and how to declare variables to hold date and time values.
Unsigned Types
How to: Optimize Storage of Positive Integers With Unsigned Types
Discusses the UInteger data type and how to declare variables to hold positive integer values with optimum efficiency.
How to: Call a Windows Function that Takes Unsigned Types
Discusses the Byte, UShort, UInteger, and ULong data types and how to interface with functions that use unsigned types.
Currency
How to: Hold Money Values in a Variable.
Discusses the Decimal data type and how to declare variables to hold monetary values.
Program using Events
How to: Call an Event Handler in Visual Basic
Demonstrates how to define an event and an event handler, and uses the AddHandler statement to associate them.
How to: Create Event Handlers in the Visual Basic Code Editor
Gives directions for using the Visual Basic Code Editor to write code to respond to events.
How to: Raise an Event (Visual Basic)
Demonstrates how to define an event and uses the RaiseEvent statement to cause the event to occur.
Walkthrough: Declaring and Raising Events
Steps through the process of declaring and raising events for a class.
Walkthrough: Handling Events
Demonstrates how to write an event handler procedure.
Handle Errors and Exceptions
How to: Retrieve Information from an Error Object
Demonstrates how to get information from the Err object's properties.
How to: Retain Control When an Error Occurs
Shows how to run a particular block of statements if a specified exception occurs while your code is running.
Walkthrough: Structured Exception Handling
Provides a walkthrough of creating a simple application and inserting exception handling code.
How to: Test Code with a Try…Catch Block in Visual Basic
Demonstrates how to use a Try...Catch block to test a section of code.
Samples
Visual Basic Language Samples
These samples demonstrate Visual Basic language concepts.
See Also
Concepts
How Do I in Visual Basic
Visual Basic Language Concepts

Data Access (How Do I in Visual Basic)


This page links to help on widely used Visual Basic data tasks. To view other categories of popular tasks covered in Help, see
How Do I in Visual Basic.
In General
What's New in Data
Provides information and links to new data features for client data applications.
Getting Started with Data Access
Provides links to topics on creating applications that work with data, using Visual Studio.
Creating Data Applications with Visual Studio
Describes the process of creating a data application in Visual Studio.
Walkthrough: Creating a Simple Data Application
Provides step by step instruction for creating a basic data access application.
Data Access for Visual Basic 6.0 Users
Describes changes to data access and data tools
ADO.NET
Provides links to topics that explain the data access features in the .NET Framework.
Local Data Overview
Describes the features in Visual Studio for working with SQL Server Express and Access databases.
Object Binding in Visual Studio
Describes the features in Visual Studio for binding data to objects.
ASP.NET Data Access (Visual Studio)
Provides links to information on working with data on ASP.NET Web pages.
Data in Office Solutions
Contains links to topics that explain how data works in Office solutions.
Data in Managed Device Projects
Describes how to manage data for devices in Visual Studio.
Display Data on Windows Forms
Displaying Data Overview
Describes the process of displaying data on Windows Forms.
Data Sources Window
Describes how to create data-bound forms by dragging items from the Data Sources Window.
How to: Bind Data to Existing Controls
Describes how to bind an existing control to a specific field of data.
How to: Display Data in a Windows Forms DataGridView Control
Describes how to present data in a DataGridView on a Windows Form.
How to: Display Data in Individual Windows Forms Controls
Describes how to present data in individual controls on a Windows Form.
How to: Display Related Data in a Windows Application
Describes how to present data from related tables in a dataset on a Windows Form.
How to: Add a Parameterized Query to a Form in a Windows Application
Describes how to modify an existing Windows Form to include controls to input parameters and execute a query.
How to: Set the Control to be Created when Dragging from the Data Sources Window
Describes how to set the control that will be created when dragging items from the Data Sources Window onto a Windows
Form.
How to: Add Custom Controls to the Data Sources Window
Describes how to modify the list of controls available for items in the Data Sources Window, and how to add custom controls
to the list.
How to: Open the Data Sources Window
Describes how to open the Data Sources Window in the Visual Studio IDE.
Walkthrough: Displaying Data on a Form in a Windows Application
Provides step by step details on querying data from a database and displaying the data on a Windows Form.
Walkthrough: Displaying Related Data on a Form in a Windows Application
Provides step by step details on displaying data from two related tables and displaying the data on a Windows Form.
Walkthrough: Creating a Form to Search Data in a Windows Application
Provides step by step details on creating a Windows Form that searches for records in a database based on values input by a
user.
Walkthrough: Creating a Lookup Table
Provides step by step details on displaying data from one table based on the data selected in another table.
Walkthrough: Passing Data Between Forms in a Windows Application
Provides step by step details on passing values from one form to a second form in an application.
Walkthrough: Creating a User Control that Supports Simple Data Binding
Provides step by step details on creating a custom control with attributes specific to working with Windows Forms
databinding.
Connect Applications to Data
Connecting to Data in Visual Studio Overview
Provides information about connecting your application to data with design time tools, and ADO.NET connection objects,
using Visual Studio.
Data Source Configuration Wizard
Provides information on connecting to data, and creating data sources, by running the Data Source Configuration Wizard.
How to: Save a Connection String
Describes how to save connection information in your application.
How to: Edit a Connection String
Describes how to edit existing connection information previously saved in your application.
How to: Connect to Data in an Object
Describes how to databind to property values in objects using the Data Source Configuration Wizard.
How to: Connect to Data in a Database
Describes how to create a connection between your application and a database using the Data Source Configuration
Wizard.
How to: Connect to Data in a Web Service
Describes how to create a connection between your application and the data returned from a web service using the Data
Source Configuration Wizard.
How to: Connect to Data in an Access Database
Describes how to create a connection between your application and an Access database using the Data Source
Configuration Wizard.
How to: Connect to Data in a SQL Server Express Database
Describes how to create a connection between your application and a SQL Express database using the Data Source
Configuration Wizard.
How to: Create Connections to SQL Server Databases
Describes how to create connection strings to SQL Server databases.
How to: Create Connections to Access Databases
Describes how to create connection strings to Access databases.
How to: Create Connections to Oracle Databases
Describes how to create connection strings to Oracle databases.
Walkthrough: Connecting to Data in a Database
Provides step by step details for creating a connection between your application and a database.
Walkthrough: Connecting to Data in a SQL Server Express Database
Provides step by step details for creating a connection between your application and a SQL Express database.
Walkthrough: Connecting to Data in a Web Service
Provides step by step details for creating a connection between your application and a Web service.
Walkthrough: Connecting to Data in Objects
Provides step by step details for creating a connection between your application and the properties of an object.
Walkthrough: Connecting to Data in an Access Database
Provides step by step details for creating a connection between your application and an Access database file.
Connecting to a Data Source Using ADO.NET
Describes the ADO.NET Connection object and how to use it to connect to a data source.
Modify Data
How to: Add Rows to a DataTable
Provides the steps to create DataRow objects and add them to a data table.
How to: Edit Rows in a DataTable
Provides the steps for editing an existing row of data in a data table.
How to: Delete Rows in a DataTable
Provides the steps to remove specific rows of data in a data table.
How to: Turn Off Constraints While Filling a Dataset
Provides details for temporarily disabling constraint checking in a dataset.
How to: Commit Changes in a Dataset
Provides information and details for accepting changes that have been made to data in a dataset.
How to: Check for Changed Rows
Provides the steps to determine if data has been changed in a dataset.
How to: Retrieve Changed Rows
Provides details for returning rows of data that have been changed since last accepting any changes.
How to: Locate a Specific Row in a DataTable
Provides details for finding data in a data table using either a primary key value, or a column value.
How to: Get Specific Versions of a DataRow
Provides details for returning specific rows of data using the DataRowVersion enumeration.
How to: Locate Rows that Have Errors
Provides details for finding data in a data table that has been marked with an error.
Save Data
Saving Data Overview
Provides links to topics explaining how to send updated data from an application to the database.
How to: Save Dataset Changes to a Database
Provides details on sending updated data back to a database using TableAdapters, and DataAdapters.
How to: Update Data Using a TableAdapter
Provides details on sending updated data back to a database using TableAdapters.
How to: Insert New Records into a Database
Provides details on creating new records in a database.
How to: Update Records in a Database
Provides details on sending modified records back to the database.
How to: Delete Records in a Database
Provides details on removing records from a database.
Walkthrough: Saving Data to a Database (Single Table)
Provides step by step details for saving modified data in a data table to the underlying database.
Walkthrough: Saving Data to a Database (Multiple Tables)
Provides step by step details for saving modified data in two related data tables to the underlying database.
Walkthrough: Saving Data in a Transaction
Provides step-by-step details for saving data using the System.Transactions namespace.
Work with TableAdapters
TableAdapter Overview
Explains what TableAdapters are and the tools available to create them.
TableAdapter Query Configuration Wizard
Describes how to run the wizard and provides details for each wizard screen.
How to: Create TableAdapters
Provides the steps to create a new TableAdapter.
How to: Edit TableAdapters
Provides the steps to edit existing TableAdapters.
How to: Create TableAdapter Queries
Provides the steps to add a query to an existing TableAdapter.
How to: Edit TableAdapter Queries
Provides the steps to edit existing TableAdapter queries.
Working with Null Values in TableAdapters
Provides the steps for enabling null values in TableAdapter parameters.
How to: View the Queries in a TableAdapter
Explains how to view the existing queries in a TableAdapter.
How to: Create Parameterized TableAdapter Queries
Provides the steps to create TableAdapter queries that accept parameters.
How to: Add Global Queries to a Dataset
Provides the steps to create a TableAdapter with a query that returns a single value.
Walkthrough: Creating a TableAdapter with Multiple Queries
Provides step-by-step instructions for creating a TableAdapter and adding a query to it.
Design and Display Reports
ReportViewer Controls in Visual Studio 2005
Describes two new ReportViewer controls that you can use to embed reports in a Windows or Web-based application.
Creating Reports (with Crystal Reports)
Provides detailed information about using the embedded Crystal Reports Designer within Visual Studio.
Data Samples
Visual Basic Data Samples
These sample demonstrate data access.
Fetch Data
Filling Datasets and Querying Data Overview
Describes how to load data into datasets, and how to execute stored procedures, and execute queries against a database.
How to: Fill a Dataset with Data
Provides details for loading data into datasets using TableAdapters, and DataAdapters.
How to: Create and Execute an SQL Statement that Returns Rows
Provides details for creating and executing SQL statements that return rows using TableAdapter queries, and Command
objects.
How to: Create and Execute an SQL Statement that Returns a Single Value
Provides details for creating and executing SQL statements that return single values using TableAdapter queries, and
Command objects.
How to: Create and Execute an SQL Statement that Returns No Value
Provides details for creating and executing SQL statements that return no value using TableAdapter queries, and Command
objects.
How to: Execute a Stored Procedure that Returns Rows
Provides details for executing stored procedures that return rows using TableAdapter queries, and Command objects.
How to: Execute a Stored Procedure that Returns a Single Value
Provides details for executing stored procedures that return single values using TableAdapter queries, and Command
objects.
How to: Execute a Stored Procedure that Returns No Value
Provides details for executing stored procedures that return no value using TableAdapter queries, and Command objects.
How to: Set and Get Parameters for Command Objects
Provides details for assigning values to parameters in queries and stored procedures, and reading values in parameters
returned from executed commands.
Validate Data
Data Validation Overview
Provides an overview of events that can be used to analyze data before being committed to the dataset.
How to: Validate Data During Column Changes
Describes how to validate data during the ColumnChanging event.
How to: Validate Data During Row Changes
Describes how to validate data during the RowChanging event.
Walkthrough: Adding Validation to a Dataset
Provides step by step information for adding validation code to a dataset.
Work with Datasets
How to: Create a Typed Dataset
Explains how to create a typed dataset using design tools in Visual Studio.
How to: Extend the Functionality of a Dataset
Explains how and where to place code when extending the functionality of a typed dataset.
How to: Create DataTables
Provides the steps to create a new DataTable with the Dataset Designer.
How to: Add Columns to a DataTable
Provides the steps to create a new DataColumn in an existing DataTable.
How to: Set the Data Type of a DataColumn
Explains how to set or change the data type property of a DataColumn.
How to: Change the Caption of a DataColumn
Explains how to set the caption of a DataColumn to either the column name or something else.
How to: Set the Default Value of a DataColumn
Provides details for setting the initial value for a new DataColumn.
How to: Restrict a Data Column to Contain Unique Values
Explains how to set a DataColumn so it cannot contain duplicate values.
How to: Set a Data Column as the Primary Key
Explains how to set a DataColumn to be the primary key in a DataTable.
How to: Create Data Columns that Display Expressions
Explains how to set a DataColumn to display a calculated value.
How to: Create DataRelations with the Dataset Designer
Explains how to use the Dataset Designer to add a DataRelation object to a dataset.
Walkthrough: Creating a DataTable in the Dataset Designer
Provides step-by-step instructions for creating a DataTable and defining the DataColumns that make up its structure.
Walkthrough: Creating a Dataset with the Dataset Designer
Provides step-by-step instructions for creating a typed dataset without the help of the Data Source Configuration Wizard.
Manage Multiple Users and Conflicts
Introduction to Data Concurrency in ADO.NET
Provides an overview of the different methods of concurrency control.
How to: Handle Concurrency Errors
Describes how to use the DBConcurrencyException object to identify concurrency exceptions and the actual record that
caused the error.
Walkthrough: Handling a Concurrency Exception
Provides step-by-step instructions for identifying and resolving a concurrency error.
Work with SQL Server 2005
SQL Server Projects
Provides an overview of what SQL Server projects are, and the different items that can be created in one.
Advantages of Using Managed Code to Create Database Objects
Provides a brief explanation of the benefits of using a .NET language to create SQL Server database objects.
Attributes for SQL Server Projects and Database Objects
Provides information on the different attributes used in SQL Server projects.
How to: Create a SQL Server Project
Provides detailed steps in creating a new SQL Server project.
How to: Deploy SQL Server Project Items to a SQL Server
Provides detailed steps for deploying a SQL Server project to the database.
How to: Create and Run a CLR SQL Server Stored Procedure
Provides detailed steps for creating a stored procedure in managed code.
How to: Create and Run a CLR SQL Server Aggregate
Provides detailed steps for creating an aggregate in managed code.
How to: Create and Run a CLR SQL Server Trigger
Provides detailed steps for creating a trigger in managed code.
How to: Create and Run a CLR SQL Server User-Defined Function
Provides detailed steps for creating a user-defined function in managed code.
How to: Create and Run a CLR SQL Server User-Defined Type
Provides detailed steps for creating a user-defined type in managed code.
Debugging SQL Server 2005
How to: Debug a SQL CLR Stored Procedure
Demonstrates how to debug stored procedures on a SQL Server.
Walkthrough: Debugging a SQL CLR Trigger
Demonstrates how to step from a stored procedure into a trigger when it fires.
Walkthrough: Debugging a SQL CLR User-Defined Aggregate
Demonstrates how to step into a User Defined Aggregate.
Walkthrough: Debugging a SQL CLR User-Defined Scalar Function
Demonstrates how to step into a User Defined Scalar Function.
Walkthrough: Debug a SQL CLR User-Defined Table-Valued Function
Demonstrates how to step into a User Defined Table-Valued Function.
Walkthrough: Debugging a SQL CLR User-Defined Type
Demonstrates how to step into a User Defined Type.
SQL CLR Database Debugging
Describes how to debug CLR database objects.
Walkthrough: Debug a T-SQL Stored Procedure
Demonstrates how to debug stored procedures on a SQL Server.
Walkthrough: Debugging a T-SQL Trigger
Demonstrates how to step from a stored procedure into a trigger when it fires.
Walkthrough: Debugging a T-SQL User-Defined Function
Demonstrates how to step from a stored procedure into a User Defined Function.
T-SQL Database Debugging
Describes how to debug T-SQL database objects.
Data Walkthroughs
Walkthrough: Adding Validation to a Dataset
Provides step by step information for adding validation code to a dataset.
Walkthrough: Connecting to Data in a Database
Provides step by step details for creating a connection between your application and a database.
Walkthrough: Connecting to Data in a SQL Server Express Database
Provides step by step details for creating a connection between your application and a SQL Express database.
Walkthrough: Connecting to Data in a Web Service
Provides step by step details for creating a connection between your application and a Web service.
Walkthrough: Connecting to Data in an Access Database
Provides step by step details for creating a connection between your application and an Access database file.
Walkthrough: Connecting to Data in Objects
Provides step by step details for creating a connection between your application and the properties of an object.
Walkthrough: Creating a Dataset with the Dataset Designer
Provides step-by-step instructions for creating a typed dataset without the help of the Data Source Configuration Wizard.
Walkthrough: Creating a DataTable in the Dataset Designer
Provides step-by-step instructions for creating a T:System.Data.DataTable and defining the T:System.Data.DataColumns that
make up its structure.
Walkthrough: Creating a Lookup Table
Provides step by step details on displaying data from one table based on the data selected in another table.
Walkthrough: Creating a Relationship between Data Tables
Provides step-by-step instructions for creating two data tables with the Dataset Designer and adding a relation between
them.
Walkthrough: Creating a TableAdapter with Multiple Queries
Provides step-by-step instructions for creating a TableAdapter and adding a query to it.
Walkthrough: Creating a Form to Search Data in a Windows Application
Provides step by step details on creating a Windows Form that searches for records in a database based on values input by a
user.
Walkthrough: Creating a User Control that Supports Simple Data Binding
Provides step by step details on creating a custom control with attributes specific to working with Windows Forms
databinding.
Walkthrough: Displaying Data on a Form in a Windows Application
Provides step by step details on querying data from a database and displaying the data on a Windows Form.
Walkthrough: Displaying Related Data on a Form in a Windows Application
Provides step by step details on displaying data from two related tables and displaying the data on a Windows Form.
Walkthrough Topics — ASP.NET Data Access (Visual Studio)
Provides links to walkthrough topics covering data access in web pages.
Samples
Data Samples
These samples demonstrate the use of data in Visual Basic applications.
See Also
Concepts
How Do I in Visual Basic
Visual Basic Language Concepts

Deployment (How Do I in Visual Basic)


This page links to help on widely used Visual Basic deployment tasks. To view other categories of popular tasks covered in
Help, see How Do I in Visual Basic.
In General
Choosing a Deployment Strategy
Compares ClickOnce and Windows Installer technology.
Deploying 64-bit Applications
Describes general considerations for deploying a 64-bit application.
Adding Custom Prerequisites
Describes how to install packages for shared components or system components that are prerequisite to running your
application.
Windows Installer Deployment Tasks
This section contains common Windows Installer deployment tasks.
Deploying with ClickOnce
How to: Publish a ClickOnce Application
Describes how to publish a ClickOnce application to a Web server, file share, or removable media.
How to: Specify Which Files Are Published via ClickOnce
Describes how to publish certain files, or install certain files based on conditions.
How to: Change the Publish Language for a ClickOnce Application
Describes how to establish the language and culture of your development computer. If you are publishing a localized
application, you need to specify a language and culture to match the localized version.
How to: Install Prerequisites with a ClickOnce Application
Describes how to choose a set of prerequisite components to be packaged along with your application.
How to: Manage Updates for a ClickOnce Application
Describes specifying when and how update checks are performed, whether updates are mandatory, and where the
application should check for updates.
How to: Enable ClickOnce Security Settings
Describes how enable security settings in order to publish the application.
How to: Sign Application and Deployment Manifests
Describes how to strong-name a manifest.
How to: Deploy a 64-bit Application Using ClickOnce
Describes how to publish a 64-bit application with ClickOnce.
Publishing Applications
How to: Publish a ClickOnce Application
Describes how to publish a ClickOnce application to a Web server, file share, or removable media.
How to: Specify Which Files Are Published via ClickOnce
Describes how to publish certain files, or install certain files based on conditions.
How to: Change the Publish Language for a ClickOnce Application
Describes how to establish the language and culture of your development computer. If you are publishing a localized
application, you need to specify a language and culture to match the localized version.
How to: Install Prerequisites with a ClickOnce Application
Describes how to choose a set of prerequisite components to be packaged along with your application.
How to: Manage Updates for a ClickOnce Application
Describes specifying when and how update checks are performed, whether updates are mandatory, and where the
application should check for updates.
How to: Automatically Increment the ClickOnce Publish Version
Describes increments to the Revision number of the Publish Version when you publish an application.
How to: Specify the ClickOnce Install Mode
Describes how to determine whether the application will be available offline or online.
How to: Set Deployment Project Properties
Describes categories of deployment properties: general project properties and configuration-dependent properties.
How to: Specify Per-user or Per-computer Installation
Describes how to specify whether you want the application to be installed for all users of the computer, or only for the user
doing the installation.
Signing Manifests
How to: Sign Application and Deployment Manifests
Describes how to strong-name a manifest.
How to: Delay Sign an Assembly (Visual Studio)
Describes how to use delayed or partial signing to provide the public key, deferring the addition of the private key until the
assembly is handed off.
Deploying Secure Applications
How to: Set a Security Zone for a ClickOnce Application
Describes how to start with a base set of permissions and add the permissions required by your application one at a time.
Deploying with Setup Projects (Windows Installer)
How to: Create or Add a Setup Project
Describes how to create Setup projects, which are used to create Windows Installer (.msi) files. There are two types of setup
projects: Standard and Web.
Walkthrough: Deploying a Windows-based Application
Provides instructions for creating an installer for a Windows application that sets up shortcuts and file associations, adds an
entry to the registry, displays custom dialogs, and checks the version of Internet Explorer during installation.
Walkthrough: Creating a Custom Action
Demonstrates the process of creating a DLL custom action to direct a user to a Web page at the end of an installation.
How to: Create a Windows Installer for a 64-bit Platform
Describes creating installers for 64-bit applications and components.
How to: Install Prerequisites in Windows Installer Deployment
Describes how to choose a set of prerequisite components to be packaged along with your application.
Other Deployment Projects
How to: Create or Add a Merge Module Project
Creates a merge module (.msm) file that includes all files, resources, registry entries, and setup logic for your component.
How to: Create or Add a Cab Project
Creates cabinet (.cab) files that can be used to download components to a Web browser. This option should be used when
you want code to run on a client computer instead of on a server.
How to: Add Merge Modules to a Deployment Project
Creates your own merge modules using Visual Studio, or you can use existing merge modules that are available for many
standard components from Microsoft as well as from third-party vendors.
See Also
Concepts
How Do I in Visual Basic
Visual Basic Language Concepts

Smart Device Applications (How Do I in Visual Basic)


This page links to help on widely used Visual Basic tasks for smart device applications. To view other categories of popular
tasks covered in Help, see How Do I in Visual Basic.
In General
How to: Create Device Applications Using Visual Basic or Visual C#
Describes creating managed projects for devices, which follows the same general process as creating projects for the
desktop.
Walkthrough: Creating Windows Forms Applications for a Device
Demonstrates a simple Windows Forms application using either Visual Basic .NET or Visual C#, and then runs the application
on a Pocket PC emulator.
Walkthrough: Hello World: A COM Interop Example for Smart Devices
Shows combining in one solution a simple COM object and a managed application.
How to: Change the Orientation and Resolution of Forms (Devices)
Shows how to change default orientation (rotation) properties; also applicable if you have installed an SDK in which these
properties are incorrect or lacking.
How to: Add a Business Object as a Data Source (Devices)
Demonstrates adding a business object as a data source in your smart device projects.
Work with Data in Smart Devices
How to: Create Parameterized Queries (Devices)
Describes creating parameterized queries; assumes you have a SQL Server Mobile database available in the Data Sources
window.
How to: Create Master-Detail Applications (Devices)
Demonstrates Master-Detail applications; assumes you have a SQL Server Mobile database with table relationships available
in the Data Sources window.
How to: Add a Web Service as a Data Source (Devices)
Shows how to add a Web service as a data source in your smart device projects.
How to: Add a SQL Server Database as a Data Source (Devices)
Shows how to use SQL Server databases as data sources in your managed device projects.
Deploy Smart Device Applications
Walkthrough: Packaging a Smart Device Solution for Deployment
Demonstrates how to use Visual Studio 2005 to package your application and its resources into a CAB file so that it can be
deployed to an end-user's smart device.
How to: Sign a Visual Basic or Visual C# Application (Devices)
Shows the steps for signing a managed device application.
Work with Controls
Walkthrough: Authoring User Controls for Devices
Creates a control library and author a user control to put in it. Distinguishes a user control, a combination of Windows Forms
controls in a single reusable unit, from a custom control, a control that requires UI or functionality not available through
standard controls.
Debugging and Testing Applications
Differences Between Device And Desktop Debuggers
Describes the differences between Device debuggers, which support most of the same features that desktop debuggers
support, with exceptions.
Walkthrough: Debugging a Windows Form
Demonstrates debugging a Windows form.
Walkthrough: Debugging a Web Form
Demonstrates debugging a Web form.
Walkthrough: Debugging an XML Web Service
Demonstrates debugging an XML Web Service.
Samples
Samples and Walkthroughs (Smart Device Projects)
These samples illustrate techniques used to solve various device programming challenges.
See Also
Concepts
How Do I in Visual Basic
How Do I in Smart Device Development
Visual Basic Language Concepts

Office Programming (How Do I in Visual Basic)


This page links to Help on widely used Office programming tasks. They show Visual Basic example code in the context of Visual
Studio Tools for Office. To view other categories of popular tasks covered in Help, see How Do I in Visual Basic.
In General
How to: Upgrade Document-Level Projects
Describes the steps to take in order to take advantage of the new project system and tools offered in the latest version of
Microsoft Visual Studio Tools for the Microsoft Office System.
How to: Install Office Primary Interop Assemblies
Provides steps for installing the required Microsoft Office 2003 primary interop assemblies on end user computers.
How to: Set Up Configuration Information for an Office Solution
Describes how you can manually add a .config file to your Office project.
How to: Create Visual Studio Tools for Office Projects
Describes how to use the Microsoft Office Project Wizard to create a Word or Excel project using a new or existing document
or workbook.
How to: Automate Office Applications By Using Primary Interop Assemblies
Describes how you can use managed code to automate other Office applications, such as Microsoft Office PowerPoint 2003
in Visual Studio.
How to: Add Controls to Office Documents
Describes how you can add Windows Forms controls to Excel 2003 and Word 2003 documents at design time or at run time.
Walkthrough: Granting and Removing Permissions for an Office Solution
Provides a step-by-step demonstration of the basics of security in Visual Studio Tools for Office solutions.
How to: Deploy Office Solutions
Describes three different ways to deploy an Office solution: deploying the document and assembly on a network, deploying
them locally, or deploying the assembly on a network and the document locally.
Excel Applications
How to: Run Excel Calculations Programmatically
Demonstrates how to use the Calculate method to run all calculations in a range, as well as in all open workbooks.
How to: Handle Errors in Office Projects
Explains how the interaction of managed and unmanaged code affects error handling in Microsoft Office Word 2003 and
Microsoft Office Excel 2003 projects.
How to: Display a String in a Worksheet Cell
Demonstrates how to display text in a cell programmatically. You can create a named range to reference the cell.
Word Applications
How to: Use Built-In Dialog Boxes in Word
Provides an example that shows how to take advantage of Word's built-in dialog boxes to display user input.
How to: Create Office Toolbars Programmatically
Provides an example showing how to programmatically create a toolbar containing two buttons in Word 2003.
Outlook Applications
How to: Create an E-Mail Item
Provides an example that shows how to create an e-mail item in Microsoft Outlook 2003.
How to: Add Custom Icons to Toolbar and Menu Items
Provides an example that applies an icon to a command on a custom menu.
Data in Office Solutions
How to: Programmatically Cache a Data Source in an Office Document
Shows how to add a data source to a document cache programmatically by calling the StartCaching method and passing in
the data source.
How to: Map Schemas to Word Documents Inside Visual Studio
Demonstrates how to map an XML schema to a document while the document is open in a Visual Studio Tools for Office
project, using the same Word 2003 tools that you use when the document is open outside of Visual Studio.
Walkthrough: Binding a Worksheet Cell to a Database Field
Steps you through the basics of binding a single data field in a SQL Server database to a named range in Excel 2003.
How to: Populate Documents with Data from Objects
Shows how accessing data that is stored in objects from Word 2003 documents is similar to working with Windows Forms
projects.
Smart Tags and Action Panes
Walkthrough: Inserting Text into a Document from an Actions Pane
Steps you through the process of creating an actions pane that populates a Word 2003 document with text that the user
types in the actions pane.
How to: Create and Modify Custom Document Properties
Describes how you can create and modify custom document properties if there is additional information you would like to
store with a document or workbook.
Samples
Office Development Samples
These samples demonstrate how to use Microsoft Visual Studio 2005 Tools for the Microsoft Office System to take
advantage of features available in Microsoft Office Word 2003 and Microsoft Office Excel 2003.
See Also
Concepts
How Do I in Visual Basic
How Do I in Visual Studio Tools for Office
Visual Basic Language Concepts

Web Applications (How Do I in Visual Basic)


This page links to help on widely used Visual Basic tasks for creating Web applications. To view other categories of popular
tasks covered in Help, see How Do I in Visual Basic.
In General
What's New in Web Development for Visual Studio
Describes Visual Web Developer, which is a set of tools and utilities for creating ASP.NET Web applications.
Walkthrough: Creating a Basic Web Page in Visual Web Developer
Provides a first-time introduction to creating and editing an ASP.NET Web page in Visual Studio, including an overview of the
Web development environment.
Walkthrough: Basic HTML Editing in Visual Web Developer
Introduces you to the HTML editing features of Visual Web Developer.
Walkthrough: Debugging Web Pages in Visual Web Developer
Provides an overview of how to use the debugger with Web pages.
Use Web Forms and Controls
How to: Validate Required Entries for ASP.NET Server Controls
Shows how to specify that a user must provide information in a specific control by adding a RequiredFieldValidator
control to the page and linking it to the required control.
How to: Respond to User Selection in a CheckBox Web Server Control
Gives directions for writing an event handler that responds directly when the user clicks an individual CheckBox control.
How to: Determine the Selection in List Web Server Controls
Gives directions for getting three values associated with a list selection: the selection's index value; the text (display value) of
the selection; and the value, if any, of the selection.
How to: Allow Users to Select Items in DataList Web Server Controls
Gives directions for providing a Select button that users can click to highlight an item.
How to: Add Rows and Cells Dynamically to a Table Web Server Control
Gives directions for creating rows and cells for a Table control at run time.
How to: Add Controls to an ASP.NET Web Page Programmatically
Uses a dropdown list change event to add labels to a Web Forms page at run time.
How to: Add Client Script Dynamically to ASP.NET Web Pages
Provides information on how to use server code to programmatically add client script to a page.
Deploy a Web Site
Walkthrough: Publishing a Web Site
Provides a guided tour of compiling a Web site into assemblies that can be deployed to a Web server.
Walkthrough: Copying a Web Site Using the Copy Web Site Tool
Provides a guided tour of creating a Web site and copying the files to a production Web server.
Develop a Web Site
How to: Create Content Pages for an ASP.NET Master Page (Visual Studio)
Provides instructions for creating a content page, which is an ASP.NET Web page that is associated with a master page.
How to: Pass Values Between ASP.NET Web Pages
Provides information on what to do if your application redirects (navigates) from one ASP.NET Web page to another, and
you want to pass information from the source page to the target page.
How to: Redirect Users to Another Page
Provides instruction to redirect users from one ASP.NET Web page to another page.
How to: Reference ASP.NET Master Page Content
Shows using code in content pages to reference properties, methods, and controls in the master page, with some restrictions.
How to: Apply ASP.NET Themes
Shows how to set a theme at the application level and page level.
Types of Validation for ASP.NET Server Controls
Lists the types of validation controls available and how you can use them.
Walkthrough: Creating Master/Detail Web Pages in Visual Studio
Shows you various ways to work with data in multiple controls and from multiple tables, including those that have a master-
detail relationship.
Walkthrough: Creating Reusable Elements with ASP.NET User Controls
Shows how to create an ASP.NET user control that acts as a picker control—the control consists of two list boxes, with a set
of choices in one list box (the source).
Walkthrough: Creating Web Pages for Mobile Devices
Creates two Web pages that inherit from the MobilePage class that are designed for a mobile device.
Walkthrough: Customizing a Web Site Using Themes in Visual Studio
Illustrates how to use themes to apply a consistent look to pages and controls in your Web site.
Walkthrough: Integrating ASP.NET Tracing with System.Diagnostics Tracing
Describes how to integrate ASP.NET tracing techniques with System.Diagnostics tracing techniques, and write all trace
messages to a single tracing output.
Walkthrough: Using Resources for Localization with ASP.NET
Demonstrates an effective way to create localized Web pages, using resources for your page's text and controls based on the
user's language and culture.
Walkthrough: Creating a Web Parts Page in Visual Web Developer
Demonstrates the essential components and tasks for working with Web Parts in a visual designer such as Visual Studio.
Upgrade from ASP
Web Project Conversion from Visual Studio .NET
Includes information about aspects of Visual Studio 2005 conversion from Visual Studio 2003 .NET projects.
Troubleshooting Conversion to Visual Web Developer
Describes situations and suggests solutions for those circumstances in which under your Web applications will behave
differently after conversion than they did before.
See Also
Concepts
How Do I in Visual Basic
How Do I in Visual Web Developer
Visual Basic Language Concepts

Web Services (How Do I in Visual Basic)


This page links to help on widely used Visual Basic tasks for creating Web Service applications. To view other categories of
popular tasks covered in Help, see How Do I in Visual Basic.
In General
Walkthrough: Creating and Using an ASP.NET Web Service in Visual Web Developer
Demonstrates creating a simple XML Web service in Visual Web Developer.
Walkthrough: Creating an XML Web Service Using Visual Basic or Visual C#
Explains how to create an XML Web service that converts temperatures measured in Fahrenheit to Celsius.
How to: Create ASP.NET Web Service Projects
Provides instructions on how to create an XML Web service using the ASP.NET Web Service project template.
How to: Connect to Data in a Web Service
Describes how to create a connection between your application and the data returned from a Web Service using the Data
Source Configuration Wizard.
Create A Web Service
Walkthrough: Creating and Using an ASP.NET Web Service in Visual Web Developer
Demonstrates creating a simple XML Web service in Visual Web Developer.
Walkthrough: Creating an XML Web Service Using Visual Basic or Visual C#
Explains how to create an XML Web service that converts temperatures measured in Fahrenheit to Celsius.
How to: Create ASP.NET Web Service Projects
Provides instructions on how to create an XML Web service using the ASP.NET Web Service project template.
How to: Connect to Data in a Web Service
Describes how to create a connection between your application and the data returned from a Web Service using the Data
Source Configuration Wizard.
Debug and Deploy a Web Service
Stepping Into an XML Web Service
Describes how to step back and forth between a client application and an XML Web Service.
How to: Deploy XML Web Services in Managed Code
Provides instructions on how to deploy a Web Service using multiple methods.
How to: Debug XML Web Services in Managed Code
Provides instructions on how to debug a Web Service using multiple methods.
Call a Web Service
Walkthrough: Accessing an XML Web Service Using Visual Basic or Visual C#
Describes the process for accessing an XML Web service from an application created with Visual Basic or Visual C#.
How to: Make an Asynchronous Call from a Web Service Client
Demonstrates how to make an asynchronous call to a Web service from a client application.
How to: Explore Existing XML Web Services Created Using ASP.NET
Provides information about the functionality of the Web service, including the Web service methods it implements, their
parameters, and their return types.
How to: Call a Web Service
Demonstrates calling a Web service method to define a string value.
How to: Add an XML Web Service to an Existing Web Project in Managed Code
Provides instructions on how to add a Web Service to an existing Web project.
See Also
Concepts
How Do I in Visual Basic
How Do I in Visual Web Developer
Visual Basic Language Concepts

Windows Applications (How Do I in Visual Basic)


This page links to help on widely used Visual Basic tasks for creating Windows applications. To view other categories of
popular tasks covered in Help, see How Do I in Visual Basic.
In General
Structure of a Visual Basic Program
Shows the general outline of a simple Visual Basic program.
Walkthrough: Creating a Simple Windows Form
Demonstrates how to make a simple "Hello, World" application.
Use Windows Forms and Controls
What's New in Windows Forms and Windows Forms Controls
Lists the new and enhanced features available with this release of Visual Studio.
What's New in Windows Forms for Visual Basic 6.0 Users
Highlights key changes for Visual Basic 6 users.
Working with Forms
Design Time
How to: Choose the Startup Form in a Windows Application
Gives directions for setting the first form shown when your application is run.
How to: Connect Multiple Events to a Single Event Handler in Windows Forms
Gives directions for assigning the same functionality to multiple controls through events.
How to: Create a Multipane User Interface with Windows Forms
Describes how to create a multipane user interface that is similar to the one used in Microsoft Outlook.
How to: Add Background Images to Windows Forms
Describes how to place a background image in a control or on the form itself.
How to: Set ToolTips for Controls on a Windows Form at Design Time
Describes how to set ToolTips in code or in the designer.
How to: Reassign Existing Controls to a Different Parent
Gives directions for assigning existing controls to a new parent container.
How to: Add ActiveX Controls to Windows Forms
Gives directions for working with legacy ActiveX controls.
How to: Provide Help in a Windows Application
Explains how to use the HelpProvider component to link controls to files in a Help system.
How to: Create Access Keys for Windows Forms Controls
Gives information on creating predefined keyboard shortcuts.
How to: Inherit Windows Forms
Gives directions for creating inherited forms in code.
How to: Inherit from Existing Windows Forms Controls
Describes how to create an inherited control.
Run Time
How to: Add to or Remove from a Collection of Controls at Run Time
Explains how to add and remove controls on a panel at run time.
How to: Enable Windows XP Visual Styles
Gives directions for using the EnableVisualStyles property to give forms and controls the standard Windows XP look.
How to: Make a Startup Windows Form Invisible
Gives directions for establishing a form's initial visibility at run time.
How to: Keep a Windows Form on Top
Gives directions for ensuring your Windows Form stays on top of all other forms at run time.
How to: Display Modal and Modeless Windows Forms
Gives directions for showing a dialog box modally versus modelessly.
How to: Make Your Control Invisible at Run Time
Gives directions for how to create a user control that is invisible at run time.
Common Controls
TextBox Controls
How to: Select Text in the Windows Forms TextBox Control
Explains how to highlight text in a text box.
How to: Put Quotation Marks in a String (Windows Forms)
Explains adding quotation marks to a string in a text box.
How to: Display Scroll Bars in the Windows Forms RichTextBox Control
Describes the many choices available for scroll bars in the RichTextBox control.
How to: Create a Read-Only Text Box (Windows Forms)
Describes how to prevent the contents of a text box from being changed.
How to: Create a Password Text Box with the Windows Forms TextBox Control
Explains how to conceal what is typed into a text box.
How to: Control the Insertion Point in a Windows Forms TextBox Control
Gives directions for specifying where the insertion point appears when an edit control first gets the focus.
How to: Retrieve Data from the Clipboard
Describes how to access the data stored on the Clipboard.
How to: Add Data to the Clipboard
Describes a method for programmatically inserting information on the Clipboard.
How to: Bind Data to the MaskedTextBox Control
Demonstrates how to reformat the data when data in the database does not match the format expected by your mask
definition.
Walkthrough: Working with the MaskedTextBox Control
Demonstrates the key features of the MaskedTextBox control.
RichTextBox Controls
How to: Load Files into the Windows Forms RichTextBox Control
Provides instructions for loading an existing file into the RichTextBox control.
How to: Display Scroll Bars in the Windows Forms RichTextBox Control
Describes the many choices available for scroll bars in the RichTextBox control.
How to: Set Font Attributes for the Windows Forms RichTextBox Control
Describes how to set the font family, size, style, and color of text in the RichTextBox control.
How to: Set Indents, Hanging Indents, and Bulleted Paragraphs with the Windows Forms RichTextBox Control
Describes how to format paragraphs in the RichTextBox control.
How to: Enable Drag-and-Drop Operations with the Windows Forms RichTextBox Control
Provides instructions for dragging data into the RichTextBox control.
How to: Display Web-Style Links with the Windows Forms RichTextBox Control
Explains how to link to Web sites from the RichTextBox control.
Button Controls
How to: Respond to Windows Forms Button Clicks
Explains the most basic use of a button on a form in a Windows application.
How to: Designate a Windows Forms Button as the Accept Button Using the Designer
Shows how to set a button up as the Accept button.
How to: Designate a Windows Forms Button as the Cancel Button Using the Designer
Shows how to set a button up as the Cancel button.
CheckBox and RadioButton Controls
CheckBox Control
How to: Set Options with Windows Forms CheckBox Controls
Describes how to use a check box to set options such as properties of an object.
How to: Respond to Windows Forms CheckBox Clicks
Explains how to use a check box to determine your application's actions.
RadioButton Controls
How to: Group Windows Forms RadioButton Controls to Function as a Set
Explains how to group radio buttons as a set, of which only one may be selected.
ListBox, ComboBox, and CheckedListBox Controls
How to: Bind a Windows Forms ComboBox or ListBox Control to Data
Gives directions for binding a list-based control to a data source.
How to: Create a Lookup Table for a Windows Forms ComboBox, ListBox, or CheckedListBox Control
Gives directions for displaying and storing form data in useful formats.
How to: Add and Remove Items from a Windows Forms ComboBox, ListBox, or CheckedListBox Control
Gives instructions for adding or removing items from a control's list of items.
How to: Access Specific Items in a Windows Forms ComboBox, ListBox, or CheckedListBox Control
Gives instructions for programmatically determining which item in a list appears in a given position.
How to: Sort the Contents of a Windows Forms ComboBox, ListBox, or CheckedListBox Control
Explains how to sort list data at its data source.
CheckedListBox Control
How to: Determine Checked Items in the Windows Forms CheckedListBox Control.
Describes how to step through a list to determine which items are checked.
DataGridView Control
How to: Bind Data to the Windows Forms DataGridView Control Using the Designer
Describes how to use the Choose Data Source option on the control's smart tag to connect to data.
How to: Create a Master/Detail Form Using Two Windows Forms DataGridView Controls
Provides code showing how to display data from two related database tables so that the values shown in one DataGridView
control depend on the currently selected row in another control.
How to: Validate Data in the Windows Forms DataGridView Control
Provides code showing how to validate user input to prevent data-entry formatting errors.
How to: Handle Errors That Occur During Data Entry in the Windows Forms DataGridView Control
Provides code showing how to handle data-entry errors that originate from the data source when the user attempts to
commit a new value.
How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control Using the Designer
Describes how to use the control's smart tag to prevent users from adding or deleting rows.
How to: Specify Default Values for New Rows in the Windows Forms DataGridView Control
Describes how to prepopulate the row for new records to save data-entry time.
How to: Create an Unbound Windows Forms DataGridView Control
Provides code showing how to manually populate the control with data.
How to: Add an Unbound Column to a Data-Bound Windows Forms DataGridView Control
Describes how to supplement data from a bound data source by displaying additional, unbound columns.
How to: Display Images in Cells of the Windows Forms DataGridView Control
Describes how to create an image column that displays an icon in every cell.
How to: Host Controls in Windows Forms DataGridView Cells
Describes how to implement the IDataGridViewEditingControl interface and create custom types derived from
DataGridViewCell and DataGridViewColumn in order to display a DateTimePicker control when a cell is in edit mode.
Walkthrough: Validating Data in the Windows Forms DataGridView Control
Describes how to validate user input to prevent data-entry formatting errors.
Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control
Describes how to handle data-entry errors that originate from the data source when the user attempts to commit a new
value.
Walkthrough: Creating an Unbound Windows Forms DataGridView Control
Describes how to manually populate the control with data.
DataGridView Layout and Formatting
How to: Freeze Columns in the Windows Forms DataGridView Control Using the Designer
Describes how to use the Edit Columns dialog box to prevent specific columns from scrolling.
How to: Make Columns Read-Only in the Windows Forms DataGridView Control Using the Designer
Describes how to use the Edit Columns dialog box to prevent users from editing values in specific columns.
How to: Enable Column Reordering in the Windows Forms DataGridView Control Using the Designer
Describes how to use the control's smart tag to enable users to rearrange columns.
How to: Change the Order of Columns in the Windows Forms DataGridView Control Using the Designer
Describes how to use the Edit Columns dialog box to rearrange columns.
How to: Add and Remove Columns in the Windows Forms DataGridView Control Using the Designer
Describes how to use the Add Columns and Edit Columns dialog boxes to populate and modify the columns collection.
ListView and TreeView Controls
Walkthrough: Creating an Explorer Style Interface with the ListView and TreeView Controls Using the Designer
Demonstrates creating a professional looking Windows application using two common controls.
ListView Control
How to: Add and Remove Items with the Windows Forms ListView Control
Describes how to add or remove items from a list view.
How to: Add Search Capabilities to a ListView Control
Describes two ways to offer search capabilities to a user: text matching and location searching.
How to: Select an Item in the Windows Forms ListView Control
Demonstrates how to programmatically select an item in a Windows Forms ListView control.
How to: Display Icons for the Windows Forms ListView Control
Explains how to associate a list view with an appropriate image list for displaying large or small icons.
How to: Display Subitems in Columns with the Windows Forms ListView Control
Provides instructions for displaying information about each list item in columns.
TreeView Control
How to: Set Icons for the Windows Forms TreeView Control
Gives instructions for displaying icons for the nodes of a tree view.
How to: Add and Remove Nodes with the Windows Forms TreeView Control
Gives instructions for adding and remove nodes from a tree view.
How to: Determine Which TreeView Node Was Clicked (Windows Forms)
Gives instructions for determining which node in a tree view was clicked, so the application can respond appropriately.
Container Controls
How to: Split a Window Horizontally
Describes how to control the orientation of the splitter within the SplitContainer control.
How to: Create a Multipane User Interface with Windows Forms
Creates a multi-pane user interface that is similar to the one used in Microsoft Outlook.
How to: Span Rows and Columns in a TableLayoutPanel Control
Describes how to spread a control across adjacent rows and columns in a TableLayoutPanel.
Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel
Describes how to create a form with a layout that arranges itself appropriately as the form is resized or as the contents
change in size.
Walkthrough: Arranging Controls on Windows Forms Using a FlowLayoutPanel
Describes how to create a form with a layout that arranges itself appropriately as the form is resized or as the contents
change in size.
Picture and Image Controls
How to: Load a Picture Using the Designer (Windows Forms)
Describes how to load and display a picture on a form at design time by setting properties.
How to: Set Pictures at Run Time (Windows Forms)
Provides instructions for displaying and clearing a picture at run time.
How to: Modify the Size or Placement of a Picture at Run Time (Windows Forms)
Explains what the SizeMode property does and how to set it.
How to: Crop and Scale Images
Explains how to programmatically crop and scale vector and raster images.
Date-Setting Controls
DateTimePicker Control
How to: Set and Return Dates with the Windows Forms DateTimePicker Control
Provides steps to set the date in the control, and to access the date the user has selected.
How to: Display a Date in a Custom Format with the Windows Forms DateTimePicker Control
Explains how to use format strings to display dates in a preferred format.
MonthCalendar Control
How to: Select a Range of Dates in the Windows Forms MonthCalendar Control
Explains how to programmatically select a range of dates from the MonthCalendar control.
How to: Display Specific Days in Bold with the Windows Forms MonthCalendar Control
Explains how to set certain dates to appear bold.
How to: Display More than One Month in the Windows Forms MonthCalendar Control
Describes how to configure the MonthCalendar control to display several months simultaneously.
How to: Change the Windows Forms MonthCalendar Control's Appearance
Describes how to customize the appearance of the MonthCalendar control.
Data Access (for Windows Forms)
What's New in Data
Provides information and links to new data features for client and data tier applications.
How to: Display Data in a Windows Forms DataGridView Control
Describes how to present data in a DataGridView control.
Walkthrough: Passing Data Between Forms in a Windows Application
Provides step by step details on passing values from one form to a second form in an application.
Walkthrough: Displaying Data on a Form in a Windows Application
Provides step by step details on querying data from a database and displaying the data on a form.
Walkthrough: Creating a User Control that Supports Simple Data Binding
Provides step by step details on creating a custom control with attributes specific to working with Windows Forms data
binding.
Walkthrough: Creating a Form to Search Data in a Windows Application
Provides step by step details on creating a form that searches for records in a database based on values input by a user.
Walkthrough: Connecting to Data in Objects
Provides step by step details for creating a connection between your application and the properties of an object.
Menus and Toolbars
ToolStrip Control
How to: Create a Basic Windows Forms ToolStrip with Standard Items Using the Designer
Demonstrates how to create a ToolStrip and add seven ToolStripButton controls that represent typical tasks.
How to: Position a ToolStripItem on a ToolStrip
Describes how to position a ToolStripButton on at the leftmost or rightmost end of a ToolStrip.
How to: Disable ToolStripMenuItems Using the Designer
Describes how to disable both entire menus and individual menu commands.
How to: Hide ToolStripMenuItems Using the Designer
Describes how to hide both entire menus and individual menu commands.
How to: Move ToolStripMenuItems
move entire top-level menus and their menu items to a different place on the MenuStrip.
How to: Change the Appearance of ToolStrip Text and Images in Windows Forms
Describes how to define and modify the arrangement of text and images on ToolStripItem controls.
Context Menus
How to: Associate a Shortcut Menu with a Windows Forms NotifyIcon Component
Provides steps for adding a context menu to a NotifyIcon component so that it provides a menu of commands when a user
right-clicks it.
How to: Add and Remove Menu Items with the Windows Forms ContextMenu Component
Explains how to add and remove context menu items.
Data Binding with Controls
How to: Handle Errors and Exceptions that Occur with Databinding
Demonstrates using the BindingSource component to gracefully handle errors that occur in a data binding operation.
BindingSource Control
How to: Bind Windows Forms Controls with the BindingSource Component Using the Designer
Describes how to bind controls to a data source, so that, at run time, users can alter and save data related to your application.
How to: Create a Lookup Table with the Windows Forms BindingSource Component
Shows how to use a combo box to display the field with the foreign-key relationship from the parent to the child table.
How to: Reflect Data Source Updates in a Windows Forms Control with the BindingSource
Demonstrates how to respond to changes in the data source using the BindingSource component.
How to: Sort and Filter ADO.NET Data with the Windows Forms BindingSource Component
Demonstrates using the BindingSource component to apply sorts and filters to displayed data.
How to: Bind to a Web Service Using the Windows Forms BindingSource
Shows how to use the BindingSource component to bind to a Web service.
BindingNavigator Control
How to: Navigate Data with the Windows Forms BindingNavigator Control
Provides steps to bind a BindingNavigator control to a data source.
How to: Move Through a DataSet with the Windows Forms BindingNavigator Control
Demonstrates using a BindingNavigator control to move through records in a DataSet.
How to: Add Load, Save, and Cancel Buttons to the Windows Forms BindingNavigator Control
Binds a text box control to data; then a ToolStrip control that is added to the form is modified to include load, save, and
cancel buttons.
Printing
How to: Create Standard Windows Forms Print Jobs
Explains how to use the PrintDocument component to print from a form.
How to: Complete Windows Forms Print Jobs
Explains how to alert users to the completion of a print job.
How to: Print a Multi-Page Text File in Windows Forms
Describes sending text to the printer.
How to: Display the PrintDialog Component
Explains how to display the dialog and where it saves properties.
How to: Display Print Preview in Windows Forms Applications
Describes showing users the PrintPreviewDialog control.
How to: Choose the Printers Attached to a User's Computer in Windows Forms
Describes changing the printer to print to using the PrintDialog component at run time.
How to: Capture User Input from a PrintDialog at Run Time
Explains how to modify selected print options programmatically using the PrintDialog component.
User Controls and Custom Controls
Walkthrough: Authoring a Composite Control with Visual Basic
Creates a simple user control and then extends its functionality through inheritance.
How to: Test the Run-Time Behavior of a UserControl
Demonstrates the use of the UserControl Test Container provided by Visual Studio.
How to: Inherit from the UserControl Class
Demonstrates inheritance with the UserControl class.
How to: Author Composite Controls
Demonstrates authoring a user control, a control class library, and inheriting from a user control.
Adding Controls to Your User Control
Demonstrates the basics of working with a user control.
Adding Code to Your User Control
Demonstrates the basics of working with a user control.
Multiple Document Interfaces (MDI)
How to: Create MDI Parent Forms
Gives directions for creating the container for the multiple documents within an MDI application.
How to: Create MDI Child Forms
Gives directions for creating one or more windows that operate within an MDI parent form.
How to: Arrange MDI Child Forms
Gives directions for tiling, cascading, or arranging the child windows of an MDI application.
How to: Determine the Active MDI Child
Gives directions for verifying the child window that has focus, and sending its contents to the Clipboard.
How to: Send Data to the Active MDI Child
Gives directions for transporting information to the active child window.
How to: Create an MDI Window List with MenuStrip (Windows Forms)
Explains how to use the MDI to create a list of all the active child forms on the parent's Window menu.
Graphics
How to: Draw an Outlined Shape
Describes how to draw a shape.
How to: Create a Linear Gradient
Shows how to create a linear gradient using the LinearGradientBrush class.
How to: Create a Path Gradient
Describes how to create a path gradient using the PathGradientBrush class.
How to: Create Figures from Lines, Curves, and Shapes
Shows how to use a GraphicsPath to create figures.
How to: Create Graphics Objects for Drawing
Shows how to create a Graphics object for drawing.
How to: Create Thumbnail Images
Describes how to create thumbnail images.
How to: Create Vertical Text
Describes how to draw vertically aligned text with GDI+.
How to: Align Drawn Text
Shows how to format GDI+ text.
How to: Draw a Line on a Windows Form
Demonstrates how to draw a line.
How to: Rotate, Reflect, and Skew Images
Describes how to draw rotated, reflected, and skewed images.
How to: Draw Text on a Windows Form
Describes how to draw text.
How to: Load and Display Bitmaps
Describes how to load and draw bitmaps.
How to: Load and Display Metafiles
Shows how to load and draw metafiles.
How to: Crop and Scale Images
Explains how to crop and scale vector and raster images.
Localizing and Globalizing Windows Forms
Walkthrough: Localizing Windows Forms
Demonstrates creating and using a resource file for a Windows Application project.
Walkthrough: Creating a Layout That Adjusts Proportion for Localization
Illustrates how to create a layout that proportionally adjusts when you translate displayed string values into other languages.
How to: Support Localization on Windows Forms Using AutoSize and the TableLayoutPanel Control
Shows how to create layouts that can adapt to different text string lengths that you cannot anticipate at design time.
How to: Set the Culture and UI Culture for Windows Forms Globalization
Explains how to set the CurrentCulture and CurrentUICulture properties to determine what resources are loaded for an
application and how information is formatted.
How to: Display Right-to-Left Text in Windows Forms for Globalization
Provides instructions for displaying text that flows from right to left on Windows Forms.
How to: Design a Windows Forms Layout that Responds Well to Localization
Demonstrates using a TableLayoutPanel control to build a form that responds well to localization.
Manage Application Resources
How to: Retrieve String Resources in Visual Basic
Shows how to access and retrieve a string resource using the My.Resources object.
How to: Retrieve an Image from the Clipboard in Visual Basic
Demonstrates how to retrieve an image from the Clipboard.
How to: Add or Remove Resources
Illustrates how to use the Resource Designer to add or remove resources for your project.
How to: Add or Remove String Resources
Shows how to use the Strings pane of the Resource Designer to add or remove string resources for your project.
Work with Files, Folders, and Drives
How to: Create a File in Visual Basic
Demonstrates how to create a file.
How to: Move a File in Visual Basic
Demonstrates how to move a file to a different directory.
How to: Rename a File in Visual Basic
Demonstrates how to rename a file.
How to: Delete a File in Visual Basic
Demonstrates how to delete a file.
How to: Create a Copy of a File in the Same Directory in Visual Basic
Demonstrates how to create a copy of a file in the same directory.
Read from Files
How to: Read Text from Files with a StreamReader (Visual Basic)
Demonstrates how to use a StreamReader to read from a file.
How to: Read From Text Files in Visual Basic
Demonstrates how to read from a text file.
How to: Read From Existing Text Files in My Documents (Visual Basic)
Demonstrates how to read from a text file in the My Documents directory.
How to: Read From Binary Files in Visual Basic
Demonstrates how to read from a binary file.
Work with Files
How to: Determine a File's Extension in Visual Basic
Demonstrates how to determine the extension of a file.
How to: Determine a File's Creation Time in Visual Basic
Demonstrates how to determine when a file was created.
How to: Determine the Absolute Path of a File in Visual Basic
Demonstrates how to determine the absolute path of a file.
How to: Determine if a File is Hidden in Visual Basic
Demonstrates how to determine if a file is hidden.
How to: Determine if a File Exists in Visual Basic
Demonstrates how to determine whether a file exists.
How to: Parse File Paths in Visual Basic
Demonstrates how to use the My methods to combine file paths.
How to: Validate File Names and Paths in Visual Basic
Demonstrates how to determine whether a string represents a file name or path.
Work with Drives
How to: Determine a Drive's Volume Label in Visual Basic
Demonstrates how to determine a drive's volume label.
How to: Determine a Drive's Type in Visual Basic
Demonstrates how to determine a drive's type.
How to: Determine a Drive's Total Space in Visual Basic
Demonstrates how to determine a drive's total space.
How to: Determine a Drive's Root Directory in Visual Basic
Demonstrates how to determine a drive's root directory.
Write to Files
How to: Write to Binary Files in Visual Basic
Demonstrates how to write to a binary file.
How to: Write Text to Files in the My Documents Directory in Visual Basic
Demonstrates how to create and write to a new text file in the My Documents directory.
How to: Write Text to Files with a StreamWriter in Visual Basic
Demonstrates how to write to a file with a StreamWriter object.
Work with Folders
How to: Create a Directory in Visual Basic
Demonstrates how to create a directory.
How to: Determine a Directory's Attributes in Visual Basic
Demonstrates how to determine a directory's attributes.
How to: Move a Directory in Visual Basic
Demonstrates how to move a directory.
How to: Determine if a Directory Exists in Visual Basic
Demonstrates how to determine whether a directory exists.
How to: Delete a Directory in Visual Basic
Demonstrates how to delete a directory.
Log and Trace Events
Walkthrough: Filtering My.Application.Log Output
Covers how to filter the output of the My.Application.Log logs.
Walkthrough: Determining Where My.Application.Log Writes Information
Covers how to determine where My.Application.Log writes information.
Walkthrough: Creating Custom Log Listeners
Covers how to create a custom log listener for My.Application.Log.
How to: Write Log Messages
Covers how to write event information to the application's logs.
How to: Write to an Application Event Log
Covers how to configure My.Application.Log to write information to an event log.
How to: Log Exceptions in Visual Basic
Covers how to write exception information to the application's logs.
Use Application Templates
How to: Create a Windows Application Project
Shows how to create a Windows Application project using the integrated development environment (IDE).
Interoperate with COM
Walkthrough: Implementing Inheritance with COM Objects
Describes using existing COM objects as the basis for new objects.
Walkthrough: Creating COM Objects with Visual Basic 2005
Steps you through the process of creating COM objects with and without the COM class template.
How to: Reference COM Objects from Visual Basic
Covers how to add references to COM objects that have type libraries.
How to: Refer to the Current Instance of an Object
Shows how to use the Me keyword to refer to the instance in which the code is currently running.
Manage Application Settings
How to: Read Application Settings in Visual Basic
Shows how to access an application's forms to determine the values of user settings.
How to: Persist User Settings in Visual Basic
Shows how to access an application's forms to save updated user setting values.
How to: Add or Remove Application Settings
Shows how to use the Settings page of the Project Designer to add or remove application settings.
Access Computer Resources
How to: Receive Strings From Serial Ports in Visual Basic
Demonstrates how to receive a string from a computer's serial port.
How to: Show Available Serial Ports in Visual Basic
Demonstrates how to show available serial ports.
How to: Start an Application and Send it Keystrokes (Visual Basic)
Demonstrates how to start an application and send it keystrokes.
Use the Clipboard
How to: Write to the Clipboard in Visual Basic
Demonstrates how to write data to the Clipboard.
How to: Retrieve an Image from the Clipboard in Visual Basic
Demonstrates how to retrieve an image from the Clipboard.
How to: Read from the Clipboard in Visual Basic
Demonstrates how to read data from the Clipboard.
Play Sounds
How to: Retrieve Audio Resources in Visual Basic
Shows how to use the My.Resources object to retrieve an audio resource.
How to: Play System Sounds in Visual Basic
Shows how to use the My.Computer.Audio object to play a system sound.
How to: Play Sounds in Visual Basic
Shows how to use the My.Computer.Audio object to play a sound from a sound file or application resource in the
background.
How to: Play Looping Sounds in Visual Basic
Shows how to use the My.Computer.Audio object to play a sound from a sound file or application resource as a
continuous loop.
How to: Stop Playing Sounds in the Background in Visual Basic
Shows how to use the My.Computer.Audio object to stop a sound playing in the background.
Work with the Registry
Walkthrough: Creating a Registry Key and Changing Its Values
Shows how to use the My.Computer.Registry object to create a registry key and set its values.
How to: Set Values in Registry Keys in Visual Basic
Shows how to use the My.Computer.Audio object to set a value in a registry key.
How to: Read a Value from a Registry Key in Visual Basic
Shows how to use the My.Computer.Audio object to read a value from a registry key.
How to: Delete a Registry Key in Visual Basic
Shows how to use the My.Computer.Audio object to delete a registry key.
How to: Determine if a Value Exists in a Registry Key in Visual Basic
Shows how to use the My.Computer.Audio object to determine whether a value exists in a specific registry key.
Use the Event Log
Walkthrough: Exploring Event Logs, Event Sources, and Entries
Takes you through the major feature areas of event logging in your Visual Studio application.
How to: Clear Event Logs
Gives directions for deleting entries from an event log.
How to: Create and Remove Custom Event Logs
Gives directions for creating custom event logs on the local computer.
How to: Delete Event Logs
Gives directions for deleting an existing log and all of its entries.
How to: Read Event Log Entries
Gives directions for reading event log entries.
How to: Determine If an Event Source Exists
Gives directions for querying to see if a specific log exists.
Work with Networks
How to: Upload a File in Visual Basic
Demonstrates how to upload a file and store it to a remote location using My.Computer.Network.
How to: Check Connection Status in Visual Basic
Shows how to determine whether the computer has a working network connection.
How to: Determine if a Remote Computer is Available in Visual Basic
Shows how to use the Ping method to determine whether a remote computer or host is available.
Use Source Code Control
How to: Open a Project or Solution from Source Control
Describes the opening of a project or solution from source control.
How to: Add a Project to Source Control
Provides procedures for adding a project to source control.
Write Secure Applications
Walkthrough: Validate That Passwords Are Complex (Visual Basic).
Demonstrates how to determine whether a string has the characteristics of a strong password.
Walkthrough: Implementing Custom Authentication and Authorization
Demonstrates how to implement custom authentication and authorization, and how to override the application thread's
default identity.
Walkthrough: Encrypting and Decrypting Strings in Visual Basic
Demonstrates how to encrypt and decrypt strings using the Data Encryption Standard (DES) algorithm.
How to: Determine if a User is in a Group
Demonstrates how to use the My.User object to determine the user's role.
How to: Determine a User's Login Name
Demonstrates how to use the My.User object to get the user's login name.
Samples
Visual Basic Windows Forms Samples
These samples demonstrate Windows Forms applications.
See Also
Concepts
How Do I in Visual Basic
Visual Basic Language Concepts

Security (How Do I in Visual Basic)


This page links to help on widely used Visual Basic security tasks. To view other categories of popular tasks covered in Help,
see How Do I in Visual Basic.
In General
Security and Visual Basic Development
Discusses the three common areas where you need to address security concerns.
Security In Visual Studio
Provides links and pointers to fundamental security concepts, including secure coding techniques.
Code Access Security Basics
Describes code access security and its most common uses.
Role-Based Security
Provides an overview of .NET Framework role-based security.
Security Policy Best Practices
Provides information for Windows developers about best practices for secure software.
Microsoft Security Developer Center
Learn how Microsoft is working to help you keep your applications and systems secure, from the desktop to network-level
systems, with links to security resources for IT professionals, developers, and home users.
How to: Modify Database Connections
Gives advice about issues like how to store the database connection string.
Best Practices
Security Policy Best Practices
Provides information for Windows developers about best practices for secure software.
Web Security
Securing XML Web Services Created Using ASP.NET
Explains how authentication and authorization work for ASP.NET Web services.
ASP.NET Web Site Security (Visual Studio)
The examples in this section show how to create ASP.NET applications that incorporate various kinds of security.
Limiting Access to ASP.NET Web Sites
Describes how to control who can gain access to your Web project files and what level of access individuals have to the
application.
Windows Security
Security in Windows Forms Overview
Briefly explains the .NET Framework security model and the basic steps necessary to ensure the Windows Forms in your
application are secure.
More Secure Printing in Windows Forms
Describes how to access printing features in a semi-trusted environment.
More Secure File and Data Access in Windows Forms
Describes how to access files and data in a semi-trusted environment.
ClickOnce Deployment and Security
Discusses permissions issues about applications deployed using ClickOnce technology, which run in a "sandbox," with
limited permissions based on a security zone.
Component Security
Code Access Security
Provides conceptual information on code security and describes the .NET Framework approach to securing your
components.
Imperative Security
Describes how to use imperative security checks to protect sensitive lines of code from unauthorized use.
Database Security
How to: Modify Database Connections
Gives advice about issues like how to store the database connection string.
Samples
Visual Basic Security Samples
These samples demonstrate security tasks.
See Also
Concepts
How Do I in Visual Basic
Visual Basic Language Concepts

Debug and Test (How Do I in Visual Basic)


This page links to Help on widely used Visual Basic building, debugging and testing tasks. To view other categories of popular
tasks covered in Help, see How Do I in Visual Basic.
In General
Walkthrough: Debugging a Windows Form
Demonstrates debugging a Windows Forms application.
Walkthrough: Debugging a Web Form
Demonstrates debugging a Web form.
Walkthrough: Debugging an XML Web Service
Demonstrates debugging an XML Web Service.
Building Applications
How to: Prepare and Manage Builds
Explains how to set the build order and save options, and build or rebuild a solution or project.
How to: Manage Build Configurations with Visual Basic Developer Settings Applied
Explains how to create and edit build configuration information in Visual Basic.
How to: Configure Projects to Target Platforms
Explains how to configure a project to target a specific platform.
Debugging Applications
Debugging Your Visual Basic Application
Provides pointers to documentation for the debugging features built into Visual Studio.
How to: Start Execution
Gives directions on how to start debugging.
How to: Step Into Code
Explains how to execute code line by line.
How to: Use the Processes Window
Demonstrates how to get started with the Processes window.
How to: Set a Simple Breakpoint
Shows how to pause an application at a certain point.
How to: Use the QuickWatch Dialog Box
Shows a fast way to look at and evaluate variables and expressions.
How to: Apply Edits in Break Mode with Edit and Continue
Explains how to edit your code in Break mode, and then continue without stopping and restarting execution.
How to: Correct Run-Time Errors with the Exception Assistant
Explains how to access troubleshooting tips when your code encounters an exception.
How to: Debug a Partial Trust Application
Demonstrates how to debug a partial trust application that you plan to deploy with ClickOnce.
Testing Applications
How to: Compile and Run a Project in Visual Basic
Describes your options for compiling and running from within the development environment.
Detecting and Correcting Managed Code Defects
Provides pointers to using Microsoft Visual Studio 2005 Team Edition for Software Developers to detect and correct code
defects.
Monitoring Applications
Walkthrough: Exploring Event Logs, Event Sources, and Entries
Demonstrates how your applications and components can record information about important events. You can use these
records to audit access to your system, troubleshoot problems, and re-create usage patterns.
How to: Trace Code in an Application
Describes the major steps involved in instrumentation and tracing.
How to: Compile Conditionally with Trace and Debug
Gives directions for including tracing options in compiled applications.
See Also
Concepts
How Do I in Visual Basic
Visual Basic Language Concepts

Visual Basic Guided Tour


Whether you are new to Visual Basic 2005, or perhaps new to computer programming, this is the place to start. The Visual
Basic Guided Tour is a series of sequential lessons that introduce you to the basics of programming in Visual Basic 2005.
In This Section
Getting Started with Visual Basic Express
A series of topics introducing Microsoft Visual Basic 2005 Express Edition and the Visual Basic development environment.
Creating Your First Visual Basic Program
In this section, you will see how easy it is to create a program for viewing Web pages.
Introduction to the Visual Basic Programming Language
In this section, you will learn the basics of the Visual Basic language.
Creating the Visual Look of Your Program: Introduction to Windows Forms
In this section, you will learn how to use forms and controls to create a user interface.
What Went Wrong? Finding and Fixing Errors through Debugging
In this section, you will learn how to use the debugging tools in Visual Basic 2005.
Managing Your Records: Using Data in Your Program
In this section, you will learn about working with databases.
Programming With Objects: Using Classes
In this section, you will learn the basics of object-oriented programming.
Visible Objects: Creating Your First User Control
In this section, you will learn how to create your own reusable control.
Drawing Pictures: Using Graphics
In this section, you will learn about the graphics capabilities of Visual Basic 2005.
Distributing Your Program
In this section, you will learn how to share your programs with others.
Moving Forward: Where Do I Go From Here?
A series of topics linking to additional resources for mastering Visual Basic 2005.
How Do I in Visual Basic Express
A series of topics linking to task-specific information.
Reference
Visual Basic Reference
Describes all the programmable elements in Visual Basic
Visual Basic Language Concepts

Getting Started with Visual Basic Express


Whether you are a Visual Basic 6.0 veteran looking to upgrade, an experienced programmer interested in learning Visual Basic
for the first time, or even someone brand new to computer programming, Microsoft Visual Basic 2005 Express Edition has
been designed for you. More than just a stripped-down version of Visual Basic, Microsoft Visual Basic 2005 Express Edition was
built expressly to make programming easier—and more fun—than ever before.
The Visual Basic Guided Tour includes a series of lessons that will help you to quickly get up to speed with both the Visual Basic
language and the Visual Basic Express Edition tools. Before you get started, you might want to review some of the topics in this
section to familiarize yourself with the capabilities of Visual Basic Express Edition. If you are brand new to programming, you
can jump in and start learning with Creating Your First Visual Basic Program, and then come back to these topics later.
In This Section
Introduction to Visual Basic Express
More than just a learning tool, Visual Basic Express Edition provides a full-fledged development environment for first-time
programmers and hobbyists who are interested in building Windows Forms applications, console applications, and class
libraries.
An Overview of the Visual Basic Express Tool
Provides an overview of Visual Basic Express Edition; a program for creating applications using the Visual Basic language.
How to: Work with an Existing Application
If you are already familiar with Visual Basic and have an application that you want to work with, opening an existing
application is easy.
Starter Kits: Getting Up and Running Quickly
Visual Basic Express Edition provides Starter Kits to help you start writing programs right away.
Project Types in Visual Basic Express
Visual Basic Express Edition allows you to create several types of applications, including Windows Forms applications,
console applications, and class libraries.
Troubleshooting Visual Basic Express
Although Visual Basic Express Edition makes programming easy, it may not always behave exactly as you might expect.
Related Sections
Visual Basic Guided Tour
The Visual Basic Guided Tour is a series of sequential lessons that will introduce you to the basics of programming in Visual
Basic 2005.
Creating Your First Visual Basic Program
The best way to learn programming with Visual Basic is to actually create a program.
Moving Forward: Where Do I Go From Here?
Now that you have completed the lessons in the Visual Basic Guided Tour, it's time to move on.
Help for Visual Basic 6.0 Users
Your knowledge of Visual Basic 6.0 will quickly help you become productive using Visual Basic 2005.
What's New for Visual Basic 6.0 Users
If you are an experienced user of Visual Basic 6.0, you will find a multitude of features in Visual Basic 2005 that are new or
significantly improved, making development with Visual Basic easier and more powerful than with any previous version.
Visual Basic Language Concepts

Introduction to Visual Basic Express


If you can imagine a computer program, you can probably create it with Microsoft Visual Basic 2005 Express Edition. From a
simple program that displays a message, to a full-fledged application that accesses a database or a Web service, Visual Basic
Express Edition gives you the tools you need.
More than just a learning tool, Visual Basic Express Edition provides a fully functional development environment for first-time
programmers and hobbyists who are interested in building Windows Forms applications, console applications, and class
libraries. Starter Kits and other introductory features make many features of Visual Basic accessible to first-time programmers.
What is Visual Basic Express?
Visual Basic Express Edition is a low-cost version of Visual Basic. It is both a tool for learning to program in Visual Basic, as well
as a fully functional development tool for programmers who do not need the full version of Visual Basic. But Visual Basic
Express Edition is more than just a subset of Visual Basic: It includes many features that make Visual Basic programming easier
than ever before.
The best way to learn what you can do with Visual Basic Express Edition is to step through the lessons in the
Visual Basic Guided Tour. When you finish, you will be familiar with Visual Basic tools and concepts—and ready to start writing
your own programs.
Who Should Use Visual Basic Express?
Visual Basic Express Edition is a powerful tool capable of creating fully functional applications and components that can be
shared with others. It is not, however, intended for professional developers or for programmers that work in a team
environment. Other versions of Visual Basic provide features that meet the advanced needs of professional and team
development.
If you need to write applications that connect to a networked database, interact with Microsoft Office, support mobile devices
or 64-bit operating systems, or require remote debugging, you will need a more advanced version of Visual Basic.
Note
Visual Basic Express Edition does not support development of Web applications; if you want to do Web development you can
download Visual Web Developer Express Edition.

Getting Help
The Help files that are included with Visual Basic Express Edition are a subset of the MSDN Library for Visual Studio 2005
Express Editions, which is in turn a subset of the full MSDN Library. If you are connected to the Internet, you can access any
Help topic in the full library. If you do not have online access or you chose not to install the MSDN Library for Visual Studio
2005 Express Editions, some Help topics may not be available. For more information, see Troubleshooting Visual Basic Express.
See Also
Concepts
Project Types in Visual Basic Express
Other Resources
Getting Started with Visual Basic Express
Visual Basic Guided Tour
Visual Basic Language Concepts

Project Types in Visual Basic Express


Microsoft Visual Basic 2005 Express Edition allows you to create several types of applications, including Windows Forms
applications, console applications, and class libraries. Each application that you create is contained in its own project, and
project templates are provided to help you get started.
When you create a new project, icons in the New Project dialog box and Add Project dialog box represent the available
project types and their templates. The following project templates are available when you open a new project in Visual Basic
Express Edition.
Project Types
Project template Used to create
Windows Application Template Used to create Windows-based applications that run locally on users' machines. You can build
anything from a simple single-window tool like Windows Calculator to a complete application
with multiple windows and advanced capabilities.

Class Library Template Used to create reusable classes or components that can be shared with other projects.

Console Application Template Used to create command-line applications, programs that run from a Windows command pro
mpt and have no visual interface.

My Movie Collection Starter Used to create the pre-built My Movie Collection sample application, which you can customize
Kit Template to meet your own needs. For more information, see
Starter Kits: Getting Up and Running Quickly.

Screen Saver Starter Kit Tem Used to create the pre-built Screen Saver sample application, which you can customize to meet
plate your own needs. For more information, see Starter Kits: Getting Up and Running Quickly.
Note
Although there is no project template for Windows control libraries, you can still create your own controls using the Class Li
brary template. For more information, see Visible Objects: Creating Your First User Control.

See Also
Concepts
Introduction to Visual Basic Express
Other Resources
Visual Basic Guided Tour
Visual Basic Language Concepts

An Overview of the Visual Basic Express Tool


This topic provides an overview of Visual Basic Express Edition, a program for creating applications using the Visual Basic
language. Just as a program like Microsoft Outlook provides a variety of tools for working with e-mail, Visual Basic Express
Edition is a toolkit for accomplishing a wide variety of programming tasks.
Tip
If you are new to programming, you may want to complete the Visual Basic Guided Tour, a set of lessons designed to teach y
ou the basics, and then return to this topic. To start the tour, see Creating Your First Visual Basic Program.

The Development Process


Visual Basic Express Edition makes the process of developing an application easy—in most cases, the process consists of the
following steps:
Create a project. A project contains all of the files necessary for your application, and it stores information about your
application. Sometimes an application will contain more than one project, for example, a Windows Application project
and one or more Class Library projects.Such an application is called a solution, which is just another name for a group of
projects.
Design the user interface. You do this by dragging various controls, such as button and text boxes, onto a design
surface known as a form. You can then set properties that define the appearance and behavior of the form and its
controls.
Note
For applications that have no user interface, such as class libraries or console applications, this step is not necessary.

Write the code. Next you will need to write the Visual Basic code that defines how your application will behave and how
it will interact with the user. Visual Basic Express Edition makes it easy to write code with features like Intellisense, auto-
completion, and code snippets.
Test the code. You will always want to test your application to make sure that it behaves the way that you expect it to—
this process is known as debugging. Visual Basic Express Edition has debugging tools that make it easy to find and fix
errors in your code interactively.
Distribute the application. Once your application is complete, you can install the resulting program on your computer
or distribute it and share it with others. Visual Basic Express Edition uses a new technology known as ClickOnce
Publishing that allows you to easily deploy an application using a wizard, and to automatically provide updated versions
of the application if you later make changes.

Getting Around
At first glance, the user interface for Visual Basic Express Edition, also known as the Integrated Development Environment or
IDE, may seem unfamiliar, but once you learn your way around, you will find it is easy to use. The following sections describe
parts of the IDE that you will use the most.
On Startup
When you first open Visual Basic Express Edition, you see that most of the IDE is filled with the Start Page window. The Start
Page contains a clickable list of your recent projects, a Getting Started area with links to important Help topics, and a list of
links to online articles and other resources. If you are connected to the Internet, this list will be updated on a regular basis.
You can change what appears on the Start Page to match your personal preferences. For more information, see
How to: Customize the News Section of the Start Page.
On the right-hand side of the IDE, you see the Solution Explorer window. It is initially blank, but this is where information
about your project, or groups of projects known as solutions, will be displayed. For more information, see
Using Solution Explorer.
Figure 1: Solution Explorer
On the left-hand side of the IDE, you see a vertical tab marked Toolbox. It is also initially blank, but as you work it will be filled
up with items that can be used for the task you are currently working on. For more information, see Using the Toolbox.
Across the top of the IDE are a menu bar and a toolbar. The available menus and toolbar buttons change based on your current
task—take some time to explore and see what choices are available. You can also customize the menus and toolbar to match
your personal preferences. For more information, see How to: Customize Toolbars (Visual Studio).
Across the very bottom of the IDE is a status bar that displays Ready. As you work in the IDE, the status bar changes, displaying
messages related to your current task—for example, the status bar shows information about the progress of a project you are
building.
Design Mode
When you open or create a project, the appearance of the IDE changes into design mode. This is the visual part of Visual Basic,
where you design the appearance of your application.
Figure 2: IDE in Design Mode

In design mode, the Start Page is covered by another window known as the Form Designer, which is basically a blank canvas
that represents the user interface for your application. Notice that the Start Page is still available by clicking its tab above the
Form Designer.
When the Form Designer is visible, the Toolbox contains a number of controls (representations of buttons, text fields, grids,
and so forth) that can be placed on the form and arranged as you like. For more information, see Windows Forms Designer.
You will also notice that a new window, the Properties window, appears below the Solution Explorer window. This is where
you will set the various properties that define the appearance and behavior of the form and its controls. For more information,
see Properties Window.
The Task List window at the bottom of the IDE isn't shown by default, but it provides a place that you can keep track of tasks
that need to be done or make notes while you are programming. For more information, see Task List (Visual Studio).
If you double-click a form or control, a new window called the Code Editor opens. This is where you write the actual code for
your application. More than just a text editor, the Code Editor uses a technology known as Intellisense to help you write code
by providing relevant information as you type. For more information, see Visual Basic-Specific IntelliSense.
Note
For some types of projects, such as Class Library projects that have no user interface, the Code Editor is shown instead of th
e Form Designer.

Run Mode
When you run or debug your application, the IDE changes into run mode. The application itself is launched, and an additional
window related to debugging appears. While in run mode, you cannot make changes in the Form Designer, Properties
window, or Solution Explorer, but you can make changes to your code in the Code Editor.
Figure 3: Visual Basic form in Break mode

In run mode, a new window known as the Immediate window appears at the bottom of the IDE. If you put the application into
break mode, you can query values and test code in the Immediate window. For more information, see Immediate Window.
Additional windows for watching the value of variables, viewing output, and other debugging tasks can be viewed at run time
by selecting them from the Debug menu.
Other Important Windows
There are numerous additional windows that you may encounter in the IDE, each geared to a specific programming task. Some
of the more common ones are listed below.
The Error List window appears at the bottom of the IDE if incorrect code is entered or other errors occur at design time.
For more information, see Error List Window.
The Object Browser window is used to examine the properties, methods, and events for any object that can be used in
your application. For more information, see Object Browser.
The Project Designer is used to configure properties for your application, including resources, debugging behavior,
deployment settings, and much more. For more information, see Introduction to the Project Designer.
The Database Explorer allows you to view and use existing databases or create and design new ones. For more
information, see Server Explorer/Database Explorer.
Customization
Visual Basic Express Edition allows you to customize the IDE by rearranging the window layout, choosing which windows are
displayed, adding or removing menu commands and toolbar buttons, and much more. For more information, see
Customizing the Development Environment.
Getting Help
As you work in Visual Basic Express Edition, help is always just a key-press away. Whether you are in the Code Editor or any
other window, pressing the F1 key displays the Help topic most closely related to what you are doing at the time. For example,
if you are in the Code Editor and the cursor is on the keyword Inherits, the Help browser is launched and a topic describing the
use of the Inherits statement is displayed.
Note
The Help files that are included with Visual Basic Express Edition are a subset of the MSDN Library for Visual Studio 2005 Exp
ress Editions, which is in turn a subset of the full MSDN Library. If you are connected to the Internet, you can access any Help
topic in the full library. If you do not have online access or you chose not to install the MSDN Library for Visual Studio 2005 E
xpress Editions, some Help topics may not be available.

Help can also be launched from the Help menu, and you can find the topics you are looking for by using the Contents or
Index windows or the Search tab. For more information, see Help on Help (Microsoft Document Explorer Help).
See Also
Other Resources
Creating Your First Visual Basic Program
Visual Basic Guided Tour
Help for Visual Basic 6.0 Users
Visual Basic Programming Guide
Creating Windows-based Applications
Visual Basic Language Concepts

How to: Work with an Existing Application


If you are already familiar with Visual Basic and have an application that you want to work with, opening an existing application
is easy.
To open an existing application
1. On the File menu, click Open Project.
2. In the Open Project dialog box, locate the project to be opened, and click Open.
See Also
Concepts
Using Solution Explorer
Other Resources
Managing Project Properties with the Project Designer
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Language Concepts

Starter Kits: Getting Up and Running Quickly


Think of a starter kit as a template or model program you can use to learn new tools and programming techniques and to
easily build a working program. Starter kits include code samples, documentation, and other helpful resources.
You can use a starter kit as is, or customize it. You can share it easily with friends and coworkers, or other members of the
Visual Basic community. All Microsoft Visual Basic 2005 Express Edition starter kits include tutorials to help you customize the
kit. In addition, all code includes comments to help you understand how it works.
Visual Basic Starter Kits
Visual Basic Express Edition includes two starter kits. You can find Visual Basic starter kits in the New Project dialog box,
accessible from the File menu. Select the one you want, and get started!
Starter Kit: My Movie Collection
The My Movie collection starter kit is a sample application designed to help you organize your movie collection and look up
information online. The application is highly customizable—you can personalize it and change it to organize something else
you collect.
You can use the My Movie collection, when built, to do the following:
Include descriptive information about your movie collection.
Store and save the information in a database.
Search online for information about your movies.
Starter Kit: Screen Saver
The Screen Saver starter kit helps you create a Windows Screen Saver that displays live Internet RSS feeds on your computer
monitor. The project comes ready to compile and run, but it is easy to customize.
Some easy customizations include:
Selecting your own built-in default image
Setting multiple background images.
Modifying the list of RSS feeds.
Building your own screen saver.
Using XML Web services to display information, for example, showing weather information.
Getting Started—Launching your Starter Kit
The first step to getting your starter kit up and running is loading the kit. You can then run the application and see some of the
simple tasks you can accomplish with it.
To load and run the application
1. On the File menu, click New Project.
2. In the New Project dialog box, click the starter kit you want from the list of Visual Studio installed templates, and
then click OK.
The starter kit project is loaded.
Note
You can change the name of your version of the application in the Name box.

3. Press F5 to run the application.


4. Follow the steps in the starter kit tutorial to start understanding and customizing your application.
See Also
Reference
New Project Dialog Box
Concepts
How to: Create Starter Kits
Other Resources
Starter Kits
Visual Basic Language Concepts

Troubleshooting Visual Basic Express


Although Visual Basic Express Edition makes programming easy, it may not always behave exactly as you expect. As you work
through the Visual Basic Guided Tour or go on to write your own programs, you may be able to find some help here if you run
into problems.
A Lesson in the Guided Tour Doesn't Work
As you work through the lessons in the guided tour, you may find that your program doesn't run or that it doesn't behave the
way that it should. In most cases, errors occur because you skipped a step or mistyped the code.
Tip
When entering code for a guided tour lesson, use the Copy Code button in the Help topic, and paste the code into the Code
Editor—it's easier than typing it, and you are less likely to make a mistake.

It is also possible that, due to late-breaking changes in the product, steps or code in the lesson may be wrong. The online
versions of these topics are constantly being updated, so a corrected version of the topic may be available online.
To correct errors in a lesson
1. Go back to the step in which the program last worked, and carefully follow each remaining step.
2. Review any code that you entered and make sure that it exactly matches the code in the lesson.
3. Press F5 to run the program.
If the program still doesn't run or behave as expected, check to see if an updated version of the topic is available. For
more information, see "I Can't Access a Help Topic" below.
I Can't Find a Command or Option
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is
described in Help, depending on your active settings or edition. To change your settings, choose Import and Export Settings
on the Tools menu. For more information, see Visual Studio Settings.
I Can't Access a Help Topic
The Help files that are included with Visual Basic Express Edition are a subset of the MSDN Library for Visual Studio 2005
Express Editions, which is in turn a subset of the full MSDN Online Library. During installation you had the option of installing
the MSDN Library for Visual Studio 2005 Express Editions—if you chose not to install it, consider doing so now.
A Link Doesn't Work
Links to topics that are not included in the MSDN Library for Visual Studio 2005 Express Editions will display the Information
Not Found page, but you can still access the topics that the links refer to by searching in the MSDN Online Library.
To access a topic when a link doesn't work
1. On the Help menu, click Search.
The Search Page opens.
2. In the search box, enter the text that was displayed in the link, and then click Search.
A search is performed and the results are displayed.
3. Select the MSDN Online tab on the right-hand side of the Search page.
Note
If MSDN Online is not displayed, your Help system may not be configured for online access. For more information, se
e "How to: Enable Online Access" below.

4. Click the topic title that most closely matches the text of the original link.
The topic is downloaded and displayed.
Pressing F1 Doesn't Work
Pressing F1 anywhere in the IDE should display context-sensitive Help. Even though not all topics are included in the MSDN
Library for Visual Studio 2005 Express Editions, if you are connected to the Internet, you can access any Help topic in the full
library using F1. If you do not have online access or you chose not enable online Help, some help topics may not be available
using F1.
You can change you Help options at any time as described below.
How to: Enable Online Access
The first time you access help from Visual Basic Express Edition you are prompted to choose how online Help is configured.
The choices are to try and find the online version of a topic first, to try locally installed Help first and look online if it isn't found,
or to use local Help only.
Tip
If you have access to the Internet, you should configure Help so that it checks online Help first—if a newer version of a topic i
s available, you will always have the most up-to-date information.

You can change you Help options at any time as described below.
Note
To access online Help, you must have an active connection to the Internet, and any proxy server or firewall must be configure
d to allow access to the MSDN online library.

To enable online access


1. If it is not already open, open Visual Basic from the Windows Start menu.
2. On the Tools menu, click Options.
3. In the Options dialog box, select the Show All Settings check box.
4. Expand the Help node under Environment, and then click Online.
5. In the When loading Help content box, click either Try online first, then local, or Try local first, then online.
You should now be able to access online Help.
My Database Isn't Reflecting Changes
A local database file can be included as a file in a project. The first time you connect your application to a local database file,
you can choose between creating a copy of the database in your project or connecting to the existing database file in its current
location.
If you choose to create a copy of the database, depending on the file settings, it is possible that a new copy of the database is
being created each time the project is run, overwriting the version that contains your changes. For more information, see
How to: Manage Local Data Files in Your Project.
See Also
Tasks
Troubleshooting Data Access in Visual Studio
Troubleshooting Data Types
Concepts
Troubleshooting ClickOnce Deployment
Resources for Troubleshooting Development Environment Errors
Visual Basic Language Concepts

Creating Your First Visual Basic Program


The best way to learn programming with Visual Basic is to actually create a program. The following exercises walk you through
the process of creating a program for viewing Web pages.
If you don't understand everything right away, don't worry—the concepts introduced here will be discussed in detail in other
sections of the Visual Basic Guided Tour.
For a video demonstration, see Video: Creating Your First Visual Basic Program.
In This Section
Step 1: Create a Project in Visual Basic
Step 2: Create a User Interface
Step 3: Customize Looks and Behavior
Step 4: Add Visual Basic Code
Step 5: Run and Test Your Program
Related Sections
Closer Look: Understanding Properties, Methods, and Events
Project Types in Visual Basic Express
Introduction to the Visual Basic Programming Language
Creating the Visual Look of Your Program: Introduction to Windows Forms
Visual Basic Express Resource Center (http://msdn.microsoft.com/vbasic/express)
Visual Basic Language Concepts

Step 1: Create a Project in Visual Basic


Your first step in creating a Visual Basic program is to open Visual Studio and create a project. You will do this when creating
any Visual Basic program.
For a video demonstration, see Video: Creating Your First Visual Basic Program.
To create a project for your program
1. From the Windows Start menu, choose Microsoft Visual Basic 2005 Express Edition.
The "Welcome to Visual Basic Express" screen appears. This is the interface for Visual Basic 2005 Express Edition, also
known as the integrated development environment or IDE.
2. On the File menu, click New Project.
The New Project dialog box opens.
3. Select Windows Application and click OK.
A new form displays in the IDE, and the necessary files for your project are added to the Solution Explorer window. If
this is the first Windows Application project that you have created, it is named "WindowsApplication1".
Closer Look
You just created a project for your Web-browsing program. A project in Visual Basic is a place to store the pieces of your
program and keep those pieces organized.
When you first create a new project, it exists only in memory. If you close the Visual Basic IDE, you are prompted to save or
discard the project. When you save it, you can give it a more meaningful name.
When you opened the New Project dialog box, there were several types of projects to choose from. Your Web-browsing
program is a regular Windows-based Application, that is, a program that can be run from your Start menu.
When you created the project, a form (also known as a form designer) displayed in the IDE. This form represents a window that
will display when the program is run. Many programs display more than one window, so a project can contain multiple forms.
Next Steps
In the next lesson, you will learn how to add controls to the form to build your Web-browsing application
Next Lesson: Step 2: Create a User Interface
See Also
Concepts
Project Types in Visual Basic Express
Other Resources
Creating Your First Visual Basic Program
Visual Basic Language Concepts

Step 2: Create a User Interface


It is now time to start building your Web browser. You will use Microsoft Visual Basic 2005 Express Edition to build the user
interface (the visible part that users interact with) by adding controls from the Toolbox to the form.
The Toolbox is on the left side of Visual Studio and consists of several tabs such as Data, Components, and All Windows
Forms. Inside each tab is a set of entries that represent controls or components that you can add to your application. For
example, the All Windows Forms tab has entries named TextBox, Button, and CheckBox that represent controls that you
can add to your application by dragging them onto the form.
For a video demonstration, see Video: Creating Your First Visual Basic Program.
To add controls to your application
1. Click the Toolbox panel.
The Toolbox opens.
Tip
The Toolbox is easier to use if you keep the window open. You can do this by clicking the Auto Hide icon, which looks
like a push pin.

2. Click the All Windows Forms tab of the Toolbox, select the Panel control, and then drag a panel onto the top-left
corner of the form.
Tip
If you have difficulty finding the correct control, right-click on the Toolbox and then select Sort Items Alphabetically.

3. From the same tab, drag a Button control and place it on top of the Panel.
Tip
You can reposition controls using a drag-and-drop operation. You can also resize controls by clicking and dragging the
edge or corner of the control.

4. From the same tab, drag a TextBox control and place it on top of the Panel.
5. Finally, from the All Windows Forms tab, select a WebBrowser control and place it below the Panel.
Tip
If you kept the Toolbox window open, you may want to close it now to give yourself more room to work. You can do s
o by clicking the Auto Hide icon again.

Closer Look
You just added four controls to the form. Controls contain code that defines what the controls look like and what tasks they can
perform.
Take, for example, the Button control—almost every program has an "OK" button or an "Exit" button. While you could write
your own code to draw a button on the screen, change its appearance when it is pressed, and perform some task when it is
clicked, doing so for every program would quickly become tedious. The Button control already contains the code necessary to
do these things, saving you a lot of unnecessary work.
As you can see, the Toolbox contains many controls, and each control has a unique purpose. Panel controls can be used to
hold other controls, such as the ones you just added. Button controls are typically used to perform tasks when the user clicks
them, for example, closing the program. TextBox controls are used to enter text on a screen through the keyboard. A
WebBrowser control provides built-in Web-browsing capabilities similar to Internet Explorer—you certainly wouldn't want to
write all the code for that!
In upcoming lessons you will learn how to customize the appearance of these and many other controls, as well as how to write
code that defines their behavior. In addition to using the Toolbox controls, you can also create your own controls known as
user controls—these are also covered in an upcoming lesson.
Next Steps
You just added all the necessary controls for your application. It probably looks rough and unfinished—because it is! In the
next lesson, you will use the Properties window to set the properties that will control the look and feel of your application.
Next Lesson: Step 3: Customize Looks and Behavior
See Also
Tasks
Step 1: Create a Project in Visual Basic
Other Resources
Creating Your First Visual Basic Program
Controls to Use on Windows Forms
Visual Basic Language Concepts

Step 3: Customize Looks and Behavior


In the previous lesson, you created a user interface by adding controls to your application. At this point, however, it neither
looks like nor functions as a finished application. In this lesson, you will set properties to control the appearance of your
controls, using the Properties window.
For a video demonstration, see Video: Creating Your First Visual Basic Program.
To set the properties of your controls
1. In the Form Designer, select the Panel control.
The Properties window in the lower-right corner of the IDE displays all properties for the Panel control named Panel1.
2. In the Properties window, select the Dock property, and then click the arrow to the right. A small property-selection
window with several boxes is displayed.
Tip
The Dock property is found under the Layout category. You can sort the properties alphabetically by clicking the AZ b
utton in the Properties window.

3. Click the top box in the property-selection window to set the Dock property to Top. The Panel control expands to fill the
top of the form.
4. In the Form Designer, select the WebBrowser control. In the Properties window, set its Dock property to Fill by
selecting the Dock property, clicking the arrow to the right, and selecting the center box in the property-selection
window.
5. In the Form Designer, select the Button control.
6. In the Properties window, select the Text property of the Button control. In the right-hand column, delete Button1 and
replace it with Go!.
7. Resize or relocate any of the controls, and resize the form to suit your taste.
Note
The TextBox and Button controls must remain on top of the Panel, or you will not be able to see them when you run t
he application.

Closer Look
In this lesson, you set several properties that changed the appearance of the controls for your application. A property in Visual
Basic represents an attribute of an object—in this case, a control. For example, one attribute of a Button control is the text it
displays. In this case, you set the Text property to display "Go!". To learn more about properties, see
Closer Look: Understanding Properties, Methods, and Events.
Properties can take many different types of values besides text. For example, the Dock property used a property-selection
window to show available options. Other property values might be numbers, an option you select from a list, or a true-or-false
option.
If you resized or relocated a control, you also set properties. The Size and Location properties determine the control's size and
location on the form. To see this in action, select the Size property in the Properties window and use the mouse to resize the
control. When you release the mouse, the new Size values display in the Properties window.
In addition to setting properties in the Properties window, most properties can be set by writing code. You will learn more
about writing code to set properties in a following lesson.
Next Steps
Your user interface is now complete! All you have to do is add the instructions (also called code) for how you want your
program to work. In the next lesson, you will add a line of code to your program.
Next Lesson: Step 4: Add Visual Basic Code
See Also
Tasks
Step 1: Create a Project in Visual Basic
Step 2: Create a User Interface
Concepts
Closer Look: Understanding Properties, Methods, and Events
Other Resources
Creating Your First Visual Basic Program
Visual Basic Language Concepts

Closer Look: Understanding Properties, Methods, and Events


All objects in the Visual Basic language, including forms and controls, have their own properties, methods, and events.
Properties can be thought of as an object's attributes, methods as its actions, and events as its responses.
An everyday object such as a helium balloon also has properties, methods, and events. A balloon's properties include visible
attributes such as its height, diameter, and color. Other properties describe its state (inflated or deflated), or attributes that are
not visible, such as its age. All balloons have these properties, although the values of these properties may differ from one
balloon to another.
A balloon also has known methods or actions that it can perform. It has an inflate method (filling it with helium), a deflate
method (expelling its contents), and a rise method (letting go of it). Again, all balloons are capable of these methods.
Balloons also have responses to certain external events. For example, a balloon responds to the event of being punctured by
deflating, or to the event of being released by rising.
Properties, Methods, and Events

A balloon has properties (Color, Height, and Diameter), responds to events (Puncture), and can perform methods (Deflate,
MakeNoise).
Properties
If you could program a balloon, the Visual Basic code might resemble the following "code," which sets a balloon's properties.
Balloon.Color = Red
Balloon.Diameter = 10
Balloon.Inflated = True

Notice the order of the code—the object (Balloon), followed by the property (Color), followed by the assignment of the value
(= Red). You could change the balloon's color by substituting a different value.
Methods
A balloon's methods are called like this.
Balloon.Inflate
Balloon.Deflate
Balloon.Rise(5)

The order is similar to that of a property—the object (a noun), followed by the method (a verb). In the third method, there is an
additional item, called an argument, which specifies the distance the balloon will rise. Some methods will have one or more
arguments to further describe the action to be performed.
Events
The balloon might respond to an event as follows.

Sub Balloon_Puncture()
Balloon.MakeNoise("Bang")
Balloon.Deflate
Balloon.Inflated = False
End Sub

In this case, the code describes the balloon's behavior when a Puncture event occurs: call the MakeNoise method with an
argument of "Bang" (the type of noise to make), then call the Deflate method. Since the balloon is no longer inflated, the
Inflated property is set to False.
While you can't actually program a balloon, you can program a Visual Basic form or control. As the programmer, you are in
charge. You decide which properties should be changed, which methods should be invoked, or which events should be
responded to in order to achieve the desired appearance and behavior.
Next Steps
In the next lesson, you will add a line of code to your program.
Next Lesson: Step 4: Add Visual Basic Code.
See Also
Other Resources
Visual Basic Programming Guide
Visual Basic Language Concepts

Step 4: Add Visual Basic Code


In the previous lesson, you used the Properties window to configure the properties of the controls on your form. In this
lesson, you will add the code that will control your program's functions.
For a video demonstration, see Video: Creating Your First Visual Basic Program.
To add code and functionality to your program
1. In the Form Designer, double-click the Button control.
A new window called the Code Editor opens. This is where you add all the code for your program.
2. In the Code Editor, type the following.
VB
WebBrowser1.Navigate(Textbox1.Text)

This code will run when users click the button.


Tip
When the Code Editor opens, the cursor is automatically located inside the Button's procedure - you can just start typin
g.

Closer Look
You may have noticed that when the Code Editor opened, it already contained some code that looked like this:
Private Sub Button1_Click(ByVal sender As System.Object...
|
End Sub

This code is an event handler, also called a Sub procedure. Any code inside this procedure (between Sub and End Sub) runs
each time the button is clicked. You may also have noticed that the cursor was located inside the event procedure, so all you
had to do was type.
The code that you typed (WebBrowser1.Navigate(TextBox1.Text)) tells the program to use the Navigate method of the
WebBrowser control (named WebBrowser1) with an argument of TextBox1.Text (the value contained in the Text property
of the TextBox control). To learn more about properties, methods, and events see
Closer Look: Understanding Properties, Methods, and Events
If you don't understand the code, don't worry—you will learn a lot more about writing code in following lessons.
Next Steps
Your application is now complete! In the next lesson, you will run your first Visual Basic application.
Next Lesson: Step 5: Run and Test Your Program
See Also
Tasks
Step 1: Create a Project in Visual Basic
Step 2: Create a User Interface
Step 3: Customize Looks and Behavior
Concepts
Closer Look: Understanding Properties, Methods, and Events
Other Resources
Creating Your First Visual Basic Program
Visual Basic Language Concepts

Step 5: Run and Test Your Program


Now that your program is complete, it is time to run and test it. For complex programs, testing can be a long and difficult
process, which will be discussed in detail in a later lesson. Happily, for this program, all you need to do is run it!
For a video demonstration, see Video: Creating Your First Visual Basic Program.
To run your program
1. Connect your computer to the Internet.
2. On the Debug menu of the Visual Basic IDE, click Start Debugging.
This command runs your program.
Tip
A shortcut to run your program is to press F5.

3. In the text box, type http://www.microsoft.com and click the Go! button.
The WebBrowser control in your program navigates to the Microsoft home page. From there, you can navigate through
any related links. To visit another Web page, type the address in the text box and click the Go! Button.
4. To close the program, on the Debug menu, click Stop Debugging.
Tip
You can also end the program by clicking the Close button on the top-right corner of the form.

Closer Look
In this lesson you ran your program to see if it worked. For most Visual Basic programs, you will repeat this process many
times. Typically after adding some new code, you will run the program to see if the code does what you expected it to do—if it
doesn't, you will need to fix it. This process is called debugging; it will be discussed in detail in a later lesson.
It may seem like magic that your program navigates to a Web page and displays it, all as a result of you writing a single line of
code. This is the beauty of Visual Basic—all the necessary code is built into the WebBrowser control, saving you time and
effort. If you had to do it all yourself, it would take hundreds or even thousands of lines of code!
Troubleshooting
If your program does not run or display the Web page, there are a few things you can check:
Make sure you are connected to the Internet. Open Internet Explorer and try to navigate to the Microsoft home page. If it
works in Internet Explorer, it should also work in your program.
Make sure that you typed the address (http://www.microsoft.com) correctly.
Go back and check Step 2: Create a User Interface and make sure that you put the correct controls on the form.
Go back to Step 4: Add Visual Basic Code and make sure that you typed the code correctly.
Next Steps
Congratulations! Your first Visual Basic program is complete. You have demonstrated how powerful programs can be
developed quickly and easily by using Visual Basic. In the following lessons, you will be introduced to more features of the
Visual Basic programming language.
Next Lesson: Introduction to the Visual Basic Programming Language
See Also
Tasks
Step 1: Create a Project in Visual Basic
Step 2: Create a User Interface
Step 3: Customize Looks and Behavior
Step 4: Add Visual Basic Code
Other Resources
Creating Your First Visual Basic Program
What Went Wrong? Finding and Fixing Errors through Debugging
Visual Basic Language Concepts

Introduction to the Visual Basic Programming Language


Microsoft Visual Basic 2005 Express Edition is a fast and easy way to create programs for Microsoft Windows. Even if you are
new to Windows programming, with Visual Basic you have a complete set of tools to simplify development.
So what is Visual Basic? "Visual" refers to the method used to create what the user sees—the graphical user interface, or GUI.
"Basic" refers to the BASIC (Beginners All-Purpose Symbolic Instruction Code) programming language, a language used by
more programmers than any other language in the history of computing. You can create useful programs by learning just a
few of its features. The following links will get you started with Visual Basic programming; each link includes examples, as well
as access to additional information.
Programming Concepts
What exactly is a programming language? The following links will give you some background on what a language is and how
it stores different types of information.
Term Definition
The Basics: How Programming Works How a programming language works, along with basic termin
ology.

Representing Words, Numbers, and Values with Variables How variables store values and represent information, along w
ith how to use variables.

Words and Text: Using String Variables to Organize Words How to use a String variable to represent words and text.

Arrays: Variables That Represent More Than One Value How to use an Array variable to represent several values of th
e same type.

Arithmetic: Creating Expressions With Variables And Operators How to write code that performs arithmetic.

Comparisons: Using Expressions to Compare Values How to write code that compares numeric values.

Your First Program


Ready for a bit of real-world programming? The following links will walk you through the creation of a simple program and
will show you how to check your program for errors.
Term Definition
Making Your Computer Do Something: Writing Your First Procedure How to write code that tells your program to
perform a particular action.

Making Your Program Repeat Actions: Looping With the For...Next Loop How to write code that repeats actions in you
r program and counts how many times these
actions have been performed.

Making Your Program Choose Between Two Possibilities: The If...Then Statement How to write code that does different things i
n response to different conditions.

What To Do When Something Goes Wrong: Handling Errors How to write code that handles errors in your
programs. You will also learn about the differ
ent types of errors.

More About Visual Basic


The following links will help you build on your knowledge of programming and of the Visual Basic 2005.
Term Definition
Closer Look: Understanding Properties, Methods, and Events How properties, methods, and events work.

Closer Look: Data Types How data is stored using the different types of v
ariables.

Closer Look: Converting from One Variable Type to Another How to convert data from one type to another, a
long with some common pitfalls of this process.

Closer Look: Using Do...While and Do...Until to Repeat Until a Condition is Met How to use the Do...While and Do...Until state
ments to repeat code based on certain condition
s.

Closer Look: Using Select Case to Decide Between Multiple Choices How to run code based on multiple conditions,
where there are many choices.

Visual Basic Guided Tour More of what you can do with the Visual Basic 2
005 programming language
Visual Basic Language Concepts

The Basics: How Programming Works


Before you jump in and start learning the Visual Basic programming language, it may help you to understand what a
programming language is and how it works, including some programming terminology. The best place to start is with the
basics.
How Programming Works
On its own, a computer isn't very smart.
A computer is essentially just a big bunch of tiny electronic switches that are either on or off. By setting different combinations
of these switches, you can make the computer do something, for example, display something on the screen or make a sound.
That's what programming is at its most basic—telling a computer what to do.
Of course, understanding which combination of switches will make the computer do what you want would be a daunting task
—that's where programming languages come in.
What is A Programming Language?
People express themselves using a language with many words. Computers use a simple language consisting of only 1s and 0s,
with a 1 meaning "on" and a 0 meaning "off." Trying to talk to a computer in its own language would be like trying to talk to
your friends using Morse code—it can be done, but why would you?
A programming language acts as a translator between you and the computer. Rather than learning the computer's native
language (known as machine language), you can use a programming language to instruct the computer in a way that is easier
to learn and understand.
A specialized program known as a compiler takes the instructions written in the programming language and converts them to
machine language. This means that as a Visual Basic programmer, you don't need to understand what the computer is doing
or how it does it, you just need to understand how the Visual Basic programming language works.
Inside the Visual Basic Language
In many ways, Visual Basic is a lot like the language that you use every day. When you speak or write, you use different types
of words, such as nouns or verbs, which define how they are used. Visual Basic also has different types of words known as
programming elements that define how they are used to write programs.
Programming elements in Visual Basic include statements, declarations, methods, operators, and keywords. As you complete
the following lessons, you will learn more about these elements and how to use them.
Written and spoken language also has rules, or syntax, that defines the order of words in a sentence. Visual Basic also has
syntax—at first it may look strange, but it is actually very simple. For example, to state "The maximum speed of my car is 55",
you would write:
Car.Speed.Maximum = 55

You will learn more about syntax later, and tools in Visual Basic such as IntelliSense provide you with guidance in using the
correct syntax when writing programs.
The language you write and speak also has structure: for example, a book has chapters with paragraphs that contain sentences.
Programs written in Visual Basic also have a structure: modules are like chapters, procedures are like paragraphs, and lines of
code are like sentences.
Next Steps
In this lesson, you learned what a programming language is and how it works. In the next lesson, you will start learning how to
use the Visual Basic programming language. Don't worry—you'll be speaking Visual Basic in no time at all!
Next Lesson: Representing Words, Numbers, and Values with Variables
See Also
Tasks
Representing Words, Numbers, and Values with Variables
Concepts
Closer Look: Understanding Properties, Methods, and Events
Introduction to the Visual Basic Programming Language
Other Resources
Creating Your First Visual Basic Program
Visual Basic Programming Guide
Visual Basic Language Concepts

Representing Words, Numbers, and Values with Variables


Variables are an important concept in computer programming. A variable is a letter or name that can store a value. When you
create computer programs, you can use variables to store numbers, such as the height of a building, or words, such as a
person's name. Simply put, you can use variables to represent any kind of information your program needs.
You might ask, "Why use a variable when I could just use the information instead?" As the name implies, variables can change
the value that they represent as the program is running. For example, you might write a program to track the number of jelly
beans you have in a jar on your desk. Because candy is meant to be eaten, the number of jelly beans in the jar is likely to
change over time. Rather than rewriting your program every time you get a sugar craving, you can represent the number of
jelly beans with a variable that can change over time.
Storing Information in Variables
There are three steps to using a variable:
1. Declare the variable. Tell the program the name and kind of variable you want to use.
2. Assign the variable. Give the variable a value to hold.
3. Use the variable. Retrieve the value held in the variable and use it in your program.
Declaring Variables
When you declare a variable, you have to decide what to call it and what data type to assign to it.
You declare a variable using the Dim and As keywords, as shown below.
VB
Dim aNumber As Integer

This line of code tells the program that you want to use a variable named aNumber, and that you want it to be a variable that
stores whole numbers (the Integer data type).
Because aNumber is an Integer, it can store only whole numbers. If you had wanted to store 42.5, for example, you would have
used the Double data type. And if you wanted to store a word, you'd use a data type called a String. One other data type
worth mentioning at this point is Boolean, which can store a True or False value.
Here are more examples of how to declare variables.
VB
Dim aDouble As Double
Dim aName As String
Dim YesOrNo As Boolean

For more information about other variable types, see Closer Look: Data Types.
Assigning Variables
You assign a value to your variable with the = sign, which is sometimes called the assignment operator, as shown in the
following example.
VB
aNumber = 42

This line of code takes the value 42 and stores it in the previously declared variable named aNumber.
Declaring and Assigning Variables with a Default Value
As shown above, you can declare a variable on one line of code, and then later assign the value on another line. This can result
in an error if you try to use the variable before assigning it a value.
For that reason, it is a better idea to declare and assign variables on a single line. Even if you don't yet know what value the
variable will hold, you can assign a default value. The code for declaring and assigning the same variables shown earlier would
look like the following.
VB
Dim aDouble As Double = 0
Dim aName As String = "default string"
Dim YesOrNo As Boolean = True

By declaring variables and assigning default values on a single line, you can prevent possible errors. You can still use
assignment to give the variable a different value later on.
Try It!
In this exercise, you will write a short program that creates four variables, assigns them values, and then displays each value in
a window called a message box. Let's begin by creating the project where the code will be stored.
To create the project
1. If it is not already open, open Visual Basic from the Windows Start menu.
2. On the File menu, click New Project.
3. In the New Project dialog box on the Templates pane, click Windows Application.
4. In the Name box, type Variables and then click OK.
Visual Basic will create the files for your program and open the Form Designer.
Next, you'll create the variables.
To create variables and display their values
1. Double-click the form.
The Code Editor opens to a section of code called Form1_Load. This section of code, which is called a procedure, contains
instructions that will be carried out when the form is first loaded into memory.
2. In the Form1_Load procedure, type the following code.
VB
Dim anInteger As Integer = 42
Dim aSingle As Single = 39.345677653
Dim aString As String = "I like candy"
Dim aBoolean As Boolean = True

This code declares four variables—an Integer, a Single, a String, and a Boolean—and assigns their default values.
Tip
As you typed the code, you may have noticed that after you typed As, a list of words appeared below the cursor. This fe
ature is called Intellisense. It allows you to just type the first few letters of a word until the word is selected in the list. O
nce selected, you can press the TAB key to finish the word.

Note
Whenever you represent actual text in a program, you must enclose it in quotation marks (""). This tells the program to
interpret the text as actual text instead of as a variable name. When you assign a Boolean variable a value of True or F
alse, you do not enclose the word in quotation marks, because True and False are Visual Basic keywords with special
meanings of their own.

3. Beneath the code you wrote in the previous step, type the following.
VB
MsgBox(anInteger)
MsgBox(aSingle)
MsgBox(aString)
MsgBox(aBoolean)

VB
End

The first four lines of code tell the program to display each value that you assigned in the previous step in a new window,
using the MsgBox function. The final line tells the program to end after executing this procedure—it uses the End
statement.
4. Press F5 to run your program.
Click OK for each window as it appears. Note that the value of each variable is displayed in turn, and then the program
ends. After the program has finished, you can go back and change the values that are assigned in the code and run the
application again—you'll see that the new values are displayed.
Next Steps
In this lesson, you learned the basics about variables. In the next lesson, you will learn more about String variables.
Next Lesson: Words and Text: Using String Variables to Organize Words
See Also
Tasks
Words and Text: Using String Variables to Organize Words
Closer Look: Converting from One Variable Type to Another
Concepts
The Basics: How Programming Works
Closer Look: Data Types
Visual Basic Language Concepts

Closer Look: Data Types


Data types in Visual Basic determine what kind of values or data can be stored in a variable, as well as how that data is stored.
Why are there different data types? Think of it this way: if you had three variables, two of which held numbers while the third
held a name, you could perform arithmetic using the first two, but you can't perform arithmetic on the name. Assigning a data
type to a variable makes it easier to determine how the variable can—or can't—be used.
Note
Data types are also used in other programming elements such as constants, properties, and functions. You will learn more ab
out the other uses of data types in a following lesson.

Data Types for Numbers


Most computer programs deal with numbers in some form or another. Since there are several different ways to express
numbers, Visual Basic has several numeric data types to deal with numbers more efficiently.
The numeric data type that you will use the most is the Integer, which is used to represent a whole number (a number without
a fractional part). When choosing a data type to represent whole numbers, you will want to use the Long data type if your
variable will be storing numbers larger than approximately two billion; otherwise an Integer is more efficient.
Not all numbers are whole numbers; for example, when you divide two whole numbers, the result is often a whole number
plus a fraction (9 divided by 2 equals 4.5). The Double data type is used to represent numbers that have a fractional part.
Note
There are additional numeric data types such as Decimal, Short, SByte, and UInteger; these are typically used in very large
programs where memory usage or speed is an issue. For now, the basic numeric data types are all you will need. If you want
to learn more about the advanced data types, see Numeric Data Types.

Data Types for Text


Most programs also deal with text, whether displaying information to the user or capturing text entered by the user. Text is
usually stored in the String data type, which can contain a series of letters, numbers, spaces, and other characters. A String can
be of any length, from a sentence or a paragraph to a single character to nothing at all (a null string).
For a variable that will always represent just one character, there is also a Char data type. If you only need to hold one
character in a single variable, you can use the Char data type instead of a String.
Other Data Types
In addition to text and numbers, programs sometimes need to store other types of information, such as a true or false value, a
date, or data that has a special meaning to the program.
For values that can be represented as true/false, yes/no, or on/off, Visual Basic has the Boolean data type. A Boolean variable
can hold one of two possible values: True or False.
Although you can represent dates or times as numbers, the Date data type makes it easy to calculate dates or times, such as
the number of days until your birthday or the number of minutes until lunch.
When you need to store more than one type of data in a single variable, you can use a composite data type. Composite data
types include arrays, structures, and classes. You will learn more about these in later lessons.
Finally, there are some cases in which the type of data that you need to store may be different at different times. The Object
data type allows you to declare a variable and then define its data type later. You will also learn more about the Object data
type in a later lesson.
Next Steps
In the next lesson, "Words and Text: Using String Variables to Organize Words," you will learn more about working with string
variables to form sentences.
Next Lesson: Words and Text: Using String Variables to Organize Words
See Also
Tasks
Words and Text: Using String Variables to Organize Words
Representing Words, Numbers, and Values with Variables
Concepts
Data Types in Visual Basic
Visual Basic Language Concepts

Words and Text: Using String Variables to Organize Words


In this lesson, you will learn how to use the String data type to represent words and text.
In the previous lesson, you learned how to use variables to store data in your program, and that each variable must be of the
appropriate type for the data that it will store. In this lesson, you will learn more about the String data type, which is used to
store text.
What Is a String?
A string is any series of text characters, such as letters, numbers, special characters, and spaces. Strings can be human-readable
phrases or sentences, such as "The quick brown fox jumps over the lazy dog," or an apparently unintelligible combination, such
as "@#fTWRE^3 35Gert".
String variables are created just as other variables: by first declaring the variable and assigning it a value, as shown below.
VB
Dim aString As String = "This is a string"

When assigning actual text (also called a string literal) to a String variable, the text must be enclosed in quotation marks ("").
You can also use the = character to assign one String variable to another String variable, as shown in this example.
VB
Dim aString As String = "This is a string"

Dim bString As String = ""


bString = aString

The previous code sets the value of bString to the same value as aString (This is a string).

You can use the ampersand (&) character to sequentially combine two or more strings into a new string, as shown below.
VB
Dim aString As String = "Across the Wide"
Dim bString As String = "Missouri"
Dim cString As String = ""
cString = aString & bString

The previous example declares three String variables and respectively assigns "Across the Wide" and "Missouri" to the first
two, and then assigns the combined values of the first two to the third variable. What do you think the value of cString is? You
might be surprised to learn that the value is Across the WideMissouri because there is no space at the end of aString or at
the beginning of bString. The two strings are simply joined together. If you want to add spaces or anything else between two
strings, you must do so with a string literal, such as " ", as shown below.
VB
Dim aString As String = "Across the Wide"
Dim bString As String = "Missouri"
Dim cString As String = ""
cString = aString & " " & bString

The text contained in cString now reads as Across the Wide Missouri.

Try It!
To join strings
1. On the File menu, click New Project.
2. In the New Project dialog box:
a. In the Templates pane, click Windows Application.
b. In the Name box, type Concatenation.
c. Click OK.
A new Windows Forms project opens.
3. Double-click the form to open the Code Editor.
4. In the Form1.Load event procedure, declare four string variables and assign the string values, as shown below:
VB
Dim aString As String = "Concatenating"
Dim bString As String = "Without"
Dim cString As String = "With"
Dim dString As String = "Spaces"

5. Add the following code to concatenate the strings and display the results:
VB
' Displays "ConcatenatingWithoutSpaces".
MsgBox(aString & bString & dString)

' Displays "Concatenating With Spaces".


MsgBox(aString & " " & cString & " " & dString)

The text displayed in the message box is the result of joining the string variables that were assigned in a previous step. In
the first box, the strings are joined together without spaces. In the second, spaces are explicitly inserted between each
string.
Next Steps
In this lesson, you learned how to declare and assign strings, and how to join strings with the concatenation operator &. In the
next lesson, "Arrays: Variables That Represent More Than One Value," you will learn about creating variables to store groups of
similar items.
Next Lesson: Arrays: Variables That Represent More Than One Value
See Also
Tasks
Arrays: Variables That Represent More Than One Value
Representing Words, Numbers, and Values with Variables
Concepts
Introduction to the Visual Basic Programming Language
Visual Basic Language Concepts

Arrays: Variables That Represent More Than One Value


In this lesson, you will learn how to use arrays to store groups of values.
As you learned in the previous lessons, variables are used to store different types of data for use by your program. There is
another type of variable called an array that provides a convenient way to store several values of the same type.
For example, suppose you were writing a program for a baseball team and you wanted to store the names of all of the players
on the field. You could create nine separate string variables, one for each player, or you could declare an array variable that
looks something like the code below.
VB
Dim players() As String

You declare an array variable by putting parentheses after the variable name. If you know how many values you need to store,
you can also specify the size of the array in the declaration as follows.
VB
Dim players(9) As String

The size of the array is 9 because a baseball team has 9 players. An array is made up of a number of values, or elements,
starting with element 0 and ending with one less than the number specified in the declaration. In this case, the array contains
the elements 0 through 8, for a total of nine elements. When you want to refer to one of the players on the team, you just
subtract 1. For example, to reference the first player, you reference element 0, to reference the ninth player, you reference
element 8.
Assigning Values to Arrays
As with other types of values, you need to assign values to arrays. To do so, you refer to the element number as part of the
assignment, as shown below.
VB
players(0) = "John"
players(3) = "Bart"

In the above code, the value John is assigned to the first element of the array (element 0) and the value Brett is assigned to the
fourth element (element 3). The elements of the array don't have to be assigned in order, and any unassigned element will
have a default value—in this case, an empty string.
As with other types of values, you can declare and assign values to an array on a single line as follows.
VB
Dim players() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9}

In this case, curly brackets indicate a list of values. The values are assigned to elements in the order listed. Notice that size of
the array isn't specified—it is determined by the number of items that you list.
Retrieving Values from Arrays
Just as you use numbers to specify an item's position in an array, you use the element number to specify which value you want
to retrieve.
VB
Dim AtBat As String
AtBat = players(3)
The above code retrieves the fourth element of the array and assigns it to the string variable AtBat.
Try It!
To store values in an array
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type MyFirstArray and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag a Textbox control onto the form.
5. From the Toolbox, drag a Button control onto the form.
6. Double-click the Button to open the Code Editor.
7. In the Button1_Click event procedure, add the following code:
VB
Dim players() As String = {"Dan", "Fred", "Bart", "Carlos", _
"Ty", "Juan", "Jay", "Sam", "Pedro"}
Dim i As Integer = CInt(Textbox1.Text)
MsgBox(players(i) & " is on first base.")

Notice that the above code uses the CInt function to convert the String value (TextBox1.Text) to an Integer (i). You can
learn more about conversions in Closer Look: Converting from One Variable Type to Another.
8. Press F5 to run the program.
9. Type a number between 0 and 8 in the text box and click the button. The name corresponding to that element is
displayed in a message box.
Tip
You should write additional code to check that the data entered is valid. For example, you can check that the value enter
ed is a numeric value between 0 and 8. For more information, see
What To Do When Something Goes Wrong: Handling Errors.

Next Steps
In this lesson, you learned how to use arrays to store and retrieve groups of similar values.
In the next lesson, you will learn how to use arithmetic operators to create expressions.
Next Lesson: Arithmetic: Creating Expressions With Variables And Operators
See Also
Tasks
Arithmetic: Creating Expressions With Variables And Operators
Words and Text: Using String Variables to Organize Words
Concepts
Overview of Arrays in Visual Basic
Visual Basic Language Concepts

Arithmetic: Creating Expressions With Variables And Operators


In this lesson, you will learn how to create expressions to perform arithmetic and then return values.
An expression is a segment of code that performs arithmetic and then returns a value. For example, a simple addition
expression is shown below.
5+4
The expression 5 + 4 returns the value 9 when evaluated and is made up of two parts: the operands (5 and 4), which are the
values that the operation is performed on, and the operator (+), which specifies the operation to be performed.
Using Values Returned by Expressions
For an expression to be useful, you must do something with the value that is returned. The most common thing to do is to
assign it to a variable, as shown below.
VB
Dim anInteger As Integer = 5 + 4

This example declares a new Integer variable called anInteger and assigns the value returned by 5 + 4 to it.
Arithmetic Operators
A common use for expressions is to perform arithmetic on variables: addition, subtraction, multiplication, or division. The
following table describes the operators commonly used for arithmetic.
Operator Description Example
+ (addition) Returns the sum of two operands 5+4

- (subtraction) Returns the difference of two operands 5-4

* (multiplication) Returns the product of two operands 5*4

/ (division) Returns the quotient of two operands 5/4

The kind of variable that you use when performing arithmetic can affect the result. Dividing two numbers often results in a
return value that is not a whole number. For example, when you divide 3 by 2, the result is 1.5. If you assigned the return value
of that expression to an Integer variable, it would be rounded to the nearest whole number, 2. When performing division, you
should use a Double variable to store the return value.
Note
You can also convert a variable from one data type to another by using the conversion functions of Visual Basic. For more inf
ormation, see Closer Look: Converting from One Variable Type to Another.

Try It!
To add numbers
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type Arithmetic and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag two Textbox controls onto the form.
5. From the Toolbox, drag a Button control onto the form.
6. Double-click the Button to open the Code Editor.
7. In the Button1_Click event procedure, type the following code.
VB
Dim A As Double = Textbox1.Text
Dim B As Double = Textbox2.Text

MsgBox(A + B)
MsgBox(A - B)
MsgBox(A * B)
MsgBox(A / B)

The first two lines declare the variables A and B, which will hold the numeric values used in this program, and assign the
values of the two TextBox controls (their text) to the variables A and B.
The final four lines create expressions with the two variables and each of the basic arithmetic operators, and display the
results of those expressions in a message box.
8. Press F5 to run the application.
9. Type a number in each of the text boxes and click Button1.
Note
If you type any other character into the text boxes, an error will occur.

Expressions are created using the two numbers that you enter and each of the four basic arithmetic operators (addition,
subtraction, multiplication, and division). The result of each expression is displayed in a message box.
Next Steps
In this topic, you learned about creating and using expressions. You also learned about operands and operators, and how to
construct an expression. At this point, you can either continue to the next lesson,
Comparisons: Using Expressions to Compare Values or learn more about converting variables to different types in
Closer Look: Converting from One Variable Type to Another. If you choose "Closer Look," you will complete it and then
proceed to the next lesson.
See Also
Tasks
Closer Look: Converting from One Variable Type to Another
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Concepts

Closer Look: Converting from One Variable Type to Another


As you have seen, variables come in different types. The type determines what kind of data a variable can hold. An Integer
variable can hold only numeric data without decimal points. A String variable can hold only text.
What happens when you want to display an Integer in a TextBox control that requires a String? The answer is that the data
must be converted from one type to another. In this topic, you will explore how to convert data from one type to another, and
you will learn some techniques used for data conversion, as well as some of its common pitfalls.
Converting Variables to Text
Every variable in Visual Basic can be converted to text by using a special function called CStr (which is shorthand for Convert to
String). This function, as the name implies, returns the data represented by the variable as a String. The following procedure
demonstrates a simple example of converting an Integer to text.
Try It!
To convert a variable to text
1. On the File menu, click New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type Conversion and then click OK.
A new Windows Forms project opens.
4. Double-click the form to open the Code Editor.
5. In the Form1_Load event handler, type the following code.
VB
Dim anInteger As Integer = 54
MsgBox(CStr(anInteger))

This code declares an Integer variable called anInteger, assigns it a value of 54, and then converts that value to text and
displays it in a message box by calling the CStr function.
6. Press F5 to build and run your application. A message box that reads 54 is displayed.
Let's try something just for fun. In the Code Editor, change the line that reads MsgBox(CStr(anInteger)) to read
MsgBox(anInteger), and press F5 to run. What happens? The program behaves exactly as it did before. Visual Basic is
smart enough to know that what you really want is to convert the Integer to text to display in the message box.
However, you cannot rely on this behavior for all cases—there are many variable types that cannot be automatically
converted. Therefore, it is good practice to always use the CStr function, even if a variable would automatically be
converted to text.
In addition to converting Integer variables to text, the CStr function can be used on any numeric data type, such as Double or
Long. It can also be used to convert the Date and Boolean data types to text. For more information on data types, see
Closer Look: Data Types.
Converting Between Numeric Data Types
As you learned in the arithmetic lesson, sometimes the result of an arithmetic operation can't be expressed as an Integer. Just
as Visual Basic has a function for converting numbers to text, it also has functions for converting variables from one numeric
data type to another. For example, you can use the CDbl (Convert to Double) function in an arithmetic operation to return a
fractional number when working with Integer variables. The following procedure shows how to use the CDbl function when
dividing two integers.
Try It!
To convert numeric data types
1. In the Code Editor, delete the code that you entered in the previous procedure and type the following:
VB
Dim A As Integer = 1
Dim B As Integer = 2
MsgBox(CDbl(A / B))

This code declares two Integer variables (A and B), assigns them values of 1 and 2, and then converts the result of the
division operation (A / B) using the CDbl function and displays it in a message box.
2. Press F5 to build and run your application. A message box that reads 0.5 is displayed.
Visual Basic has functions for other types of numeric variables as well. For example, if you add two variables of the type
Double and want to round the result to the nearest whole number, use the CInt function. Other numeric conversion functions
include CByte, CDec, CLng, and CShort. For a list of all the Visual Basic conversion functions, see Type Conversion Functions.
Next Steps
In this lesson, you learned how to convert numeric variables to text, and also how to convert between different types of
numeric variables. In the next lesson, Comparisons: Using Expressions to Compare Values, you will learn how to evaluate
expressions.
See Also
Tasks
Arithmetic: Creating Expressions With Variables And Operators
Concepts
Closer Look: Data Types
Other Resources
Type Conversions in Visual Basic
Visual Basic Language Concepts

Comparisons: Using Expressions to Compare Values


In this lesson, you will learn how to use comparison operators to create expressions that compare values.
In the last lesson, you learned how to use arithmetic operators to create numeric expressions and return numeric values.
Another kind of operator, the comparison operators, can be used to compare numeric values and return Boolean (True or
False) values.
Comparison operators are most frequently used to compare values and make decisions based on that comparison. Making
decisions in your program will be covered in-depth in
Making Your Program Choose Between Two Possibilities: The If...Then Statement.
The following table summarizes the comparison operators:
Operator Description Examples
= (equals) Returns True if the number on the left-hand side is equal to the number on the right-h 5 = 4 (false)
and side.
4 = 5 (false)
4 = 4 (true)

<> (not equal to) Returns True if the number on the left is not equal to the number on the right. 5 <> 4 (true
)
4 <> 5 (true
)
4 <> 4 (fals
e)

> (greater than) Returns True if the number on the left is greater than the number on the right. 5 > 4 (true)
4 > 5 (false)
4 > 4 (false)

< (less than) Returns True if the number on the left is less than the number on the right. 5 < 4 (false)
4 < 5 (true)
4 < 4 (false)

>= (greater than or equal Returns True if the number on the left is greater than or equal to the number on the ri 5 >= 4 (true
to) ght. )
4 >= 5 (fals
e)
4 >= 4 (true
)

<= (less than or equal to) Returns True if the number on the left is less than or equal to the number on the right. 5 <= 4 (fals
e)
4 <= 5 (true
)
4 <= 4 (true
)
Try It!
To compare expressions
1. On the File menu, click New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type Comparison and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag two Textbox controls onto the form.
5. From the Toolbox, drag a Button control onto the form.
6. Double-click the Button to open the Code Editor.
7. In the Button1_Click event handler, type the following code:
VB
Dim A As Double = CDbl(Textbox1.Text)
Dim B As Double = CDbl(Textbox2.Text)
MsgBox(A > B)
MsgBox(A < B)
MsgBox(A = B)

The first two lines declare the variables A and B, which will hold the numeric values used in this program; they use the
CDbl statement to convert the text from Textbox1 and Textbox2 into numeric values. Finally, the last three lines create
expressions to compare the two variables using three basic comparison operators, and display the results of those
expressions in three message boxes.
8. Press F5 to run the application.
9. Type a number in each of the text boxes and click Button1.
The first message box will display True if A (the number that you entered in the first text box) is greater than B (the
number that you entered in the second text box); otherwise it will display False. The second message box will display
True if A is less than B, and the third message box will display True if both numbers are the same.
Try typing different numbers into the text boxes to see how the results change.
Next Steps
In this lesson, you learned how to use comparison operators to compare numeric values. In the next lesson, you will learn how
to create and call a procedure—code that performs an action.
Next Lesson: Making Your Computer Do Something: Writing Your First Procedure
See Also
Tasks
Arithmetic: Creating Expressions With Variables And Operators
Closer Look: Converting from One Variable Type to Another
Making Your Program Choose Between Two Possibilities: The If...Then Statement
Concepts
Comparison Operators in Visual Basic
Visual Basic Language Concepts

Making Your Computer Do Something: Writing Your First


Procedure
In this lesson, you will learn how to create a procedure, a self-contained block of code that can be run from other blocks of
code, and then how to create parameters for your procedures.
A procedure is simply a piece of code that tells the program to perform an action. Although you may not have realized it, you
have already used procedures in the previous lessons. For example, the MsgBox function is a built-in procedure that performs
the action of displaying a dialog box.
While Visual Basic has many built-in procedures for performing common actions, there will always be cases when you want
your program to perform an action that a built-in procedure can't handle. For example, the MsgBox function cannot display a
dialog box with a picture. You need to write your own procedure to accomplish this task.
What is a Procedure?
A procedure is a self-contained block of code that can be run from other blocks of code. Generally speaking, procedures each
contain the code necessary to accomplish one task. For example, you might have a procedure called PlaySound, which
contains the code required to play a wave file. While you could write the code to play a sound every time your program needed
to make a noise, it makes more sense to create a single procedure that you can call from anywhere in your program.
A procedure is run, or executed, by calling it in code. For example, to run the PlaySound procedure, you simply add a line of
code to your program with the name of your procedure, as shown below.
PlaySound

That's all there is to it! When the program reaches that line, it will jump to the PlaySound procedure and execute the code
contained there. The program will then jump back to the next line that follows the call to PlaySound.
You can call as many procedures as you like. Procedures are run in the order that they are called. For example, you might also
have a procedure called DisplayResults; to execute it after executing the PlaySounds procedure, call the procedures as shown
below.
PlaySounds
DisplayResults

Functions and Subs


There are two kinds of procedures: functions and subroutines (sometimes called subs). A function returns a value to the
procedure that called it, whereas a sub simply executes code. Subs are called when a line of code that contains the name of the
sub is added to the program, as in the following example.
DisplayResults

Functions are different, because functions not only execute code, they also return a value. For example, imagine a function
called GetDayOfWeek that returns an Integer indicating the day of the week. You call this function by first declaring a
variable in which to store the return value, and then assigning the returned value to the variable for later use, as shown below.
Dim Today As Integer
Today = GetDayOfWeek

In this example, the value returned by the function is copied to the variable named Today and stored for later use.
Writing Procedures
You write procedures by first writing a procedure declaration. A procedure declaration does several things: states whether the
procedure is a function or a sub, names the procedure, and details any parameters the procedure might have (parameters will
be discussed in detail later in this lesson). The following is an example of a simple procedure declaration.
VB
Sub MyFirstSub()
End Sub

The Sub keyword tells the program that this procedure is a sub and will not return a value. The name of the sub (MyFirstSub)
comes next, and the empty parentheses indicate that there are no parameters for this procedure. Finally, the End Sub keyword
indicates the end of the subroutine. All code that is to be executed by this sub goes between these two lines.
Declaring functions is similar, but with the added step that the return type (such as Integer, String, etc.) must be specified. For
example, a function that returned an Integer might look like this.
VB
Function MyFirstFunction() As Integer
End Function

The As Integer keywords indicate that this function will return an Integer value. To return a value from a function, use the
Return keyword, as shown in the following example.
VB
Function GetTheNumberOne() As Integer
Return 1
End Function

This procedure will return the number 1.


Try It!
To create procedures
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type MyFirstProcedure and then click OK.
A new Windows Forms project opens.
4. Double-click the form to open the Code Editor.
5. In the Code Editor, locate the line that reads End Class. This is the end of the code section that makes up your form.
Immediately before this line, add the following procedure:
VB
Function GetTime() As String
Return CStr(Now)
End Function

This function uses the built-in Now procedure to get the current time, then uses the CStr function to convert the value
returned by Now into a human-readable String. Finally, that String value is returned as the result of the function.
6. Above the function you added in the previous step, add the following Sub.
VB
Sub DisplayTime()
MsgBox(GetTime)
End Sub

This sub calls the function GetTime and displays the result returned by it in a message box.
7. Finally, add a line to the Form1_Load event handler that calls the DisplayTime sub, as shown below.
VB
DisplayTime()
8. Press F5 to run the program.
When the program starts, the Form1_Load event procedure is executed. This procedure calls the DisplayTime sub, so
program execution jumps to the DisplayTime sub procedure. That sub in turn calls the GetTime function, so program
execution then jumps to the GetTime function. This function returns a String representing the time to the DisplayTime
sub procedure, which then displays that string in a message box. After the sub is finished executing, the program
continues normally and displays the form.
Parameters in Functions and Subs
At times you will need to provide additional information to your procedures. For example, in the PlaySound procedure, you
may want to play one of several different sounds. You can provide the information on which sound to play by using
parameters.
Parameters are a lot like variables. They have a type and a name, and they store information just like variables. They can be
used just like variables in a procedure. The two main differences between parameters and variables are:
Parameters are declared in the procedure declaration, not in individual lines of code.
Parameters are usable only in the procedure they are declared in.
Parameters are declared in the procedure declaration in the parentheses that follow the procedure name. The As keyword is
used to declare the type, and each parameter is generally preceded by the ByVal keyword. This keyword will be added
automatically by Visual Basic if you do not add it, and it has a fairly advanced function that is beyond the scope of this lesson to
explain.
An example of a sub with parameters is shown below.
VB
Sub PlaySound(ByVal SoundFile As String, ByVal Volume As Integer)
My.Computer.Audio.Play(SoundFile, Volume)
End Sub

You would then call the sub with the values for the parameters as shown below.
VB
PlaySound("Startup.wav", 1)

You can also declare parameters for functions in exactly the same way you would for subs.
Try It!
To create a function with parameters
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type parameters and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag two Textbox controls onto the form.
5. From the Toolbox, drag a Button control onto the form.
6. Double-click the Button to open the Code Editor.
7. Immediately after the End Sub line of the Button1_Click event handler, add the following procedure:
VB
Function AddTwoNumbers(ByVal N1 As Integer, ByVal N2 As Integer) _
As Integer
Return N1 + N2
End Function

8. In the Button1_Click procedure, add the following code:


VB
Dim aNumber As Integer = CInt(Textbox1.Text)
Dim bNumber As Integer = CInt(Textbox2.Text)
MsgBox(AddTwoNumbers(aNumber, bNumber))

This code declares two integers and converts the text in the two text boxes to integer values. It then passes those values
to the AddTwoNumbers function and displays the value returned in a message box.
9. Press F5 to run the program.
10. Type a number value in each text box and click the button. The two numbers are added, and the result is displayed in a
message box.
Next Steps
In this lesson, you learned the difference between functions and subs, and how to create each of these two procedures. You
have also learned how to call procedures and how to create procedures that have parameters.
In the next lesson, you will learn how to use the For...Next statement to repeat actions.
Next Lesson: Making Your Program Repeat Actions: Looping With the For...Next Loop
See Also
Tasks
Comparisons: Using Expressions to Compare Values
Concepts
Procedures in Visual Basic
Visual Basic Language Concepts

Making Your Program Repeat Actions: Looping With the


For...Next Loop
In this lesson, you will learn how to use the For...Next statement to repeat actions in your program, and to count how many
times these actions have been performed.
When you write a program, you frequently need to repeat actions. For example, suppose you are writing a method that
displays a series of numbers on screen. You will want to repeat the line of code that displays the numbers as many times as
necessary.
The For...Next loop allows you to specify a number, and then repeat code contained within that loop for the specified number
of times. The following example shows how a For...Next loop appears in code.
VB
Dim i As Integer = 0
For i = 1 To 10
DisplayNumber(i)
Next

The For...Next loop begins with a counter variable, i. This is a variable that the loop uses to count the number of times it has
executed. The next line (For i = 1 to 10) tells the program how many times to repeat the loop and the values i is going to
have.
When the code enters the For...Next loop, it starts with i containing the first value (in this case 1). The program then executes
the lines of code between the For line and the Next line, in this case calling the DisplayNumber method with a parameter of i
(in this case also 1).
When the line Next is reached, 1 is added to i and program execution jumps back to the For line again. This repeats until the
value of i is larger than the second number in the For line, in this case 10. When this occurs, the program continues with any
code after the Next line.
Try It!
To use the For...Next statement
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type ForNext and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag one TextBox control and one Button control onto the form.
5. Double-click the Button to open the Code Editor
6. In the Button1_Click event handler, type the following code:
VB
Dim i As Integer = 0
Dim NumberOfRepetitions As Integer = CInt(Textbox1.Text)
For i = 1 To NumberOfRepetitions
MsgBox("This line has been repeated " & i & " times")
Next

7. Press F5 to run the program.


8. In the text box, type a number and click the button.
A message box appears as many times as you indicated in the text box.
Next Steps
In this topic, you have learned how to use the For...Next loop to repeat code a specified number of times. At this point, you can
either go on to the next lesson in the series, Making Your Program Choose Between Two Possibilities: The If...Then Statement or
you can explore another kind of looping in Closer Look: Using Do...While and Do...Until to Repeat Until a Condition is Met.
See Also
Tasks
Making Your Computer Do Something: Writing Your First Procedure
Reference
For...Next Statement (Visual Basic)
Concepts
Decision Structures
Visual Basic Language Concepts

Closer Look: Using Do...While and Do...Until to Repeat Until a


Condition is Met
In this lesson, you will learn how to use the Do...While and Do...Until statements to repeat code based on certain conditions.
In the previous lesson, you learned how to use the For...Next statement to loop through a block of code a specified number of
times—but what if the number of times that the code needs to be repeated is different for certain conditions? The Do...While
and Do...Until statements allow you to repeat a block of code while a certain condition is True, or until a certain condition is
True.
For example, suppose you had a program to add a series of numbers, but you never wanted the sum of the numbers to be
more than 100. You could use the Do...While statement to perform the addition as follows:
VB
Dim sum As Integer = 0
Do While sum < 100
sum = sum + 10
Loop

In the above code, the Do While line evaluates the variable sum to see if it is less than 100: If it is, the next line of code is run; if
not, then it moves to the next line of code following Loop. The Loop keyword tells the code to go back to the DoWhile line and
evaluate the new value of sum.
Try It!
To use a Do...While statement
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type DoWhile and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag one TextBox control and one Button control onto the form.
5. Double-click the Button to open the Code Editor.
6. In the Button1_Click event handler, type the following code:
VB
Dim sum As Integer = 0
Dim counter As Integer = 0
Do While sum < 100
sum = sum + CInt(Textbox1.Text)
counter = counter + 1
Loop
MsgBox("The loop has run " & CStr(counter) & " times!")

7. Press F5 to run the program.


8. In the text box, type a number and click the button.
A message box appears displaying how many times the number was added to itself before reaching 100.
9. On the Debug menu, choose Stop Debugging to end the program. Keep this project open. We are about to add to it.
Do...Until Statement
The Do...While statement repeats a loop while a condition remains True, but sometimes you might want your code to repeat
itself until a condition becomes True. You can use the Do...Until statement as follows:
VB
Dim sum As Integer = 0
Do Until sum >= 100
sum = sum + 10
Loop

This code is similar to the code for the Do...While statement, except that this time the code is evaluating the sum variable to see
if it is equal to or greater than 100.
Try It!
To use a Do...Until statement
1. Add the following code beneath the MsgBox line.
VB
Dim sum2 As Integer = 0
Dim counter2 As Integer = 0
Do Until sum2 >= 100
sum2 = sum2 + CInt(Textbox1.Text)
counter2 = counter2 + 1
Loop
MsgBox("The loop has run " & CStr(counter2) & " times!")

2. Press F5 to run the program.


3. In the text box, type a number and click the button.
A second message box appears displaying how many times the number was added to itself before equaling 100 or
greater.
Next Steps
In this topic, you learned how to use the Do...While and Do...Until loops to repeat code conditionally. At this point, you can go
on to the next lesson, Making Your Program Choose Between Two Possibilities: The If...Then Statement.
See Also
Tasks
Making Your Program Repeat Actions: Looping With the For...Next Loop
Reference
Do...Loop Statement (Visual Basic)
Visual Basic Language Concepts

Making Your Program Choose Between Two Possibilities: The


If...Then Statement
In this lesson, you will learn to use the If...Then statement to run code based on conditions.
Programs need to do different things in response to different conditions. For example, you might want your program to check
what day of the week it is, and then do something different depending on the day. The If...Then statement allows you to
evaluate a condition and to then run different sections of code based on the results of that condition.
The following example demonstrates how the If...Then statement works.
VB
If My.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Monday Then
MsgBox("Today is Monday!")
End If

When this code is run, the condition (the part between If and Then) is evaluated. If the condition is true, the next line of code is
run and a message box is displayed; if it is false, the code skips to the End If line. In other words, the code states "If today is
Monday, then display the message."
Try It!
To use the If...Then statement
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type IfThen and then click OK.
A new Windows Forms project opens.
4. Double-click the form to open the Code Editor.
5. In the Form1_Load event handler, type the following code.
VB
If My.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Saturday Or _
My.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Sunday Then
MsgBox("Happy Weekend!")
End If

6. Press F5 to run your program.


If today is Saturday or Sunday, a message box appears telling you Happy Weekend! Otherwise, no message box appears.

7. On the Debug menu, choose Stop Debugging to end the program. Keep this project open. You will add to it in the next
procedure, "To use the Else clause".
You may have noticed in the above example that the If...Then statement used the Or operator to evaluate multiple conditions
("if it is Saturday Or if it is Sunday"). You can use the Or and And operators to evaluate as many conditions as you want in a
single If...Then statement.
The Else Clause
You have seen how to use the If...Then statement to run code if a condition is true—but what if you want to run one set of
code if a condition is true, and another if it is false? In this case, you can use the Else clause. The Else clause allows you to
specify a block of code that will be run if the condition is false. The following example demonstrates how the Else clause works.
VB
If My.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Friday Then
MsgBox("Today is Friday!")
Else
MsgBox("It isn't Friday yet!")
End If

In this example, the expression is evaluated; if it is true, then the next line of code is run, and the first message box is displayed.
If it is false, then the code skips to the Else clause, and the line following Else is run, displaying the second message box.
Try It!
To use the Else clause
1. Change the code in the If...Then statement to the following.
VB
If My.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Saturday Or _
My.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Sunday Then
MsgBox("Happy Weekend!")
Else
MsgBox("Happy Weekday! Don't work too hard!")
End If

2. Press F5 to run your program. Your program will now display a message box stating whether it is a weekend or a
weekday, with appropriate content.
Note
You can change the day of the week by double-clicking the time on the Windows taskbar, if you want to test the executi
on of both code blocks. (The taskbar is the bar that contains the Windows Start button; by default, it is at the bottom of
the desktop, and the time appears in the right corner.)

Next Steps
In this lesson, you learned how to use the If...Then statement together with the Else clause to make your program selectively
run blocks of code based on conditions at run time. For your next lesson, you can choose to either explore how to select code
to run by reading Closer Look: Using Select Case to Decide Between Multiple Choices, or, you can continue with the next
lesson, What To Do When Something Goes Wrong: Handling Errors.
See Also
Tasks
Making Your Program Repeat Actions: Looping With the For...Next Loop
Comparisons: Using Expressions to Compare Values
Reference
If...Then...Else Statement (Visual Basic)
Visual Basic Language Concepts

Closer Look: Using Select Case to Decide Between Multiple


Choices
In this lesson, you will learn to use the Select Case statement to run code based on multiple conditions.
In the previous lesson, you learned how to use If...Then statements to run different blocks of code for different conditions.
While it's possible to evaluate more than two conditions in an If...Then statement by using the ElseIf keyword, the Select
Case statement provides a much better way to evaluate multiple conditions.
The Select Case statement allows you to use as many conditions (or cases) as you need, making it convenient to write code for
situations in which there are many choices. For example, suppose your program used a String variable to store a color choice
and you needed to get the color value. The code for the Select Case statement might look like the following:
VB
Select Case Color
Case "red"
MsgBox("You selected red")
Case "blue"
MsgBox("You selected blue")
Case "green"
MsgBox("You selected green")
End Select

When this code is run, the Select Case line determines the value (Color) of the expression. Assume that Color is a String
variable and that this variable is a parameter for a method that contains the Select Case statement. The value of Color is then
compared to the value for first Case statement. If the value matches, the next line of code is run, and then the code skips to the
End Select line; if the value doesn't match, then the next Case line is evaluated.
The Case statement can take many different forms—in the example above, it is a String. However, it can be any data type or
expression.
You can evaluate a range of numbers by using the To keyword, as follows:
VB
Case 1 To 10

In this example, any number between 1 and 10 would result in a match.


You can also evaluate multiple values in a single Case statement by separating them with commas, as follows:
VB
Case "red", "white", "blue"

In this example, any of the three values would result in a match.


You can also use comparison operators and the Is keyword to evaluate values, as follows.
VB
Case Is > 9

In this example, any number greater than 9 would result in a match.


Case Else
The above example works when you know all possible conditions, but what happens if there is a condition you didn't account
for? For example, if the value of Color was yellow, the code would simply evaluate the three cases without finding a match,
and no message box would display.
The Case Else statement can be used to run code when no match is found, as in the following example.
VB
Select Case Color
Case "red"
MsgBox("You selected red")
Case "blue"
MsgBox("You selected blue")
Case "green"
MsgBox("You selected green")
Case Else
MsgBox("Please choose red, blue, or green")
End Select

In the above code, if the value of Color is yellow, the code compares it with the first three Case lines without finding a match.
When the Case Else line is reached, the next line of code is run before moving to End Select.
To use the Select Case statement
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type SelectCase and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag one TextBox control and one Button control onto the form.
5. Double-click the button to open the Code Editor.
6. In the Button1_Click event handler, type the following code.
VB
Dim Number As Integer = CInt(Textbox1.Text)
Select Case Number
Case 1
MsgBox("Less than 2")
Case 2 To 5
MsgBox("Between 2 and 5")
Case 6, 7, 8
MsgBox("Between 6 and 8")
Case 9 To 10
MsgBox("Greater than 8")
Case Else
MsgBox("Not between 1 and 10")
End Select

7. Press F5 to run the program.


8. In the text box, type a number and click the button.
A message box appears displaying the message for the Case statement matching the number that you entered.
Next Steps
In this topic, you learned how to use the Select Case statement to choose between multiple conditions. At this point, you can
go on to the next lesson, "What to Do When Something Goes Wrong: Handling Errors."
Next Lesson: What To Do When Something Goes Wrong: Handling Errors
See Also
Tasks
What To Do When Something Goes Wrong: Handling Errors
Making Your Program Choose Between Two Possibilities: The If...Then Statement
Reference
Select...Case Statement (Visual Basic)
Visual Basic Language Concepts

What To Do When Something Goes Wrong: Handling Errors


In this lesson, you will learn how to create basic error-handling code for your programs.
Even the best designed programs sometimes encounter errors. Some errors are defects in your code that can be found and
corrected. Other errors are a natural consequence of the program; for example, your program might attempt to open a file that
is already in use. In cases like this, errors can be predicted but not prevented. As a programmer, it is your job to predict these
errors and help your program deal with them.
Run-Time Errors
An error that occurs while a program is running is called a run-time error. A run-time error occurs when a program tries to do
something it wasn't designed to do. For example, if your program attempts to perform an illegal operation, such as converting
a non-numeric string to a numeric value, a run-time error occurs.
When a run-time error occurs, the program issues an exception, which deals with errors by looking for code within the
program to handle the error. If no such code is found, the program stops and has to be restarted. Because this can lead to the
loss of data, it is wise to create error-handling code wherever you anticipate errors occurring.
The Try...Catch...Finally block.
You can use the Try...Catch...Finally block to handle run-time errors in your code. You can Try a segment of code—if an
exception is issued by that code, it jumps to the Catch block, and then the code in the Catch block is executed. After that code
has finished, any code in the Finally block is executed. The entire Try...Catch...Finally block is closed by an End Try statement.
The following example illustrates how each block is used.
VB
Try
' Code here attempts to do something.
Catch
' If an error occurs, code here will be run.
Finally
' Code in this block will always be run.
End Try

First, the code in the Try block is executed. If it runs without error, the program skips the Catch block and runs the code in the
Finally block. If an error does occur in the Try block, execution immediately jumps to the Catch block, and the code there is
run; then the code in the Finally block is run.
Try It!
To use the Try...Catch block
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type TryCatch and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag one TextBox control and one Button control onto the form.
5. Double-click the Button to open the Code Editor.
6. In the Button1_Click event handler, type the following code:
VB
Try
Dim aNumber As Double = CDbl(Textbox1.Text)
MsgBox("You entered the number " & aNumber)
Catch
MsgBox("Please enter a number.")
Finally
MsgBox("Why not try it again?")
End Try

7. Press F5 to run the program.


8. In the text box, type a numeric value and click the button. A message box that displays the number you entered, followed
by an invitation to try again, is displayed.
9. Next, type a non-numeric value in the text box, such as a word, and click the button. This time, when the program
attempts to convert the text in the text box to a number, it cannot, and an error occurs. Instead of finishing the code in the
Try block, the Catch block is executed and you receive a message box asking you to enter a number. The Finally block
then executes, inviting you to try again.
Next Steps
In this lesson, you learned how to use Try...Catch...Finally blocks to create a basic error-handling structure. This lesson ends
the introduction to the Visual Basic language. In the next series of lessons, you will learn how to create the user interface for
your programs.
Next Lesson: Creating the Visual Look of Your Program: Introduction to Windows Forms
See Also
Tasks
Making Your Program Choose Between Two Possibilities: The If...Then Statement
Know Your Bugs: Three Kinds of Programming Errors
Reference
Try...Catch...Finally Statement (Visual Basic)
Other Resources
Structured Exception Handling in Visual Basic
Visual Basic Language Concepts

Creating the Visual Look of Your Program: Introduction to


Windows Forms
The user interface is the part of your program that users see when they run the program. A user interface usually consists of a
main window or form, and several controls, such as buttons, fields for entering text, and so forth. Visual Basic programs that
run on your computer are known as Windows Forms applications, and the user interface is created using Windows Forms
controls.
The lessons in this section will show you how to create a user interface using some of the most common Windows Forms
controls.
In This Section
Communicating with Your Program's User: The User Interface
Interacting with the User: Using Buttons
Displaying and Receiving Text: Using Labels and Text Boxes
Making Your Program React to the User: Creating an Event Handler
Getting User Choices: Using Check Boxes and Radio Buttons
Picture This: Displaying Images
Giving Users Choices: Creating Menus at Design Time
On Time: Using Timers to Perform Regular Actions
Related Sections
Closer Look: Sharing an Event Handler
Closer Look: Using Multiple Groups of Radio Buttons
Closer Look: More About Menus
Visual Basic Guided Tour
What Went Wrong? Finding and Fixing Errors through Debugging
Introduction to the Visual Basic Programming Language
Visual Basic Language Concepts

Communicating with Your Program's User: The User Interface


In this lesson, you will learn what a user interface (UI) is, what controls are, and how to add controls to a UI.
In the early days of personal computers, users interacted with programs primarily through a command line. A program would
start and then pause to receive user input before continuing. Most of the programs you use today, however, run in one or
more windows that allow the user to communicate—or interface—with the program by typing, clicking buttons, choosing
items from preset menus, and so forth. In this and subsequent lessons, you will learn how build your own Windows-based UIs.
Using Forms
Forms are the basic building blocks for your UI. Each form in your program represents a window that appears to users. When
working in the Visual Basic IDE (integrated development environment), a form is the designer that you use to design your UI,
much the same as you would use Windows Paint to draw a picture.
Controls are used in the designer to create the look of your UI. A control is an object that has a predefined appearance and
behavior. For example, a Button control looks and behaves like a push button—when a user clicks it, its appearance changes to
show that it has been pressed.
Each control in Visual Basic has its own purpose. For example, a TextBox control is used for entering text, while a PictureBox
control is used for displaying pictures. There are more than fifty different controls included in Visual Basic; you can also create
your own controls known as user controls. You will learn more about each kind of control in later lessons.
When designing your UI, you drag controls from the Toolbox, drop them onto a form, and then position them and resize them
to create the desired look. You can further change the appearance by setting properties of forms and controls in the
Properties window. For example, forms and most controls have a BackColor property which is used to set their background
color.
Properties are also used to define the behavior of a form or control. For example, the ShowInTaskbar property of a form
determines if the form will appear in the Windows taskbar when the program is running. Using properties, you can customize
the look and behavior of your UI.
Try It!
To change the properties of a form
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type FirstForm, and then click OK.
A new Windows Forms project is created. A new form appears in the main window, and its properties are visible in the
Properties window in the lower-right corner of the Visual Basic IDE.
4. Click the form once to select it.
5. In the Properties window, change the Text property to read "My First Form" and then press ENTER.
The text at the top of the form changes after you enter the new value.
6. In the Properties window, change the BackColor property to a different color by selecting a color from the drop-down
list.
Notice that the BackColor property is changed through a special interface. This interface allows you to see the color
before selecting it, and allows you to choose between colors currently used by your system, standard Web colors, or a
more custom color selection. You can also just type the name of the color (for example, Red) into the box in the
Properties window.
Experiment by changing other properties of the form. When you are ready, continue with the next procedure.
Adding controls to your form
In this procedure, you will add controls to your form by selecting the control in the Toolbox window, usually found on the left-
hand side of the Visual Basic IDE, and then dragging the control onto your form. You will then manipulate the controls'
properties.
To add controls to your form
1. From the Toolbox, drag a Button control, then a TextBox control, then a Label control, and finally a CheckBox control
onto the form.
2. Select the Button control and drag it around on the form to change its location.
Notice how guidelines appear when you drag it near the other controls. These guidelines can help you to position the
controls precisely.
3. Repeat the process with the other controls until the UI looks the way you want it.
4. Select the Button control, and then click and drag the white square in its lower-right corner to change its size.
5. Spend some time experimenting with control properties. Click each control on the form to select it, and then change
some of its properties in the Properties window. Properties you might try changing include Font, BackColor,
ForeColor, and Text.
6. Press F5 to run your program. A window appears with the controls you just added. Notice that you can click the button,
select and clear the check box, and type in the text box.
Next Steps
In this lesson, you learned how to create a form and add controls to it. You also learned how to change properties of forms and
controls in the Properties window. In the next few lessons, we will take a more in-depth look at some of the controls.
Next Lesson: Interacting with the User: Using Buttons
See Also
Concepts
Closer Look: Understanding Properties, Methods, and Events
Other Resources
Creating the Visual Look of Your Program: Introduction to Windows Forms
Visual Basic Language Concepts

Interacting with the User: Using Buttons


In this lesson, you will learn how to add a Button to a form, how to change the appearance of the button, and how to write code
that runs when it is clicked.
The easiest way for users to interact with your program is through buttons. For example, many programs have Exit buttons .
As you saw in the previous lesson, the Button control in Visual Basic looks and behaves like a push button. The Button control
also has predefined events that can be used to initiate actions such as ending a program.
Using Buttons
Buttons are, in general, rectangular controls with a raised appearance on the form. There are many properties, however, that
can be set to change their appearance. The most obvious is the Text property, which determines the text displayed, and this text
is displayed in the font or typeface determined by the Font property. The BackColor property determines the button's color,
and the ForeColor property determines the text's color.
When the user clicks a button at run time, the Button raises the Click event. When an event occurs, controls run code in
response to those events. You can write code that is run by creating an event handler.
An event handler is a method that executes when an event happens. When a user clicks a button, the button's Click event has
an event handler. It is easier than it sounds, and you'll learn how to write an event handler in the example below. Events and
event handlers will be covered in greater detail in Making Your Program React to the User: Creating an Event Handler.
Try It!
To use buttons
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type ButtonExample, and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag a Button onto the form.
5. In the Properties window, change the Text property to read: What time is it? and then press ENTER.

Notice that the text doesn't fit on the button.


6. In the Properties window, select the AutoSize property and set it to True.
The button resizes itself to fit the text.
7. In the form, double-click the button to open the Code Editor.
The Code Editor opens in the middle of a method called Button1_Click. This is the Button1.Click event handler. The
code you write here will execute when the button is clicked.
8. In the Button1_Click event handler, type the following line of code.
VB
MsgBox("The current time is " & Now.ToShortTimeString)

9. Press F5 to run your program.


The program begins and the form appears. When you click the Button, a message box displaying the current time
appears.
Next Steps
In this lesson, you learned how to add a button to a form and how to add code that will execute when the user clicks the button
with the mouse. In the next lesson, you will learn how to work with the controls designed for displaying and receiving text:
Label and TextBox.
Next Lesson: Displaying and Receiving Text: Using Labels and Text Boxes
See Also
Tasks
Communicating with Your Program's User: The User Interface
Reference
Button Control Overview (Windows Forms)
Concepts
Closer Look: Understanding Properties, Methods, and Events
Other Resources
Creating the Visual Look of Your Program: Introduction to Windows Forms
Visual Basic Language Concepts

Displaying and Receiving Text: Using Labels and Text Boxes


In this topic you will learn to use the Label and TextBox controls to display text and accept text input from the user.
One of the easiest ways to convey information to and receive it from users is through text. You can display text about a
program's functionality, and you can receive data as text from the user and use it in your program. Visual Basic provides two
controls that are designed for displaying and receiving text. They are the Label and TextBox controls.
Displaying Text with the Label Control
The Label control is the primary control for displaying text. It appears on the form as text surrounded by a rectangular-shaped
area. The color of this area is usually the same as the color of the form, so it appears as though it is just text on the form.
Because a Label is primarily meant to display text, the most important properties for a Label control are the properties that
control its appearance. The Text property contains the text that is displayed in the Label control. The Font property determines
the display font for the text in the Text property. The ForeColor property determines the color of the text itself, and the
BackColor property determines the color of the area surrounding the text.
Receiving Text with the TextBox Control
When you need to both display and receive text, the TextBox control is designed to handle the job. In addition to being able to
display text, the TextBox control allows users to type text into the TextBox at run time, and the program can retrieve that text.
As with the Label control, the properties that are most important for the TextBox control are those related to appearance. A
significant property is the Text property, which represents the text in the TextBox control. When a user types in the TextBox
control, the Text property is updated to reflect the changes. Thus, the text showing in the TextBox control always reflects the
value of the Text property.
There are also properties that affect the TextBox control's behavior. The Multiline property determines if the TextBox control
allows multiple lines. If this property is set to False, then the TextBox control will always be exactly one line tall, and cannot be
enlarged vertically. If set to True, the TextBox control allows multiple lines and can be as tall as you like.
Try It!
To create a user interface with Label and Textbox controls
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type TextBoxExample, and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag a TextBox, Label, and Button control onto the form.
5. Select the Label control and drag it above the TextBox control
6. In the Properties window, change the Text property of the Label control to the following code.
Enter your name and click the button.

Now that you have created a basic user interface, you will need to add a little bit of code to your program, and then it will be
ready to test!
To add code and test your program
1. Double-click the Button control to open the Code Editor.
The Code Editor opens the Button1_Click event handler.
2. Add the following line of code to the Button1_Click event handler.
VB
MsgBox("Your Name is " & Textbox1.Text)
3. Press F5 to run your program.
4. When the form appears, type your name in the TextBox control and click the button. A message box appears, displaying
the text in the TextBox control. Change the text and click the button again. Each time you click the button, the updated
text is displayed.
Next Steps
In this topic, you learned about the Label and TextBox controls, and how they can be used to display and receive text. In the
next topic, you will learn how to create methods that handle control events. Though you've already learned how to create some
basic event handlers, such as the Button_Click event handler, you will learn how to create methods to handle some of the
other events that happen to controls.
Next Lesson: Making Your Program React to the User: Creating an Event Handler
See Also
Tasks
Interacting with the User: Using Buttons
Reference
Label Control Overview (Windows Forms)
TextBox Control Overview (Windows Forms)
Visual Basic Language Concepts

Making Your Program React to the User: Creating an Event


Handler
In this lesson, you will learn how to create an event handler.
As you have seen in previous lessons, controls have properties, methods, and events and are used to create the user interface.
Events are interesting things that can happen to a control. For example, a control can be clicked, text can be typed into it, the
mouse pointer can move over it, and so forth.
When something interesting occurs, the control raises an event, meaning it sends a signal to the program to let it know that
something has happened. The program then checks if it has any methods to handle that event. Such methods are called event
handlers. An example is a method that runs when a button is clicked, such as the method you created in
Interacting with the User: Using Buttons.
You can create event handlers for a variety of control events. In this lesson, you will create event handlers to handle a button's
MouseEnter and MouseLeave events—the events that occur when a mouse moves over a control.
Try It!
To handle the MouseEnter event
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type EventHandler, and click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag a Button control onto the form.
5. In the Properties windows, set the AutoSize property to True.
6. On the View menu, choose Code to open the Code Editor.
Just above the Code Editor, note the two drop-down boxes. The box on the left contains a list of all the controls on the
form, as well as Form1, (General), and (Form1 Events). The box on the right lists each of the events available for the
item listed in the box on the left.
7. In the box on the left, choose Button1.
8. In the box on the right, choose MouseEnter.
A new event handler called Button1_MouseEnter appears in the Code Editor.
9. In the Button1_MouseEnter event handler, type the following code.
VB
Button1.Text = "The Mouse has entered"

10. Press F5 to run your application. Pass the mouse pointer over the button. Note that when the mouse pointer passes over
Button1, the text of the button changes.
Adding another Event Handler
You might have noticed in the previous example that though the text of Button1 changes when the mouse pointer passes over
it, the text does not change back when the mouse pointer leaves. If you want the text to change when the mouse is no longer
over the button, you must handle the MouseLeave event in addition to the MouseEnter event.
To handle the MouseLeave event
1. In the Code Editor, make certain that Button1 is selected in the left-hand drop-down box, and then select MouseLeave
from the right-hand drop-down box.
A new event handler called Button1_MouseLeave appears in the Code Editor.
2. In the Button1_MouseLeave event handler, type the following code.
VB
Button1.Text = "The mouse has left"

3. Press F5 to run your application.


Now when the mouse pointer passes over the button, the text changes to The mouse has entered, but when the mouse
is no longer over the button, the text changes to The mouse has left.
Next Steps
In this lesson, you learned how to create an event handler using the Code Editor. At this point, you can either go to the next
lesson in the sequence, Getting User Choices: Using Check Boxes and Radio Buttons or examine event handlers with
Closer Look: Sharing an Event Handler. If you choose the second option, you should save your EventHandler project for use in
that lesson.
See Also
Tasks
Displaying and Receiving Text: Using Labels and Text Boxes
Reference
Label Control Overview (Windows Forms)
TextBox Control Overview (Windows Forms)
Visual Basic Language Concepts

Closer Look: Sharing an Event Handler


In this lesson, you will learn how to create a shared event handler that handles events for more than one control.
In the previous lesson, Making Your Program React to the User: Creating an Event Handler, you learned how to write code in
response to the MouseEnter and MouseLeave events for a Button control. What happens, though, if you have two or more
Button controls and you want to display the same message for all of them? You could write code in the event handlers for
each control, but fortunately there is an easier way.
If you look closely at the event handler methods for the MouseEnter event, you will notice that the Method declaration
(Private Sub Button1_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles
Button1.MouseEnter) contains a Handles clause (Handles Button1.MouseEnter). Not surprisingly, the Handles keyword tells
the event handler which events it should handle.
To share an event handler between multiple controls, you simply need to add the additional control names and the name of
the event you want to handle. The event handler is then notified when the event occurs for any one of those controls. For
example, if you had two Button controls and you wanted to use the same event handler for both, the Handles clause would
look like the following.
Handles Button1.MouseEnter, Button2.MouseEnter.

You now have a single method that handles the MouseEnter event for both controls, but how does the event handler knows
which control raised the event? If you look again at the Method declaration, you will notice the clause ByVal sender As
Object—the Sender keyword tells the event handler which object (in this case which control) raised the event.

Try It!
To share an event handler
1. Open the EventHandler project that you created in the previous lesson. If you didn't save it, you will first need to go back
to the previous lesson, Making Your Program React to the User: Creating an Event Handler, and complete the procedures
in that lesson.
2. In Solution Explorer, select Form1.vb, and then on the View menu choose Designer.
3. From the Toolbox, drag another Button control onto the form.
4. In the Properties window, set the AutoSize property to True.
5. On the View menu, choose Code to open the Code Editor.
6. In the Button1_MouseEnter method declaration (Private Sub Button1_MouseEnter(ByVal sender As Object, ByVal
e As System.EventArgs) Handles Button1.MouseEnter), change the Handles clause to read Handles
Button1.MouseEnter, Button2.MouseEnter.

7. In the body of the event declaration, replace the code with the following.
VB
If sender.Equals(Button1) Then
Button1.Text = "The mouse has entered Button1"
Else
Button2.Text = "The mouse has entered Button2"
End If

This code checks to see if the sender was Button1—if so, then Button1's Text property is updated; if not, then
Button2's Text property is updated.
8. In the Button1_MouseLeave method declaration, change the Handles clause to read as follows.
Handles Button1.MouseLeave, Button2.MouseLeave.

9. In the body of the event declaration, replace the code with the following.
VB
sender.Text = "The mouse has left"

In this case, the code sets the Text property of the sender (either Button1 or Button2) to the same string.
10. Press F5 to run your application.
Now when the mouse pointer passes over the button, the text changes to The mouse has entered, along with the name
of the button, and when the mouse is no longer over the button, the text changes back to The mouse has left.
Try adding more controls to the form and modifying the Handles clauses to include them—they don't even have to be
the same kind of controls!
Next Steps
In this lesson, you learned how to share a single event handler between multiple controls. In the next lesson, you will learn how
to use two new kinds of controls, the CheckBox and RadioButton controls, to present choices to users.
Next Lesson: Getting User Choices: Using Check Boxes and Radio Buttons
See Also
Tasks
Making Your Program React to the User: Creating an Event Handler
Visual Basic Language Concepts

Getting User Choices: Using Check Boxes and Radio Buttons


In this lesson, you will learn how to use check boxes and radio buttons to present and retrieve user choices.
When you create the user interface for your program, you often need a way to present choices. For example, suppose you
wrote an application to take orders for a pizza restaurant—you might want to allow users to select any or all of a variety of
toppings. The CheckBox control provides a visual representation that makes this option easy to create.
The CheckBox control consists of a text label and a box that the user can select. When the user clicks the box, a check mark
appears in the box. If the box is clicked again, the check mark is removed. The status of the check box can be retrieved using the
CheckBox.Checked property. If the box displays a check mark, the property returns True. If no check is displayed, the
property returns False.
Try It!
To use check boxes
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type UserChoices and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag a Button and three CheckBox controls onto the form.
5. In the Properties Window, change the Text property of CheckBox1, CheckBox2, and CheckBox3 to read Cheese,
Peppers, and Mushrooms, respectively.

6. In the Properties window, change the Text property of Button1 to read Order Pizza.

7. In the form, double-click the button; this opens the Button1_Click event handler in the Code Editor.
8. Add the following code to the Button1_Click event handler:
VB
Dim toppings As String = ""
If CheckBox1.Checked = True Then
toppings &= "Cheese "
End If
If CheckBox2.Checked = True Then
toppings &= "Peppers "
End If
If CheckBox3.Checked = True Then
toppings &= "Mushrooms"
End If
If toppings <> "" Then
MsgBox("Your pizza has the following toppings: " & toppings)
End If

9. Press F5 to run your program. When the form appears, select some toppings and click the button. A message box
indicating your choice of pizza toppings is displayed.
Using Radio Buttons to Make Exclusive Choices
You just learned how to allow a user to choose any or all of several options. But what if you want the user to choose only one
of several options? In this case, you can use the RadioButton control.
Unlike check boxes, radio buttons (also known as option buttons) always work as part of a group. Selecting one radio button
immediately clears all the other radio buttons in the group. Defining a group of radio buttons tells the user, "Here is a set of
choices from which you can choose one and only one."
You can use groups of RadioButton controls to allow users to choose between exclusive options. For example, you might
allow users to choose either regular sauce or spicy sauce on their pizza, but not both. Like a CheckBox control, you can get
information about the status of the RadioButton control from the RadioButton.Checked property.
To use radio buttons
1. From the Toolbox, drag two RadioButton controls onto the form.
2. In the Properties window, set the Text property for RadioButton1 to Regular Sauce.
3. Set the Checked property for RadioButton1 to True.
Tip
When defining a group of choices, you should always set one choice to be the default.

4. In the Properties window, set the Text property for RadioButton2 to Spicy Sauce.

5. In the form, double-click the button to open the Button1_Click event handler in the Code Editor.
6. In the Button1_Click event handler, add the following code:
VB
If RadioButton1.Checked = True Then
MsgBox("You chose regular sauce")
Else
MsgBox("You chose spicy sauce")
End If

7. Press F5 to run your program. Choose one of the radio buttons and then click the Order Pizza button. A message box
noting your choice is displayed.
Try to select both radio buttons at the same time. Notice that the radio buttons are exclusive. After you click one, the
other is cleared automatically.
Next Steps
In this lesson, you learned how to use the CheckBox and RadioButton controls to give users choices in the user interface. At
this point, you can either go to the next lesson, Picture This: Displaying Images, or learn how to create multiple groups of radio
buttons with Closer Look: Using Multiple Groups of Radio Buttons. If you choose the second option, you should save your
UserChoices project for use in the next lesson.
See Also
Reference
CheckBox Control Overview (Windows Forms)
RadioButton Control Overview (Windows Forms)
Visual Basic Language Concepts

Closer Look: Using Multiple Groups of Radio Buttons


In this lesson, you will learn how to create multiple groups of mutually exclusive radio buttons on a single form.
In the previous lesson, you learned how to create a group of radio buttons to present a set of mutually exclusive choices to the
user. What happens, though, if you present two or more sets of choices? You will find that all RadioButton controls on a form
are treated as a single group, allowing only one radio button to be selected.
Fortunately, Visual Basic has several controls known aptly as container controls that can contain other controls. By placing a
container control on the form and then placing RadioButton controls inside the container control, you can have multiple
groups of radio buttons on the same form.
The most common container controls are the GroupBox control and the Panel control. The main difference between the two is
that the GroupBox control has a visible border around it, and the Panel does not. When using a container control to group
radio buttons, the GroupBox control is the best choice, because the border provides a visual cue that the group of choices
belongs together.
Try It!
To use a GroupBox as a container
1. Open the UserChoices project that you created in the previous lesson. If you didn't save it, you will need to first go back
to the previous lesson, Getting User Choices: Using Check Boxes and Radio Buttons, and complete the procedures.
2. In Solution Explorer, select Form1.vb, and then on the View menu choose Designer.
3. From the Toolbox, drag a GroupBox control onto the form.
4. In the Properties window, change the Text property for the GroupBox control to read Select a crust.

5. With the GroupBox control still selected, drag two RadioButton controls from the Toolbox, and drop them on top of
the GroupBox control.
6. In the Properties window, change the Text properties of RadioButton3 and RadioButton4 to Thin crust and Thick
crust, respectively.

7. In the form, double-click the Order Pizza button to open the Button1_Click event handler in the Code Editor.
8. In the Button1_Click event handler, add the following code.
VB
If RadioButton3.Checked = True Then
MsgBox("You chose a thin crust")
Else
MsgBox("You chose a thick crust")
End If

9. Press F5 to run your program. Choose one of the radio buttons, and then click the Order Pizza button. A message box
noting your choice is displayed. Notice that your choice of sauce is preserved.
Next Steps
In this lesson, you learned how to use a container control to group RadioButton controls. In the next lesson, you will learn
how to display pictures.
Next Lesson: Picture This: Displaying Images
See Also
Tasks
Getting User Choices: Using Check Boxes and Radio Buttons
How to: Group Controls with the Windows Forms GroupBox Control
Reference
Panel Control Overview (Windows Forms)
Visual Basic Language Concepts

Picture This: Displaying Images


In this lesson, you will learn how to use a PictureBox control to display images and also how to display a picture as a
background image on a form.
It is said that a picture is worth a thousand words, and, in fact, many programs use pictures to convey information. There are
several ways to display pictures in Visual Basic—the most common way is to use a PictureBox control.
The PictureBox control acts as a container for pictures; you choose the picture to be displayed by setting the Image property.
The Image property can be set in the Properties window, or you can write code to tell the program which picture to display.
Some other useful properties for the PictureBox control are the AutoSize property, which determines if the PictureBox will
stretch to fit the picture, and the SizeMode property, which can be used to stretch, center, or zoom the image within the
PictureBox control.
Before you add a picture to a PictureBox control, you will typically add the picture file to your project as a resource. Once you
add a resource to your project, you can reuse it as many times as you want—for example, you might want to display the same
picture in several places.
Try It!
To add a picture as a resource
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type Pictures and then click OK.
A new Windows Forms project opens.
4. In the Solution Explorer window, double-click the My Project node to open the Project Designer.
5. In the Project Designer, click the Resources tab.
6. Click Add Resource, and then choose Add Existing File from the drop-down list.
The Add existing file to resources dialog box opens. If you don't see any picture files, browse to a folder that does
contain pictures.
7. Select an image file (a file with a .bmp, .gif, or .jpg file extension), and then click Open. For this example, it is best to pick a
small picture.
The picture is added to your project and will appear in the Resource Manager window.
8. Repeat the previous two steps to add a second picture to your project.
9. On the File menu, choose Close. If asked to save changes, choose Yes.
To display pictures using a PictureBox control
1. In Solution Explorer, select Form1.vb, and then on the View menu, choose Designer.
2. From the Toolbox, drag a PictureBox control onto the form.
3. In the Properties window, click the … button next to the Image property to open the Select Resource dialog box.
4. From the Entry list, choose one of the pictures that you added, and then click OK.
5. Select the SizeMode property, and set it to AutoSize.
Notice how the PictureBox control automatically resizes to fit the picture.
6. In the form, double-click the PictureBox control to open the PictureBox1_Click event handler in the Code Editor.
7. Add the following code to the PictureBox1_Click event handler.
Note
You will need to replace "MyPictureName2" with the actual name of the second picture that you added earlier.

VB
PictureBox1.Image = My.Resources.MyPictureName2

8. Press F5 to run your program. When the form appears, click the picture to make the second picture appear.
Displaying a Background Image on a Form
In addition to displaying a picture in a PictureBox control, you can also display a picture as the background for your form. The
BackgroundImage property of a form is used to display a picture that will appear behind any other controls on the form, much
the same as wallpaper on the Windows desktop.
Just as Windows allows you to choose whether wallpaper is centered, tiled, or stretched to fill the screen, the
BackgroundImageLayout property can be used to do the same for a form.
Tip
Many of the other controls, such as the Panel, GroupBox, and even the Button control also have a BackgroundImage proper
ty. Try them and see!

Try It!
To display a background image on a form
1. In Solution Explorer, select Form1.vb, and then on the View menu, choose Designer.
2. Select the form by clicking on it anywhere outside of the PictureBox.
3. In the Properties window, click the … button next to the BackgroundImage property to open the Select Resource
dialog box.
4. From the Entry list, choose one of the pictures that you added earlier, and then click OK.
Notice that the picture is displayed on the form behind the PictureBox and is tiled by default.
Note
If the picture in the PictureBox control is too large, you may not be able to see the background picture. In this case, sel
ect the PictureBox control, and drag it to the bottom of the form to get it out of the way.

5. Select the BackgroundImageLayout property, and set it to Stretch.


Notice how the picture stretches to fill the entire form.
6. Double-click the form to open the Code Editor.
7. Make certain that Form1 Events is selected in the left-hand drop-down box, and then choose Click from the right-hand
drop-down box.
8. Add the following code to the Form1_Click event handler
VB
If Me.BackgroundImageLayout = ImageLayout.Stretch Then
Me.BackgroundImageLayout = ImageLayout.Center
Else
Me.BackgroundImageLayout = ImageLayout.Stretch
End If

9. Press F5 to run your program. When the form appears, click it to change the layout.
Next Steps
In this lesson, you learned how to use the PictureBox control to display images, and also how to use the BackgroundImage
property of a form. In the next lesson, you will learn how to create menus to present choices to users.
Next Lesson: Giving Users Choices: Creating Menus at Design Time
See Also
Tasks
Getting User Choices: Using Check Boxes and Radio Buttons
How to: Set the Background of a Windows Forms Panel
Reference
PictureBox Control Overview (Windows Forms)
Visual Basic Language Concepts

Giving Users Choices: Creating Menus at Design Time


In this lesson, you will learn how to create menus and write code that executes when menu items are chosen.
Menus are an easy and familiar way for users to make choices regarding your program. Common uses for menus include
exposing program options, adding shortcuts for common tasks such as cut and paste, or loading and saving files.
Visual Basic makes it easy to implement menus. You can use the MenuStrip control to create menus graphically. When
dragged onto a form, the MenuStrip control appears as a box containing the words "Type Here," located in the upper part of
the form. You can click the box and type inside it to create the menu titles.
When the title for one menu item is set, additional menu items can be created below and to the right of the first, allowing you
to extend the menu with as many additional items or sub-items as you want. When the look of your menu is complete, you can
create event handlers to handle the Click events for each item.
Try It!
To add a menu
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type Menus and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag a MenuStrip control onto the form.
Regardless of where you drop it, the MenuStrip control attaches itself to the uppermost part of the form.
You may also have noticed that there is a MenuStrip1 icon added in a gray area below the form—this area is called the
component tray. If you click outside of the MenuStrip control, it will disappear; you can bring it back by clicking on the
MenuStrip1 icon.
5. In the form, click the MenuStrip control, type File, and then press Enter.
New boxes for additional menu entries appear below and to the right of the first menu item. These are spaces for
additional menu items. You can continue to add menu items in either direction until your menu is complete.
6. In the box beneath the first box, type Exit, and then press Enter.
7. Double-click the Exit menu to open the Code Editor.
8. In the ExitToolStripMenuItem_Click event handler, type the following code.
VB
Application.Exit()

9. Press F5 to run your program. Using the mouse, click the File menu, and then choose Exit. Your application closes.
In this lesson, you learned how to use the MenuStrip control to design menus. At this point, you can continue to the next
lesson about timers, or you can explore more advanced ways to use menus in Closer Look: More About Menus, and then
proceed to the timers lesson.
Next Lesson: On Time: Using Timers to Perform Regular Actions
See Also
Tasks
Picture This: Displaying Images
Visual Basic Language Concepts

Closer Look: More About Menus


In this lesson, you will learn how to enable or disable menus at run time, and also how to create pop-up menus.
In the previous lesson, you learned how to use the MenuStrip control to create menus that allow users to make choices
regarding your program. In some cases, however, choices may only be available at certain times. For example, a Copy menu
command would only be available when there is something that can be copied.
Most programs disable, rather than hide, menu commands when they aren't available. When a menu item is disabled, the color
of the menu text is changed to gray, and clicking on the menu item does nothing. When using a MenuStrip control, you can
disable and enable menu items using the Enabled property of the MenuItem.
Try It!
To disable or enable menu items
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type Menus2, and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag a MenuStrip control and a TextBox control onto the form.
5. In the form, click the MenuStrip control and type Edit, and then press ENTER.
6. In the box beneath the first box, type Copy, and then press ENTER.
7. In the Properties window, set the Enabled property of the CopyToolStripMenuItem to False.
8. Double-click the TextBox control to open the Code Editor.
9. In the TextBox1_TextChanged event handler, type the following code.
VB
If Textbox1.Text <> "" Then
CopyToolStripMenuItem.Enabled = True
Else
CopyToolStripMenuItem.Enabled = False
End If

10. Press F5 to run your program. Click the Edit menu—the Copy menu item is disabled. Type something into the TextBox
control, and then click the Edit menu again—the Copy menu item is now enabled.
Creating Pop-up Menus
Many programs use pop-up menus, also known as context menus, to provide easy access to commonly used commands. You
access a context menu by right-clicking a form or control at run time. You can create your own context menus in Visual Basic
using a ContextMenuStrip control.
As with the MenuStrip control, when you drag a ContextMenuStrip control onto a form, the ContextMenuStrip control
appears as a box in the upper part of the form with the words "Type Here" inside, and an icon is added to the component tray.
Unlike MenuStrip, additional items can only be added below the first menu item, creating a vertical menu.
In addition, a ContextMenuStrip needs to be associated with the form or control where you want it to appear. You do this by
setting the ContextMenuStrip property of the form or control to the name of the ContextMenuStrip control. You can
associate a single ContextMenuStrip with as many controls as you like.
Try It!
To create a context menu
1. On the File menu, select New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type ContextMenus and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag a ContextMenuStrip control onto the form.
5. In the Properties window, select the ContextMenuStrip property of the form and choose ContextMenuStrip1 from
the drop-down list.
6. In the form, click the ContextMenuStrip control and type Option1, and then press ENTER.
7. In the box beneath the first box, type Option2, and then press ENTER.
8. Double-click the Option1 menu item to open the Code Editor.
9. In the Option1ToolStripMenuItem_Click event handler, type the following code.
VB
MsgBox("You chose Option 1")

10. In the Code Editor, select Option2ToolStripMenuItem in the left-hand drop down box, and then choose Click from
the right-hand drop down box.
A new event handler called Option2ToolStripMenuItem _Click appears in the code editor.
11. In the Option2ToolStripMenuItem _Click event handler, type the following code.
VB
MsgBox("You chose Option 2")

12. Press F5 to run your program. Right-click the form and click one of the items on the context menu—a message box
appears telling you which option you chose.
Next Steps
In this lesson, you learned how to enable and disable menus, and also how to create a context menu. In the next topic, you will
learn how to use a different type of control—a Timer—to perform actions.
Next Lesson: On Time: Using Timers to Perform Regular Actions
See Also
Tasks
Giving Users Choices: Creating Menus at Design Time
How to: Associate a ContextMenuStrip with a Control
Reference
MenuStrip Control Overview (Windows Forms)
Visual Basic Language Concepts

On Time: Using Timers to Perform Regular Actions


In this lesson, you will learn how to use the Timer component to perform actions not prompted by user input.
At times, you may find it useful to repeatedly perform actions in your programs—for example, saving a file every few minutes,
or updating the user interface. The Timer component allows you to perform set actions on a regular basis without any input
from the user.
The Timer component is different from the controls that you have used so far, in that it does not have a visual representation
at run time. Controls that have no visual representation are known as components. Because there is no way for the user to
interact directly with the Timer component, it runs in the background when the program runs.
The Timer component has two properties and one event that are used most often. The Enabled property determines if the
Timer component works. If Enabled is set to True, Timer is active. If Enabled is set to False, Timer is not active.
The Interval property determines the number of milliseconds between ticks of the Timer. For example, if the Interval property
is set to 1000, the Timer component will raise the Tick event every 1000 milliseconds, or every second.
The Tick event is raised by the Timer component at regular intervals, depending on the value of the Interval property. You
can add code to a Timer.Tick event handler, and this code executes when the Tick event fires.
By setting the Enabled and Interval properties and adding code to the Tick event handler, you can create code that executes
at regular intervals without the need for user action.
Try It!
To use a Timer component
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type Timer, and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag a Label control and a Timer component onto the form.
The Timer component does not appear on the form itself, but rather in the component tray beneath the form. This is
because the timer doesn't have a visual representation.
5. Select the Timer component, and then in the Properties window, set the Enabled property to True and the Interval
property to 1000.
6. Double-click the Timer component to open the Code Editor.
7. In the Timer1_Tick event handler, type the following code.
VB
Label1.Text = My.Computer.Clock.LocalTime.ToLongTimeString

8. Press F5 to run your application.


The text in the label is updated every second with the correct time.
Next Steps
In this lesson, you learned to use the Timer component to run code at regular intervals. Using a Timer component, you can
schedule code to run at any regular interval you choose. This is the final lesson for this section of the guided tour.
In the next section, you will learn how to use the Visual Basic tools to track down and fix errors (commonly called bugs) in your
program.
Next Lesson: What Went Wrong? Finding and Fixing Errors through Debugging
See Also
Tasks
Giving Users Choices: Creating Menus at Design Time
Reference
Timer Component Overview (Windows Forms)
Visual Basic Language Concepts

What Went Wrong? Finding and Fixing Errors through


Debugging
When writing a computer program, errors can and will happen. You might make a typographical error, your program might
not behave as expected, or it might not run at all. When there is an error in your program, you need to find it and fix it—the
process of finding and fixing errors is called debugging.
In the following lessons, you will learn several techniques for debugging a Visual Basic program.
In This Section
Finding the Errors: Introduction to Visual Basic Debugging
Know Your Bugs: Three Kinds of Programming Errors
Oops, a Typo: Finding and Getting Rid of Compiler Errors
Ouch! My Program Didn't Like That! Finding and Eliminating Run-Time Errors
What? It Wasn't Supposed To Do That! Tracking Down Logic Errors
Making Notes in Your Programs: Using Comments
Related Sections
Closer Look: What If... Testing Code in the Immediate Window
Extra Credit: Something is Still Wrong
Creating the Visual Look of Your Program: Introduction to Windows Forms
Managing Your Records: Using Data in Your Program
Visual Basic Guided Tour
Visual Basic Language Concepts

Finding the Errors: Introduction to Visual Basic Debugging


In this lesson, you will learn about fixing program errors through debugging.
No matter how carefully you design a program or write code, errors are bound to happen. Sometimes errors keep the
program from even starting, sometimes they cause the program to stop running or crash, and other times, the program may
run but not give the expected results.
Of course, when errors do occur, you will want to find them and fix them. Errors in a program are commonly known as bugs,
and the process of finding them and fixing them is known as debugging.
The process of debugging is iterative—that is, it is a process you will repeat over and over again. Typically you will write some
code, run the program until an error occurs, find the bug, fix it, and then run the program again.
In most cases, you do not need to stop the program to fix it. You can fix the code where the error occurred and keep running
the program where you left off; this process is called Edit and Continue.
Debugging is done in the Visual Basic IDE (integrated development environment)—which contains several special commands
and windows to help you find bugs. You will learn more about these in the following lessons.
Try It!
Note
This example involves an exception. Exceptions are objects that get created (and thrown) when the program realizes that an e
rror has occurred. Different types of exceptions are created, depending on the type of error that has occurred. Under the defa
ult user settings, if an exception occurs while running your Visual Basic program, a dialog box appears to explain the error an
d help you fix it.

To use edit and continue


1. On the File menu, select New Project.
2. On the Templates pane in the New Project dialog box, click Windows Application.
3. In the Name box, type Edit and then click OK.
A new Windows Forms project opens.
4. Double-click the form to open the Code Editor.
5. In the Form_Load event handler, add the following code.
VB
Dim number As Integer = 1
Dim numbers As String = ""
MsgBox(numbers + 1)

6. Press F5 to run the program. The program will halt and an exception dialog box is shown with the message
"InvalidCastException was unhandled".
The exception occurred because there is a typographical error in the code. The wrong variable was used—it should be
number, the Integer variable, not numbers, which is a String variable.

Notice that the program is still running; it is just in the debugging break mode. Using Edit and Continue, you can fix the
error without having to stop the program (and re-running to check it).
7. In the Code Editor, change numbers + 1 to number + 1.

8. Press F5 to continue. A message box with the number 2 should appear.


Next Steps
In this lesson, you learned about debugging, as well as how to fix a bug and continue running your program. In the next lesson,
you will learn about the different types of errors.
Next Lesson: Know Your Bugs: Three Kinds of Programming Errors
See Also
Other Resources
What Went Wrong? Finding and Fixing Errors through Debugging
Creating the Visual Look of Your Program: Introduction to Windows Forms
Visual Basic Guided Tour
Visual Basic Language Concepts

Know Your Bugs: Three Kinds of Programming Errors


In this lesson, you will learn about the different types of errors that can occur when writing a program.
Even the most experienced programmers make mistakes, and knowing how to debug an application and find those mistakes is
an important part of programming. Before you learn about the debugging process, however, it helps to know the types of bugs
that you will need to find and fix.
Programming errors fall into three categories: compilation errors, run-time errors, and logic errors. The techniques for
debugging each of these are covered in the next three lessons.
Compilation Errors
Compilation errors, also known as compiler errors, are errors that prevent your program from running. When you press F5 to
run a program, Visual Basic compiles your code into a binary language that the computer understands. If the Visual Basic
compiler comes across code that it does not understand, it issues a compiler error.
Most compiler errors are caused by mistakes that you make when typing code. For example, you might misspell a keyword,
leave out some necessary punctuation, or try to use an End If statement without first using an If statement.
Fortunately the Visual Basic Code Editor was designed to identify these mistakes before you try to run the program. You will
learn how to find and fix compilation errors in the next lesson, Oops, a Typo: Finding and Getting Rid of Compiler Errors.
Run Time Errors
Run-time errors are errors that occur while your program runs. These typically occur when your program attempts an
operation that is impossible to carry out.
An example of this is division by zero. Suppose you had the following statement:
Speed = Miles / Hours

If the variable Hours has a value of 0, the division operation fails and causes a run-time error. The program must run in order
for this error to be detected, and if Hours contains a valid value, it will not occur at all.
When a run-time error does occur, you can use the debugging tools in Visual Basic to determine the cause. You will learn how
to find and fix run-time errors in the lesson Ouch! My Program Didn't Like That! Finding and Eliminating Run-Time Errors.
Logic Errors
Logic errors are errors that prevent your program from doing what you intended it to do. Your code may compile and run
without error, but the result of an operation may produce a result that you did not expect.
For example, you might have a variable named FirstName that is initially set to a blank string. Later in your program, you
might concatenate FirstName with another variable named LastName to display a full name. If you forgot to assign a value to
FirstName, only the last name would be displayed, not the full name as you intended.

Logic errors are the hardest to find and fix, but Visual Basic has debugging tools that make this job easier, also. You will learn
how to find and fix logic errors in What? It Wasn't Supposed To Do That! Tracking Down Logic Errors.
Next Steps
In this lesson, you learned about the three categories of programming errors. In the next lesson you will learn about debugging
compiler errors.
Next Lesson:Oops, a Typo: Finding and Getting Rid of Compiler Errors
See Also
Tasks
Finding the Errors: Introduction to Visual Basic Debugging
Other Resources
What Went Wrong? Finding and Fixing Errors through Debugging
Visual Basic Language Concepts

Oops, a Typo: Finding and Getting Rid of Compiler Errors


In this lesson, you will learn how to find and fix compiler errors.
As you learned in the previous lesson, compiler errors occur when the Visual Basic compiler comes across unrecognizable code
—usually because you made a mistake when typing. Because compiler errors prevent a program from running, you need to
find and fix, or debug, those errors before trying to run your program.
Finding and Fixing Compiler Errors
Finding compiler errors is actually pretty easy, since the program cannot run until errors are fixed. When you press F5, if there
are any compiler errors, you see a dialog box that reads "There were build errors. Continue?". If you choose Yes, the last
error-free version of the program will run; if you choose No, the program stops and the Error List window appears.
The Error List window displays information about the compiler error, including a description of the error and its location in
your code. If you double-click the error in the Error List, the offending line of code is highlighted in the Code Editor. You can
also press F1 to display Help and get more information about the error and how to fix it.
The Visual Basic Code Editor can also help you to find and fix compiler errors before you even try to run the program. Using a
feature called IntelliSense, Visual Basic inspects your code as you type—if it finds code that will cause a compiler error, it
underlines that code with a wavy blue line. If you hold the mouse over that line, a message describing the error is displayed. If
the Error List window is visible, the error message is displayed there, as well.
Try It!
To find and fix compiler errors
1. On the File menu, select New Project.
2. On the Templates pane in the New Project dialog box, click Windows Application.
3. In the Name box, type CompilerErrors and then click OK.
A new Windows Forms project opens.
4. Double-click the form to open the Code Editor.
5. In the Form_Load event handler, add the following code.
VB
End If

6. Press ENTER. You will see a wavy blue line underneath End If.

If you hold the mouse over the line, you will see the message "'End If' must be preceded by a matching 'If'."
7. Change the code to look like the following.
VB
If 1 < 2 Then
End If

Note that the wavy blue line has disappeared.


8. Add the following new line of code after the If...Then statement.
VB
MgBox("Hello")

9. Press F5 to run the program. A dialog box appears with the message "There were build errors. Would you like to
continue and run the last successful build?"
10. Click No. The Error List window displays the error message "Name 'MgBox' is not declared."
11. Double-click the error message in the Error List, and change the code to MsgBox("Hello").
12. Press F5 again. This time the program should run, causing a message box to appear.
Next Steps
In this lesson, you learned how to find and fix compiler errors. In the next lesson, you will learn how to fix a different type of
error—run-time errors. Next Lesson: Ouch! My Program Didn't Like That! Finding and Eliminating Run-Time Errors
See Also
Tasks
Know Your Bugs: Three Kinds of Programming Errors
Finding the Errors: Introduction to Visual Basic Debugging
Visual Basic Language Concepts

Ouch! My Program Didn't Like That! Finding and Eliminating


Run-Time Errors
In this lesson, you will learn how to debug your program and fix run-time errors.
As you learned earlier, run-time errors occur when your program attempts an operation that is impossible to complete. When
a run-time error occurs, the program stops and an error message is displayed—you need to debug the error and fix it before
the program can continue.
Finding and Fixing Run Time Errors
Most run-time errors occur because you made a mistake in your code, for example, forgetting to assign a value to a variable
before you use it. When you run your program and the mistake is discovered, the program will stop and the Exception
Assistant dialog box is displayed in the Code Editor window. When this occurs, the program is in break mode, the mode in
which debugging is done.
The Exception Assistant dialog box contains a description of the error, as well as troubleshooting tips that suggest the cause.
You can click the troubleshooting tips to display Help topics for more details.
You need to fix the error before the program can continue—in order to do so, you need to inspect your code to find the cause
of the error. For example, if you suspect that an error occurred because a variable contains the wrong value, while you are still
in break mode, you can use IntelliSense to see the value of the variable. When you hold the mouse over the variable in the
Code Editor, a ToolTip displays the value of the variable. If the value is not what you expected, look at the preceding code to see
where the value was set, then fix that code and continue.
Try It!
To inspect the value of a variable
1. On the File menu, choose New Project.
2. On the Templates pane, in the New Project dialog box, click Windows Application.
3. In the Name box, type RunTimeErrors and then click OK.
A new Windows Forms project opens.
4. Double-click the form to open the Code Editor.
5. In the Form_Load event handler, add the following code.
VB
Dim miles As Integer = 0
Dim hours As Integer = 0
Dim speed As Integer = 0

VB
miles = 55
speed = miles / hours
MsgBox(CStr(speed) & " miles per hour")

6. Press F5 to run the program. An Exception Assistant dialog box is shown with the message "OverflowException was
unhandled".
A dotted line from the dialog box to your code file shows you which line of code caused the error.
Notice that the first troubleshooting tip in the Exception Assistant suggests that you should make sure you are not
dividing by zero.
7. Move your mouse over the variable miles, and hold it there for a few seconds. You should see a ToolTip that reads "miles
55".
8. Now move your mouse over the variable hours—the ToolTip should read "hours 0".
Because you cannot divide by zero and the value of hours is zero, you found the cause of the error—not updating the
value of hours.
9. Add the following line of code above the line miles = 55.

VB
hours = 2

10. Click the yellow arrow in the left-hand margin of the code and drag it up to the line hours = 2.

This allows the program to continue from that line, rather than the line that contains the error. This is required to execute
the new line of code you just added, in order for your error fix to be recognized.
11. Press F5 to continue the program. A dialog box appears, displaying "28 miles per hour".
Next Steps
In this lesson, you learned how to find and fix run-time errors. In the next lesson, you will learn about the third type of
programming error—logic errors. You can explore more advanced debugging techniques in
Closer Look: What If... Testing Code in the Immediate Window, and then proceed to the logic errors lesson.
Next Lesson:What? It Wasn't Supposed To Do That! Tracking Down Logic Errors
See Also
Tasks
Oops, a Typo: Finding and Getting Rid of Compiler Errors
Know Your Bugs: Three Kinds of Programming Errors
Finding the Errors: Introduction to Visual Basic Debugging
Visual Basic Language Concepts

Closer Look: What If... Testing Code in the Immediate Window


In this lesson, you will learn how to evaluate and run code using the Immediate window.
In the previous lesson, you learned how to fix run-time errors using the Exception Assistant. Sometimes, however, it may not
be clear how to fix an error, and you may want to test a possible fix without changing the actual code. A special debugging
window, the Immediate window, allows you to do that and more.
The Immediate Window
When your program is in break mode, the Immediate window can be used to run pieces of code and to evaluate variables or
expressions. For example, if a run-time error occurs because of an empty variable, you can check the value of a variable. You
can also use the Immediate window to assign that variable a value, and check how the rest of the program runs as a result.
Tip
When running your program in debug mode, you can put your program into break mode at any time by selecting Break fro
m the Debug menu.

You can execute code in the Immediate Window by typing it in as you would in the Code Editor, and then pressing ENTER. To
evaluate a variable or expression, type a question mark followed by the variable or expression you want to evaluate, and then
press ENTER—the result is then displayed on the following line.
Try It!
To test code in the Immediate window
1. On the File menu, choose New Project.
2. On the Templates pane, in the New Project dialog box, click Windows Application.
3. In the Name box, type Immediate, and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag two TextBox controls and a Button control onto the form.
5. Double-click the button to open the Code Editor.
6. In the Button_Click event handler, add the following code.
VB
Dim miles As Integer = 0
Dim hours As Integer = 0
Dim speed As Integer = 0

VB
miles = CInt(Textbox1.Text)
hours = CInt(Textbox2.Text)
speed = miles / hours
MsgBox(CStr(speed) & " miles per hour")

7. Press F5 to run the program. Enter 100 in the first text box, and then enter 0 in the second text box.
8. Click Button1. The program stops, and the Exception Assistant dialog box appears with the message
"OverflowException was unhandled".
9. In the Immediate window at the bottom of the IDE, type ?miles, and then press ENTER.
The value 100 should appear on the next line.
Tip
You can open the Immediate window at any time by choosing Windows, Immediate from the Debug menu.

10. Type ?hours, and then press ENTER.


The value 0 should appear on the next line.
11. Type hours = 4, and press ENTER. Then type ?hours, and press ENTER.

Notice that the value of hours is now 4, the value you entered on the previous line. You could change the value of hours
in the Immediate window without changing the program's code.
12. Press F5 to continue. A message box is displayed with the result.
Tip
To prevent this run-time error from occurring, add an error handler to check for a valid number in the Try block, and th
en display a message to the user in the Catch block. For more information on error handlers, see
What To Do When Something Goes Wrong: Handling Errors.

Next Steps
In this lesson, you learned how to use the Immediate window to check values and run code. In the next lesson, you will learn
how to find and fix logic errors.
Next Lesson: What? It Wasn't Supposed To Do That! Tracking Down Logic Errors
See Also
Tasks
Ouch! My Program Didn't Like That! Finding and Eliminating Run-Time Errors
What To Do When Something Goes Wrong: Handling Errors
Visual Basic Language Concepts

What? It Wasn't Supposed To Do That! Tracking Down Logic


Errors
In this lesson, you will learn how find logic errors in your program.
In previous lessons you learned how to find and fix compiler errors and run-time errors. The third type of programming error,
logic errors, can be the most difficult to discover. With logic errors you get no warning at all—the program will run but give
incorrect results. You then have to dig into your code and determine why.
Fortunately the debugging tools in Visual Basic can help. Two debugging techniques, setting breakpoints and stepping through
code, help you to inspect your code one line at a time as it executes to find the error.
You can set a breakpoint in the Code Editor on any executable line of code. When the program is run, breakpoints force it to
stop and go into break mode when that line of code is reached. You can then get whatever information you may want about
the state of the program at that point in time. You can check the value of any variable, test expressions in the Immediate
window, or make changes to your code with Edit and Continue.
Once you are in break mode, you can also step through your code, executing one line at a time so that you can see how the
code works. Pressing the F8 key causes the current line of code to execute and then stop at the next line. You can then inspect
the values of variables to see how they change from one line to the next.
If the current line of code calls a function or Sub procedure elsewhere in your code, when you press F8, execution will step into
that procedure. Once you have stepped through that procedure, you are sent to the line after the one that called the procedure.
If you do not want to step through a procedure, you can press SHIFT+F8 to step over the procedure.
Try It!
To observe a logic error
1. On the File menu, choose New Project.
2. On the Templates pane in the New Project dialog box, click Windows Application.
3. In the Name box, type LogicErrors and then click OK.
A new Windows Forms project opens.
4. From the Toolbox, drag two TextBox controls and a Button control onto the form.
5. Double-click Button1 to open the Code Editor.
6. In the Button1_Click event handler, add the following code.
VB
Dim minutes As Integer = CInt(Textbox1.Text)
Dim miles As Double = CDbl(Textbox2.Text)
Dim hours As Double = 0
hours = minutes / 60
MsgBox("Average speed " & GetMPH(hours, miles))

7. Below the End Sub line, add the following function.

VB
Function GetMPH(ByVal miles As Double, ByVal hours As Double) _
As String
GetMPH = CStr(miles / hours)
End Function

8. Press F5 to run the program. In the first text box, enter 10 (to represent 10 minutes) and in the second text box, enter 5 (to
represent 5 miles), and then click Button1.
A message box is displayed with the message "Average speed 0.03333334"; however, if you are traveling five miles in
ten minutes, the correct answer would be 30 mph.
Keep the project open—in the next procedure, you will learn how to find the logic error.
Finding Logic Errors
In the last example, something is obviously wrong with the program logic. According to the result, you are traveling less than
one mile per hour, not thirty miles per hour as you would expect—but where is the error?
In the next procedure, you will set a breakpoint and step through the code to find the error.
Try It!
To set a breakpoint and step through code
1. In the Code Editor, find the line hours = minutes / 60, and then click in the left-hand margin next to that line of code.

A red dot should appear in the margin, and the code should be highlighted in red, representing a breakpoint.
2. Press F5 to run the program again. In the first text box, enter 10, and in the second text box, enter 5. Then click Button1.
The program stops when it reaches the breakpoint. The line hours = minutes / 60 is highlighted in yellow.

Inspect the values of the variables by holding the mouse over them—the value of hours should be 0, and the value of
minutes should be 10.

3. Press F8 to execute the line hours = minutes / 60, and step to the next line.

Inspect the values of the variables in the line MsgBox("Average speed " & GetMPH(hours, miles))—the value of hours
should now be 0.166666672, and the value of miles should be 5.0.
4. Press F8 again to execute the current line.
Notice that the execution steps down to the line Function GetMPH.

Inspect the values of the variables on this line—you should notice that the value of miles is now 0.166666672, and the
value of hours is now 5.0, the opposite of what they were on the previous line. You've found the error.
Keep the project open—in the next procedure, you will learn how to fix the logic error.
Fixing Logic Errors
In the last procedure, the values for the variables miles and hours switched places. Can you spot the cause?
If you look at the line MsgBox("Average speed " & GetMPH(hours, miles)), you will see that the GetMPH function is being
passed two arguments, hours and miles, in that order. If you look at the function declaration Function GetMPH(ByVal miles
As Double, ByVal hours As Double)..., you will notice that the arguments are listed as miles first and hours second.

An error in logic occurred because the arguments were passed in the wrong order, resulting in an incorrect calculation. If the
arguments had been of different types, you would have seen a run-time error; because the arguments were the same type, no
run-time error occurred. It was a simple mistake, but the resulting bug was difficult to find.
In the next procedure, you will set a breakpoint and step through the code to find the error.
Try It!
To fix the logic error
1. In the Code Editor, change the line MsgBox("Average speed " & GetMPH(hours, miles)) to read as follows:

VB
MsgBox("Average speed " & GetMPH(miles, hours))

2. Clear the breakpoint by clicking the red dot in the left-hand margin.
3. Press F5 to run the program. In the first text box, enter 10, and in the second text box, enter 5. Then click Button1.
This time the message box should display the correct result, "Average speed 30".
It may appear that the program is fixed, but there is another even harder-to-find logic error. If you want to try and find it,
keep the project open—you will use it again in the lesson Extra Credit: Something is Still Wrong.
Next Steps
In this lesson, you learned how to find and fix a logic error. At this point, you can go on to the next lesson on using comments,
or you can try your hand at finding another logic error in Extra Credit: Something is Still Wrong.
Next Lesson: Making Notes in Your Programs: Using Comments
See Also
Tasks
Ouch! My Program Didn't Like That! Finding and Eliminating Run-Time Errors
Know Your Bugs: Three Kinds of Programming Errors
Finding the Errors: Introduction to Visual Basic Debugging
Visual Basic Language Concepts

Extra Credit: Something is Still Wrong


In this lesson, you will learn to track down a logic error that occurs only in certain situations.
In the previous lesson, What? It Wasn't Supposed To Do That! Tracking Down Logic Errors, you learned how to find and fix an
error in logic. In the example code for that lesson, there is still a nasty bug hiding—one that is harder to find because it occurs
only in certain situations.
Testing a Program
As a programmer, when it comes to testing your program to see if it behaves as you want it to, you are at a disadvantage. You
know how it should work, so it is unlikely that you will make a mistake that could uncover a logic error. A user who is
unfamiliar with the program, however, can and will do things you have not thought of.
For example, in a program that calculates miles per hour by dividing the number of miles traveled by the number of hours the
journey took, what happens if the user enters zero for either the hours or the miles? Let's try it and see.
Try It!
To test the program
1. Open the LogicErrors project that was created in the previous lesson,
What? It Wasn't Supposed To Do That! Tracking Down Logic Errors.
Note
If you did not complete or save the previous project, you will need to go back and complete it before you can continue.

2. Press F5 to run the program. In the first text box, enter 0 (to represent minutes), and in the second text box, enter 5 (to
represent miles), and then click Button1.
A message box is displayed with the message "Average speed Infinity".
Keep the project open—in the next procedure, you will learn how to find the logic error.
5 Divided by 0 = Infinity?
In the previous procedure, "Infinity" might not be what you expected, but it is mathematically correct—0 goes into 5 an infinite
number of times. That, however, is not the result you would want users of your program to see. Can you think of a way to
prevent this?
You might think of adding an error handler, a procedure you learned in the lesson
What To Do When Something Goes Wrong: Handling Errors. However, in this case that wouldn't work—the result "Infinity"
isn't an error; it's just not what you want.
Since it is probably not useful to show a speed of zero, one way to fix the problem is to test for a value of zero, then warn the
user that they must enter a higher number. While you are at it, you might as well prevent the user from entering negative
numbers as well, since negative numbers can also produce a false result.
In the next procedure, you will modify the code in the Button1_Click event handler to call the GetMPH function only if the
values are greater than zero.
Try It!
To fix the bug
1. In the Code Editor, change the code in the Button1_Click event handler as follows:
VB
Dim minutes As Integer = CInt(Textbox1.Text)
Dim miles As Double = CDbl(Textbox2.Text)
Dim hours As Double = 0
If minutes <= 0 Or miles <= 0 Then
MsgBox("Please enter a number greater than zero")
Else
hours = minutes / 60
MsgBox("Average speed " & GetMPH(miles, hours))
End If

2. Press F5 to run the program again. In the first text box, enter 0, and in the second text box, enter 5. Then click Button1.
You should see the message box instructing you to enter a number greater than 0. Try testing your program with other
combinations of numbers until you are satisfied that the bug is fixed.
Next Steps
In this lesson, you learned how to find and fix a logic error that caused unexpected behavior. In the next lesson, you will learn
how to use comments in your code.
Next Lesson: Making Notes in Your Programs: Using Comments
See Also
Tasks
What? It Wasn't Supposed To Do That! Tracking Down Logic Errors
What To Do When Something Goes Wrong: Handling Errors
Know Your Bugs: Three Kinds of Programming Errors
Finding the Errors: Introduction to Visual Basic Debugging
Reference
/ Operator (Visual Basic)
Visual Basic Language Concepts

Making Notes in Your Programs: Using Comments


In this lesson, you will learn how to create comments in the code for your programs.
The code that makes up a program can be difficult to read and understand, particularly if you are not the person who originally
wrote it. By using comments, you can create notes to yourself or to other users of your code.
Comments are text entries in the Code Editor that are ignored by the Visual Basic compiler when the program is run. Thus, you
can write a note to yourself that explains what a particular section of your program does, or that reminds you to finish
uncompleted programming tasks.
You create a comment by starting a line with the ' character. The following example demonstrates how to create a comment.
VB
' This is a comment. WOW!

You can add comments to the ends of lines, as well, also by using the ' character. This is frequently done to provide comments
about individual lines of code, as seen in the following example.
VB
MsgBox("Hello World!") ' This line causes a message box to appear.

As with single-line comments, anything following the ' character on that line is ignored by the program.
Using Comments for Debugging
Another common use for comments is to temporarily prevent a line of code from executing while you debug your program.
For example, suppose you had a line of code that displayed a message box.
VB
MsgBox("Hello World!")

If you wanted to run the program without displaying it, but did not want to delete it permanently, you could use the comment
character (') to temporarily hide it from your program, as shown below.
VB
' MsgBox("Hello World!")

Because everything after the ' character is ignored, the program will run without executing this line. You can later remove the '
character, and the message box will be displayed.
Try It!
To insert comments
1. On the File menu, choose New Project.
2. On the Templates pane in the New Project dialog box, click Windows Application.
3. In the Name box, type Comments and then click OK.
A new Windows Forms project opens.
4. Double-click the form to open the Code Editor.
5. In the Form1_Load event handler, type the following code.
VB
' This code will cause two message boxes to appear
MsgBox("This is Message Box 1") ' Display Message Box 1
MsgBox("This is Message Box 2") ' Display Message Box 2

6. Press F5 to run the program.


The program starts, and each of the two message boxes are shown in turn.
7. On the Debug menu, choose Stop Debugging to end the program.
8. In the Code Editor, add a comment character (') to the first message-box line, so it reads as follows.
VB
' MsgBox("This is MessageBox 1") ' Ignore Message Box 1

9. Press F5 to run the program.


Notice that this time, the first message-box line is ignored by the program, and only the second message box is shown.
Next Steps
In this lesson, you learned to use comments to create notes in your code and to temporarily inactivate individual lines of code.
This completes the lessons on debugging. In the next set of lessons, you will learn how to use a database to store and retrieve
information for your program.
Next Lesson: Managing Your Records: Using Data in Your Program
See Also
Concepts
Comments in Code
Other Resources
What Went Wrong? Finding and Fixing Errors through Debugging
Visual Basic Language Concepts

Managing Your Records: Using Data in Your Program


Most programs use data in one way or another. For example, in an earlier lesson, you entered data in the form of numbers;
that data was then used in a calculation with the result returned in a message box.
In very simple programs, data is represented as fields within the program itself. For more complex programs, however, data is
stored in a structure separate from the program called a database.
In this set of lessons, you will learn how to create a database and use it to display and update data in your programs.
In This Section
Storing and Accessing Data
Creating Your First Database
Getting the Information You Need: Connecting to an Existing Database
Showing Information to the User: Displaying Data in Your User Interface
Adding or Modifying Your Records: Updating Data
Related Sections
Visual Basic Guided Tour
Visual Basic Language Concepts

Storing and Accessing Data


In this lesson, you will learn about using a database to store and access data.
Data is a central concept in computer programming. Most programs use data in one way or another. For example, in an earlier
lesson, you entered data in the form of numbers; that data was then used in a calculation and returned in a message box.
In very simple programs, data is represented as fields within the program. For more complex programs, however, data is
stored in a structure separate from the program; this structure is called a database.
What is a Database?
A database is a collection of data, stored in a file independent of your program. The data stored in a database can be of many
different types—text, number, pictures, and more. Different programs can connect to the same database and view and update
the data it contains.
A database is typically divided into one or more tables. A table is a collection of related records. For example, if you used a
database that held the data for a small business, you might have one table that represented products, another table for orders,
and another table for customers.

Each table is organized into a grid of columns and rows. The columns represent categories for the data in a record, and the
rows represent individual records. For example, in the above illustration, the Orders table contains a separate row or record
representing each order, and columns representing the product ordered, along with the quantity and the price.
Getting Started with Data
To access the data in a database from your program, you first must have a database to access. Using Visual Basic, it is easy to
create your own database, or to use a database that someone else created.
With Visual Basic Express Edition, you can access two different types of databases: Microsoft SQL Server databases or
Microsoft Access databases. For the purpose of these lessons, you will use a SQL Server database.
Once you have a database, you connect it to your program using an object called a DataSet, and then you connect the fields or
controls on a form to the data in the database using a technique called data binding.
When a field in your program, for example a TextBox control, is bound to a column in a database table, you can display the
data from that column in the text box, modify the data in the text box and save it in the database, or enter data for a new record
and add it to the database.
Although this may sound complicated, it really is not difficult. The database tools in Visual Basic make working with data a
snap, as you will see in the next few lessons.
Next Steps
In this lesson, you learned what a database is and how it relates to your program. In the next lesson, you will learn how to
create a database that can be used by your programs.
Note
To create and access a SQL Server database with Visual Basic Express Edition, you must also install SQL Server Express Editio
n. It is installed by default when you install Visual Basic Express Edition; however, if you chose not to install it, you will need to
do so before continuing on to the next lesson.

Next Lesson: Creating Your First Database


See Also
Other Resources
Managing Your Records: Using Data in Your Program
Visual Basic Guided Tour
Visual Basic Language Concepts

Creating Your First Database


In this lesson, you will learn how to create a database that you will use in subsequent lessons to create an address-book
program.
In the previous lesson, you learned that a database can be used to store and retrieve data for your Visual Basic programs. First,
you must have a database to access. While you could use an existing database, for the purpose of these lessons, you will learn
how to create a new database using the Visual Database Tools included in Visual Basic.
Prerequisites
To create and access a SQL Server database with Visual Basic Express Edition you must also install SQL Server Express Edition.
It is installed by default when you install Visual Basic Express Edition; however, if you chose not to install it, you will need to do
so before continuing.
Try It!
To create a database
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type FirstDatabase and then click OK.
A new Windows Forms project opens.
4. On the Project menu, choose Add New Item.
5. In the Add New Item dialog box, choose SQL Database.
6. In the Name box, type FirstDatabase and then click Add.
The Data Source Configuration Wizard launches.
7. In the Data Source Configuration Wizard, click Cancel.
A new database, FirstDatabase.mdf, is added to the project and displays in Solution Explorer.
Adding a Table
As you can see from the above procedure, creating a database is easy. At this point, the database is not useful, because it
contains no data. In the next procedure, you will add a table to the database—in this case, a table to store address information.
Try It!
To add a table to the database
1. On the View menu, choose Database Explorer.
2. In the Database Explorer, expand the FirstDatabase.mdf node (click the plus sign) and select the Tables node.
3. On the Data menu, choose Add New Table.
A Table Designer window opens.
4. In the Properties window, select Name, and type Addresses.
5. In the Table Designer window, select the Column Name field, and type FirstName.
6. Select the Data Type field and select nvarchar(50) from the drop-down list; the AllowNulls column will automatically
be checked.
You have now defined the first column in your new table.
Repeat the previous two steps to add four more columns with the following values:
a. Column Name: LastName, Data Type: nvarchar(50)
b. Column Name: StreetAddress, Data Type: nvarchar(50)
c. Column Name: City, Data Type: nvarchar(50)
d. Column Name: Phone, Data Type: nvarchar(50)
7. On the File menu, choose Save Addresses.
Adding a Key
You now have a table in your database that you can use to store names, addresses, and phone data for your address book.
There is one more step—adding a key so that you do not have duplicate records.
A key column—also known as a primary key—designates a column or columns in your table as a unique value. There can only
be one row in the table that contains this value; if you try to enter a second row with the same value, you will receive an error.
In the case of the Addresses table, designate both the FirstName and LastName columns as your primary key—while you might
know several people with the same first name or last name, it is not likely that you know two people with both.
Try It!
To add a key to the table
1. In the Table Designer, clear the Allow Nulls check box for the FirstName and LastName rows
2. Select both the FirstName and LastName rows.
Tip
You can click the gray square to the left of the FirstName field, and then press the CTRL key and click the LastName r
ow, to select both.

3. On the Table Designer menu, choose Set Primary Key.


A small key symbol appears to the left of each row.
4. On the File menu, choose Save Addresses.
Adding Data
You now have a database containing a single table, Addresses. Of course, a database is not of much use unless it contains data.
In the following procedure, you will add some data to the Addresses table. If you wish, you can substitute the names and
addresses of people that you know for those given in the example.
Try It!
To add data to the table
1. In the Database Explorer, expand the Tables node and select the Addresses node, and then on the Data menu, choose
Show Table Data.
A data-table window opens.
2. In the data-table window, select the FirstName field and type Samantha.
Note
Notice that when you first select the field, the value NULL appears in each field—null is a database term meaning that t
he field is empty.

3. Select the LastName field and type Smith.


4. Select the StreetAddress field and type 123 45th Ave. E.

5. Select the City field and type Seattle.


6. Select the Phone field and type 2065550100, and then press the TAB key.
You have now defined the first record in the Addresses table.
Repeat the previous five steps to add two more records with the following values:
a. FirstName: Michael, LastName: Alexander, StreetAddress: 789 W. Capital Way, City: Tacoma, Phone:
2065550101.

b. FirstName: Andrea, LastName: Dunker, StreetAddress: 722 Moss Bay Blvd, City: Kirkland, Phone: 2065550102.

7. On the File menu, choose Save All to save the project and the database.
As you were entering the data, you may have noticed that a small pencil icon appeared next to the data; when you used the
TAB key to move to the next row, the icons disappeared. The pencil icon means that the data hasn't been saved to the database.
When you move away from the row where you are entering data, the data for the entire row is saved to the database
automatically.
Next Steps
In this lesson, you created a database, added a database table, and then added records to the table in the IDE. In the next lesson,
you will learn how to use a database in your program.
Next Lesson: Getting the Information You Need: Connecting to an Existing Database.
See Also
Tasks
Storing and Accessing Data
Other Resources
Managing Your Records: Using Data in Your Program
Visual Basic Guided Tour
Visual Basic Language Concepts

Getting the Information You Need: Connecting to an Existing


Database
In this lesson, you will learn how to connect your program to an existing database.
Connecting to an existing database is easy. You can use the visual tools in Visual Basic Express Edition to browse to your
database and add a local copy to your project. In this lesson, you will create a new project and connect it to the Addresses
database you created in the previous lesson.
Note
Complete Creating Your First Database before proceeding.

Try It!
To connect to an existing database
1. On the File menu, click New Project.
2. On the Templates pane in the New Project dialog box, click Windows Application.
3. In the Name box, type Addresses and then click OK.
A new Windows Forms project opens.
4. On the Data menu, click Show Data Sources.
5. In the Data Sources window, click Add New Data Source.
The Data Source Configuration Wizard opens.
6. Select Database and click Next.
7. Click the New Connection button.
The Add Connection dialog box opens.
8. In the Add Connection dialog box, if the Data source is not Microsoft SQL Server Database File (SQL Client), click
the Change button and select Microsoft SQL Server Database File from the Change Data Source dialog box. Click
OK.
9. Click the Browse button and navigate to the location where you saved the FirstDatabase.mdf database, and then click
Open.
10. Click OK to close the dialog box, and then in the Data Source Configuration Wizard, click Next. If prompted to copy
the data file to your project, click Yes.
11. On the next page of the wizard, the Yes, save the connection as check box should be selected. Click Next to continue.
12. On the Choose Your Database Objects page, expand the Tables node, and then select the check box for the Addresses
table.
13. Click Finish to finish.
A local database file has been added to your project. Notice that a FirstDatabaseDataSet object has been added to the
Data Sources window.
14. In Solution Explorer, select the FirstDatabase.mdf node.
15. In the Properties window, select the Copy to Output Directory property and change the value to Copy if newer.
16. On the File menu, choose Save All to save your project.
Next Steps
In this lesson, you learned how to add a local database to your project. In the next lesson, you will learn how to create a user
interface to display the records in your database.
Next Lesson: Showing Information to the User: Displaying Data in Your User Interface
See Also
Tasks
Creating Your First Database
Other Resources
Managing Your Records: Using Data in Your Program
Visual Basic Guided Tour
Visual Basic Language Concepts

Showing Information to the User: Displaying Data in Your User


Interface
In this lesson, you will learn how to create a basic user interface for viewing the data in your local database.
Now that you have created a connection to a local database file, the next step is to create a user interface to display the data.
The programming behind retrieving data from a database and displaying it in a user interface is very complicated. Fortunately,
Visual Basic automatically creates and configures the required data objects for you, so all you need to do is select and position
the objects. In this lesson, you will learn how to create a simple data display form.
Try It!
To create a data access form
1. Open the Addresses project from the previous lesson. If you have not yet completed it, go to
Getting the Information You Need: Connecting to an Existing Database and finish that lesson before proceeding.
2. In Solution Explorer, select Form1.vb, and then on the View menu, choose Designer.
3. In Solution Explorer, click the Data Sources tab.
In the Data Sources window, take some time to explore the FirstDatabaseDataSet and Addresses nodes. You can
expand the Addresses node to view all the individual fields in the table.
4. Drag the Addresses node from the Data Sources window to the form.
Note
Some controls are automatically added to the form, and several components are created and added to the component t
ray beneath the form. There is a DataGridView control that will display the rows and columns of the table, and a contr
ol for navigation (the AddressesBindingNavigator). Additionally, Visual Basic creates components that connect to the
database, manage retrieval and updating of data, and store the data in a local DataSet (AddressesBindingSource, Ad
dressesTableAdapter, and FirstDatabaseDataSet, respectively).

5. Select the AddressesDataGridView control, and in the Properties window, set the Dock property to Fill (click the
center button).
This will expand the grid to fill the form.
6. Press F5 to run your program.
The data from the Addresses table is displayed in the DataGridView control on the form. You can use the controls in the
BindingNavigator to navigate between rows, and even add or delete records. You can also make changes to the
records by modifying the data displayed in the grid, but these changes will not be saved unless you click the Save Data
icon. You will learn how to automatically save changes to your data in the next topic.
Next Steps
In this lesson, you learned how to use the Visual Basic visual tools to create a basic data-oriented user interface. In the next
lesson, you will learn how to create a data entry form and save changes to your database.
Next Lesson: Adding or Modifying Your Records: Updating Data
See Also
Tasks
Getting the Information You Need: Connecting to an Existing Database
Other Resources
Managing Your Records: Using Data in Your Program
Visual Basic Guided Tour
Visual Basic Language Concepts

Adding or Modifying Your Records: Updating Data


In this lesson, you will learn how to create a data-entry form to update data in your local database.
In the last three lessons, you created a database, added a database file to your project, and created a basic user interface. As
you may have noticed, you could make changes to the address data and even add new records—but if you closed the program
and started it again, those changes were lost.
This data was actually a copy of the data in the database, stored in a local DataSet. Each time the program starts, the DataSet
retrieves its data from the database. When changes are made in the DataSet they are not made in the database.
If you click the Save button on the AddressesBindingNavigator control, any changes are copied from the DataSet back to
the database. Since a user probably will not always remember to save their work, add code to automatically save changes to
the database when the program closes. While you are at it, you will also change the user interface to make data entry easier.
Try It!
To update your local database file
1. Open the Addresses project from the previous lesson. If you have not yet completed the previous lesson, go to
Showing Information to the User: Displaying Data in Your User Interface and complete the steps.
2. In Solution Explorer, select Form1, and then on the View menu, choose Designer.
3. On the form, select the AddressesDatGridView control and delete it.
4. In Solution Explorer, click the Data Sources tab.
5. In the Data Sources window, select the Addresses table, and then select Details from the drop-down list.
6. Drag the Addresses node from the Data Sources window to the new form.
TextBox controls are added for each field in the table, along with Label controls describing the fields.
7. Double-click the form to open the Code Editor.
8. In the Events drop-down list, click FormClosing.
9. In the Form1_FormClosing event handler, type the following code:

Me.AddressesBindingSource.EndEdit()
Me.AddressesTableAdapter.Update(Me.FirstDatabaseDataSet.Addresses)

This code causes the AddressesTableAdapter to copy any changes in the dataset back to the local database.
10. Press F5 to run your program.
Make changes to some of the data, or add a new record, and then close the form.
11. Press F5 again. Your changes should be saved.
In this set of lessons, you learned how to create a database and a program to access the database. In the next set of lessons,
you will learn about classes, the blueprints for objects that you can reuse in your programs.
Next Lesson: Programming With Objects: Using Classes
See Also
Tasks
Getting the Information You Need: Connecting to an Existing Database
Other Resources
Managing Your Records: Using Data in Your Program
Visual Basic Guided Tour
Visual Basic Language Concepts

Programming With Objects: Using Classes


As you learned in an earlier lesson, Visual Basic programs are built with objects such as forms and controls. Objects can also
represent real-world things such as a person, a computer, or even something more abstract such as a bank account.
A class is simply a representation of a type of object; think of it as the object's blueprint. Just as a single blueprint can be used
to build multiple buildings, a class can be used to create multiple copies of an object.
In the following lessons, you will learn how to uses classes in your Visual Basic programs.
In This Section
What is a Class?
Modeling a Real-World Object: Creating Your First Class
Adding Properties to Your Class
Adding Methods to Your Class
Testing Your Class
Building Your Class on an Existing Class: Using Inheritance
Keeping Track Of Things: Using Collections to Manage Multiple Objects
Related Sections
Closer Look: Creating Multiple Versions of the Same Method with Overloading
Closer Look: Overriding Members
Closer Look: Using a For Each...Next Loop in a Collection
Visual Basic Language Concepts

What is a Class?
In this lesson, you will learn how to use classes to represent objects in your programs.
As you learned in an earlier lesson, Visual Basic programs are built with objects such as forms or controls. Objects can also be
used to represent real-world things, such as a person, a computer, or even something more abstract, such as a bank account.
A class is simply a representation of a type of object; think of it as a blueprint that describes the object. Just as a single blueprint
can be used to build multiple buildings, a class can be used to create multiple copies of an object.
Although you may not have realized it, you have already used classes. For example, the TextBox control is defined by a
TextBox class, which defines its appearance and its capabilities. Each time you drag a TextBox control onto a form, you are
actually creating a new instance of the TextBox class.
Each TextBox control is an exact yet distinct copy of the class that defines it, the TextBox class. Because each object is a
separate "instance" of a class, the act of creating a class is called instantiation.
So far you have added TextBox controls to your form by dragging them from the Toolbox, but you can also instantiate a
TextBox object in your code by declaring it with the New keyword.
VB
Dim Textbox1 As New TextBox

You will learn more about creating and using classes in the next few lessons.
What's in a Class?
In an earlier lesson, Closer Look: Understanding Properties, Methods, and Events, you learned that all objects have properties
that describe their attributes, methods that define their actions, and events that define their responses. Likewise, the class that
defines an object has its own properties, methods, and events (sometimes called members) that are passed on to all instances
of that class.
For example, a class that represents a bank account might have properties such as AccountNumber or AccountBalance, methods
such as CalculateInterest, and events such as BalanceChanged. Once you instantiate a bank-account object, you can access
its properties, methods and events just as you would with an object such as TextBox.
Some members of a class are private—they can only be accessed by code within the class. For example, a bank-account class
might have a method to calculate a balance. You would allow a program to read that balance, but you would not want the
program to be able to change the balance directly.
You can hide members in a class by declaring them as Private, or you can expose them by declaring them as Public. You can
also allow access to a property but prevent the program from changing its value by declaring it as ReadOnly. The following
code shows what a BankAccount class might look like.
VB
Class BankAccount
Private AccountNumber As String
Private AccountBalance As Decimal
Public Sub UpdateBalance()
' add code to recalculate balance.
End Sub
ReadOnly Property Balance() As Decimal
Get
Return AccountBalance
End Get
End Property
End Class

Next Steps
In this topic, you learned the basics of classes, as well as some new terminology. In the next lesson, you will learn how to create
a class.
Next Lesson: Modeling a Real-World Object: Creating Your First Class.
See Also
Concepts
Closer Look: Understanding Properties, Methods, and Events
Classes: Blueprints for Objects
Other Resources
Programming With Objects: Using Classes
Visual Basic Language Concepts

Modeling a Real-World Object: Creating Your First Class


In this lesson, you will learn how to create a class using a Class Library project.
In the previous lesson, you learned that classes can be used as blueprints for objects that model real-world things. One of the
best reasons for using classes is that once you have created a class for a certain type of object, you can reuse that class in any
project.
For example, many programs that you write might involve people—an address-book program for keeping track of your
friends, a contact-manager program for your business contacts, or a program for tracking employees. Although the programs
may be considerably different, the attributes that apply to a person would be the same. Every person has a name, an age, an
address, and a phone number.
In this and the next few lessons, you will create a class that represents a person; you can save this class and use it in other
programs that you write in the future.
Classes can be created in three ways—as a part of the code in a form module in a Windows Application project, as a
separate class module added to a Windows Application project, or as a stand-alone Class Library project.
Creating Classes
You may have noticed in some of the earlier lessons that when you double-click a form and open the Code Editor, you see
something like the following:

Public Class Form1


Private Sub Form1_Load...

End Sub
End Class

That's right—the form is actually a class, marked by Class and End Class statements, and any code that you enter between
those two statements is part of the class. Although by default a form module contains only a single class, you could create
additional modules by adding code below the End Class statement as follows:

Public Class Form1


' Form1 code here
End Class
Public Class MyFirstClass
' Your class code here
End Class

The drawback to creating classes this way is that they are available only within the project in which you created them. If you
want to share a class with other projects, you'll want to put it in a class module.
Class Modules
A class module is a separate code file that contains one or more classes. Because it is a separate file, it can be reused in other
projects. Class modules can be created in two ways—as a module added to a Windows Application project, or as a stand-
alone Class Library project.
You can add a new class module to an existing project by selecting Class in the Add New Item dialog box, available from the
Project menu. For the purpose of this set of lessons, you will be creating a stand-alone Class Library project.
Try It!
To create a Class Library project
1. On the File menu, choose New Project.
2. On the Templates pane, in the New Project dialog box, click Class Library.
3. In the Name box, type Persons and then click OK.
A new Class Library project opens, and the Code Editor displays the class module Class1.vb.
4. In Solution Explorer, right-click Class1.vb and select Rename, and then change the name to Persons.vb.
Notice that the name in the Code Editor also changed to Persons.vb.
5. On the File menu, choose Save All.
6. In the Save Project dialog box, click Save.
Tip
Rather than saving the project in the default location, you may want to create a directory where you can store all of you
r classes for reuse. You can enter that folder in the Location field of the Save Project dialog box before you save.

For now, keep the project open—you will add to it in the next lesson.
Next Steps
In this lesson, you learned how to create a class module. An empty class is of little use though—in the next lesson, you will
learn how to add properties to your class.
Next Lesson: Adding Properties to Your Class
See Also
Tasks
How to: Add New Project Items
Concepts
What is a Class?
Other Resources
Programming With Objects: Using Classes
Visual Basic Language Concepts

Adding Properties to Your Class


In this lesson, you will learn how to add properties to the class that you created in the previous lesson.
In an earlier lesson, Closer Look: Understanding Properties, Methods, and Events, you learned that all objects have attributes,
and that properties represent attributes. In the previous lesson, you created a Persons class that represents a person; people
have attributes such as name and age, so the Persons class needs properties to represent those attributes.
Properties can be added to a class in one of two ways: as a field, or as a property procedure. You can also determine how a
property works by using the Public, ReadOnly, or WriteOnly modifiers for the property.
Fields and Property Procedures
Fields are really just public variables within a class that can be set or read from outside of the class. They are useful for
properties that don't need to be validated—for example, a Boolean (True or False) value. In the case of the Persons class, you
might have a Boolean property named Alive that specifies whether a person is dead or alive. Since there are only two
possible values, a field works well for this property.
To add a field to a class, the code would look like the following.
VB
Public Alive As Boolean

Most properties, however, are more complex than that—in most cases you will want to use a property procedure to add a
property to a class. Property procedures have three parts: a declaration of a private variable to store the property value; a Get
procedure that exposes the value; and a Set procedure that, as it sounds, sets the value.
For example, a property procedure for a Name property for the Persons class would look like the following.
VB
Private nameValue As String
Public Property Name() As String
Get
Name = nameValue
End Get
Set(ByVal value As String)
nameValue = value
End Set
End Property

The first line of code declares a private String variable, nameValue, which will store the value of the property. The property
procedure itself begins with Public Property and ends with End Property.
The Get procedure contains the code that will be executed when you want to read its value—for example, if you read the
Persons.Name property, the code would return the value stored in the nameValue variable.

The Set procedure contains code used to assign a new value to the nameValue variable using a value passed to it as a value
argument. For example, if you wrote the code Persons.Name = "John", the String value John would be passed as the value
argument; the code in the Set procedure would then assign it to the NameValue variable for storage.
You might ask why you would go to all that trouble rather than use a field to represent the Name property. In the real world,
there are certain rules for names—for example, names do not usually contain numbers. You could add code to the Set
procedure to check the value argument and return an error if it contains numbers.
In the following procedure, you will add a field and three properties to the Persons class.
Try It!
To add properties to your class
1. Open the Persons project that you created in the previous lesson. If you did not save it, you will first need to go back to
the previous lesson, Modeling a Real-World Object: Creating Your First Class, and complete the procedures in that lesson.
2. In Solution Explorer, select Persons.vb, and then on the View menu, choose Code.
3. Add the following declaration code below the Public Class Persons line.

VB
Private firstNameValue As String
Private middleNameValue As String
Private lastNameValue As String
Public Alive As Boolean

4. Add the following property procedures below the declaration code.


VB
Public Property FirstName() As String
Get
FirstName = firstNameValue
End Get
Set(ByVal value As String)
firstNameValue = value
End Set
End Property

Public Property MiddleName() As String


Get
MiddleName = middleNameValue
End Get
Set(ByVal value As String)
middleNameValue = value
End Set
End Property

Public Property LastName() As String


Get
LastName = lastNameValue
End Get
Set(ByVal value As String)
lastNameValue = value
End Set
End Property

5. On the File menu, choose Save All to save your work.


Read-only and Write-only Properties
Sometimes a property is meant to be set once and never changed during the execution of your program. For example, a
property representing an employee number should never change, so it could be read by another program but you would not
allow that program to change its value.
The ReadOnly keyword is used to specify that a property value can be read but not modified. If you try to assign a value to a
ReadOnly property, an error occurs in the Code Editor.
To create a read-only property, you would create a property procedure with a Get procedure but no Set procedure, as follows.
VB
Private IDValue As Integer
ReadOnly Property ID() As Integer
Get
ID = IDValue
End Get
End Property

Likewise, the WriteOnly keyword allows a property value to be set but not read—for example, you would not allow a
password property to be read by other programs. You might use that value to do things within your class, but you would want
to keep it private.
To create a write-only property, you would create a property with a Set procedure but no Get procedure, as follows.
VB
Private passwordValue As String
WriteOnly Property Password() As String
Set(ByVal value As String)
passwordValue = value
End Set
End Property

ReadOnly and WriteOnly property procedures are also useful when you want to take one property value and convert it to a
different value. For example, consider a person's age. Unlike a name, age changes over time—if you assigned your age to a
class and read it back a year later, it would be wrong.
In the Persons class, you could prevent this by adding two properties—a WriteOnly BirthYear property that represents the
year of your birth, which never changes, and a ReadOnly Age property that returns a value by calculating the difference
between the current year and your birth year.
Try It!
To add ReadOnly and WriteOnly properties to your class
1. Add the following declaration code below the other declarations at the top of the class module.
VB
Private birthYearValue As Integer

2. Add the following property procedures below the declaration code.


VB
WriteOnly Property BirthYear() As Integer
Set(ByVal value As Integer)
birthYearValue = value
End Set
End Property

ReadOnly Property Age() As String


Get
Age = My.Computer.Clock.LocalTime.Year - birthYearValue
End Get
End Property

3. On the File menu, choose Save All to save your work.


Next Steps
In this lesson, you learned about properties and the different ways to add them to your class. In the next lesson, you will learn
how to add methods to your class so that it can perform actions.
Next Lesson: Adding Methods to Your Class
See Also
Tasks
Modeling a Real-World Object: Creating Your First Class
Concepts
Property Procedures vs. Fields
Other Resources
Programming With Objects: Using Classes
Visual Basic Language Concepts

Adding Methods to Your Class


In this lesson, you will learn how to add methods to a class so that it can perform actions.
In an earlier lesson, Closer Look: Understanding Properties, Methods, and Events, you learned that most objects have actions
that they can perform; these actions are known as methods. The Persons class that you created in the
Modeling a Real-World Object: Creating Your First Class lesson represents a person. There are many actions that people can
perform, and for the Persons class, those actions can be expressed as class methods.
Class Methods
The methods of a class are simply Sub or Function procedures declared within the class. For example, an Account class might
have a Sub procedure named Recalculate that would update the balance, or a CurrentBalance Function procedure to return
the latest balance. The code to declare those methods might look like the following:
VB
Public Sub Recalculate()
' add code to recalculate the account.
End Sub
Public Function CurrentBalance(ByVal AccountNumber As Integer) As Double
' add code to return a balance.
End Function

While most class methods are public, you might also want to add methods that can only be used by the class itself. For
example, the Persons class might have its own function for calculating a person's age. By declaring the function as Private, it
can not be seen or called from outside the class.
The code for a private function might look like the following:
VB
Private Function CalcAge(ByVal year As Integer) As Integer
CalcAge = My.Computer.Clock.LocalTime.Year - year
End Function

You could later change the code that calculates the value of CalcAge, and the method would still work fine without changing
any code that uses the method. Hiding the code that performs the method is known as encapsulation.
In the Persons class, you will create a public method that returns a full name, and a private function to calculate the age.
Try It!
To add a method to your class
1. Open the Persons project that you created in the previous lesson. If you did not save it, you will first need to go back to
the previous lesson, Adding Properties to Your Class, and complete the procedures.
2. In Solution Explorer, select Persons.vb, and then on the View menu choose Code.
3. Add the following code below the property procedures.
VB
Public Function FullName() As String
If middleNameValue <> "" Then
FullName = firstNameValue & " " & middleNameValue & " " _
& lastNameValue
Else
FullName = firstNameValue & " " & lastNameValue
End If
End Function
VB
Private Function CalcAge(ByVal year As Integer) As Integer
CalcAge = My.Computer.Clock.LocalTime.Year - year
End Function

4. Modify the code in the Age property procedure to use the private function.
VB
ReadOnly Property Age() As String
Get
' Age = My.Computer.Clock.LocalTime.Year - birthDateValue
Age = CalcAge(birthYearValue)
End Get
End Property

5. On the File menu, choose Save All to save your work.


Next Steps
In this lesson, you learned how to add both public and private methods to a class. You can learn more about methods in
Closer Look: Creating Multiple Versions of the Same Method with Overloading, or you can go on to the next lesson and learn
how to use and test the class you created.
Next Lesson: Testing Your Class
See Also
Tasks
Adding Properties to Your Class
Other Resources
Programming With Objects: Using Classes
Visual Basic Language Concepts

Closer Look: Creating Multiple Versions of the Same Method


with Overloading
In this lesson, you will learn how to add multiple versions of a method to your class.
In the previous lesson, you learned how to add methods to the Persons class. Sometimes there are cases where a single
method will not do—for example, you might need to pass different data types to the method in different situations, or you
might want to return different formats as a result.
You can create multiple versions of a method using a technique called overloading. When a class has more than one method
with the same name but with a different set of arguments, the method is overloaded.
Overloading
To create an overloaded method, add two or more Sub or Function procedures to your class, each with the same name. In the
procedure declarations, the set of arguments for each procedure must be different or an error will occur.
The following shows a method with two overloads, one which takes a String and the other which takes an Integer as an
argument.
VB
Public Sub TestFunction(ByVal input As String)
MsgBox(input)
End Sub
Public Sub TestFunction(ByVal input As Integer)
MsgBox(CStr(input))
End Sub

If you were to call this method from your code and pass it a string, the first overload would be executed and a message box
would display the string; if you passed it a number, the second overload would be executed, and the number would be
converted to a string and then displayed in the message box.
You can create as many overloads as you need, and each overload can contain a different number of arguments.
In the Persons class, you will add a method with two overloads to return a person's middle initial: one with just the initial, the
other with the initial followed by a period.
Try It!
To create an overloaded method
1. Open the Persons project that you created in the previous lesson. If you did not save it, go back to the previous lesson,
Adding Methods to Your Class, and complete the procedures.
2. In Solution Explorer, select Persons.vb, and then on the View menu, choose Code.
3. Add the following code below the existing methods.
VB
Public Function MiddleInitial() As String
MiddleInitial = Left$(middleNameValue, 1)
End Function

Public Function MiddleInitial(ByVal period As Boolean) As String


MiddleInitial = Left$(middleNameValue, 1) & "."
End Function

4. On the File menu, choose Save All to save your work.


Next Steps
In this lesson, you learned how to create an overloaded method. In the next lesson, you will learn how to use the class that you
created in a test project.
Next Lesson: Testing Your Class
See Also
Tasks
Adding Methods to Your Class
Concepts
Considerations in Overloading Procedures
Other Resources
Programming With Objects: Using Classes
Visual Basic Guided Tour
Visual Basic Language Concepts

Testing Your Class


In this lesson, you will learn how to create an instance of a class in order to test the class.
In the past few lessons, you have created a Persons class and given it properties and methods. So far, all you've done is add
code—now it is time to use the Persons class and make sure that it works as expected.
Creating an Instance of a Class
Although you may not have realized it, you have been using classes in many of the previous lessons. Forms and controls are
actually classes; when you drag a Button control onto a form, you are actually creating an instance of the Button class.
Any class can also be instantiated in your code using a declaration with the New keyword. For example, to create a new
instance of the Button class, you would add the following code.
VB
Dim aButton As New Button

To use and test the Persons class, you must first create a test project and add a reference to the class module.
Try It!
To create a test project for your class
1. Open the Persons project that you created in the previous lesson. If you did not save it, you will first need to go back to
the previous lesson, Adding Methods to Your Class, and complete the procedures.
2. On the File menu, point to Add, and choose New Project.
3. On the Templates pane in the New Project dialog box, click Windows Application.
4. In the Name box, type PersonsTest and then click OK.
A new Windows Forms project is added to Solution Explorer, and a new form is displayed.
5. In Solution Explorer, select the PersonsTest project, and then on the Project menu, choose Set as StartUp Project.
6. In the Solution Explorer, select the PersonsTest project, and then on the Project menu, choose Add Reference.
The Add Reference dialog box opens.
7. Click the Projects tab, and then select Persons and click OK.
8. Double-click the form to open the Code Editor, and then enter the following declaration just below the line Public Class
Form1.

VB
Dim person1 As New Persons.Persons

This declares a new instance of the Persons class. You might wonder why you needed to type Persons twice—the first
instance is the Persons.vb class module; the second instance is the Persons class within that module.
9. On the File menu, choose Save All.
Testing Your Class
The next step is to add a user interface and code that uses the Persons class. You will add text boxes into which the user will
enter values for each of the properties (except the read-only Age property), a check box for the Alive field, and buttons to test
each of the public methods.
Try It!
To test your class
1. In Solution Explorer, select Form1, and then on the View menu, choose Designer.
2. From the Toolbox, drag four TextBox controls, a CheckBox control, and two Button controls onto the form.
3. Select the first Button control, and then in the Properties window set its Text property to Update.
4. Select the second Button control, and then in the Properties window set its Text property to Full Name.

5. Double-click the first button (Update) to open the Code Editor, and then in the Button1_Click event handler, add the
following code.
VB
With person1
.FirstName = Textbox1.Text
.MiddleName = Textbox2.Text
.LastName = Textbox3.Text
.BirthYear = Textbox4.Text
.Alive = CheckBox1.Checked
End With

Notice that as you type, a list containing all of the members of the Persons class is displayed. Since it was added as a
reference, IntelliSense displays information about your class just as it would for any other class.
6. In the Button2_Click event handler, add the following code.
VB
' Test the FullName method.
MsgBox(person1.FullName)

' test the Age property and CalcAge method.


MsgBox(CStr(person1.Age) & " years old")

' Test the Alive property.


If person1.Alive = True Then
MsgBox(person1.FirstName & " is alive")
Else
MsgBox(person1.FirstName & " is no longer with us")
End If

7. Press F5 to run the project and display the form.


a. In the first text box, enter your first name.
b. In the second text box, enter your middle name.
c. In the third text box, enter your last name.
d. In the fourth text box, enter the four-digit year you were born (i.e. 1983).
e. If you are still alive, select that check box.
8. Click the Update button to set the properties of the class, and then click the Full Name button.
Three message boxes are displayed, showing your full name, your age, and your status.
9. On the File menu, choose Save All.
Testing the Overloaded Methods
If you completed the optional lesson Closer Look: Creating Multiple Versions of the Same Method with Overloading, you will
also want to test the overloaded methods that you added to the Persons class. If you did not complete the lesson, you can go
back and do so now, or you can skip the following procedure.
Try It!
To test the overloaded methods
1. In Solution Explorer, select Form1, and then on the View menu, choose Designer.
2. From the Toolbox, drag two more Button controls onto the form.
3. Select the third Button control, and then in the Properties window set its Text property to With.
4. Select the fourth Button control, and then in the Properties window set its Text property to Without.
5. Double-click the first button (With) to open the Code Editor, and then enter the following code in the Button3_Click
event handler.
VB
MsgBox(person1.FirstName & " " & person1.MiddleInitial(True) & _
" " & person1.LastName)

Notice that as you type, a list containing all of the members of the Persons class is displayed. Since it was added as a
reference, IntelliSense displays information about your class, just as it would for any other class.
6. In the Button4_Click event handler, add the following code.
VB
MsgBox(person1.FirstName & " " & person1.MiddleInitial & _
" " & person1.LastName)

7. Press F5 to run the project and display the form.


a. In the first text box, type your first name.
b. In the second text box, type your middle name.
c. In the third text box, type your last name.
d. In the fourth text box, type the four-digit year you were born (i.e. 1983).
e. If you are still alive, select the check box.
8. Click the Update button to set the properties of the class, and then click the With button.
A message box displays showing your name with a period after the middle initial.
9. Click the Without button.
A message box displays showing your name without a period after the middle initial
10. On the File menu, choose Save All.
Next Steps
In this lesson, you learned how to create a test project and then use it to test the properties and methods of your class. In the
next lesson, you will learn how to use inheritance to create a class based on an existing class.
Next Lesson: Building Your Class on an Existing Class: Using Inheritance.
See Also
Tasks
Adding Methods to Your Class
Closer Look: Creating Multiple Versions of the Same Method with Overloading
Visual Basic Language Concepts

Building Your Class on an Existing Class: Using Inheritance


In this lesson, you will learn how to use inheritance to create a class based on an existing class.
Many real-life objects have attributes and behaviors in common—for example, all cars have wheels and engines, and can roll
and (hopefully) stop. Some cars, however, have attributes that are not common—for example, a convertible has a removable
top, which may be lowered electronically or by hand.
If you created an object to represent a car, you would want to include properties and methods for all of the common attributes
and behaviors, but you would not want to add attributes such as a convertible top, since that attribute does not apply to all
cars.
Using inheritance, you can create a "convertible" class that is derived from the car class. It inherits all of the attributes of the car
class, and it can add those attributes and behaviors that are unique to a convertible.
Inheriting From an Existing Class
The Inherits statement is used to declare a new class, called a derived class, based on an existing class, known as a base class.
Derived classes inherit all of the properties, methods, events, fields, and constants defined in the base class. The following code
shows the declaration for a derived class.
VB
Class DerivedClass
Inherits BaseClass
End Class

The new class, DerivedClass, can then be instantiated, its properties and methods accessed just like BaseClass, and you can
add new properties and methods that are specific to the new class. For an example, look at the Persons class that you created
in the previous lessons.
Suppose you wanted a class that represented baseball players—baseball players have all of the attributes defined in the
Persons class, but they also have unique attributes such as number and position. Rather than adding those properties to the
Persons class, you will create a new derived class that inherits from Persons, and add the new properties to that class.

Try It!
To create a derived class
1. Open the Persons project that you created in the previous lesson. If you did not save it, go back to, Testing Your Class,
and complete the procedures.
2. In Solution Explorer, select the Persons project node.
3. On the Project menu, choose Add Class.
4. In the Add New Item dialog box, type Players in the Name box, and then click Add.
A new class module is added to the project.
5. In the Code Editor, add the following just below the Public Class Players line.

VB
Inherits Persons

6. Add the following code to define two new properties.


VB
Private numberValue As Integer
Private positionValue As String
Public Property Number() As Integer
Get
Number = numberValue
End Get
Set(ByVal value As Integer)
numberValue = value
End Set
End Property
Public Property Position() As String
Get
Position = positionValue
End Get
Set(ByVal value As String)
positionValue = value
End Set
End Property

7. On the File menu, choose Save All.


Testing the Players Class
You have now created a Players class derived from the Persons class. In the following procedure you will create a new
program to test the Players class.
To create a test project for your class
1. On the File menu, point to Add, and then choose New Project.
2. In the Add New Project dialog box, in the Templates pane, select Windows Application.
3. In the Name box, type PlayerTest and then click OK.
4. A new Windows Forms project is added to Solution Explorer, and a new form displays.
5. In Solution Explorer, select the PlayerTest project, and then on the Project menu, choose Set as StartUp Project.
6. In Solution Explorer, select the PlayerTest project, and then on the Project menu, choose Add Reference.
The Add Reference dialog box opens.
7. Click the Projects tab and choose Persons, and then click OK.
8. Double-click the form to open the Code Editor, and then enter the following declaration just below the line Public Class
Form1.

VB
Dim player1 As New Persons.Players
Dim player2 As New Persons.Players

9. This declares two new instances of the Players class.


10. On the File menu, choose Save All.
To test the derived class
1. In Solution Explorer, select Form1 in the PlayerTest project, and then on the View menu, choose Code.
2. In the Code Editor, add the following code to the Form1_Load event procedure.
VB
With player1
.FirstName = "Andrew"
.LastName = "Cencini"
.Number = 43
.Position = "Shortstop"
End With
With player2
.FirstName = "Robert"
.LastName = "Lyon"
.Number = 11
.Position = "Catcher"
End With

3. In Solution Explorer, select Form1 in the PlayerTest project, and then on the View menu, choose Designer.
4. From the Toolbox, drag two Button controls onto the form.
5. Select the first Button control, and then in the Properties window, set its Text property to At Bat.

6. Select the second Button control, and then in the Properties window, set its Text property to On Deck.

7. Double-click the first button (At Bat) to open the Code Editor, and then enter the following code in the Button1_Click
event handler.
VB
MsgBox(player1.Position & " " & player1.FullName & ", #" & _
CStr(player1.Number) & " is now at bat.")

Notice that you are using the FullName method, which was inherited from the base class Persons.
8. In the Button2_Click event handler, add the following code.
VB
MsgBox(player2.Position & " " & player2.FullName & ", #" & _
CStr(player2.Number) & " is on deck.")

9. Press F5 to run the program. Click each button to see the results.
10. On the File menu, choose Save All.
Next Steps
In this lesson, you learned how to inherit from an existing class and how to extend the derived class. You can learn more about
inheritance in Closer Look: Overriding Members, or you can go on to the next lesson and learn about collections.
Next Lesson: Keeping Track Of Things: Using Collections to Manage Multiple Objects
See Also
Concepts
Inheritance Basics
Visual Basic Language Concepts

Closer Look: Overriding Members


In this lesson, you will learn how to override a member of a derived class.
In the previous lesson, you learned how to inherit from a base class and extend the derived class with new properties. In
addition to adding new properties or methods to a derived class, you may also want to change, or override, the behavior of
existing properties or methods.
For example, you might create a Truck class that is derived from a Car class that has a StartEngine method. If the truck has a
diesel engine, the process of starting the engine might differ from that of a car; in this case you would want to override the
StartEngine method to better fit the truck.

Overriding Properties and Methods


By default, properties and methods in a class cannot be overridden. To allow a derived class to override a property or method,
it must be marked as overridable by declaring it with the Overridable keyword.
Public Overridable Property EngineType As String
Public Overridable Sub StartEngine(ByVal EngineType As String)

When inheriting from a base class, properties and methods that are marked as Overridable can be used as is, or they can be
modified to suit your needs by declaring them with the Overrides keyword.
Public Overrides Property EngineType As String
Public Overrides Sub StartEngine(ByVal EngineType As String)

In the Players class that you created in the previous lesson, you might want to override the FullName method to include the
player's number and to eliminate the code that returns a middle name.
Try It!
To override the FullName method
1. Open the Persons project that you created in the previous lesson. If you did not save it, go back to the previous lesson,
Building Your Class on an Existing Class: Using Inheritance, and complete the procedures.
2. In Solution Explorer, select the Persons.vb node, and then on the View menu, choose Code.
3. In the Code Editor, modify the declaration for the FullName method as follows.
VB
Public Overridable Function FullName() As String

4. In Solution Explorer, select the Players.vb node, and then on the View menu, choose Code.
5. In the Code Editor, add the following code to the class.
VB
Public Overrides Function FullName() As String
FullName = FirstName & " " & LastName & ", #" & numberValue
End Function

6. In Solution Explorer, select the Form1.vb node in the PlayerTest project, and then on the View menu, choose Code.
7. In the Code Editor, modify the Button1_Click event code as follows.
VB
MsgBox(player1.Position & " " & player1.FullName & _
" is now at bat.")
8. Modify the Button2_Click event code as follows.
VB
MsgBox(player2.Position & " " & player2.FullName & _
" is on deck.")

9. Press F5 to run the program, and click each button to display the results.
Notice that the results are the same as before, even though you are now using the overridden FullName method.
10. On the File menu, choose Save All.
Next Steps
In this lesson, you learned how to override a method. In the next lesson, you will learn about using collections to manage
groups of similar objects.
Next Lesson: Keeping Track Of Things: Using Collections to Manage Multiple Objects
See Also
Tasks
Building Your Class on an Existing Class: Using Inheritance
Reference
Overridable
Overrides
Visual Basic Language Concepts

Keeping Track Of Things: Using Collections to Manage Multiple


Objects
In this lesson, you will learn how to use a collection to manage groups of objects.
In an earlier lesson, you learned about using arrays to manage groups of variables. While you could use arrays to manage
groups of objects, Visual Basic also has a special type of object called a collection that can be used to store and retrieve groups
of like objects.
Like an array, each item in a Collection object has an index that can be used to identify that item. In addition, each item in a
Collection object has a key, a String value that can be used to identify the item. The advantage to using a key is that you do
not need to remember the index of an item; instead you can refer to it using a meaningful name.
Creating a Collection
Collections are useful when your program uses multiple instances of the same class. For example, look at the Players class
that you created in a previous lesson. It is likely that you need multiple Players objects to represent a baseball team.
The first step in creating a collection is to create an instance of a Collection object, as shown in the following declaration.
VB
Dim baseballTeam As New Collection

Once you create the Collection object, you can use the Add method to add items to it, and the Remove method to delete the
items. When adding items, first specify the item to add, and then specify the String value to be used as a key.
VB
baseballTeam.Add(playerObject, "Player's Name")

When removing an item, use the key to specify the item to remove.
VB
baseballTeam.Remove("Player's Name")

In the following procedure, you will add two new Players objects, and then create a team collection and add the Players
objects to it, using the Position property as a key.
Try It!
To create a collection of objects
1. Open the Persons project that you created in the previous lesson. If you did not save it, go back to the previous lesson,
Building Your Class on an Existing Class: Using Inheritance, and complete the procedures.
2. In Solution Explorer, in the PlayerTest project, select the Form1.vb node, and then on the View menu, choose Code.
3. In the Code Editor, add the following to the declarations section (below the declaration for player2).
VB
Dim player3 As New Persons.Players
Dim player4 As New Persons.Players
Dim team As New Collection

4. Add the following code to the Form1_Load event procedure.


VB
With player3
.FirstName = "Eduardo"
.LastName = "Saavedra"
.Number = 52
.Position = "First Base"
End With

With player4
.FirstName = "Karl"
.LastName = "Jablonski"
.Number = 22
.Position = "Pitcher"
End With

team.Add(player1, player1.Position)
team.Add(player2, player2.Position)
team.Add(player3, player3.Position)
team.Add(player4, player4.Position)

5. In Solution Explorer, in the PlayerTest project, select the Form1.vb node. Then on the View menu, choose Designer.
6. From the Toolbox, drag a ComboBox control onto the form.
7. In the Properties window, select the Items property and click the … button.
8. In the String Collection Editor, enter the following, and then click OK.
Catcher

First Base

Pitcher

Shortstop

9. Double-click the ComboBox control to open the Code Editor, and then enter the following code in the
ComboBox1_SelectedIndexChanged event handler.

Dim SelectedPlayer As Persons.Players


SelectedPlayer = team(ComboBox1.SelectedItem)
MsgBox("Playing " & ComboBox1.SelectedItem & " is " & _
SelectedPlayer.FullName & "!")

10. Press F5 to run the program. Select a position from the drop-down list—the player for that position is displayed in a
message box.
Next Steps
In this lesson, you learned how to use a Collection object to manage a group of objects. At this point, you can learn more
about collections in Closer Look: Using a For Each...Next Loop in a Collection, or you can go on to the next group of lessons and
learn about creating your own controls.
Next Lesson: Visible Objects: Creating Your First User Control
See Also
Tasks
Closer Look: Using a For Each...Next Loop in a Collection
Closer Look: Overriding Members
Building Your Class on an Existing Class: Using Inheritance
Concepts
Visual Basic Collection Class
Other Resources
Visible Objects: Creating Your First User Control
Visual Basic Language Concepts

Closer Look: Using a For Each...Next Loop in a Collection


In this lesson, you will learn to use a For Each...Next loop to loop through a collection.
In an earlier lesson, you learned to use a For...Next loop to execute a block of code a specified number of times. The Visual
Basic collection objects support a special type of loop, the For Each...Next loop, which you can use to execute a block of code
for each element in the collection instead of executing the block a set number of times.
Adding a For Each...Next Loop
In the previous lesson, you manually added the values for the Position property of the Players objects in the team collection
to the ComboBox control. While this worked for the example, it is not the best practice—each time you added a new player,
you would also have to update the Items collection of the ComboBox control.
A better way to handle this would be to add the Position values to the Items collection by looping through the team collection
using a For Each...Next loop.
In a For...Next loop, you must first declare a counter variable; with a For Each...Next loop, you must first declare an object
variable. The following code demonstrates a For Each...Next loop.
VB
Dim player As Persons.Players
For Each player In team
ComboBox1.Items.Add(player.Position)
Next

In this case, no matter how many Players you have, the ComboBox1.Items.Add method is executed once for each Players
object in the team collection, and the Position value is added to the list.
Try It!
To loop through a collection
1. Open the Persons project from the previous lesson. If you did not finish it, go back to the previous lesson,
Keeping Track Of Things: Using Collections to Manage Multiple Objects, and complete the procedures.
2. In Solution Explorer, select the Form1.vb node in the PlayerTest project, and then from the View menu, choose
Designer.
3. Select the ComboBox control. Then, in the Properties window, select the Items property and click the … button.
4. In the String Collection Editor, delete the four existing entries, and then click OK.
5. Double-click the form to open the Code Editor.
6. In the Code Editor, add the following to the declarations section (below the declaration for team).
VB
Dim player As Persons.Players
For Each player In team
ComboBox1.Items.Add(player.Position)
Next

7. Press F5 to run the program. Select a position from the drop-down list. The player for that position is displayed in a
message box.
Next Steps
In this lesson, you used a For Each...Next loop in a collection. In the following lessons, you will create another type of object—
a user control.
Next Lesson: Visible Objects: Creating Your First User Control
See Also
Tasks
Keeping Track Of Things: Using Collections to Manage Multiple Objects
Reference
For Each...Next Statement (Visual Basic)
Other Resources
Programming With Objects: Using Classes
Visual Basic Language Concepts

Visible Objects: Creating Your First User Control


In the previous set of lessons you learned how to work with classes—blueprints for objects. The classes that you created can be
reused in other programs, so you don't have to write the same code over and over again.
Controls are also classes that can be reused in multiple projects. You will probably find yourself designing the same user
interface over and over again—for example, adding TextBox controls for entering first and last names, and then adding code
to combine them into a full name. Wouldn't it be nice if you could avoid all of that extra work?
That's where user controls come in. You can think of a user control as a class for creating visible objects—your own custom
controls that can be reused just like the controls that come with Visual Basic 2005. Most user controls are composite controls
—that is, controls that are composed of one or more standard Visual Basic 2005 controls.
In the following lessons, you will learn how to create a composite user control that you can reuse in other programs.
In This Section
Understanding the User Control Designer
Adding Controls to Your User Control
Adding Code to Your User Control
Testing Your User Control
Related Sections
Closer Look: Adding Properties with Named Values
Closer Look: Customizing Your User Control
Visual Basic Language Concepts

Understanding the User Control Designer


In this lesson, you will learn how to create your own control using the User Control Designer.
In the previous set of lessons, you learned how to use a Class Library project to create a class. A user control is simply a class
that you can see. Just like the standard controls that come with Visual Basic 2005, a user control can be placed on a form at
design time, and it appears when you run the program.
When you are designing your program, the form designer is where you arrange your controls and decide how they look. There
is also a designer for user controls, the User Control Designer, that lets you, the developer, decide what the control will look
like.
Creating User Controls
A User Control is similar to any other class, but with the added ability to be placed in the Toolbox and displayed on a form.
Where a Class module has only code, a user control module has both code and a designer. The User Control Designer is
similar to a form designer—it has properties for controlling the appearance and behavior of the user control.
The ways to create a user control differ slightly, depending on the version of Visual Basic that you are using: Visual Basic 2005
has a Windows Control Library project type; in Visual Basic Express Edition, you must first create a Class Library project and
then add a User Control template.
Try It!
To create a user control using Visual Basic Express Edition
1. On the File menu, click New Project.
2. On the Templates pane, in the New Project dialog box, click Class Library and then click OK.
3. On the Project menu, click Add User Control.
4. In the Add New Item dialog box, select User Control.
5. In the Name box, type NamesControl and then click Add.
A new User Control template is added to the project and the User Control Designer opens.
6. In the Solution Explorer, right-click Class1.vb and choose Delete, and then click OK.
7. On the File menu, click Save All.
8. In the Save Project dialog box, type NamesUserControl and then click Save.

To create a user control using Visual Studio 2005


1. On the File menu, click New Project.
2. On the Templates pane, in the New Project dialog box, click Windows Control Library.
3. In the Name box, type NamesControl and then click OK.
A new User Control template is added to the project, and the User Control Designer opens.
4. On the File menu, click Save All.
5. In the Save Project dialog box, type NamesUserControl and then click Save.
Next Steps
In this lesson, you learned how to create a project that has a user control and how to display the User Control Designer. A
blank control is of little use though—in the next lesson, you will learn how to add controls to your user control to create its
user interface.
Next Lesson: Adding Controls to Your User Control.
See Also
Other Resources
Visible Objects: Creating Your First User Control
Programming With Objects: Using Classes
Visual Basic Guided Tour
Visual Basic Language Concepts

Adding Controls to Your User Control


In this lesson, you will learn how to add controls to create a composite user control.
Designing Your User Control
As mentioned earlier, the most common type of user control is a composite control—one that is made up of one or more
standard Windows Forms controls. Controls can be added to a User Control template by dragging them from the Toolbox to
the User Control Designer, just as you would do when designing a form.
Once you have added a control, you can resize it and move it in the designer, and you can set its properties in the Properties
window.
For this example, you will add a Label control to display a full name, and three TextBox controls for entering first, last, and
middle names.
Try It!
To add controls to a User Control
1. Open the NamesUserControl project that you created in the previous lesson. If you did not save it, you will first need to go
back to the previous lesson, Understanding the User Control Designer, and complete the procedures in that lesson.
2. In Solution Explorer, select NamesControl.vb, and then on the View menu, choose Designer.
3. From the Toolbox, drag a Label control onto the designer.
Tip
The Toolbox is easier to use if you keep the window open. You can do this by clicking the Auto Hide icon, which looks
like a push pin.

4. In the Properties window, change the Name property to FullName.


5. From the Toolbox, drag three TextBox controls onto the designer. You can arrange them however you like.
6. In the Properties window, change their Name properties to FirstName, MiddleName, and LastName.
7. On the File menu, choose Save All to save your work.
Next Steps
In this lesson, you learned how to add controls in the User Control Designer and set their properties. Now you are ready to
add to your control so that it actually performs a useful task. The next lesson shows you how to write code that will direct your
user control to display first, middle, and last names, as well as expose new properties.
Next Lesson: Adding Code to Your User Control.
See Also
Tasks
Understanding the User Control Designer
Other Resources
Visible Objects: Creating Your First User Control
Programming With Objects: Using Classes
Visual Basic Guided Tour
Visual Basic Language Concepts

Adding Code to Your User Control


In this lesson, you will learn how to add code to your user control to display the full name and to expose new properties.
Like standard controls, user controls have properties, methods, and events. As the developer, you will write code to handle
your control's events, and you will decide which properties are exposed to the user of your control.
Handling Events in a User Control
In order to make your user control useful, you will need to write some code to handle the control's events. Writing an event-
handling procedure for a user control is no different than it is for a form or a control.
In this example, you will write an event procedure that will update the FullName label with the contents of the FirstName,
MiddleName, and LastName boxes as you type, using the TextChanged event handler.

Try It!
To add code to a user control
1. Open the NamesUserControl project that you created in the previous lesson. If you did not save it, you will first need to go
back to the previous lesson, Understanding the User Control Designer, and complete the procedures in that lesson.
2. In the Solution Explorer, select NamesControl.vb, and then on the View menu choose Code.
3. In the Code Editor, add the following code for the FirstName_TextChanged event handler.

Private Sub FirstName_TextChanged(ByVal sender As System.Object, ByVal e As System.Eve


ntArgs) Handles FirstName.TextChanged, MiddleName.TextChanged, LastName.TextChanged
' Display the contents of the three text boxes in the label.
FullName.Text = FirstName.Text & " " & MiddleName.Text & " " & LastName.Text
End Sub

4. Press F5 to run the program. The UserControl TestContainer opens and displays your user control.
5. Enter your first, middle and last names in the three text boxes—as you type, your name is displayed in the FullName label.
If you look at the code that you entered above, you will notice that the Handles clause in the declaration handles the
TextChanged event for all three TextBox controls. No matter which text box you type in first, the FullName label is always
updated as you type.
Exposing Properties in a User Control
Properties of standard controls allow you to set and retrieve values for a control at design time and at run time. You will also
want to make certain properties of your user control available so that you can set them in the Properties window at design
time and reference them in your code.
Exposing properties in a user control is very similar to exposing properties in a class, the main difference being that you can
also expose the properties of the controls contained in your user control. As with classes, you declare a Property and add code
to the Get and Set procedures. If you are exposing a property of a contained control, you do not need to declare a private
variable to store the value—the control's property stores it for you.
As it stands now, there is no way to retrieve the text that is entered into the FirstName, MiddleName, and LastName controls or
the value of the FullName label. You need to expose their values as properties to make the control useful. Since you do not
want the value of the FullName label to be changed outside of your own code, you will want to expose it as a read-only
property.
Try It!
To add properties
1. In the Code Editor, add the following code to expose the FirstName, MiddleName, and LastName values as properties.

Property FirstNameText() As String


Get
Return FirstName.Text
End Get
Set(ByVal value As String)
FirstName.Text = value
End Set
End Property
Property MiddleNameText() As String
Get
Return MiddleName.Text
End Get
Set(ByVal value As String)
MiddleName.Text = value
End Set
End Property
Property LastNameText() As String
Get
Return LastName.Text
End Get
Set(ByVal value As String)
LastName.Text = value
End Set
End Property

2. Add the following code to expose the value of the FullName label as a read-only property.

ReadOnly Property FullNameText() As String


Get
Return FullName.Text
End Get
End Property

3. Press F5 to run the program.


4. In the UserControl TestContainer, scroll to the bottom of the Properties grid and select the FirstNameText property.
Enter your name, and then select the FullNameText property—the FirstName text box should display your name, and
the FullNameText property should match.
Try changing some of the other properties in both the Properties grid and the control itself to see how they are related.
This is what a user of your control will experience at design time.
5. On the File menu, choose Save All to save your work.
Next Steps
In this lesson, you learned how to handle events in your user control and how to expose some of its properties. You can learn
more about properties in Closer Look: Adding Properties with Named Values, or you can go on to the next lesson and learn
how to use the control that you created.
Next Lesson: Testing Your User Control.
See Also
Tasks
Adding Controls to Your User Control
Other Resources
Visible Objects: Creating Your First User Control
Programming With Objects: Using Classes
Visual Basic Guided Tour
Visual Basic Language Concepts

Testing Your User Control


In this lesson, you will learn how to test your user control in another project and observe its run-time behavior.
Run-Time Behavior
Once you have completed your user control and tested its design-time behavior in the TestContainer, you will also want to
see how it behaves when used in a program. Visual Basic 2005 makes it easy to test your user control by adding a Windows
Application project.
Your user control automatically appears in the Toolbox, and you can add it to a form and set its properties just as you would
with any other control.
Try It!
To test your user control
1. Open the NamesUserControl project that you created in the previous lesson. If you did not save it, you will first need to go
back to the previous lesson, Adding Code to Your User Control, and complete the procedures in that lesson.
2. On the File menu, point to Add and click New Project.
3. In the Add New Project dialog box, select Windows Application.
4. In the Name box, type UserControlTest, and then click OK.
A new project will be added in Solution Explorer, and a new form will be displayed.
5. In Solution Explorer, select the UserControlTest project, and on the Project menu, select Set as StartUp Project.
6. In the Toolbox, select NamesControl and drag it to the form.
7. In the Properties window, set the FirstNameText, MiddleNameText, and LastNameText properties to match your
name.
8. Press F5 to run the program. Change the names in the text boxes to make sure the label updates correctly.
9. On the File menu, choose Save All to save your work.
Next Steps
In this lesson, you learned how to add your user control to a form and observe its run-time behavior. At this point, you can
learn more about user controls in Closer Look: Customizing Your User Control, or you can go on to the next group of lessons
and learn about graphics.
Next Lesson: Drawing Pictures: Using Graphics
See Also
Tasks
Adding Code to Your User Control
Other Resources
Visible Objects: Creating Your First User Control
Programming With Objects: Using Classes
Visual Basic Guided Tour
Visual Basic Language Concepts

Closer Look: Customizing Your User Control


In this lesson, you will learn how to customize your user control to make it more useful.
Adding Labels
In the last lesson, you tested the NamesControl user control and found that it works like it should. You may have also noticed
some ways it could be improved. For example, it isn't obvious which name should be entered in which text box, and there is no
way to make sure that a user enters all three names.
In order to make the user control more useful, you can add labels to identify each text box. You could set the text for the labels
to read "First Name", "Middle Name", and "Last Name", but what if you later decided that you wanted a "Middle Initial" instead?
It is better to create properties for the label text so that you can change the text at design time and provide a default value for
each property.
Try It!
To customize your user control
1. Open the NamesUserControl project that you created in the previous lesson. If you did not save it, you will first need to go
back to the previous lesson, Testing Your User Control, and complete the procedures in that lesson.
2. In Solution Explorer, select NamesControl.vb, and then on the View menu, choose Designer.
3. From the Toolbox, drag three Label controls onto the designer, and place one above each TextBox.
4. In Solution Explorer, select NamesControl.vb, and then on the View menu, choose Code.
5. In the Code Editor, add the following code to create properties for the label text.

Private text1 As String = "First Name"


Property Label1Text() As String
Get
Return text1
End Get
Set(ByVal value As String)
text1 = value
Label1.Text = text1
End Set
End Property
Private text2 As String = "Middle Name"
Property Label2Text() As String
Get
Return text2
End Get
Set(ByVal value As String)
text2 = value
Label2.Text = text2
End Set
End Property
Private text3 As String = "Last Name"
Property Label3Text() As String
Get
Return text3
End Get
Set(ByVal value As String)
text3 = value
Label3.Text = text3
End Set
End Property
Notice that the code declares three Private variables for the label text, and that the declarations include the default value
to be displayed.
6. In the Code Editor, select (NamesControl Events) from the left drop-down box, and then select the Load event from the
right drop-down box.
7. Add the following code to the NamesControl_Load event handler.

' Initialize the three labels


Me.Label1.Text = Label1Text
Me.Label2.Text = Label2Text
Me.Label3.Text = Label3Text

8. On the Build menu, choose Build Solution.


9. In Solution Explorer, select Form1.vb, and then on the View menu, choose Designer.
Verify that labels have the default text. Try changing the Label1Text property in the Properties window, and verify that
it changes in the control as well.
10. On the File menu, choose Close to close the form designer.
Adding Validation
Another useful customization would be to add code to validate what gets entered to make sure it is correct. Instead of
validating each of the TextBox controls on their own, you can write validation code for the entire user control.
Most controls have a Validating event that is raised when the focus moves away from the control; this is where you will enter
the validation code. In this case, you will want to write code to make sure that each text box contains a name.
If one or more of the text boxes is empty, you will want to display a message box to remind the user to enter his or her name.
You can expose a property that contains a default message; that way, the user of your control can change the message to say
what they want.
It is also possible that the user of your control may not require a middle name, so you will also want to add a Boolean
property to turn off validation for the MiddleName text box.
Try It!
To add validation
1. In the Code Editor, add code for two properties related to validation—one to specify if the middle name is required, and
another to specify a message to be displayed if validation fails.

Private required As Boolean = True


Property MiddleNameRequired() As Boolean
Get
Return required
End Get
Set(ByVal value As Boolean)
required = value
End Set
End Property
Private errormessage As String = "Please enter your name."
Property ValidationErrorMessage() As String
Get
Return errormessage
End Get
Set(ByVal value As String)
errormessage = value
End Set
End Property

2. In the Code Editor, select (NamesControl Events) from the left drop-down box, and then select the Validating event
from the right drop-down box.
3. Add the following code to the NamesControl_Validating event handler.

If MiddleNameRequired = True Then


If FirstName.Text = "" Or MiddleName.Text = "" Or _
LastName.Text = "" Then
MsgBox(ValidationErrorMessage)
End If
Else
' Middle name isn't required.
If FirstName.Text = "" Or LastName.Text = "" Then
MsgBox(ValidationErrorMessage)
End If
End If

4. On the Build menu, choose Build Solution.


5. In Solution Explorer, select Form1.vb, and then on the View menu, choose Designer.
Select the user control on the form, and verify that the two new properties appear in the Properties window.
6. From the Toolbox, drag a Button control to the form.
7. Press F5 to run the program.
Enter your first and last name, but do not enter your middle name. Click the button, and a message box containing the
ValidationErrorMessage should be displayed.
8. On the File menu, choose Save All to save your work.
Next Steps
In this lesson, you learned how to customize your user control to make it more useful. In the next lesson, you will learn how to
use graphics to draw pictures and text.
Next Lesson: Drawing Pictures: Using Graphics
See Also
Tasks
Testing Your User Control
Other Resources
Visible Objects: Creating Your First User Control
Programming With Objects: Using Classes
Visual Basic Guided Tour
Visual Basic Language Concepts

Drawing Pictures: Using Graphics


In a previous lesson, you learned how to create the user interface using forms and controls. Sometimes you might want to
customize the look of your program with images or effects that cannot be created with controls.
In Visual Basic, you can use graphics methods to draw just about anything on a form or on a control. In this set of lessons, you
will be introduced to the graphics capabilities in Visual Basic.
In This Section
Making Graphics Appear
Drawing Shapes on Your Form
Drawing Text on Your Form
Drawing an Image on Your Form
Related Sections
Picture This: Displaying Images
Visual Basic Guided Tour
Visual Basic Language Concepts

Making Graphics Appear


In this lesson, you will learn how to use the graphics methods in Visual Basic to draw on a form.
In an earlier lesson, you learned how to display pictures on a form using a PictureBox control. That works fine if you already
have a picture, but sometimes you might want to draw something directly on your form. For example, you might want to draw
a line to separate two fields, or a circle to highlight an important label.
In Visual Basic, you can use graphics methods to draw just about anything on a form or on a control.
Graphics Basics
Before you start drawing, there are a few things that you need to know. A computer screen is made up of thousands of tiny
dots known as pixels—by defining the color of each pixel, your program controls what displays on the screen. Of course, most
of this work is already done for you by the code that defines forms and controls.
Think of a form as a canvas upon which you can draw or paint—as with a real canvas, a form has dimensions. Where a real
canvas is measured in inches or centimeters, a form is measured in pixels. A system of coordinates determines where each
pixel is located, with the X coordinate measuring left to right and the Y coordinate measuring top to bottom.
The coordinates start at the upper-left corner of the form, so if you wanted to draw a single dot 10 pixels from the left and 10
pixels down, you would express the X and Y coordinates as 10, 10.
Pixels are also used to express the width and height of graphics. To define a square that is 100 pixels wide and 100 pixels tall,
with its upper-left corner 10 pixels from the left and 10 pixels down, you would express the coordinates as 10, 10, 100, 100.
The act of drawing on the screen is known as painting. Forms and controls have a Paint event that occurs whenever they need
to be redrawn, for example, when a form is first displayed or when it has been covered by another window. Any code that you
write to display graphics is usually contained in the Paint event handler.
Drawing a Line
To draw a line across a form, there are two things that you need to define—its coordinates and its color. As noted above, the X
and Y coordinates are expressed in pixels. For a line, there are two sets of coordinates—the starting location followed by the
ending location.
Just as you would use a pen to draw a line on a piece of paper, Visual Basic uses a Pen object to draw on the form. The Pen
object defines the appearance of the line—in this case, the color. In the following procedure, you will draw horizontal, vertical,
and diagonal lines on a form.
Try It!
To draw lines
1. On the File menu, choose New Project.
2. On the Template pane, in the New Project dialog box, click Windows Application.
3. In the Name box, type Lines and then click OK.
A new Windows Forms project opens.
4. Double-click the form to open the Code Editor, and then select Paint from the Events drop-down list.
5. In the Form1_Paint event handler, add the following code.
VB
' Draw a 400 pixel black line 25 pixels from the top of the form.
e.Graphics.DrawLine(Pens.Black, 0, 25, 400, 25)
' Draw a 500 pixel red line 100 pixels from the left of the form.
e.Graphics.DrawLine(Pens.Red, 100, 0, 100, 500)
' Draw a diagonal blue line from the upper left to the lower right.
e.Graphics.DrawLine(Pens.Blue, 0, 0, Me.Width, Me.Height)

6. Press F5 to run the program. You should see three lines on the form.
Next Steps
In this lesson, you learned the basics of graphics, as well as how to draw lines. In the next lesson, you will learn to draw shapes
such as rectangles and circles.
Next Lesson: Drawing Shapes on Your Form
See Also
Tasks
Picture This: Displaying Images
Other Resources
Drawing Pictures: Using Graphics
Visual Basic Guided Tour
Visual Basic Language Concepts

Drawing Shapes on Your Form


In this lesson, you will learn how to draw shapes such as rectangles or circles on a form.
In the previous lesson, you learned how to draw lines on a form using the DrawLine graphics method and a Pen object. In
addition to the DrawLine method, Visual Basic also has graphics methods for drawing shapes, and graphics objects known as
brushes for filling shapes.
Drawing Simple Shapes
Drawing a shape is similar to drawing a line—you need to define the coordinates and the color with which to draw. Where a
line took coordinates defining a starting and ending point, a shape such as a square or rectangle takes coordinates describing
its upper-left corner, width, and height.
Circles and ovals (also known as ellipses) do not have upper-left corners, so instead the coordinates describe the upper-left
corners of their bounding rectangles—an imaginary rectangle of the same width and height of the circle or oval.
Try It!
To draw shapes
1. On the File menu, choose New Project.
2. On the Templates pane, in the New Project dialog box, select Windows Application.
3. In the Name box, type Shapes and then click OK.
A new Windows Forms project opens.
4. Double-click the form to open the Code Editor, and then select Paint from the Events drop-down list.
5. In the Form1_Paint event handler, add the following code.
VB
' Draw a 200 by 150 pixel green rectangle.
e.Graphics.DrawRectangle(Pens.Green, 10, 10, 200, 150)
' Draw a blue square
e.Graphics.DrawRectangle(Pens.Blue, 30, 30, 150, 150)
' Draw a 150 pixel diameter red circle.
e.Graphics.DrawEllipse(Pens.Red, 0, 0, 150, 150)
' Draw a 250 by 125 pixel yellow oval.
e.Graphics.DrawEllipse(Pens.Yellow, 20, 20, 250, 125)

6. Press F5 to run the program. You should see four shapes on the form.
Keep the project open—you will add to it in the next procedure.
Drawing Filled Shapes
So far, the shapes that you have drawn are just outlines. To draw shapes with solid colors, you need to use one of the fill
methods such as FillRectangle or FillEllipse. The fill methods use a Brush object, another type of graphics object that can
paint.
When filling a shape with a different color, you will need to define coordinates that are smaller than the shape; otherwise the
border will be covered. For example, to fill a square with the coordinates 0, 0, 150, 150 you would specify a fill with the
coordinates 1, 1, 148, 148, accounting for the one pixel thickness of the line.
To draw filled shapes
1. In the Form1_Paint event handler, add the following code below the code that you entered earlier.
VB
' Fill the circle with the same color as its border.
e.Graphics.FillEllipse(Brushes.Red, 0, 0, 150, 150)
' Fill the square with a different color.
e.Graphics.FillRectangle(Brushes.Aquamarine, 31, 31, 148, 148)

2. Press F5 to run the program.


Notice that the filled square appears on top of the filled circle, but that part of its border has disappeared. The order in
which you call the graphics methods determines the order in which they are drawn—in this case, the filled circle was
drawn after the blue-border rectangle.
Try changing the order of the methods and see what happens.
Next Steps
In this lesson, you learned how to draw and fill shapes. In the next lesson, you will learn how to draw text using graphics
methods.
Next Lesson: Drawing Text on Your Form
See Also
Tasks
Making Graphics Appear
Other Resources
Drawing Pictures: Using Graphics
Visual Basic Guided Tour
Visual Basic Language Concepts

Drawing Text on Your Form


In this lesson, you will learn how to draw text on a form using graphics methods.
In an earlier lesson, you learned how to display text using a Label control. There are cases, however, when you may want or
need to draw the text yourself using graphics methods. For example, if you want text that is slanted, you can't use a Label
control—but you can use graphics methods to draw text at any angle.
Drawing Text
To draw text on a form or control, you use the DrawString graphics method. Like the other draw methods, DrawString takes
a Brush object that determines the color, and coordinates that specify where to draw the text—in this case, the X and Y
coordinates of the upper-left corner of the bounding rectangle for the text.
The DrawString method also has two additional arguments—the string that you want to draw, and the font that determines
what the text looks like. In order to specify the font, you must first create a Font object, and then use that object as an
argument to the DrawString method.
Try It!
To draw text
1. On the File menu, choose New Project.
a. In the New Project dialog box, in the Templates pane, click Windows Application.
b. In the Name box, type DrawText and then click OK.
A new Windows Forms project opens.
2. Double-click the form to open the Code Editor, and then select Paint from the Events dropdown list.
3. In the Form1_Paint event handler, add the following code.
VB
' Create a font object.
Dim aFont As New System.Drawing.Font("Arial", 22, FontStyle.Bold)
' Display the text with the DrawString method.
e.Graphics.DrawString("Graphics are fun!", aFont, Brushes.Black, _
20, 10)

4. Press F5 to run the program. You should see the text displayed on the form.
Keep the project open—you will be adding to it in the next procedure.
Drawing Rotated Text
In order to draw text at an angle, you need to use another type of graphics method called a transform. There are several types
of transforms available for different graphics effects; in this case, you will use the RotateTransform method.
The RotateTransform method takes a single argument, the angle at which to rotate the text. The transformation is performed
on the line of code following the RotateTransform method; you could also use it to rotate shapes or lines drawn using the
other draw methods.
Try It!
To draw rotated text
1. In the Form1_Paint event handler, add the following code below the code that you entered earlier.
VB
' Rotate the text 45 degrees.
e.Graphics.RotateTransform(45)
e.Graphics.DrawString("And exciting too!", aFont, Brushes.Red, _
100, 0)

2. Press F5 to run the program. You should see the rotated text displayed on the form.
Next Steps
In this lesson, you learned how to use the DrawString method to display text. In the next lesson, you will learn to display an
image using graphics methods.
Next Lesson: Drawing an Image on Your Form
See Also
Tasks
Drawing Shapes on Your Form
Other Resources
Drawing Pictures: Using Graphics
Visual Basic Guided Tour
Visual Basic Language Concepts

Drawing an Image on Your Form


In this lesson, you will learn how to display an image using graphics calls.
In an earlier lesson, you learned how to display an image using a PictureBox control. It is also possible to display an image
from a file using the graphics methods in Visual Basic. As with the previous lesson, using the graphics methods instead of a
PictureBox control is a necessity if you want to do something special, such as rotate the image.
Displaying an Image
To display an image on a form or control, use the DrawImage graphics method. The DrawImage method takes a bitmap
image as an argument, along with the X and Y coordinates defining the upper-left corner of the image.
Try It!
To display a rotated image
1. On the File menu, choose New Project.
2. On the Templates pane, in the New Project dialog box, click Windows Application.
3. In the Name box, type DrawImage and then click OK.
A new Windows Forms project opens.
4. In Solution Explorer, double-click the My Project node to open the Project Designer.
5. In the Project Designer, click the Resources tab, select Add Resource, and then select Add Existing File.
6. In the Add existing file to resources dialog box, browse to any image file and select it, and then click Open.
7. In Solution Explorer, select the Form1 node, and then on the View menu, select Code to open the Code Editor.
8. In the Code Editor, select Paint from the Events drop-down list.
9. In the Form1_Paint event handler, add the following code.
VB
e.Graphics.RotateTransform(45)
e.Graphics.DrawImage(My.Resources.picture, 50, 0)

Note
Replace picture with the name of the resource that you added in an earlier step.

10. Press F5 to run the program. You should see the rotated image on the form.
Next Steps
In this lesson, you learned how to display a rotated image on a form. That completes the lessons on graphics. In the next set of
lessons, you will learn how to share the programs you create.
Next Lesson: Distributing Your Program
See Also
Tasks
Drawing Text on Your Form
Other Resources
Drawing Pictures: Using Graphics
Visual Basic Guided Tour
Visual Basic Language Concepts

Distributing Your Program


There are several ways for you to share your program with others. Using ClickOnce publishing, you can make your program
available on a CD-ROM or DVD-ROM, or you can publish it to a Web site where others can download and run it. You can also
send it through e-mail, or simply copy it to a disk.
In This Section
Sharing Your Program: Introduction to Deployment
Distributing Your Program on CD: Publishing with ClickOnce
Related Sections
Closer Look: Including Prerequisites with Your Program
Closer Look: Distributing Your Program on the Internet
Sending Your Program through E-mail: Creating a Compressed (zipped) File
Getting a Program through E-mail: Extracting a Compressed (zipped) Program
Visual Basic Language Concepts

Sharing Your Program: Introduction to Deployment


In this lesson, you will learn about the different ways to share your programs with others.
Once you finish writing, testing and debugging, you probably want to share your masterpiece with others. The process of
making copies of your program and distributing them is known as deployment.
You might think that you can simply copy the program files to another computer and run the program. However, in many
cases, you will then find that the program does not run. This is because most programs depend on other pieces of software
known as components that must be installed on the other computer. If you try to run your program and a component is
missing, your program won't run.
ClickOnce Publishing
Visual Basic includes tools for deploying your program using a method known as ClickOnce publishing, which makes
deployment easy by automatically including and installing all of the necessary components along with your program.
ClickOnce allows you to publish your program to a CD-ROM or DVD that you can then share with others.
If you have access to a Web server, you can also use ClickOnce to publish your program to a Web site; the program can then
be downloaded over the Internet. If you later change your program, you can then publish the new version, and anyone who
downloaded your program can automatically download the new version the next time they run the program.
To publish a program using ClickOnce, you need access to a CD or DVD burner, or to a Web server. If you do not have access
to either of these, you may still be able to share your program by compressing it and copying it to a floppy disk or sending it
through e-mail.
Next Steps
In this topic, you learned about deployment and ClickOnce publishing. In the next lesson, you will learn how to publish your
program using ClickOnce.
Next Lesson: Distributing Your Program on CD: Publishing with ClickOnce
See Also
Tasks
Sending Your Program through E-mail: Creating a Compressed (zipped) File
Other Resources
Distributing Your Program
Visual Basic Language Concepts

Distributing Your Program on CD: Publishing with ClickOnce


In this lesson, you will learn how to publish your program to a CD-ROM or DVD in order to share it with others.
To share your program with others, you will first need to create a Setup program and copy it onto a CD-ROM or other media.
In addition to the program itself, the Setup program will need to include other components or files that your program needs in
order to run; these are known as prerequisites.
As you might imagine, determining exactly what prerequisites you need can be a difficult task; fortunately, the ClickOnce
publishing tools in Visual Basic do all of this and more for you. You can also use ClickOnce publishing to publish your program
on the Internet or a local network. However, in this lesson, you will be publishing your program to a CD.
Note
To publish a program to a CD-ROM or DVD, you must have the appropriate hardware and software on the computer that yo
u are using to write the program. If you can burn music CDs, you should also be able to publish to a CD. If you do not have th
is capability, you may still be able to share your program using another method—for more information, see
Sending Your Program through E-mail: Creating a Compressed (zipped) File.

Publishing with ClickOnce


Publishing your program using ClickOnce is a fairly simple process involving making a few choices in the Publish Wizard and
then burning the resulting files to a CD.
Before publishing your program, make sure that you have tested it and that it runs without any errors. Once you are ready to
publish, you can launch the Publish Wizard by choosing the Publish command on the Build menu.
The Publish Wizard consists of three steps. The first step is to select where you want the Setup program and any associated
files to be located. If you are publishing to a CD, select a folder on your local disk; you will later re-select this location to burn
the program to a CD. The second step is to specify how users will install your program—in this case, from a CD-ROM.
The final step involves specifying whether your program will automatically check for a newer version of the program each time
it starts. If you have access to a Web server, it is possible to publish updated versions of your program there as described in
Closer Look: Distributing Your Program on the Internet. In this case, however, since you are publishing to a CD, your program
will not have the ability to check for updates.
When the Publish Wizard runs, it automatically determines any prerequisites for your program. By default, prerequisites such
as the .NET Framework are not actually packaged with the setup program—during installation, the setup program checks for
the prerequisites and, if necessary, downloads and installs them from the Internet.
To include the prerequisites in the Setup program on the CD, you can set a property in the Project Designer. However, you
must first download the redistributable files for the prerequisites to your local computer. To learn more, see
Closer Look: Including Prerequisites with Your Program.
Try It!
To publish to a CD
1. On the File menu, choose Open Project.
2. In the Open Project dialog box, browse to any Windows Application project that you created in an earlier lesson, and
then click Open.
3. Press F5 to run the project. If there are any errors, you will need to fix them before continuing.
4. On the Debug menu, choose Stop Debugging.
5. On the Build menu, choose Publish Projectname, where Projectname is the name of your project.
The Publish Wizard launches.
6. On the Where do you want to publish the application? page of the Publish Wizard, enter the path where you want
to publish your program, for example, C:\My Programs. If the folder does not exist, you are prompted to create it.
Click Next to go to the next page of the wizard.
7. On the How will the users install the application? page, select From a CD-ROM or DVD-ROM, and then click Next.
8. On the Where will the application check for updates? page, select The application will not check for updates.
9. Click Finish. The program will be published to the location that you specified on the first page of the wizard.
You can now use your CD or DVD burning application to burn a CD or DVD for your program. You should include all of
the files in the folder where you published the program.
10. Take the finished CD or DVD to another computer, and then run the Setup.exe file. If any prerequisites such as the .NET
Framework need to be installed, you are prompted to download and install them.
11. Once the installation is complete, you can run the program from the shortcut located on the Start menu.
To learn how to package prerequisites with your program, keep the project open—you will use it in the lesson
Closer Look: Including Prerequisites with Your Program.
Next Steps
In this lesson, you learned how to publish a program to a CD-ROM using ClickOnce publishing. At this point, you have several
choices on where to go next.
If you have access to a Web server and want to learn how to publish your program to the Internet, see
Closer Look: Distributing Your Program on the Internet.
If you were unable to burn a CD-ROM or DVD-ROM, see
Sending Your Program through E-mail: Creating a Compressed (zipped) File.
If you want to learn how to package prerequisites with your program, see
Closer Look: Including Prerequisites with Your Program.
Otherwise, you are done with the main part of the guided tour. You can go on to the next topic for some suggestions on
resources for learning more about Visual Basic.
Next Lesson: Moving Forward: Where Do I Go From Here?
See Also
Concepts
Sharing Your Program: Introduction to Deployment
Visual Basic Language Concepts

Closer Look: Including Prerequisites with Your Program


In this lesson, you will learn how to package required components with your program using ClickOnce publishing.
By default, programs published using ClickOnce technology will download any required prerequisites from the Internet during
installation. If you try to install the program on a computer that doesn't have Internet access, the installation could fail.
To prevent this, you can package prerequisites such as the .NET Framework redistributable files along with the program.
Note
If you know that everyone who will install your program has Internet access, you should use the default method—that way, if
a newer version of the prerequisite is available, users will get the latest version.

Including Prerequisites
To include prerequisites with your program, change the Publishing property in the Project Designer. Notice that if you
include one prerequisite, you must include all prerequisites—you cannot include one prerequisite and have another
downloaded from the Internet.
Try It!
To include prerequisites
1. Open your project from the previous lesson, Distributing Your Program on CD: Publishing with ClickOnce.
2. In Solution Explorer, select the project node, and then on the Project menu, choose Properties.
The Project Designer opens.
3. In the Project Designer, click the Publish tab.
4. Click the Prerequisites button to open the Prerequisites dialog box.
5. In the Prerequisites dialog box, select the Download prerequisites from the same location as my application
check box and then click OK
6. On the Build menu, choose Publish ProjectName, where ProjectName is the name of your project.
The Publish Wizard is launched.
7. Click Finish to publish the program.
Note
You may be prompted to download the .NET Framework redistributable files if you have not already done so.

8. In Windows Explorer, browse to the location the program was published, and verify that both the Setup.exe and
Dotnetfx.exe files are there.
Next Steps
In this lesson, you learned how to publish prerequisites along with your program. At this point, you have several choices for
where to go next.
If you have access to a Web server and want to learn how to publish your program to the Internet, see
Closer Look: Distributing Your Program on the Internet.
If you were unable to burn a CD-ROM or DVD-ROM, see
Sending Your Program through E-mail: Creating a Compressed (zipped) File.
Otherwise, you are done with the lessons in the guided tour. You can go on to the next topic for some suggestions on other
resources for learning more about Visual Basic.
Next Lesson: Moving Forward: Where Do I Go From Here?
See Also
Tasks
Distributing Your Program on CD: Publishing with ClickOnce
Concepts
Sharing Your Program: Introduction to Deployment
Visual Basic Language Concepts

Closer Look: Distributing Your Program on the Internet


In this lesson, you will learn how to use ClickOnce publishing to deploy your program to a Web server.
In the previous lesson, you learned how to publish a program to a CD-ROM or DVD-ROM. If you have access to a Web server,
you can also use ClickOnce to publish your program so that it is available over the Internet.
In addition to making the program more widely available, publishing to a Web server allows you to take advantage of the
automatic update capabilities of ClickOnce. If you later publish a new version of your program, the next time a user tries to run
the program, he or she will be prompted to download and install the new version.
Note
To publish to a Web server, the Web server must be running IIS (Internet Information Services), FrontPage Extensions must b
e installed, and you must have Administrative privileges in IIS.

Publishing to a Web Server


Publishing to a Web server is very similar to publishing to a CD-ROM or DVD-ROM; you just need to make a few choices in the
Publish Wizard.
One choice is whether the program will be available offline—that is, when the computer is not connected to the Internet. If you
make the program available both online and offline, an entry is added to the Windows Start menu so that the user can launch
the program. If you make the program available only online, the program is downloaded each time a user wants to run it; it is
not added to the Start menu.
Try It!
To publish to a Web server
1. On the File menu, choose Open Project.
2. In the Open Project dialog box, browse to any Windows Application project, and then click Open.
3. Press F5 to run the project. If there are any errors, you will need to fix them before continuing.
4. On the Debug menu, choose Stop Debugging.
5. On the Build menu, choose Publish ProjectName, where ProjectName is the name of your project.
The Publish Wizard is launched.
6. On the Where do you want to publish the application? page of the Publish Wizard, enter the URL for the Web site
on which you want to publish your program, for example, http://www.microsoft.com/myprogram.
Note
To publish to a Web server, the Web server must be running IIS (Internet Information Services), FrontPage Extensions
must be installed, and you must have Administrative privileges in IIS.

Click Next to go to the next page of the wizard.


7. On the Will the application be available offline? page, select Yes, this application is available online or offline,
the default.
8. Click Finish to publish the program.
The program is published to the specified Web site, and an HTML page is created.
9. On another computer, open Internet Explorer and navigate to the same URL you entered in Step 6; then click the Install
link to install the program.
Next Steps
In this lesson, you learned how to publish a program to a Web site using ClickOnce publishing. At this point, you have several
options for what to do next.
If you were unable to burn a CD-ROM or DVD-ROM, see
Sending Your Program through E-mail: Creating a Compressed (zipped) File.
If you want to learn how to package prerequisites with your program, see
Closer Look: Including Prerequisites with Your Program.
Otherwise, you are done with the lessons in the guided tour. You can go on to the next topic for some suggestions on other
resources for learning more about Visual Basic.
Next Lesson: Moving Forward: Where Do I Go From Here?
See Also
Concepts
Sharing Your Program: Introduction to Deployment
Visual Basic Language Concepts

Sending Your Program through E-mail: Creating a Compressed


(zipped) File
In this lesson, you will learn how to package your program as a compressed (zipped) file and send it through e-mail.
Once you have finished your program, you might want to share your hard work with your friends and colleagues. Publishing
your program to a CD-ROM or DVD using ClickOnce publishing is the best way to do this. If you do not have access to a CD or
DVD burner, you may be able to distribute your program by packaging it in a compressed file and sending it through e-mail.
Note
You should never open an attachment of any kind, including a .zip file, from a sender you do not trust. Unwanted or unsolicit
ed attachments might contain viruses that can crash or hijack your computer, or steal your personal information. For similar
reasons, you should not send your application to anyone who is not expecting it.

For most simple programs, you can package the executable file (.exe) and the configuration file (.config) in a compressed file
and distribute it. For example, if you have a simple program named Calculator, you will need the Calculator.exe file and the
Calculator.exe.config file, which you can find in the your Visual Studio Projects/Calculator/Calculator/bin directory, where
your Visual Studio Projects is the directory that your Visual Studio projects are kept in, usually My Documents/Visual
Studio/Projects.
Note
All programs created with Visual Basic require the Microsoft .NET Framework version 2.0. If you distribute your program thro
ugh e-mail, make sure that the .NET Framework is already installed on the computers of any recipients.

Tip
The .NET Framework is distributed with many other programs; it can also be downloaded from the Microsoft Web site. You c
an check if the .NET Framework is installed by going to the Control Panel, opening Add or Remove Programs, and looking
for Microsoft .NET Framework version 2.0.

For more complicated programs, such as programs that include a local database, you might need to include additional files. In
this case, it is best to publish your program using ClickOnce publishing instead of sending it through e-mail.
Try It!
The following procedure shows you how to compress a file using the default Compressed (zipped) Folders feature in Windows.
If you installed a different program to work with .zip files, the steps needed to compress a file may be different.
To send a simple program through e-mail
1. Select a project that you have completed and run, and then in Windows Explorer, navigate to the project folder.
2. In the project folder, open the folder that has the name of the project, open the folder named Bin, and then select the
Debug folder.
3. Select the ProjectName.exe file (where ProjectName is the name of your project), right-click the file, and choose Send To,
Compressed (zipped) Folder.
A new file named ProjectName.zip is created and added to the directory. You can send this file as an attachment to an e-
mail message.
Next Steps
In this lesson, you learned how to package your program for sending through e-mail. In the next lesson, you will learn how to
extract and run a program that you have received.
Next Lesson: Getting a Program through E-mail: Extracting a Compressed (zipped) Program
See Also
Tasks
Distributing Your Program on CD: Publishing with ClickOnce
Concepts
Sharing Your Program: Introduction to Deployment
Other Resources
Distributing Your Program
Visual Basic Language Concepts

Getting a Program through E-mail: Extracting a Compressed


(zipped) Program
In this lesson, you will learn how to extract and run a program that you received from a friend or colleague through e-mail.
Your friends and colleagues may occasionally want to share their hard work with you. In the last lesson, you learned how to
add your program to a compressed (zipped) file so it could be sent through e-mail. In this lesson, you will learn how to open
and execute a program that you receive through e-mail.
Note
You should never open an attachment of any kind, including a .zip file from a sender you do not trust. Unwanted or unsolicite
d attachments might contain viruses that could crash or hijack your computer, or steal your personal information. By the sam
e token, you should not send your application to anyone who does not expect it.

Try It!
To extract a compressed (zipped) program
1. Navigate to the .zip file you created in the previous lesson. If you have not completed this lesson, take a moment to
complete Sending Your Program through E-mail: Creating a Compressed (zipped) File.
2. Right-click the .zip file and choose Extract All.
The Extraction Wizard opens.
3. In the wizard, click the Next button.
The Select a Destination pane displays.
4. Type the path for the folder into which you want to install the program, or click the Browse button to navigate to the
folder, and then click Next.
The files are extracted and the Extraction Complete pane displays.
5. Select the Show extracted files check box, and then click Finish.
A new Windows Explorer window opens, bringing you to the folder that you chose in the previous step.
6. Double-click the ProgramName.exe file (where ProgramName is the name of the program) to run the program.
Note
All programs created with Visual Basic require the Microsoft .NET Framework version 2.0. If you are going to distribute
your program through e-mail, make sure that the .NET Framework is already installed on the computers of any recipie
nts.

Tip
The .NET Framework is distributed with many other programs. It can also be downloaded from the Microsoft Web site.
You can check to see if the .NET Framework is installed by going to the Control Panel, opening Add or Remove Prog
rams, and looking for Microsoft .NET Framework version 2.0.

Next Steps
In this lesson, you learned how to extract and run a program that you received through e-mail from a trusted source. You also
learned that it is dangerous to execute any file from a source that you do not trust. You have now completed the basics! You
can take some time to explore Visual Basic on your own and write a few programs, or you can read suggestions for learning
more about Visual Basic.
Next Lesson: Moving Forward: Where Do I Go From Here?
See Also
Tasks
Sending Your Program through E-mail: Creating a Compressed (zipped) File
Other Resources
Distributing Your Program
Visual Basic Guided Tour
Visual Basic Language Concepts

Moving Forward: Where Do I Go From Here?


You have completed the Visual Basic Guided Tour lessons. You are not yet a Visual Basic expert, but you know enough to start
writing your own programs.
If you already have an idea for your own program, go ahead and get started. If you would first like to learn more about Visual
Basic, check out the following.
To Learn More
Increasing Productivity: Rapid Application Development
In the early days of computer programming, even a simple program could take days or even weeks to complete.
Tips and Tricks: I Didn't Know I Could Do That
In the Visual Basic Guided Tour, you learned how to do a number of things—but that was just a small sample of what you
can do with Visual Basic 2005.
Community Resources: A Little Help From My Friends
Learning to program isn't always easy—even an experienced programmer will run into problems that they can't solve by
themselves.
Tell Me More: Resources for Learning Visual Basic
After completing all of the lessons in the Visual Basic Guided Tour, you will have learned enough to begin writing you own
programs, but you certainly won't be an expert.
Stealing is Okay: Samples and Starter Kits
The only thing better than writing code is not having to write code—Visual Basic 2005 makes it easy to reuse code contained
in Help topics, sample applications, and Starter Kits.
Digging Deeper: I Want to Know More About...
The Visual Basic Guided Tour introduced you to some of the things you can do with Visual Basic Express Edition and Visual
Basic 2005, but it just barely scratched the surface. If you would like to dig deeper into an area that was covered in the tour,
this is the place to start.
See Also
Tasks
Troubleshooting Visual Basic Express
Concepts
How Do I in Visual Basic Express
Other Resources
Distributing Your Program
Visual Basic Guided Tour
Visual Basic Language Concepts

Increasing Productivity: Rapid Application Development


In the early days of computer programming, even a simple program could take days or even weeks to complete. When Visual
Basic was first introduced in 1991, it revolutionized programming—you no longer needed to write code to create a user
interface, and you no longer needed to worry about memory management. This new way of programming was known as
Rapid Application Development, or RAD.
The main benefit of RAD programming is increased productivity—Visual Basic 2005 has many features that can help you to
create better applications, faster than ever before. The following are a few of those features.
Note
If you are using Visual Basic Express Edition, some of the Help links on this page may be unavailable, depending on the optio
ns that you chose during installation. For more information, see Troubleshooting Visual Basic Express.

Code Snippets
One way to increase your productivity is to avoid writing the same code over and over again. Visual Basic 2005 includes a code
library of approximately 500 pieces of code, called IntelliSense code snippets, which are ready to be inserted into your
application. Each snippet performs a complete programming task, such as creating a file, sending an e-mail message, or
drawing a circle. You can insert a snippet into your source code with a few mouse clicks.
Once the snippet has been inserted, the parts of the code that need to be replaced are highlighted; you can enter your own
values if you like. For example, a code snippet to draw a line on a form has values for the color, location, and length of the line.
You can change these values to meet your needs, or you can do nothing and draw a line using the default values.
You can also create your own snippets that suit your own needs, add them to the library, and then use them when needed.
When creating your own snippets, you decide which parts of the code will be highlighted and what the default values are. For
more information, see Creating and Using IntelliSense Code Snippets.
One common task that can be accomplished using code snippets is reading and writing text to a file. The following procedure
shows how code snippets can make you more productive.
Try It!
To use code snippets
1. On the File menu, choose New Project.
2. In the Templates pane, in the New Project dialog box, click Windows Application.
3. In the Name box, type Snippets and then click OK.
A new Windows Forms project opens.
4. Double-click the form to open the Code Editor.
5. In the Code Editor, right-click the Form1_Load event handler, and choose Insert Snippet from the drop-down menu.
A list of snippet categories is displayed.
6. Double-click Processing Drives, Folders, and Files.
A list of code snippets is displayed.
7. Double-click Write Text to a File.
The following code will be inserted, and "C\Test.txt" and "Text" will be highlighted.

My.Computer.FileSystem.WriteAllText("C:\Test.txt", "Text", True)

Note
The WriteAllText method will create the file if it doesn't exist. If it already exists, it will add the text at the end of the file
.
8. Replace "C\Test.txt" with "C\MySnippetTest.txt", and replace "Text" with "This is really fast!".

9. Add a second snippet—right-click and choose Insert Snippet from the menu.
10. Double-click Processing Drives, Folders, and Files.
11. Double-click Read Text from a File.
The following code will be inserted, and "C\Test.txt" will be highlighted.

Dim fileContents As String


fileContents = My.Computer.FileSystem.ReadAllText("C:\Test.txt")

12. Replace "C\Test.txt" with "C\MySnippetTest.txt".


13. Add the following code below the last snippet to display the result.

MsgBox(fileContents)

14. Press F5 to run the program.


A file is created containing the text you specified, and a message box is displayed with the contents of the file.
Take some time to familiarize yourself with the code snippets included in Visual Basic 2005—they can save you a lot of time
and wasted effort when writing code. For more information, see How to: Manage Code Snippets.
Development with My
Another RAD feature introduced in Visual Basic 2005 is called My. My is a set of objects that contain commonly used functions
related to the computer, the application, the user, and so forth. You can think of My as a speed-dial to get to functions that
would otherwise require a lot of extra code.
For example, suppose that you want to determine the version number of your application. In the previous version of Visual
Basic, the code would have looked like the following.

Dim VersionNumber As String


VersionNumber = System.Diagnostics.FileVersionInfo.GetVersionInfo _ (System.Reflection.Asse
mbly.GetExecutingAssembly.Location).FileVersion

Using the new My.Application object, it looks like this.

Dim VersionNumber As String


VersionNumber = My.Application.Info.Version.ToString

As you can see, the My way is much simpler (and much easier to discover), saving you time and effort. You could still use the
other way of determining the version number, by why would you?
Although you may not have noticed, you have already used My in a number of earlier lessons. As you enter code for your next
application, explore the My objects by typing My and drilling down through the list of items that appears. For more information,
see Development with My.
IntelliSense
As you have worked through the lessons and entered code, you probably noticed that as you type, a drop down list of choices
appears in the Code Editor. This is one example of the feature known as IntelliSense.
IntelliSense provides a number of features that make language references easily accessible. When writing code, you do not
need to leave the Code Editor to get information about language elements. You can stay where you are, find the information
you need, insert language elements directly into your code, and even have IntelliSense complete your typing for you.
IntelliSense is also helpful when you are debugging. In the Code Editor, you can move the cursor over a variable in your code
to display a ToolTip with the current value of the variable. IntelliSense is also available when entering code in the Immediate
window. For more information, see Using IntelliSense.
Next Steps
In this lesson, you learned about some of the productivity features in Visual Basic 2005. There are many other features that
help to make Visual Basic 2005 the best tool for rapid application development; links to a few of them are listed below.
In the next lesson you will learn about some of the more surprising things that you can do with Visual Basic 2005.
Next Lesson: Tips and Tricks: I Didn't Know I Could Do That.
See Also
Concepts
Moving Forward: Where Do I Go From Here?
How Do I in Visual Basic Express
Other Resources
Distributing Your Program
Visual Basic Guided Tour
Visual Basic Language Concepts

Tips and Tricks: I Didn't Know I Could Do That


In the Visual Basic Guided Tour, you learned how to do a number of things—but that was just a small sample of what you can
do with Visual Basic 2005. Even so-called Visual Basic experts are constantly learning new tips and tricks. The following are just
a few of the lesser-known things that you can do.
Note
If you are using Visual Basic Express Edition, some of the Help links on this page may be unavailable, depending on the optio
ns that you chose during installation. For more information, see Troubleshooting Visual Basic Express.

Create Shaped Windows Forms


Tired of boring rectangular forms? Want to create a "skinned" look for your application, like Windows Media Player? It's easy
with Visual Basic 2005—you can create a bitmap image in the shape that you want and use it as a form, adding code so that
the form can be moved and closed. For more information, see How to: Create Nonrectangular Windows Forms.
Create Split Windows
Want to create a form like the Document Explorer you are using right now, with two or more areas that can be resized by the
user? The Windows Forms SplitContainer control allows you to do just that, without any code. Just drop a SplitContainer
control onto your form, and then add other controls on top of it; the resizing behavior is automatically available when you run
the application.
You can also add multiple SplitContainer controls to the form in order to have resizable regions within regions, allowing you
to create an application that looks like Microsoft Outlook. For more information, see SplitContainer Control (Windows Forms).
Play Sounds
If you are creating a game, you will probably want your program to make sounds in response to various events. The
My.Computer.Audio object allows you to do just that, playing wave files that you include in your application, or even playing
files directly from the Internet. For more information, see My.Computer.Audio Object.
Save User Preferences
You have probably noticed that many Windows-based applications "remember" your preferences, such as the way you like
your windows arranged, or the toolbars that were displayed the last time you used the application. You can do the same thing
in your own programs by creating and using application settings to store information and retrieve it the next time the
application is run. For more information, see Application Settings Overview.
Add Personalization
Ever wonder how Web pages remember a user's name, displaying messages like "Welcome back (insert your name here)"?
You can do something similar in your own application by using the My.User.Name Property property to get the name of the
user currently logged on to the computer. For more information, see My.User Object.
Use Visual Basic 6.0 Code
Do you have a Visual Basic 6.0 code example that you would like to use in Visual Basic 2005? The Upgrade Visual Basic 6
Code tool can convert Visual Basic 6.0 code and insert it into your Visual Basic 2005 code. If the code can't be fully translated,
comments are added with links to Help topics that explain what you need to do to make the code work. For more information,
see How to: Upgrade Visual Basic 6.0 Code with the Upgrade Visual Basic 6 Code Dialog Box.
Use Multithreading to Improve Performance
Visual Basic applications can perform multiple tasks at the same time using a technique called multithreading. Multithreading
is a process in which a task executes on a separate thread of execution, improving the performance and responsiveness of your
program.
For example, suppose you have a program that downloads a file from the Internet—the download could take a long time,
preventing the user from doing other things until the download is finished. By performing the download on a separate thread,
the user is free to do other things while the file downloads in the background. For more information, see
Multithreading in Visual Basic.
Visual Basic 2005 also has a BackgroundWorker component that makes it easy to perform a task in the background. For
more information, see Walkthrough: Implementing a Form That Uses a Background Operation.
Create XML Documentation
XML Documentation allows you to add comments to a class or user control, so that another programmer will understand how
to use them. For example, suppose your user control has a property named "Stretch"—the property name doesn't tell you what
the property actually does. XML Documentation lets you add a description like "Determines whether the text will stretch to fill
the banner"; the description will show up in the Properties window and in IntelliSense. For more information, see
Documenting Your Code with XML (Visual Basic).
Install the .NET Framework Along with Your Program
Any programs you create with Visual Basic 2005 require that the .NET Framework runtime is already installed on any computer
on which you want to run the program; some programs may require other files or prerequisites as well. If you share your
program using ClickOnce publishing, you can use a feature called bootstrapping to include these files and automatically install
them, if needed. For more information, see How to: Install Prerequisites with a ClickOnce Application.
Next Steps
In this lesson, you learned a few of the things that you can do with Visual Basic 2005. Of course, this was only a small sample—
as you go on to use Visual Basic 2005, you will discover many more things that you didn't know you could do.
In the next lesson, you will learn about ways to connect with other users of Visual Basic 2005.
Next lesson: Community Resources: A Little Help From My Friends
See Also
Tasks
Increasing Productivity: Rapid Application Development
Concepts
Moving Forward: Where Do I Go From Here?
How Do I in Visual Basic Express
Other Resources
Visual Basic Guided Tour
Visual Basic Language Concepts

Community Resources: A Little Help From My Friends


Learning to program isn't always easy—even experienced programmers run into problems that they can't solve by themselves.
Fortunately, there are several million other programmers out there that use Visual Basic, and many of them are eager to help
each other.
Note
If you are using Visual Basic Express Edition, some of the Help links on this page may be unavailable, depending on the optio
ns that you chose during installation. For more information, see Troubleshooting Visual Basic Express.

Using Forums to Exchange Information


One of the best ways to get additional help with Visual Basic is by visiting an online forum, a virtual community where users
ask and answer each other's questions. You may have noticed the Ask a Question button on the Help viewer toolbar—clicking
that button takes you to the MSDN Community Forums search page. You can enter a question and a search will be performed,
returning any previous answers related to your question.
Note
You must have an active connection to the Internet, and any proxy server or firewall must be configured to allow access to th
e MSDN Community Forums.

An individual question or answer in a forum is known as a post; a collection of posts on a single topic is known as a thread. If
you can't find a previous thread that answers your question, you can post a message to the forum with your specific question,
and then check the thread later to see if anyone has answered your question.
Some tips for using forums:
Read the Visual Basic documentation first. If a topic is covered in Help, don't expect other users to research it for you. On
the other hand, if the Help is there but you don't understand it, ask away.
Search the forum to see if the question has already been asked and answered. If you are asking a frequently asked
question, your post may be ignored.
Choose the correct forum. If you post a question about the Visual Basic language in a Windows Forms forum, you are
less likely to get an answer than if you post to the Visual Basic Language forum.
Use a descriptive title for your post. Asking "Can someone help me?" is less likely to get a response than asking "Does
anyone know how to make a user control with a transparent background?"
Phrase your question clearly. Explain what you are trying to do and what isn't working; include what you have already
tried and what the results were.
Include code where appropriate. If a particular line of code is causing an error, include enough code to make it clear what
that line is trying to accomplish. Do not, however, try to post you entire application and expect someone else to debug it
for you.
If you ask a question, try to answer someone else's question. The more you are willing to help others in the community,
the more they will be willing to help you.
Always be polite. If someone answers your question, thank them. Remember that everyone answering questions on the
forum is doing so voluntarily.
In addition to the MSDN Community Forums, there are many other forums related to Visual Basic, Windows Forms, and other
technologies. Some of these may be available by choosing Codezone Community from the Community menu in Visual
Basic 2005, or you can search online.
Try It!
To visit a forum
1. On the Community menu in Visual Basic 2005, select Ask a Question.
The MSDN Community Forums search page is displayed.
2. In the Enter Keywords field, type VB Transparent User Control, and then click Go.

Previous posts that match the keywords are displayed if any are available.
3. Review the posts to see if any of them explain how to create a transparent user control.
If none of the posts answers your question, you could post a more specific question by choosing Visual Basic General
from the Can't find the answer? list.
4. To check and see if your question has been answered, on the Community menu, choose Check Question Status.
Tip
You can also choose to be notified by e-mail, instant messenger, or even by a text message to your cell phone when a t
hread is responded to. When you enter a post or reply to a post on a forum, just click the Alert Me button.

Other Community Resources


In addition to online forums, there are many other community resources that can help you as you learn to use Visual Basic
2005.
The Start Page displayed when you start Visual Basic Express Edition contains a News section that displays links to
community events such as online chats and Webcasts that are available to everyone. These links are updated on a regular
basis.
Tip
The links on the Start Page are provided by a RSS feed; you can choose the types of links that you want to see. For more inf
ormation, see How to: Customize the News Section of the Start Page.

The Search function in Help allows you to search not only in the local Help system, but also in the MSDN Online Library and in
the Codezone community, a collection of online resources for Visual Basic. The MSDN Online Library may contain newer
versions of Help topics, as well as articles that aren't in the documentation; the Web sites that make up the Codezone
community contain helpful information from many Visual Basic experts.
Note
To access the MSDN Online Library and the Codezone community, you must have an active connection to the Internet, and a
ny proxy server or firewall must be configured to allow access. In addition, your Help settings must be configured for online
access. For more information, see How to: Include Online Content in Search and F1 Help Results.

The Visual Basic team at Microsoft is always interested in hearing from you, whether you want to suggest an improvement to
Visual Basic 2005, report a product bug, or make suggestions regarding the documentation.
The Product Feedback Center allows you to enter both product and documentation suggestions and report bugs, as well as to
see those entered by others. You can also track the progress of your suggestions and bug reports, vote on suggested features,
and much more. To access the Product Feedback Center, on the Community menu, choose Send Feedback.
The Microsoft Visual Basic Developer Center contains frequently updated articles and other information about Visual Basic. To
access the Developer Center, on the Community menu, choose Developer Center.
The CodeWise Community site is a resource for third-party tips, code samples, advice, and news from independent experts on
the Microsoft .NET Framework and Microsoft Visual Studio 2005. To access the CodeWise Community site, on the Community
menu, choose Codezone Community.
User groups are local organizations of programmers with similar interests—there are many user groups throughout the world
dedicated to Visual Basic and Visual Basic 2005. Most user groups meet on a regular basis to demonstrate coding techniques,
exchange information, and make contacts with other programmers. If you live in or near a major city, chances are there is a
Visual Basic user group near you.
Next Steps
In this lesson, you learned about some of the resources available to the world-wide Visual Basic community. In the next lesson
you will learn about resources for learning more about Visual Basic 2005.
Next lesson: Tell Me More: Resources for Learning Visual Basic.
See Also
Tasks
Tips and Tricks: I Didn't Know I Could Do That
Concepts
Moving Forward: Where Do I Go From Here?
How Do I in Visual Basic Express
Other Resources
Visual Basic Guided Tour
Visual Basic Language Concepts

Tell Me More: Resources for Learning Visual Basic


After completing all of the lessons in the Visual Basic Guided Tour you will have learned enough to begin writing you own
programs, but you certainly won't be an expert. Even seasoned Visual Basic professionals never stop learning—there is no one
person that knows everything there is to know about Visual Basic 2005. The following are some suggestions for learning more
about Visual Basic.
Note
If you are using Visual Basic Express Edition, some of the Help links on this page may be unavailable, depending on the optio
ns that you chose during installation. For more information, see Troubleshooting Visual Basic Express.

Getting Help While You Work


For many people, the best way to learn is by doing. The easiest way to get help while working in the Visual Basic Express
Edition IDE (integrated development environment) is by pressing the F1 key to display context-sensitive Help.
Pressing F1 when a window in the IDE is selected displays a Help topic that describes the window and how to use it.
Pressing F1 in design mode when a control is selected displays a Help topic about that control.
Pressing F1 in the Properties window displays Help for the selected property.
Pressing F1 in the Code Editor displays the Language Reference topic for the language keyword nearest the current
cursor location.
Try It!
To display context-sensitive Help.
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. Select the form, and in the Properties window select the KeyPreview property.
4. Press F1.
A Help topic explaining the KeyPreview property is displayed.
Tip
You may have noticed that some Help topics include syntax and code examples for languages other than Visual Basic. If
you want to show only Visual Basic syntax and code, point to Language Filter, located near the top of your Help topic;
in the drop-down list, clear the check boxes for all entries except Visual Basic (Usage). Your setting will be remember
ed until you change it again.

5. Double-click the form to open the Code Editor, and enter the following in the Form1_Load event handler.

Dim CurrentUser As String


CurrentUser = My.User.Name

6. Place the cursor inside the word Name and press F1.
A Help topic for the My.User.Name property is displayed.
7. Place the cursor inside the word User and press F1 again.
A Help topic for the My.User object is displayed.
Product Documentation
The product documentation for Visual Basic 2005 contains a wealth of information for learning Visual Basic, including
numerous "How to" topics, walkthroughs, and in-depth conceptual information, as well as reference topics for every member
of the .NET Framework. Taking some time to browse through the documentation is a good way to learn about features of
Visual Basic 2005 that you might not know about.
Depending on the choices that you made when you installed Visual Basic Express Edition, you may find that some of the topics
are not available. The Help files that are included with Visual Basic Express Edition are a limited subset of the MSDN Library for
Visual Studio 2005 Express Editions, which is, in turn, a subset of the full MSDN Online Library. During installation you had the
option of installing the MSDN Library for Visual Studio 2005 Express Editions—if you chose not to install it, you should
consider doing so now.
Additional product documentation and updated versions of topics included in the MSDN Library for Visual Studio 2005
Express Editions are available in the MSDN Online Library. To access the MSDN Online Library, on the Community menu,
choose Developer Center, and then on the Microsoft Visual Basic Developer Center home page, choose Library.
Note
To access the MSDN Online Library, you must have an active connection to the Internet, and any proxy server or firewall mus
t be configured to allow access.

Online Resources
With several million programmers world-wide using Visual Basic, it's not surprising that there are numerous online resources
for learning more about Visual Basic. An MSN search on the keyword Visual Basic returns over 49 million results; a search on
the keyword Visual Basic 2005 returns over 2 million. With that many online resources, where do you start?
The best place to start looking for online learning resources is the Microsoft Visual Basic Developer Center, available from the
Community menu. The Developer Center is constantly updated with new articles on Visual Basic, as well as links to online
books, multimedia and Webcasts, walkthroughs, and much more. Just click on the Learning Visual Basic link on the Microsoft
Visual Basic Developer Center home page.
Another good starting place is the CodeWise Community, also available from the Community menu. The CodeWise
Community site is an online resource for third-party tips, code samples, advice, and news from independent experts on Visual
Basic and Visual Basic 2005.
Members of the CodeWise Community have established expertise in Microsoft developer tools and technologies. They provide
you with a wide range of content through their online communities and opportunities to share your opinions and learn from
others.
Additional Resources
If you prefer more traditional methods of learning, there are many additional opportunities available.
There are numerous books available covering Visual Basic 2005, ranging from beginner-level books to books on specific uses
for Visual Basic 2005, such as programming games. You can browse the Computer Programming section of your local library,
bookstore, or online bookseller to see what is currently available.
Tip
Make sure that the books that you select cover Visual Basic 2005 and not an earlier version of Visual Basic. Although much of
the material written for older versions still applies, in some cases there are newer and better techniques available in Visual Ba
sic 2005.

Many colleges, universities, and technical schools offer courses covering Visual Basic 2005, some even specifically focused on
Visual Basic Express Edition. Check in your area to see what courses are available.
Next Steps
In this lesson, you learned about some of the ways to continue learning Visual Basic. In the next lesson, you will learn how to
find and use sample code.
Next Lesson: Stealing is Okay: Samples and Starter Kits.
See Also
Tasks
Community Resources: A Little Help From My Friends
Concepts
Moving Forward: Where Do I Go From Here?
How Do I in Visual Basic Express
Other Resources
Visual Basic Guided Tour
Visual Basic Language Concepts

Digging Deeper: I Want to Know More About...


The Visual Basic Guided Tour introduced you to some of the things you can do with Visual Basic Express Edition and Visual
Basic 2005, but it just barely scratched the surface. If you would like to dig deeper into an area that was covered in the tour, this
is the place to start.
Note
If you are using Visual Basic Express Edition, some of the Help links on this page may be unavailable, depending on the optio
ns that you chose during installation. For more information, see Troubleshooting Visual Basic Express.

To Learn More about the Visual Basic Language


Program Structure and Code Conventions
Contains documentation on the basic structure and code conventions of Visual Basic, such as naming conventions,
comments in code, and limitations of Visual Basic.
Visual Basic Language Features
Provides an overview of the essential components of Visual Basic.
Declared Elements in Visual Basic
Covers variables, constants, enumerations, structures, properties, methods, procedures, procedure arguments, function
returns, events, delegates, interfaces, and classes.
Procedures in Visual Basic
Describes Sub, Function, Property, and Operator procedures, as well as advanced topics such as recursive and overloaded
procedures.
Control Flow in Visual Basic
Shows how to regulate the flow of your program's execution.
Development with My
Discusses a new feature called My, which provides access to information and default object instances that are related to an
application and its run-time environment.
To Learn More about Windows Forms and Controls
Getting Started with Windows Forms
Describes in-depth how to harness the power of Windows Forms to display data, handle user input, and deploy your
applications easily and with strong security.
Enhancing Windows Forms Applications
Describes enhanced features that enable you to build world-class Windows-based applications.
Windows Applications (How Do I in Visual Basic)
This page links to help on widely used Visual Basic tasks for creating Windows-based applications.
Controls to Use on Windows Forms
An alphabetic list of controls and components that can be used on Windows Forms.
Windows Forms Controls by Function
Lists the Windows Forms controls and components according to general function.
What's New in Windows Forms and Windows Forms Controls
Lists the new and enhanced features available with this release of Visual Basic 2005.
To Learn More about Debugging and Error Handling
Debugging Your Visual Basic Application
This page provides pointers to documentation for the debugging features built into Visual Basic 2005.
How to: Correct Run-Time Errors with the Exception Assistant
The Exception Assistant, which appears whenever a run-time exception occurs in the debugger, shows the type of
exception, troubleshooting tips, and corrective actions that may be applied through the Exception Assistant.
How to: Apply Edits in Break Mode with Edit and Continue
You can use Edit and Continue to edit your code in break mode, and then continue without stopping and restarting
execution.
How to: Set a Simple Breakpoint
The Visual Studio debugger provides many ways of setting breakpoints. This topic gives two quick ways of setting simple
breakpoints.
How to: Correct Compiler Errors with Auto Correction
Shows how to correct compiler errors in the Code Editor through the Smart Compile Auto Correction feature.
Structured Exception Handling Overview for Visual Basic
Discusses and demonstrates structured exception handling in Visual Basic.
To Learn More about Databases
Accessing Data in Visual Basic Applications
Visual Basic includes several new features to assist in developing applications that access data.
Displaying Data Overview
Display data to users of your application by binding data to controls on a form. Create data-bound controls by dragging
items from the Data Sources window onto a Windows Form.
Data Sources Overview
Data sources represent the data available to your application and are displayed in the Data Sources window.
TableAdapter Overview
TableAdapters provide communication between your application and a database.
Walkthrough: Displaying Related Data on a Form in a Windows Application
Provides step-by-step details on displaying data from two related tables and displaying the data on a Windows Form.
Validating Data
Datasets provide specific events that are raised as values in data rows change. Event handlers can be created to validate
these changes based on your particular application requirements.
To Learn More about Object Oriented Programming
Introduction to Objects in Visual Basic
Provides an introduction to the terms and concepts used in object-oriented programming.
Creating and Using Objects
Shows how to create and use instances of classes.
Managing Groups of Objects
Provides techniques for working with arrays and collections of objects.
Understanding Classes
Covers object creation and lifetime issues in a step-by-step procedure.
Interfaces in Visual Basic
Describes what interfaces are and how you can use them in your applications.
Inheritance in Visual Basic
Describes how to define classes that serve as the basis for other classes.
To Learn More about User Controls and Components
Property Statement
Declares the name of a property, and the property procedures used to store and retrieve the value of the property.
Creating and Using Components in Visual Basic
Defines the term "component" and discusses how and when to create components.
How to: Work with ActiveX Controls
Demonstrates how to use existing ActiveX Controls to add features to the Visual Studio Toolbox.
Constants and Enumerations in Visual Basic
Discusses storing unchanging values for repeated use.
Enumerations Overview
Discusses storing and naming sets of related constant values.
To Learn More about Graphics
Graphics and Drawing in Windows Forms
Contains links to topics that describe and show how to use the graphics interface in Windows Forms.
Getting Started with Graphics Programming
Describes how to accomplish basic tasks with GDI+.
Using Fonts and Text
Shows how to draw text and use fonts and font families.
Using Graphics Containers
Shows how to manage graphics-object states and nested graphics containers.
Double Buffered Graphics
Demonstrates how to reduce flicker with double buffering.
Controls with Built-In Owner-Drawing Support
Owner drawing in Windows Forms, which is also known as custom drawing, is a technique for changing the visual
appearance of certain controls.
To Learn More about Deployment
ClickOnce Deployment Overview
Describes the purpose of ClickOnce and how it solves key problems in deploying Windows Forms applications to client
computers.
Choosing a ClickOnce Deployment Strategy
Describes the different ways in which you can deploy a ClickOnce application to client computers, including the benefits and
limitations of each strategy.
Choosing a ClickOnce Update Strategy
Describes the different options available for updating a ClickOnce application once it is installed, including automated update
subscriptions and on-demand updates.
Troubleshooting ClickOnce Deployments
Describes the most common problems encountered when deploying ClickOnce applications, and how to resolve them.
See Also
Tasks
Stealing is Okay: Samples and Starter Kits
Concepts
Moving Forward: Where Do I Go From Here?
How Do I in Visual Basic Express
Other Resources
Visual Basic Guided Tour
Visual Basic Language Concepts

Stealing is Okay: Samples and Starter Kits


The only thing better than writing code is not having to write code—Visual Basic 2005 makes it easy to reuse code contained in
Help topics, sample applications, and Starter Kits.
Note
If you are using Visual Basic Express Edition, some of the Help links on this page may be unavailable, depending on the optio
ns that you chose during installation. For more information, see Troubleshooting Visual Basic Express.

Copying Code
You may have noticed as you worked through the lessons that wherever there were blocks of code in the Help topics there
were also links marked Copy Code. Clicking the Copy Code link in a Help topic copies the code in that block to the Clipboard;
you can then paste it directly into the Code Editor instead of typing it.
Many Help topics contain code examples to show how you might use a particular language element, property, or function.
Although they may not match exactly what you want to do, you can copy them into your code as a starting point, and then
modify them to fit your needs by changing variable names and references.
Using Sample Applications
Visual Basic 2005 includes a number of sample applications that can give you a head start in creating your own programs.
Sample applications are complete projects that can be loaded into Visual Basic 2005 and run without modification. In most
cases they aren't very useful as programs; however, they often contain a lot of useful code.
For example, the Game sample application demonstrates a simple Windows Forms game, complete with GDI+ graphics, timer
features, user configuration, and high-score storage. If you are writing your own card game, the user interface code in the
Game sample probably won't be of much use. However, the code for storing and displaying high scores might be very useful;
you might be able to copy it and use it in your program as is.
In other cases, you might want to take the sample application and use it as a starting point, modifying and adding to it to meet
your own needs. Even if the sample doesn't do exactly what you want, it is often easier than starting from scratch. For more
information, see Visual Basic Express Sample Applications.
Starter Kits
Starter Kits are similar to sample applications, but unlike most samples, they are complete applications that can be used on
their own. For example, the My Movie Collection Starter Kit is a complete application for keeping track of your DVD movie
collection.
Like sample applications, Starter Kits can be used as a starting point for your own program. If you want to create a program for
keeping track of music files instead of movies, you can easily customize the My Movie Collection to meet your needs. Starter
Kits contain suggestions for customization, along with sample code, to help you. For more information, see
Starter Kits: Getting Up and Running Quickly.
Reusing Your Own Code
After you have been programming for a while, you will probably find that you are writing the same code over and over again.
For example, you might write code for a TextBox control to allow only numbers to be entered. Rather than writing the same
code for every program, you can write the code once and save it by dragging it to the Toolbox. The next time you need that
piece of code, you can drag it back onto the Code Editor to insert it in your code.
Tip
If you find that you are saving a lot of code to the Toolbox, you may find it difficult to find the code that you need. You can al
so save code as a Code Snippet and access it just like the Code Snippets that ship with Visual Basic 2005.

Finding Code
In addition to the code that is included in Visual Basic Express Edition, there are many other sources for obtaining code, both
from Microsoft and from third parties. You can search for code snippets, templates and starter kits, samples, and controls by
choosing Community Search on the Community menu. For more information, see How to: Search for Code Snippets Online.
You can also search Help to find topics that contain code. For more information, see How to: Find Topics with Sample Code.
Next Steps
In this lesson, you learned about several options for finding code so you don't have to write it yourself. In the next lesson, you
will find out where to get in-depth information about different features of Visual Basic Express Edition.
Next Lesson: Digging Deeper: I Want to Know More About....
See Also
Tasks
Tell Me More: Resources for Learning Visual Basic
Concepts
Moving Forward: Where Do I Go From Here?
How Do I in Visual Basic Express
Other Resources
Visual Basic Guided Tour
Visual Basic Concepts

Help for Visual Basic 6.0 Users


As a veteran developer, you have spent a lot of time and effort learning Visual Basic 6.0. At first glance, it may appear that
Visual Basic 2005 is radically different and that you will need to relearn everything. However, while many things have changed,
the overall experience of developing in Visual Basic 6.0 is essentially the same. Your knowledge of Visual Basic 6.0 will quickly
help you become productive using Visual Basic 2005.
You will need to learn about a number of changes to Visual Basic 6.0 and set aside some old habits. Some language rules, tasks
such as debugging and deployment, and even terminology have changed — often in subtle ways. Ultimately, the changes
make Visual Basic 2005 easier and more powerful.
The following topics will help you identify the changes in Visual Basic 2005.
In This Section
Integrated Development Environment for Visual Basic 6.0 Users
Changes in development environment.
Project Management for Visual Basic 6.0 Users
Changes in project system.
Web Programming for Visual Basic 6.0 Users
Changes in Web-related development.
WebClasses for Visual Basic 6.0 Users
Changes in WebClass projects (also known as IIS Application projects).
Data Access for Visual Basic 6.0 Users
Changes in data access and data tools.
Component Authoring for Visual Basic 6.0 Users
Changes in component authoring.
User Controls for Visual Basic 6.0 Users
Changes in UserControl projects (also known as ActiveX Control projects). Provides a link to information about the
PropertyBag object.
Windows Forms for Visual Basic 6.0 Users
Changes in forms.
Debugging for Visual Basic 6.0 Users
Changes in debugging.
Setup and Deployment for Visual Basic 6.0 Users
Changes in Setup and deployment.
Localization and Globalization for Visual Basic 6.0 Users
Changes in localization.
Windows API Programming for Visual Basic 6.0 Users
Changes in accessing the Windows API.
Registry Access for Visual Basic 6.0 Users
Changes in setting and retrieving registry settings.
Constant Equivalents for Visual Basic 6.0 Users
Changes in constants that have changed in Visual Basic 2005.
Object Libraries and Namespaces for Visual Basic 6.0 Users
Differences and similarities between Visual Basic 6.0 object libraries and namespaces in Visual Basic 2005.
Run Time Libraries for Visual Basic 6.0 Users
Differences between Visual Basic 6.0 run-time files and the .NET Framework common language runtime.
Related Sections
Language Changes for Visual Basic 6.0 Users
Changes in Visual Basic language.
Windows Forms Controls for Visual Basic 6.0 Users
Changes in controls.
Upgrading from Visual Basic 6.0
Converting applications to Visual Basic 2005.
What's New in Visual Basic
New features for Visual Basic 2005.
Visual Basic Concepts

What's New for Visual Basic 6.0 Users


If you are an experienced user of Visual Basic 6.0, you will find a multitude of features in Visual Basic 2005 that are new or
significantly improved, making development with Visual Basic easier and more powerful than any previous version. The
following list highlights some of the biggest changes and provides links to in-depth information.
What's New in the Visual Basic Language
Visual Basic has many new and improved language features—such as inheritance, interfaces, and overloading—that make it a
powerful object-oriented programming language. As a Visual Basic developer, you can now create true multithreaded
applications. Other new language features in Visual Basic 2005 include structured exception handling, custom attributes, and
common language specification (CLS) compliance.
Visual Basic 2005 supports many new or improved object-oriented language features such as inheritance, overloading, the
Overrides keyword, interfaces, shared members, and constructors.
For more information on what's new in the Visual Basic language, see
What's New in the Visual Basic Language for Visual Basic 6.0 Users.
For a discussion of features and functionality that have changed from earlier versions, see
Language Changes for Visual Basic 6.0 Users.
Visual Basic Development with My
Visual Basic 2005 provides new features for rapid application development that aim to improve productivity and ease of use
while delivering power. One of these features, called My, provides access to commonly used functionality provided by the .NET
Framework, as well as information and default object instances that are related to the application and its run-time
environment. This information is organized in a format that is discoverable through IntelliSense and logically delineated
according to use. For more information, see Development with My.
What's New in Forms and Controls
Windows Forms is the new object-oriented framework that implements the .NET Framework. Windows Forms, in combination
with the Windows Forms controls, provide a robust architecture for Windows-based application development in Visual Basic.
For more information on what's new in forms and controls, see What's New in Windows Forms for Visual Basic 6.0 Users.
If you are familiar with forms in Visual Basic 6.0, see Forms Tasks for Visual Basic 6.0 Users for an introduction to the new
concepts.
What's New in the Visual Basic IDE
At first glance, the Visual Basic 2005 integrated development environment may seem unfamiliar, but as you start to use it you
will find that it has many new features that make you more productive.
For more information, see What's New in the Visual Studio IDE for Visual Basic 6.0 Users.
What's New in Data
Visual Basic 2005 includes several new features to assist in developing applications that access data. The
Data Source Configuration Wizard simplifies connecting your application to data in databases, Web services, and user-created
objects. The new Data Sources Window provides a central location to view the data available to and associated with your
project, and it reduces the complexity of data binding by allowing you to drag items from the window onto forms to create
data-bound controls. Filling datasets, running queries, and executing stored procedures can now be accomplished using the
new Visual Studio-generated TableAdapter Overview object. The new local data feature allows you to include Microsoft Access
database files and Microsoft SQL Server Express database files directly into your application. For a complete list of new
features, see What's New in Data.
What's New in Setup and Deployment
Deploying applications created in Visual Basic 2005 is easier and more powerful than ever, thanks to new technologies such as
ClickOnce deployment.
ClickOnce deployment allows you to publish self-updating Windows-based and console applications that can be installed,
updated, and run as easily as Web applications. The new Security, Signing, and Publish tabs on the Project Designer allow
you to customize your ClickOnce deployment. Use the new Publish command on the Build menu (and shortcut menu in
Solution Explorer) to get to the Publish Wizard, a tool to step you through publishing your application. For more
information, see ClickOnce Deployment.
In addition, the Setup and Deployment wizard in Visual Basic 6.0 is replaced by Windows Installer-based Setup and
Deployment projects in Visual Basic 2005. For more information, see Setup and Deployment for Visual Basic 6.0 Users
Upgrading Applications Created in Visual Basic 6.0
Visual Studio 2005 provides the ability to upgrade applications created in Visual Basic 6.0 so that you can continue
development, taking advantage of the benefits of the .NET Framework. When you first open a Visual Basic 6.0 project file (.vbp),
the Upgrade Wizard appears. A command-line tool is also provided for upgrading projects outside of the development
environment. For more information, see Upgrading Applications Created in Previous Versions of Visual Basic.
See Also
Concepts
What's New in Visual Basic
Other Resources
Visual Basic Guided Tour
Visual Basic Concepts

What's New in the Visual Basic Language for Visual Basic 6.0
Users
Visual Basic 2005 has many new and improved language features—such as inheritance, interfaces, and overloading—making
it a powerful object-oriented programming language. This page highlights some of the biggest changes and provides links to
in-depth information.
Note
If you are familiar with Visual Basic 6.0, see Language Changes for Visual Basic 6.0 Users for an introduction to the new conc
epts.

Tip
For a hands-on introduction to new language features in Visual Basic 2005, see Visual Basic Guided Tour.

What's New
The following are new language features in Visual Basic 2005.
Inheritance
Visual Basic 2005 supports inheritance by allowing you to define classes that serve as the basis for derived classes. Derived
classes inherit and can extend on the properties and methods of the base class. They can also override inherited methods with
new implementations of the base class. All classes created with Visual Basic 2005 are inheritable by default. Because the forms
you design are really classes, you can use inheritance to define new forms based on existing ones. For details, see
Inheritance in Visual Basic.
Exception Handling
Visual Basic 2005 supports structured exception handling, using an enhanced version of the Try...Catch...Finally syntax
supported by other languages such as C++. Structured exception handling combines a modern control structure (similar to
Select Case or While) with exceptions, protected blocks of code, and filters. Structured exception handling makes it easy to
create and maintain programs with robust, comprehensive error handlers. For details, see Introduction to Exception Handling.
Overloading
Overloading is the ability to define properties, methods, procedures, or operators that have the same name but use different
data types. You can use overloaded procedures to provide as many implementations as necessary to handle different kinds of
data, while giving the appearance of a single, versatile procedure. For details, see Overloaded Properties and Methods.
Overriding Properties and Methods
The Overrides keyword allows derived objects to override characteristics inherited from parent objects. Overridden members
have the same arguments as the members inherited from the base class, but they have different implementations. A member's
new implementation can call the original implementation in the parent class by preceding the member name with MyBase.
For details, see Overriding Properties and Methods.
Constructors and Destructors
Constructors are procedures that control initialization of new instances of a class. Conversely, destructors are methods that free
system resources when a class leaves scope or is set to Nothing. Visual Basic 2005 supports constructors and destructors
using the Sub New and Sub Finalize procedures. For details, see Object Lifetime: How Objects Are Created and Destroyed.
Data Types
Visual Basic 2005 introduces three new data types. The Char data type is an unsigned 16-bit quantity used to store Unicode
characters. It is equivalent to the .NET Framework System.Char data type. The Short data type, a signed 16-bit integer, was
named Integer in earlier versions of Visual Basic. The Decimal data type is a 96-bit signed integer scaled by a variable power
of 10. In earlier versions of Visual Basic, it was available only within a Variant. In addition, Visual Basic now supports unsigned
integer data types (UShort, UInteger, and ULong), as well as the signed type SByte. For details, see Data Types in Visual Basic.
Interfaces
Interfaces describe the properties and methods of classes, but unlike classes, interfaces do not provide implementations. Use
the Interface statement to declare interfaces; use the Implements statement to write code that puts the items described in the
interface into practice. For details, see Interfaces in Visual Basic.
Delegates
Delegates are objects that can call the methods of objects on your behalf and are sometimes described as type-safe, object-
oriented function pointers. You can use delegates to let procedures specify an event handler method that runs when an event
occurs. You can also use delegates with multithreaded applications. For details, see Delegates and the AddressOf Operator.
Shared Members
Shared members are properties, procedures, and fields that are shared by all instances of a class. Shared data members are
useful when multiple objects need to use information that is common to all objects. You can use shared class methods without
first creating an object from a class. For details, see Shared Members in Visual Basic.
References
You can use References to use objects defined in other assemblies. In Visual Basic 2005, references point to assemblies instead
of type libraries. For details, see References and the Imports Statement.
Namespaces
Namespaces prevent naming conflicts by organizing classes, interfaces, and methods into hierarchies. For details, see
Namespaces in Visual Basic.
Assemblies
Assemblies replace and extend the capabilities of type libraries by describing all the required files for a particular component or
application. An assembly can contain one or more namespaces. For details, see Assemblies.
Attributes
You can use attributes to provide additional information about program elements. For example, you can use an attribute to
specify which methods in a class should be exposed when the class is used as a XML Web service. For details, see
Attributes in Visual Basic.
Multithreading
You can use Visual Basic 2005 to write applications that can perform multiple tasks independently. A task that can hold up
other tasks can execute on a separate thread, a process known as multithreading. By causing complicated tasks to run on
threads that are separate from your user interface, multithreading makes your applications more responsive to user input. For
details, see Multithreaded Applications.
Bit Shift Operators
Visual Basic 2005 now supports arithmetic left- and right-shift operations on integral data types (Byte, Short, Integer, and
Long) as well as on unsigned types (UShort, UInteger, and ULong). Arithmetic shifts are not circular, which means the bits
shifted off one end of the result are not reintroduced at the other end. The corresponding assignment operators are provided
as well. For details, see Bit Shift Operators and Assignment Operators.
Loop Variable Declaration
You can use Visual Basic 2005 to declare a loop variable as part of a For or For Each loop. You can include an As clause for the
variable in the For or For Each statement, provided no variable of that name has been declared outside the loop. The scope of
a loop variable declared in this manner is the loop itself. For details, see For...Next Statement (Visual Basic) and
For Each...Next Statement (Visual Basic).
What's New in the Visual Basic Language for Visual Basic 2005
In this version of Visual Studio, new language features in Visual Basic 2005 include loop continuation, guaranteed resource
disposal, mixed access properties, unsigned data types, operator overloading, generic types, and much more. For more
information, see What's New in the Visual Basic Language.
See Also
Concepts
What's New for Visual Basic 6.0 Users
What's New in Windows Forms for Visual Basic 6.0 Users
What's New in the Visual Studio IDE for Visual Basic 6.0 Users
Visual Basic Concepts

What's New in Windows Forms for Visual Basic 6.0 Users


Windows Forms is the new object-oriented framework that implements the .NET Framework. Windows Forms and the
Windows Forms controls provide a robust architecture for Windows-based application development in Visual Basic.
Note
If you are familiar with forms in Visual Basic 6.0, see Forms Tasks for Visual Basic 6.0 Users for an introduction to the new co
ncepts.

What's New
The following are all a part of client application development with Windows Forms.
Windows Forms
Windows Forms is the new platform for Microsoft Windows-based application development, based on the .NET Framework.
You can use this framework to create powerful and rich Windows-based applications using a clear, object-oriented, extensible
set of classes. For details, see Windows Forms Overview.
Windows Forms Controls
Visual Basic 2005 includes all of the controls that you are familiar with from Visual Basic 6.0, and most controls are enhanced
with new properties, methods, and events that make them more powerful. Also, there are a number of new controls and
components to create your user interface. For more information, see Controls to Use on Windows Forms.
Windows Forms as the Presentation Layer of a Three-Tier Application
Using HTTP calls to a server connected to a database, Windows Forms can act as the user interface combining the user
interface of a client application with the advanced processing of an application server. For details, see
Walkthrough: Creating a Distributed Application.
Creating a Client Application
You can use Windows Forms to create a rich client application using Visual Basic. This application can access a wide variety of
data sources and provide data-display and data-editing facilities using Windows Forms controls. For details, see
Walkthrough: Creating a Simple Windows Form.
Windows Forms Security Model
Windows Forms security is based on the security policies established within the .NET Framework. The System.Security
namespace provides the underlying structure of the .NET Framework security system, including base classes for permissions.
For details, see Windows Forms Security.
Tag and Name Properties
The Tag and Name properties are now part of the Control class. The Tag property is a repository within memory to store
data about the control. The Name property contains the name of the control. The Name property can be used at run time to
evaluate the object by name rather than by type and programmatic name. For more information about the Tag property, see
Control.Tag Property. For more information about the Name property, see Control.Name Property.
Nonrectangular Windows Forms
It is easy to customize the shape of Windows Forms. For nonrectangular forms, you just need an image file and a few property
settings. For details, see How to: Create a Shaped Windows Form.
Smart Device Programmability
You can now use Visual Basic to develop rich applications for resource-constrained devices. You can use the tools provided by
Visual Studio 2005 and the .NET Compact Framework, a subset of the .NET Framework, to create, build, and debug applications
that run on smart devices.
While almost the entire Visual Basic language is supported for device development, certain Visual Basic 2005 features were
changed or dropped to accommodate for the inherent differences in device applications. For more information, see
Differences from Desktop in .NET Compact Framework Development.
What's New in Windows Forms and Controls for Visual Studio 2005
In addition to the features listed above, there are a number of features and enhancements that are brand new in Visual Basic
2005, including several new controls, support for background operations, and custom drawing of several controls. For more
information, see What's New in Windows Forms and Windows Forms Controls.
See Also
Concepts
What's New for Visual Basic 6.0 Users
What's New in the Visual Basic Language for Visual Basic 6.0 Users
What's New in the Visual Studio IDE for Visual Basic 6.0 Users
Visual Basic Concepts

What's New in the Visual Studio IDE for Visual Basic 6.0 Users
At first glance, the Visual Basic 2005 integrated development environment (IDE) may seem unfamiliar, but as you start to use it,
you will find that it has many new features that make you more productive. This page highlights some of the biggest changes
and provides links to in-depth information.
Note
If you are familiar with Visual Basic 6.0, see Integrated Development Environment for Visual Basic 6.0 Users.

Tip
For a hands-on introduction to new features in Visual Basic 2005, see Visual Basic Guided Tour.

What's New
The following are a few of the new IDE features in Visual Basic 2005.
Shared IDE
All of the .NET languages, including Visual Basic, Visual C#, Visual C++ and more, are hosted within the Visual Studio IDE.
Sharing a single IDE provides many benefits, including consolidating similar tools from the various products into a set of
shared tools used throughout Visual Studio.
Window Management
Visual Studio makes it easier than ever to view more of your code on-screen at one time.
Tabbed documents automatically tab document windows together within the IDE. For example, when you edit multiple
documents in an editor or designer, the documents all appear in the multiple-document interface (MDI) area as tabs at the top.
Auto Hide allows you to minimize tool windows such as Solution Explorer and the Toolbox along the edges of the IDE so
that the windows do not occupy valuable space. By minimizing tool windows, you can increase the viewable space of the
editor.
For more information, see Window Management.
Editing Features
Visual Studio now has a unified Code Editor for all languages in the IDE; it includes specialized features for each language. The
Code Editor has several enhancements, such as word wrap, incremental search, code outlining, collapse to definition, line
numbering, color printing, and shortcuts. You can access these features from the Edit or context menus. For more information,
see What's New in Code Editing.
Code Snippets are segments of sample code ready to insert into Visual Basic projects. To display a list of available code
snippets, right-click the active document in the Code Editor and then click Insert Snippet on the shortcut menu. Click the
name of the snippet you want, and the code is inserted into the editor, ready for you to modify as needed. For more
information, see How to: Manage Code Snippets.
Similar to Office smart tags, Visual Studio smart tags make common tasks available that apply to the context of your work. For
example, using smart tags, you can now correct some common errors in Visual Basic with a click of a button.
Deployment
ClickOnce deployment allows you to deploy self-updating Windows-based applications that can be installed and run as easily
as Web applications. You can deploy Windows client and command-line applications. There is a new Publish Project
command on the Project menus. For more information, see ClickOnce Deployment.
You can now include required system components, such as the .NET Framework runtime, as a part of a deployment project or
ClickOnce deployment. For more information, see Deploying Prerequisites (Visual Studio).
Using Setup and Deployment projects, you can distribute applications using Microsoft Windows Installer technology, deploy
to production and staging servers, deploy tiers of your application to different test computers, and deploy ASP.NET Web
applications to Web servers. For more information, see Windows Installer Deployment.
Microsoft Build Engine
The Microsoft Build Engine (MSBuild) is the new build platform for Microsoft and Visual Studio. MSBuild introduces a new
XML-based project file format that is simple to understand, easy to extend, and fully supported by Microsoft. The MSBuild
project file format enables developers to fully describe what items need to be built, as well as how they need to be built, with
different platforms and configurations. In addition, the project file format enables developers to author re-usable rules that can
be factored into separate files so that builds can be done consistently across different projects within their product. For more
information, see MSBuild.
What's New in the Visual Studio IDE for Visual Basic 2005
In this version of Visual Studio, new IDE features in Visual Basic 2005 include predefined settings, task list and error list
enhancements, improved docking behavior, the IDE Navigator window, and much more. For more information, see
What's New in the Development Environment.
See Also
Concepts
What's New for Visual Basic 6.0 Users
What's New in the Visual Basic Language for Visual Basic 6.0 Users
What's New in Windows Forms for Visual Basic 6.0 Users
What's New in Visual Basic
Visual Basic Concepts

Events and Event Handling for Visual Basic 6.0 Users


If you are familiar with events and event handling in Visual Basic 6.0, the event model in Visual Basic 2005 may at first seem
confusing, but ultimately it is simpler and much more powerful.
Conceptual Differences
In Visual Basic 6.0, events are tied to specific objects and have their own event-handling code. For example, on a form with a
button and a menu, each has its own Click event; you have to write code in the event handler for each, even if they both
perform exactly the same function.

' Visual Basic 6.0


Private Sub HelpButton_Click()
HelpButton.Caption = "Help me!"
End Sub
Private Sub HelpMenu_Click()
HelpMenu.Caption = "Help me!"
End Sub

In Visual Basic 2005, events are tied to event handlers by means of delegates, allowing you to create a single event handler for
multiple objects.
VB
Private Sub HelpButton_Click(ByVal sender As Object, ByVal e As _
System.EventArgs) Handles HelpButton.Click, HelpMenu.Click
sender.Text = "Help me!"
End Sub

In the above example, notice that the event declaration has a Handles clause that defines which events will be handled—in this
case, the Click events for both the HelpButton and HelpMenu objects. The objects and events do not have to be of the same
type; for example you might have a single event handler that handles the Click event of a button, the DoubleClick event of a
text box, and the Tick event of a timer.
Notice also that the event declaration contains two parameters: ByVal sender As Object and ByVal e As System.EventArgs.
The first parameter, sender, provides a reference to the object that raised the event. The second parameter, e, passes an object
specific to the event that is being handled. By referencing the object's properties (and, sometimes, its methods), you can obtain
information such as the location of the mouse for mouse events, or data being transferred in drag-and-drop events.
In the following example, the MouseDown event handler uses the sender parameter to determine the type of object that
generated the event, and if the object is a PictureBox, the e parameter is used to move a label to the location where the click
took place. To duplicate this example, add two PictureBox controls and a Label control to a form.
VB
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As _
System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown, _
PictureBox1.MouseDown, PictureBox2.MouseDown
If TypeOf sender Is PictureBox Then
Label1.Location = sender.Location + e.Location
Else
MsgBox("Please click a picture")
End If
End Sub

Typically, each event produces an event handler with a different event-object type for the second parameter. Some event
handlers, such as those for the MouseDown and MouseUp events, have the same object type (MouseEventArgs) for their
second parameter. For these types of events, you can use the same event handler to handle both events.
For events that pass different event object types, you must create separate event handlers. For example, the TextChanged
event of a TextBox control passes the generic EventArgs event object, and the MouseDown event passes the more
specialized MouseEventArgs event object. The MouseEventArgs object contains properties that are specific to mouse events
such as Button, to determine which mouse button was pressed; these properties do not apply to a TextBox control and would
cause an error if you tried to reference them.
In addition to the conceptual differences in event handling, the names and behavior of some events for various objects are
different in Visual Basic 2005. For more information, see Windows Forms Controls for Visual Basic 6.0 Users.
See Also
Concepts
Event Handlers Overview (Windows Forms)
Other Resources
Creating Event Handlers in Windows Forms
Visual Basic Concepts

Integrated Development Environment for Visual Basic 6.0


Users
Visual Basic 2005 is fully integrated into the Microsoft Visual Studio 2005 integrated development environment (IDE), which
differs in several ways from the Visual Basic 6.0 IDE.
Window and Layout Changes
In Visual Basic 2005, the standard arrangement of windows is different than it was in Visual Basic 6.0. If you prefer the Visual
Basic 6.0 arrangement, you can set it by manually arranging the windows—the next time you open the IDE, your arrangement
is preserved.
In Visual Basic 6.0, the IDE is set to MDI (multiple-document interface) layout by default; you had the option to set it to SDI
(single-document interface) layout. In Visual Basic 2005, the default layout for the IDE is the Tabbed documents layout; SDI
layout is no longer supported. To change to the MDI layout, on the Tools menu choose Options, and on the Environment,
General tab, select Multiple documents.
In Visual Basic 6.0, you can control the docking behavior for some tool windows by choosing Options from the Tools menu. In
Visual Basic 2005, all windows are dockable by default; you can control their behavior with the Dockable command on the
Windows menu.
There are also some differences in the available windows between Visual Basic 6.0 and Visual Basic 2005.
Note
In Visual Basic 2005, some of the debugging windows are available only in run mode; when you switch to design mode, the
windows are hidden.

The following table shows some Visual Basic 6.0 windows and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005
Color Palette New implementation

Data View New implementation; replaced by Server Explorer

Form Layout New implementation

Project Explorer Solution Explorer

Watches Watch 1, Watch 2, Watch 3, Watch 4

Menu Changes
Menu commands in Microsoft Visual Studio 2005 are standardized for all languages; in some cases, Visual Basic 6.0 menu
commands are replaced by different commands in Microsoft Visual Studio 2005.
In Visual Basic 6.0, all menu commands are visible at all times but are dimmed when out of context; in Visual Basic 2005, the
set of available commands differs according to context.
The following table lists some common Visual Basic 6.0 commands and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005
Add-Ins, Add-In Manager Tools, Add-in Manager

Debug, Add Watch Add Watch (context menu only)

Debug, Edit Watch New implementation. Watches are edited in the Watch window.
Debug, Run To Cursor Run To Cursor (context menu only)

Debug, Set Next Statement Set Next Statement (context menu only)
Debug, Show Next Stateme Show Next Statement (context menu only)
nt

Edit, Complete Word Edit, IntelliSense, Complete Word

Edit, Find Edit, Quick Find

Edit, Find Next Edit, Quick Find

Edit, Indent Edit, Advanced, Increase Line Indent

Edit, Insert File Edit, Insert File As Text

Edit, List Constants Edit, IntelliSense, List Members

Edit, List Properties/Method Edit, IntelliSense, List Members


s

Edit, Outdent Edit, Advanced, Decrease Line Indent

Edit, Parameter Info Edit, IntelliSense, Parameter Info

Edit, Quick Info Edit, IntelliSense, Quick Info

Edit, Replace Edit, Quick Replace

File, Make ProjectName Build, Build ProjectName

File, Make Project Group Build, Build Solution

File, Print Setup File, Page Setup

File, Recent files list File, Recent Projects

File, Remove Project Edit, Remove

File, Save Project Group File, Save SolutionName or File, Save All

File, Save Project Group As File, Save SolutionName As

File, Save Selection File, Save Selected Items

Format, Size to Grid New implementation. Controlled by Snap to Grid environment option.

Help, Microsoft on the Web Community, Developer Center

Project, Add Class Module Project, Add Class

Project, Add Data Environm New implementation. Data Environment is not supported.
ent
Project, Add Data Report New implementation. Data Reports are not supported.

Project, Add DHTML Page New implementation. DHTML Pages are not supported.
Project, Add File Project, Add New Item or Project, Add Existing Item
Note In Visual Basic 6.0, the file itself is added to the project; in Visual Basic 2005 a copy of the fil
e is added.

Project, Add Form Project, Add Windows Form or Project, Add Inherited Form

Project, Add MDI Form Project, Add Windows Form or Project, Add Inherited Form

Project, Add Property Page New implementation. Property Pages are not supported.

Project, Add User Documen New implementation. ActiveX Documents are not supported.
t

Project, Add Web Class New implementation. Web Classes are not supported.

Project, Components New implementation. Components are managed in the Toolbox.

Project, References New implementation. References are managed in Solution Explorer.

Project, Remove item Edit, Delete


Note
"Remove item" removed the item from the project but not from disk; "Delete" deletes the item.

Run, Break Debug, Break All

Run, End Debug, Stop Debugging

Run, Restart Debug, Restart

Run, Start Debug, Start Debugging

Run, Start With Full Compil New implementation. You can still run without debugging by pressing CTRL+F5.
e

Tools, Add Procedure New implementation. Procedures are added in the Code Editor.

Tools, Menu Editor New implementation. The Menu Editor is replaced by the MainMenu and ContextMenu componen
ts.

Tools, Procedure Attributes New implementation.

Tools, SourceSafe File, Source Control

View, Call Stack Debug, Windows, Call Stack

View, Color Palette New implementation. There is no Color Palette window.

View, Data View Window New implementation. There is no Data View window.
View, Definition Go To Definition (context menu only)

View, Form Layout Window New implementation. There is no Form Layout window.
View, Immediate Window Debug, Windows, Immediate

View, Last Position New implementation. Use Bookmarks

View, Locals Window Debug, Windows, Locals

View, Object View, Designer

View, Project Explorer View, Solution Explorer

View, Watch Window Debug, Windows, Watch

Window, Arrange Icons New implementation.

Window, Cascade Only available in MDI layout mode.

Window, Tile Horizontally Only available in MDI layout mode.

Window, Tile Vertically Only available in MDI layout mode.

Window, Window list Windows

Keyboard Mapping Changes


Keyboard mappings in Microsoft Visual Studio 2005 are based on a settings profile that you choose the first time you load the
IDE. If you chose the Visual Basic profile, the keyboard mappings will be the same as in Visual Basic 6.0. You can change the
keyboard mappings or restore them to their original settings in the Tools, Options dialog box. For more information, see
Visual Studio Settings.
See Also
Other Resources
Customizing the Development Environment
Debugger Roadmap
Help for Visual Basic 6.0 Users
Visual Basic Concepts

Project Management for Visual Basic 6.0 Users


Projects in Visual Basic 2005 are similar to projects in Visual Basic 6.0; however, there are some differences that you should be
aware of.
In This Section
Project Behavior for Visual Basic 6.0 Users
Describes general differences in project behavior between Visual Basic 6.0 and Visual Basic 2005.
Project Properties for Visual Basic 6.0 Users
Describes project property differences between Visual Basic 6.0 and Visual Basic 2005.
Project References for Visual Basic 6.0 Users
Describes differences in reference handling between Visual Basic 6.0 and Visual Basic 2005.
Project Types for Visual Basic 6.0 Users
Describes project type differences between Visual Basic 6.0 and Visual Basic 2005.
Related Sections
Project Properties (Visual Studio)
Describes the project system for managing your applications as you write them.
Visual Basic Concepts

Project Behavior for Visual Basic 6.0 Users


Projects in Visual Basic 2005 are similar to projects in Visual Basic 6.0. However, there are some differences in behavior. This
topic discusses those differences.
Project Model
In Visual Basic 6.0, projects use a reference-based model—the project file contains references to project items, specifying their
path. For example, when you add a text file to a project, the project file points to the location of the file. When the project is
built, the text file is be loaded from that location.
Visual Basic 2005 uses a folder-based model—all project items are placed in the project folder hierarchy. When you add a text
file, a copy of the file is placed in the project folder. When the project is built, the text file is loaded from that copy of the file.
Remove Command
In Visual Basic 6.0, the Remove command removes an item from a project, but the file still remains on disk.
In Visual Basic 2005, the Remove command is replaced by a Delete command, which both removes and deletes the file. The
Exclude From Project command can be used to exclude a file from a project without deleting it.
Project Groups
In Visual Basic 6.0, multiple projects can be added in the Project Explorer; multiple projects are called Project Groups.
In Visual Basic 2005, the Solution Explorer replaces the Project Explorer; Project Groups are replaced by solutions. Where
Project Groups can contain only Visual Basic projects, solutions can contain projects created in any combination of Visual Basic
2005 languages.
Project Files
In Visual Basic 6.0, project files (.vbp) and project group files (.vbg) are text files that can be edited directly in a text editor.
In Visual Basic 2005, project and solution files are in an XML format; they should not be edited directly.
See Also
Concepts
Project Properties for Visual Basic 6.0 Users
Project Types for Visual Basic 6.0 Users
Other Resources
Project Management for Visual Basic 6.0 Users
Visual Basic Concepts

Project Properties for Visual Basic 6.0 Users


Project properties in both Visual Basic 6.0 and Visual Basic 2005 specify various global settings for a project; many of the
project properties differ between Visual Basic 6.0 and Visual Basic 2005.
Conceptual Differences
In Visual Basic 6.0, project properties are set in the Project Properties dialog box.
In Visual Basic 2005, project properties are set in the Project Designer. For more information, see
Introduction to the Project Designer.
ActiveX Component Properties
In Visual Basic 6.0, there are several properties related to ActiveX components, including Unattended Execution, Threading
Model, Require License Key, Retain in Memory, Start Mode, Remote Server, and Version Compatibility.
In Visual Basic 2005, the model for creating components is considerably different, and there are no direct equivalents for these
project properties. For more information, see Component Authoring for Visual Basic 6.0 Users.
Upgrade ActiveX Controls Property
In Visual Basic 6.0, the Upgrade ActiveX Controls project property automatically updates any ActiveX controls if you have
installed a newer version of them on your machine since the last time you opened the project.
In Visual Basic 2005, although you can use ActiveX controls, there is no equivalent for this property. The project will use the
version of the ActiveX control that you referenced when you added it to the project.
Remove information about Unused ActiveX Controls Property
In Visual Basic 6.0, the Remove information about Unused ActiveX Controls project property strips out references to
unused controls before compiling.
In Visual Basic 2005, there is no equivalent; unused controls are never compiled.
Compiler Optimizations
Although both Visual Basic 6.0 and Visual Basic 2005 support compiler optimizations, the compilers, and therefore the
available optimizations, are different. For more information, see Visual Basic Compiler.
Visual Basic 2005 compiler optimizations are set in the Advanced Compiler Settings dialog box, accessible from the
Compile tab of the Project Designer.
Project Property Equivalencies
The following list provides a comparison of Visual Basic 6.0 and Visual Basic 2005 project properties. Information on where to
find the Visual Basic 2005 project properties is indented under each property name Notice that not all properties are available
for all project types.
Visual Basic 6.0 Visual Basic 2005
Auto Increment Automatically increment revision with each publish
Publish tab of the Project Designer.

Command Line Arguments Command line arguments


Debug tab of the Project Designer.

Compile options New implementation. For more information, see Visual Basic Compiler.

Conditional Compilation Arguments Compilation Constants


Advanced Compiler Settings dialog box, accessible from the Compile tab of the
Project Designer.
DLL Base Address DLL base address
Advanced Compiler Settings dialog box, accessible from the Compile tab of the
Project Designer.

Help File Name New implementation. For more information, see


Help Support for Visual Basic 6.0 Users.

Icon Icon
Application tab of the Project Designer.

Project Description Description—Assembly Information dialog box, accessible from the Applicatio
n tab of the Project Designer.

Project Help Context ID New implementation. For more information, see


Help Support for Visual Basic 6.0 Users.

Project Name Assembly name


Application tab of the Project Designer.

Project Type Application type


Application tab of the Project Designer.

Remote Server No equivalent.

Remove information about Unused Ac No equivalent.


tiveX Controls

Require License Key No equivalent.

Retained In Memory No equivalent.

Start Mode (components) No equivalent.

Startup Object Startup form, Startup object


Application tab of the Project Designer

Threading Model No equivalent.

Title Title
Assembly Information dialog box, accessible from the Application tab of the Pr
oject Designer.

Unattended Execution No equivalent.

Upgrade ActiveX Controls No equivalent.

Version Compatibility No equivalent.

Version Information Company, Product, Copyright, Trademark


Assembly Information dialog box, accessible from the Application tab of the Pr
oject Designer.
Version Number Assembly Version
Assembly Information dialog box, accessible from the Application tab of the Pr
oject Designer.

When this project starts Start Action


Debug tab of the Project Designer

See Also
Concepts
Component Authoring for Visual Basic 6.0 Users
Other Resources
Project Properties (Visual Studio)
Project Management for Visual Basic 6.0 Users
Visual Basic Concepts

Project References for Visual Basic 6.0 Users


The methods for adding project references differ between Visual Basic 2005 and Visual Basic 6.0.
Conceptual Differences
Adding References
In Visual Basic 6.0, project references to type libraries are managed in the References dialog box. Once a reference is added,
you can access the object in code.
In Visual Basic 2005, references are made to assemblies and are added and removed in the Project Designer. References can
also be made to COM components. Project-to-project references and Web references to ASP.NET Web services are also
supported. For more information, see Managing References.
Adding Controls
In Visual Basic 6.0, controls are added to a project in the Components dialog box. Once added, they are visible in the Toolbox.
In Visual Basic 2005, controls are added to the Toolbox in the Customize Toolbox dialog box. For more information, see
How to: Add Items to the Toolbox.
See Also
Other Resources
Referencing Namespaces and Components
Project Management for Visual Basic 6.0 Users
Visual Basic Concepts

Project Types for Visual Basic 6.0 Users


The types of projects that can be created with Visual Basic 2005 differ from Visual Basic 6.0. In some cases, the project types
are essentially the same but the names have changed. In other cases, some Visual Basic 6.0 project types have no direct
equivalent.
The following list provides a comparison of Visual Basic 6.0 project types and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005
Standard EXE Windows Application

ActiveX DLL Class Library

ActiveX EXE Class Library

ActiveX Control Windows Control Library


Note
Windows Control Library projects create Windows Forms controls; the creation of ActiveX control
s is no longer supported.

ActiveX Document No equivalent. Visual Basic 2005 can interoperate with ActiveX Documents.

DHTML Application No equivalent. Use a Visual Web Developer ASP.NET Web Site Application.

IIS Application (Web No equivalent. Use a Visual Web Developer ASP.NET Web Site Application.
Class)

See Also
Concepts
Default Project Templates in Visual Studio
Web Programming for Visual Basic 6.0 Users
Other Resources
Project Management for Visual Basic 6.0 Users
Visual Basic Concepts

Language Changes for Visual Basic 6.0 Users


While earlier versions of Visual Basic are targeted for Microsoft Windows client applications, the versions beginning with
Visual Basic .NET 2002 are intended for creating XML Web service applications as well. For this purpose, Visual Basic generates
managed code for the common language runtime. This entails changes to the language itself.
The changes in Visual Basic are intended to:
Simplify the language and make it more consistent.
Add new features requested by users.
Make code easy to read and maintain.
Help programmers avoid introducing coding errors.
Make applications more robust and easier to debug.
The following topics describe language changes from previous versions of Visual Basic. For a discussion of features that are
new to the Visual Basic language, see What's New in the Visual Basic Language.
In This Section
Programming Element Support Changes Summary
Provides an alphabetical list of programming elements that have changed or are no longer supported in Visual Basic, and
includes their replacements.
Arrays for Visual Basic 6.0 Users
Provides links to topics covering changes to array bounds, size declarations, and the ReDim Statement (Visual Basic).
Data Types for Visual Basic 6.0 Users
Provides links to topics covering changes to data type declaration, usage, and conversion, including the
Integer Data Type (Visual Basic) and the universal data type.
Declaration Changes for Visual Basic 6.0 Users
Provides links to topics covering changes to declaration syntax, string length, structures, and the scope of variables inside
blocks.
Function Changes for Visual Basic 6.0 Users
Provides links to topics covering changes to the Format Function, functions related to dates and times, and functions that
include the String Data Type (Visual Basic) ($) suffix.
Miscellaneous Language Changes for Visual Basic 6.0 Users
Provides links to topics covering changes to operators and file handling.
Procedure Changes for Visual Basic 6.0 Users
Provides links to topics covering changes to parameter passing, procedure calling sequences, and procedure declarations.
Property Changes for Visual Basic 6.0 Users
Provides links to topics covering changes to default properties, property procedures, and property arguments.
Control Flow Changes for Visual Basic 6.0 Users
Provides links to topics covering changes to execution flow, and new support for structured exception handling.
Object-Oriented Programming for Visual Basic 6.0 Users
Provides links to topics covering changes to object creation, binary compatibility, and interfaces and classes.
Related Sections
What's New in the Visual Basic Language
Includes information on loop continuation, guaranteed resource disposal, mixed access properties, unsigned data types,
operator overloading, generic types, and Common Language Specification (CLS) compliance.
Help for Visual Basic 6.0 Users
Covers changes to Visual Basic that include, among others, Web functionality, projects, forms, constants, the Circle, Line, and
Pset methods, and the integrated development environment (IDE).
Visual Basic Reference
Provides a complete reference for the Visual Basic language and its run-time elements.
Visual Basic Concepts

Programming Element Support Changes Summary


Visual Basic 2005 changes the manner in which it supports various programming elements, mostly for interoperability with
the common language runtime. Many Visual Basic 6.0 elements are renamed, reclassified, or combined with other
programming elements for Visual Basic 2005. Several elements are no longer supported, because the common language
runtime (CLR) includes functionality that makes them unnecessary. For more information, see Common Language Runtime.
For additional information on changes to Visual Basic — including the integrated development environment (IDE), Web
functionality, projects, forms, constants, and the Circle, Line, and Pset methods — see Help for Visual Basic 6.0 Users.
Changed Elements
The following table lists changed programming elements and their replacements.
Visual Basic 6.0 pro Visual Basic 2005 equivalent Namespace, class, or run-time librar
gramming elemen y location
t
Abs function Abs Method System Namespace, Math Class

AscB function Asc Function Visual Basic Run-Time Library Members


, Strings module

As Any keyword phr Not supported in Visual Basic 2005. See Does not apply
ase Declaration Syntax for Visual Basic 6.0 Users.

Atn function Atan Method System Namespace, Math Class

Calendar property CurrentCulture Property System.Globalization Namespace,


CultureInfo Class

ChDir statement ChDir Function Visual Basic Run-Time Library Members


, FileSystem module

ChDrive statement ChDrive Function Visual Basic Run-Time Library Members


, FileSystem module

Chr$, ChrB, function Chr Function Visual Basic Run-Time Library Members
s , Strings module

Close statement FileClose Function Visual Basic Run-Time Library Members


, FileSystem module

Cos function Cos Method System Namespace, Math Class

Currency data type Decimal Data Type; see Visual Basic Run-Time Library Members
Data Type Changes for Visual Basic 6.0 Users , VariantType Enumeration

CVDate function DateValue Function Visual Basic Run-Time Library Members


, DateAndTime module

CVErr function Error Statement Does not apply

Date function, Date Now Property, Today Property Visual Basic Run-Time Library Members
statement , DateAndTime module
Date$ function DateString Property Visual Basic Run-Time Library Members
, DateAndTime module

Debug.Assert meth Assert, Fail methods System.Diagnostics Namespace,


od Debug Class
Debug.Print metho Write, WriteIf, WriteLine, and WriteLineIf methods System.Diagnostics Namespace,
d Debug Class

Deftype statements Not supported in Visual Basic 2005. See Does not apply
Data Type Changes for Visual Basic 6.0 Users

DeleteSetting state DeleteSetting Function Visual Basic Run-Time Library Members


ment , Interaction module

DoEvents function DoEvents Method System.Windows.Forms Namespace,


Application Class

Empty keyword Nothing Does not apply

Eqv operator = Operator; see Boolean Operator for Visual Basic 6.0 Users Does not apply

Exp function Exp Method System Namespace, Math Class

FileCopy statement FileCopy Function Visual Basic Run-Time Library Members


, FileSystem module

Get statement FileGet Function Visual Basic Run-Time Library Members


, FileSystem module

GoSub statement Not supported in Visual Basic 2005; use the Return Statement. S Does not apply
ee Control Statement for Visual Basic 6.0 Users.

Imp operator Not supported in Visual Basic 2005. See Not and Or operators, a Does not apply
nd Boolean Operator for Visual Basic 6.0 Users.

Initialize event Not supported in Visual Basic 2005; use Sub New. See Does not apply
Class_Initialize Changes for Visual Basic 6.0 Users and
Using Constructors and Destructors

Input #, Input$ stat Input Function Visual Basic Run-Time Library Members
ements, Input$, Inp , FileSystem module
utB, InputB$ functio
ns

Instancing property Not supported in Visual Basic 2005. For class-level declarations, Does not apply
see Private (Visual Basic) and Public (Visual Basic). For procedur
e-level declarations, see Shared (Visual Basic).

InStrB function InStr Function Visual Basic Run-Time Library Members


, Strings module

IsEmpty function IsNothing Function Visual Basic Run-Time Library Members


, Information module
IsMissing function Not supported in Visual Basic 2005. See Does not apply
Procedure Declaration for Visual Basic 6.0 Users.

IsNull function IsDbNull Function Visual Basic Run-Time Library Members


, Information module

IsObject function IsReference Function Visual Basic Run-Time Library Members


, Information module

Kill statement Kill Function Visual Basic Run-Time Library Members


, FileSystem module

LCase$ function LCase Function Visual Basic Run-Time Library Members


, Strings module

Left$, LeftB, LeftB$ Left Function Visual Basic Run-Time Library Members
functions , Strings module

LenB function Len Function Visual Basic Run-Time Library Members


, Strings module

Let, Set assignment Not supported in Visual Basic 2005; the new Set statement is un Does not apply
statements related to the older one. See
Default Property Changes for Visual Basic 6.0 Users.

Line Input # statem LineInput Function Visual Basic Run-Time Library Members
ent , FileSystem module

Load statement New (Visual Basic) keyword, Show method, Load event Visual Basic Run-Time Library Members
, System.Windows.Forms namespace

Lock statement Lock, Unlock Functions Visual Basic Run-Time Library Members
, FileSystem module

Log function Log Method System Namespace, Math Class

LSet, RSet statement LSet Function, PadRight, PadLeft; see Visual Basic Run-Time Library Members
s Data Type Changes for Visual Basic 6.0 Users , Strings module; and
System Namespace, String Class

LTrim$ function LTrim Function Visual Basic Run-Time Library Members


, Strings module

MidB function Mid Function Visual Basic Run-Time Library Members


, Strings module

MidB statement Mid Statement Visual Basic Run-Time Library Members


, Strings module

MkDir statement MkDir Function Visual Basic Run-Time Library Members


, FileSystem module

Name statement Rename Function Visual Basic Run-Time Library Members


, FileSystem module
Now function Now Property Visual Basic Run-Time Library Members
, DateAndTime module

Null keyword Nothing Does not apply

Oct$ function Oct Function Visual Basic Run-Time Library Members


, Conversion module

On ... GoSub constr Not supported in Visual Basic 2005; use Select...Case Statement. Does not apply
uction See Control Statement for Visual Basic 6.0 Users.

On ... GoTo construc Not supported in Visual Basic 2005; use Select...Case Statement. Does not apply
tion See Control Statement for Visual Basic 6.0 Users.

Open statement FileOpen Function Visual Basic Run-Time Library Members


, FileSystem module

Option Base statem Not supported in Visual Basic 2005. See Does not apply
ent Array Bounds for Visual Basic 6.0 Users.

Option PrivateMod Not supported in Visual Basic 2005; use Module Statement. Does not apply
ule statement

Print # statement Print, PrintLine Functions Visual Basic Run-Time Library Members
, FileSystem module

Property Get, Prop Not supported in Visual Basic 2005. See Does not apply
erty Let, Property S Property Procedure Changes for Visual Basic 6.0 Users.
et statements

Put statement FilePut Function Visual Basic Run-Time Library Members


, FileSystem module

Reset statement Reset Function Visual Basic Run-Time Library Members


, FileSystem module

Right$, RightB func Right Function Visual Basic Run-Time Library Members
tions , Strings module

RmDir statement RmDir Function Visual Basic Run-Time Library Members


, FileSystem module

Round function Round Method System Namespace, Math Class

RSet, LSet statement RSet Function; see Data Type Changes for Visual Basic 6.0 Users Visual Basic Run-Time Library Members
s , Strings module

RTrim$ function RTrim Function Visual Basic Run-Time Library Members


, Strings module

SaveSetting statem SaveSetting Function Visual Basic Run-Time Library Members


ent , Interaction module

Scale method Not supported in Visual Basic 2005 Does not apply
Set, Let assignment Not supported in Visual Basic 2005; the new Set statement is un Does not apply
statements related to the older one. See
Default Property Changes for Visual Basic 6.0 Users

SetAttr statement SetAttr Function Visual Basic Run-Time Library Members


, FileSystem module

Sgn function Sign Function System Namespace, Math Class

Sin function Sin Method System Namespace, Math Class

Sqr function Sqrt Function System Namespace, Math Class

String function String Constructor; see System Namespace, String Class


String ($) Function for Visual Basic 6.0 Users

String ($) functions Not supported in Visual Basic 2005. See Does not apply
String ($) Function for Visual Basic 6.0 Users.

Terminate event Not supported in Visual Basic 2005; use Sub Dispose and Sub Does not apply
Finalize. See Using Constructors and Destructors.

Time function, Time TimeOfDay Property; see DateTime Structure, Date Data Type Visual Basic Run-Time Library Members
statement , DateAndTime module

Time$ function TimeString Property Visual Basic Run-Time Library Members


, DateAndTime module

Timer function Timer Property Visual Basic Run-Time Library Members


, DateAndTime module

Trim$ function LTrim, RTrim, and Trim Functions Visual Basic Run-Time Library Members
, Strings module

Type statement Not supported in Visual Basic 2005; use Structure Statement. Se Does not apply
e Structure Declaration for Visual Basic 6.0 Users.

UCase$ function UCase Function Visual Basic Run-Time Library Members


, Strings module

Unlock statement Lock, Unlock Functions Visual Basic Run-Time Library Members
, FileSystem module

Variant data type Object Data Type; see Does not apply
Universal Data Type Changes for Visual Basic 6.0 Users

Wend keyword While...End While Statements and End Statement; see Does not apply
Control Statement for Visual Basic 6.0 Users

Width # statement FileWidth Function Visual Basic Run-Time Library Members


, FileSystem module

Write # statement Write, WriteLine Functions Visual Basic Run-Time Library Members
, FileSystem module
See Also
Other Resources
Language Changes for Visual Basic 6.0 Users
Help for Visual Basic 6.0 Users
Common Language Runtime
Visual Basic Concepts

Arrays for Visual Basic 6.0 Users


The following topics describe changes to arrays between Visual Basic 6.0 and Visual Basic 2005.
In This Section
Array Bounds for Visual Basic 6.0 Users
Discusses changes to array bounds and default bounds.
Array Size Declaration for Visual Basic 6.0 Users
Describes changes to the specification of array sizes.
ReDim Statement for Visual Basic 6.0 Users
Discusses changes to declarations that include the ReDim statement.
Related Sections
Programming Element Support Changes Summary
Provides an alphabetical list of programming elements that have changed or are no longer supported in Visual Basic 2005,
and includes their replacements.
Language Changes for Visual Basic 6.0 Users
Provides an overview of new and changed features in Visual Basic 2005.
Visual Basic Concepts

Array Bounds for Visual Basic 6.0 Users


Visual Basic 2005 updates the declaration of array bounds to provide interoperability with arrays in other programming
languages.
Visual Basic 6.0
In Visual Basic 6.0, the default lower bound of every dimension of an array is 0. You can change this to 1 with the Option Base
statement. You can also override the default lower bound in individual array declarations.
If you leave the default at 0, the number of elements in the array is equal to the upper bound plus one. The following
declaration reserves 21 elements for the array Weight:
VB
Dim Weight(20) As Single

Visual Basic 2005


In Visual Basic 2005, the lower bound of every array dimension is 0, and you cannot declare it to be otherwise. The Option
Base statement is not supported.
The number you specify for each dimension in the declaration is the upper bound, and the initial element count is equal to the
upper bound plus one. The declaration in the preceding example reserves 21 elements for Weight, with indexes 0 through 20.
You can also specify a zero-length array, which does not contain any elements, by declaring one of its upper bounds to be –1.
See Also
Reference
Dim Statement (Visual Basic)
UBound Function (Visual Basic)
Concepts
Declaration Syntax for Visual Basic 6.0 Users
Array Size Declaration for Visual Basic 6.0 Users
Programming Element Support Changes Summary
Other Resources
Arrays in Visual Basic
Visual Basic Concepts

Array Size Declaration for Visual Basic 6.0 Users


Visual Basic 2005 updates array size declaration for interoperability with the common language runtime.
Visual Basic 6.0
In Visual Basic 6.0, you can specify the size of an array in its declaration, as in the following example:
Dim Month(0 To 11) As Integer

This causes the array to have a fixed size, which you cannot change with the ReDim statement.
Visual Basic 2005
In Visual Basic 2005, an array does not have a permanent size. The preceding example can be rewritten as either of the
following declarations:
VB
Dim Month(11) As Integer ' Reserves 12 elements -- (0) through (11).

VB
Dim Month() As Integer = New Integer(11) {}

These declarations are equivalent. Each specifies an initial size, which you can change during execution with the ReDim
statement. To initialize the elements, you can use the following syntax:
VB
Dim Month() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

If you specify –1 for one of the dimensions, the array does not contain any elements. A ReDim statement can change an array
back and forth between empty and nonempty.
Number of Dimensions
Although an array's size can change in Visual Basic 2005, the number of dimensions must be fixed. The following example
declares a three-dimensional array:
VB
Dim Point(,,) As Double

The ReDim statement can set or change the size of each dimension, but the array always remains three-dimensional.
See Also
Reference
Dim Statement (Visual Basic)
New (Visual Basic)
ReDim Statement (Visual Basic)
Concepts
Programming Element Support Changes Summary
Other Resources
Arrays in Visual Basic
Visual Basic Concepts

ReDim Statement for Visual Basic 6.0 Users


Visual Basic 2005 updates declaration with the ReDim statement for simplification and improved readability.
Visual Basic 6.0
In Visual Basic 6.0, you can use the ReDim statement to serve as the initial declaration of a dynamic array. The array does not
have to be declared anywhere else.
Visual Basic 6.0 also allows you to change the rank of an array with ReDim, as in the following example:

Dim X(10) As Single


ReDim X(10, 10)

Visual Basic 2005


In Visual Basic 2005, you cannot use ReDim as a declaration. You must declare an array just like any other variable, using Dim
or an equivalent statement, before it can appear in a ReDim statement.
You cannot change the rank of an array in Visual Basic 2005. The code in the preceding example causes an error.
See Also
Reference
ReDim Statement (Visual Basic)
Dim Statement (Visual Basic)
Concepts
Programming Element Support Changes Summary
Visual Basic Concepts

Data Types for Visual Basic 6.0 Users


The following topics describe changes to data types between Visual Basic 6.0 and Visual Basic 2005.
In This Section
Data Type Changes for Visual Basic 6.0 Users
Describes data type declaration, usage, and conversion.
Integer Data Type for Visual Basic 6.0 Users
Covers integer data type updates.
Universal Data Type Changes for Visual Basic 6.0 Users
Covers universal data type updates.
Related Sections
Programming Element Support Changes Summary
Provides an alphabetical list of programming elements that have changed or are no longer supported in Visual Basic 2005,
and includes their replacements.
Language Changes for Visual Basic 6.0 Users
Provides an overview of new and changed features in Visual Basic 2005.
Visual Basic Concepts

Data Type Changes for Visual Basic 6.0 Users


Visual Basic 2005 updates data types for interoperability with other programming languages and the common language
runtime. The changes affect data type declaration, usage, and conversion.
Visual Basic 6.0
In Visual Basic 6.0, you use the Deftype statements — DefBool, DefByte, DefCur, DefDate, DefDbl, DefDec, DefInt,
DefLng, DefObj, DefSng, DefStr, and DefVar — to set a variable's default type.
Use the Currency data type for calculations involving money and for fixed-point calculations.
A Date is stored in a Double format using eight bytes.
If two Variant variables containing integers are multiplied, an overflow condition causes the data type of the result to be
changed to Double.
Use the LSet and RSet statements to copy a variable of one user-defined type to another variable of a different user-defined
type.
Visual Basic 2005
The Deftype statements are not supported in Visual Basic 2005. The Currency data type also is not supported. Instead, use the
new Decimal data type, which can handle more digits on both sides of the decimal point, for all money variables and
calculations. Decimal is also directly supported by the common language runtime.
In Visual Basic 2005, the Date data type uses the common language runtime DateTime data type, which is an eight-byte
integer value. Because of these different representations, there is no implicit conversion between the Date and Double data
types. To convert between Double and the Visual Basic 6.0 representation of Date, use the ToOADate and FromOADate
methods of the DateTime structure in the System namespace.
If multiplication of two Object variables containing integers results in an overflow, the result is changed to the 64-bit Long
data type.
You cannot use LSet and RSet to assign one data type to another. Doing this requires a type-unsafe operation, particularly
with structures, which could result in unverifiable code.
See Also
Reference
Decimal Data Type (Visual Basic)
Date Data Type (Visual Basic)
Val Function
Type Conversion Functions
Data Type Summary (Visual Basic)
Double Data Type (Visual Basic)
Long Data Type (Visual Basic)
DateTime
TimeSpan
Concepts
Programming Element Support Changes Summary
Visual Basic Concepts

Integer Data Type for Visual Basic 6.0 Users


Visual Basic updates the integer data types for interoperability with other programming languages and with the common
language runtime.
The following table shows correspondences between integer types in Visual Basic 6.0 and Visual Basic 2005.
Integer siz Visual Basic 6.0 type and identifier t Visual Basic 2005 type and identifier t Common language runtime
e ype character ype character (CLR) type
8 bits, signe (none) SByte (none) System.SByte
d

8 bits, unsig Byte (none) Byte (none) System.Byte


ned

16 bits, sign Integer (%) Short (none) System.Int16


ed

16 bits, unsi (none) UShort (none) System.UInt16


gned

32 bits, sign Long (&) Integer (%) System.Int32


ed

32 bits, unsi (none) UInteger (none) System.UInt32


gned

64 bits, sign (none) Long (&) System.Int64


ed

64 bits, unsi (none) ULong (none) System.UInt64


gned

On 32-bit systems, 32-bit integer operations are faster than either 16-bit or 64-bit integer operations. This means that in Visual
Basic 2005, Integer and UInteger are the most efficient and fundamental numeric types. You can improve performance in
your applications by changing your Long declarations to Integer when you migrate to Visual Basic 2005.
Note
If you are interfacing with components created on platforms other than Visual Basic 2005, you must take care that your data
types correspond to those of the other components. For example, if you use a Declare statement to refer to an external proc
edure created in Visual Basic 6.0, and the procedure defines an Integer argument (two bytes in Visual Basic 6.0), you must id
entify that argument as Short in the Declare statement, because that is the two-byte integer type in Visual Basic 2005.

See Also
Reference
Data Type Summary (Visual Basic)
Declare Statement
Concepts
Type Characters
Programming Element Support Changes Summary
Visual Basic Concepts

Universal Data Type Changes for Visual Basic 6.0 Users


Visual Basic 2005 updates the universal data type for interoperability with the common language runtime.
Visual Basic 6.0
In Visual Basic 6.0, Variant serves as the universal data type. This means that you can store data of any type in a variable of
type Variant.
Visual Basic 2005
In Visual Basic 2005, Object is the universal data type. A variable of type Object can hold data of any type. The Variant type is
not supported, and all its functionality is supplied by Object.
Variant is still a reserved word in Visual Basic 2005, even though it has no syntactical use. This helps avoid confusion with its
former meanings.
The VarType function returns a member of the VariantType enumeration that provides the data type classification of an
object variable. You can also use classes in the System namespace to obtain numeric data type information for an Object
instance, as shown in the following code:
VB
' Visual Basic 2005
Dim SomeObj As New Object
' ... ... ... ... SomeObj is assigned some value during processing.
' ... ... ... ... Now we want to find out the data type of SomeObj.
Dim Dtype As Integer ' To hold numeric data type result.
Dtype = Type.GetTypeCode(SomeObj.GetType())

See Also
Reference
Object Data Type
VarType Function (Visual Basic)
VariantType Enumeration
System
Object
Type
Concepts
Data Types in Visual Basic
Value Types and Reference Types
Programming Element Support Changes Summary
Visual Basic Concepts

Declaration Changes for Visual Basic 6.0 Users


The following topics describe changes to declarations between Visual Basic 6.0 and Visual Basic 2005.
In This Section
Declaration Syntax for Visual Basic 6.0 Users
Describes multiple variable declaration and return type declaration.
String Length Declaration for Visual Basic 6.0 Users
Discusses the specification of string length.
Structure Declaration for Visual Basic 6.0 Users
Discusses structures, also known as user-defined types (UDTs).
Variable Scope for Visual Basic 6.0 Users
Discusses the scope of variables inside a block.
Related Sections
Programming Element Support Changes Summary
Provides an alphabetical list of programming elements that have changed or are no longer supported in Visual Basic 2005,
and includes their replacements.
Language Changes for Visual Basic 6.0 Users
Provides an overview of new and changed features in Visual Basic 2005.
Visual Basic Concepts

Declaration Syntax for Visual Basic 6.0 Users


Visual Basic 2005 introduces several changes related to the declaration of programming elements.
Multiple Variable Declaration
Visual Basic 2005 revises simultaneous declaration of several variables for simplification.
Visual Basic 6.0
In Visual Basic 6.0, you can declare variables of different types in the same statement, but you must specify the data type of
each variable or it defaults to Variant. The following example shows multiple declarations and their resulting data types:

Dim I, J As Integer ' I is Variant, J is Integer.


Dim L As Integer, M As Integer ' L is Integer, M is Integer.
Dim N As Integer, X As Double ' N is Integer, X is Double.

Visual Basic 2005


In Visual Basic 2005, you can declare multiple variables of the same data type without having to repeat the type keyword. The
declarations equivalent to those in the preceding example are as follows:
VB
Dim I ' I is Object.
Dim J As Integer ' J is Integer.

Or
VB
Dim I As Object, J As Integer ' I is Object, J is Integer.
Dim L, M As Integer ' L is Integer, M is Integer.
Dim N As Integer, X As Double ' N is Integer, X is Double.

External Procedure Declaration


Visual Basic 6.0
In Visual Basic 6.0, when you declare a reference to an external procedure with the Declare statement, you can specify As Any
for the data type of any of the arguments and the return type. The As Any keywords disable type checking and allow any data
type to be passed in or returned.
Visual Basic 2005
Visual Basic 2005 does not support the Any keyword. In a Declare statement, you must specifically declare the data type of
every argument and the return if Option Strict is On. This improves type safety. You can overload your procedure declaration
to accommodate various argument data types. You cannot overload only on return types, but you can use the argument type
overloads to vary the return type, or you can turn Option Strict Off.
Line Label Declaration
Visual Basic 6.0
In Visual Basic 6.0, a line number can directly precede a statement on the same line, without any separating character.
Visual Basic 2005
Visual Basic 2005 requires that every line label be followed by a colon (:). A statement can optionally follow the colon on the
same line, or the line label and colon can stand alone on the line.
See Also
Reference
Declare Statement
Option Strict Statement
Concepts
Universal Data Type Changes for Visual Basic 6.0 Users
Procedure Calling Sequence for Visual Basic 6.0 Users
Data Types in Visual Basic
Programming Element Support Changes Summary
Visual Basic Concepts

String Length Declaration for Visual Basic 6.0 Users


Visual Basic 2005 updates string length declaration for interoperability with the common language runtime.
Visual Basic 6.0
In Visual Basic 6.0, you can specify the length of a string in its declaration. This causes the string to have a fixed length, as in the
following example:

Dim Name As String * 30

Visual Basic 2005


In Visual Basic 2005, you cannot declare a string to have a fixed length unless you use the VBFixedStringAttribute Class
attribute in the declaration. The code in the preceding example causes an error.
You declare a string without a length. When your code assigns a value to the string, the length of the value determines the
length of the string, as in the following example:
VB
Dim Name As String
' ...
Name = "Name is now 30 characters long" ' Length can be changed later.

See Also
Reference
String Data Type (Visual Basic)
Dim Statement (Visual Basic)
Concepts
Attributes Used in Visual Basic
Programming Element Support Changes Summary
Visual Basic Concepts

Structure Declaration for Visual Basic 6.0 Users


Visual Basic considers structures and user-defined types (UDTs) to be the same type of programming element. Visual Basic
2005 updates structure declaration for unification and improved readability.
Visual Basic 6.0
In Visual Basic 6.0, you declare a structure using the Type ... End Type construction. The structure and its members all default
to public access. Explicit access declaration is optional. The following example shows a valid structure declaration:
Type Employee

EmpNumber As Integer ' Defaults to Public access.


EmpOfficePhone As String
EmpHomePhone As String ' Cannot be declared Private inside Type.
End Type

Visual Basic 2005


In Visual Basic 2005, the Type statement is not supported. You must declare structures using the Structure statement as part
of a Structure ... End Structure construction. Every member of a structure must have an access modifier, which can be
Public, Friend, or Private. You can also use the Dim statement, which defaults to public access. The structure in the preceding
example can be declared as follows:
VB
Structure Employee
Public EmpNumber As Integer 'Must declare access, even if Public.
Dim EmpOfficePhone As String 'Still defaults to Public access.
Private EmpHomePhone As String 'Can be made Private inside Structure.
End Structure

Visual Basic 2005 unifies the syntax for structures and classes. Structures support most of the features of classes, including
methods.
See Also
Reference
Structure Statement
Dim Statement (Visual Basic)
Public (Visual Basic)
Private (Visual Basic)
Concepts
Programming Element Support Changes Summary
Visual Basic Concepts

Variable Scope for Visual Basic 6.0 Users


Visual Basic 2005 updates local variable scope to support block scope and improve structured programming.
Visual Basic 6.0
In Visual Basic 6.0, any variable declared inside a procedure has procedure scope, so it can be accessed anywhere else within
the same procedure. If the variable is declared inside a block — that is, a set of statements terminated by an End, Loop, or
Next statement — the variable is still accessible outside the block.
The following example illustrates procedure scope, where the block is a For loop:
For I = 1 To 10
Dim N As Long = 0
' N has procedure scope although it was declared within a block.
N = N + Incr(I)
Next I
W = Base ^ N
' N is still visible outside the block it is declared in.

Visual Basic 2005


In Visual Basic 2005, a variable declared inside a block has block scope, and it is not accessible outside the block. The preceding
example can be rewritten as follows:
VB
Dim N As Long = 0
' N is declared outside the block and has procedure scope.
For I As Integer = 1 To 10
' I is declared by the For statement and therefore within the block.
N = N + Incr(I)
Next I
w = Base ^ N
' N is visible outside the block but I is not.

Because the For statement declares I as part of the For block, I has block scope only.
However, a variable's lifetime is still that of the entire procedure. This is true whether the variable has block scope or procedure
scope. If you declare a variable inside a block, and if you enter that block several times during the lifetime of the procedure, you
should initialize the variable to avoid unexpected values.
See Also
Concepts
Programming Element Support Changes Summary
Visual Basic Concepts

Function Changes for Visual Basic 6.0 Users


The following topics describe changes to functions between Visual Basic 6.0 and Visual Basic 2005.
In This Section
Format Function for Visual Basic 6.0 Users
Discusses date/time, numeric, and string format changes to the Format function.
Date and Time for Visual Basic 6.0 Users
Discusses changes to the Date, Date$, Time, and Time$ functions.
String ($) Function for Visual Basic 6.0 Users
Discusses functions that include the String ($) suffix.
Related Sections
Programming Element Support Changes Summary
Provides an alphabetical list of programming elements that have changed or are no longer supported in Visual Basic 2005,
and includes their replacements.
Language Changes for Visual Basic 6.0 Users
Provides an overview of new and changed features in Visual Basic 2005.
Visual Basic Concepts

Format Function for Visual Basic 6.0 Users


The Visual Basic 2005 Format function now follows the common language runtime (CLR) specification for formatting data. For
more information on data formatting in the .NET Framework, see Formatting Types.
The following sections detail the changes Visual Basic 2005 makes to the user-defined date/time, numeric, and string formats.
User-Defined Date/Time Formats
Visual Basic 6.0
In Visual Basic 6.0, to display a short or long date, you use either the "ddddd" or "dddddd" format specifier. The DayOfWeek
("w") and WeekOfYear ("ww") specifiers display the day considered to be the first day of the week, and the week considered to
be the first week of the year. The lowercase "m" character displays the month as a number without a leading zero. The Quarter
specifier ("q") displays the quarter of the year as a number from 1 to 4.
To display a minute as a number with or without leading zeros, you use either the "Nn" or the "N" format specifier. The
characters "Hh" display the hour as a number with leading zeros, and "ttttt" displays the time as a complete time. To display
either an uppercase or lowercase "A" or "P" with any hour before or after noon, you use either "AM/PM", "am/pm", "A/P", "a/p",
or "AMPM."
The short date/time specifier ("c") displays a date and time in the "ddddd ttttt" format.
Visual Basic 2005
In Visual Basic 2005, "ddddd" and "dddddd" behave the same as "dddd", displaying the full name of the day. They do not
display the short date and long date. DayOfWeek ("w") and WeekOfYear ("ww") are not supported. Instead, you can use the
DatePart function, as the following example shows.
VB
Format(DatePart(DateInterval.Weekday, Now))
... Format(DatePart(DateInterval.WeekOfYear, Now))

"M" and "m" mean different things, so they are case sensitive. Use uppercase "M" only for the month in the date portion of a
date/time format, and lowercase "m" only for the minutes in the time portion.
The Quarter format specifier is not supported. Instead, you can use the DatePart function, as the following example shows.
VB
Format(DatePart(DateInterval.Quarter, Now))

To display the minute as a number with or without leading zeros, use "mm" or "m", respectively. The "ttttt" format is no longer
supported. "H" and "h" mean different things, so they are case sensitive. Use uppercase "H" only for a 24-hour clock, and
lowercase "h" only for a 12-hour clock. The AM/PM formats are replaced with "t" and "tt."
The "c" specifier is used for currency formatting. For date/time formatting, use "g" for the short date/time specifier and "G" for
the general date/time specifier. Both "g" and "G" use your current locale setting to determine the appropriate date and time
formats.
User-Defined Numeric Formats
Visual Basic 6.0
In Visual Basic 6.0, the Format function converts strings to numbers if necessary before formatting them. Format displays a
trailing decimal point if there is no fractional part.
Visual Basic 6.0 supports four sections in the formatting string. These are separated by semicolons (;) and specify how to
format positive, negative, zero, and null values, respectively. Negative numbers with an empty negative section of the format
string display an empty string.
Scientific notation formatting supports both the "0" and "#" digit placeholders following the exponent.
Visual Basic 2005
In Visual Basic 2005, the Format function does not convert strings to numbers before formatting. You must pass a number in
the first argument, not a string. In the following example, the first line of code does not produce the intended result in Visual
Basic 2005, while the second one does.
VB
MsgBox(Format("1.234", "#.#")) ' Displays "#.#".
... MsgBox(Format(CSng("1.234"), "#.#")) ' Displays "1.2".

Trailing decimal points are not displayed, as the following example shows.
VB
MsgBox(Format(123, "###.")) ' Displays "123"
... MsgBox(Format(123, "###.#")) ' Displays "123"

Visual Basic 2005 supports three sections in the formatting string, for formatting of positive, negative, and zero values. If a
non-zero value rounds to zero according to the first or second format section, it is formatted according to the third section.
Negative numbers with an empty negative section of the format string display a minus sign, as the following example shows.
VB
MsgBox(Format(-1, ";")) ' Displays "-".

Scientific notation formatting supports only the "0" digit placeholder and not "#". In the following example, the first line of code
does not produce the intended result in Visual Basic 2005, while the second one does.
VB
MsgBox(Format(123, "#e+#")) ' Displays "12e+3".
... MsgBox(Format(123, "#e+0")) ' Displays "1e+2".

String Format
Visual Basic 6.0
In Visual Basic 6.0, you can create expressions for user-defined format strings with the @, &, <, >, and ! specifiers.
Visual Basic 2005
Visual Basic 2005 eliminates expression support for user-defined format strings, so the @, &, <, >, and ! format specifiers have
no meaning and are no longer supported.
See Also
Reference
Format Function
DatePart Function (Visual Basic)
Concepts
Date and Time for Visual Basic 6.0 Users
Programming Element Support Changes Summary
Visual Basic Concepts

Date and Time for Visual Basic 6.0 Users


Visual Basic 2005 updates the Date, Date$, Time, and Time$ functions, and replaces the Now and Timer functions with
properties.
Visual Basic 6.0
In Visual Basic 6.0, the Date and Time functions return the system date and time in the four-byte Date format. Similarly, the
Date and Time statements use the Visual Basic 6.0 format to set the system date and time.
The Date$ and Time$ functions return the system date and time in String format.
The Now and Timer functions specify the current date and time and the number of seconds elapsed since midnight.
Visual Basic 2005
Visual Basic 2005 replaces Date and Time with the Today and TimeOfDay properties, which use the eight-byte common
language runtime (CLR) DateTime structure. This corresponds with the Date data type in Visual Basic 2005. You can use
Today and TimeOfDay to both set and fetch the system date and time.
Visual Basic 2005 replaces the Date$ and Time$ functions with the DateString and TimeString properties. You can use
DateString and TimeString to both set and fetch the system date and time.
The Now and Timer functions are replaced by read-only properties of the same names. Their calling sequences remain
unchanged.
See Also
Reference
Format Function
Today Property
TimeOfDay Property
Date Data Type (Visual Basic)
DateString Property
TimeString Property
Now Property
Timer Property
Concepts
Format Function for Visual Basic 6.0 Users
Programming Element Support Changes Summary
Visual Basic Concepts

String ($) Function for Visual Basic 6.0 Users


Visual Basic 2005 eliminates the need for some functions to have both a String version and a Variant version.
Visual Basic 6.0
In Visual Basic 6.0, some functions have two versions, one that returns a String value and one that returns a Variant value.
These function pairs are differentiated by a dollar sign ($) suffix for the String version; for example, Chr and Chr$.
Visual Basic 2005
Visual Basic 2005 replaces each function pair with a single function. The Variant versions are discontinued, and you can call
the String versions either with or without the $ suffix.
Although only Trim is defined, Visual Basic 2005 accepts Trim$ because the $ works as an identifier type character for the
String data type.
See Also
Reference
Trim, LTrim, and RTrim Functions
Concepts
Format Function for Visual Basic 6.0 Users
Date and Time for Visual Basic 6.0 Users
Programming Element Support Changes Summary
Visual Basic Concepts

Miscellaneous Language Changes for Visual Basic 6.0 Users


The following topics describe changes to operators and file handling between Visual Basic 6.0 and Visual Basic 2005.
In This Section
Boolean Operator for Visual Basic 6.0 Users
Describes Boolean operators and logical expressions.
File Handling for Visual Basic 6.0 Users
Discusses expansion of file handling capabilities, and compatibility with previous versions of Visual Basic file I/O functions.
Related Sections
Programming Element Support Changes Summary
Provides an alphabetical list of programming elements that have changed or are no longer supported in Visual Basic 2005,
and includes their replacements.
Language Changes for Visual Basic 6.0 Users
Provides an overview of new and changed features in Visual Basic 2005.
Visual Basic Concepts

Boolean Operator for Visual Basic 6.0 Users


Visual Basic 2005 removes two Boolean operators and adds two others to improve performance.
Visual Basic 6.0
In Visual Basic 6.0, Boolean operators — And, Or, Not, and Xor — always evaluate all the expressions in their operands.
You use the Eqv and Imp operators to perform logical equivalences and implications on two expressions.
Visual Basic 2005
In Visual Basic 2005, the And, Or, Not, and Xor operators still evaluate all expressions contributing to their operands. Visual
Basic 2005 also introduces two new operators, AndAlso and OrElse, that can reduce execution time by short-circuiting logical
evaluations. If the first operand of an AndAlso operator evaluates to False, the second operand is not evaluated. Similarly, if
the first operand of an OrElse operator evaluates to True, the second operand is not evaluated.
Note
You should be careful using short-circuiting operators. If the second operand contains a procedure call, you cannot rely on th
at procedure being called every time the operator executes.

The Eqv and Imp operators are not supported. Use the equals (=) comparison operator in place of Eqv for both logical and
bitwise evaluations. You can replace the logical Imp operator with an expression using the Not and Or operators, as shown in
the following example:
VB
Result = (Not A) Or B 'Same as A Imp B
'(True unless A is True and B is False.)

You can replace a bitwise Imp in the same manner, using Not and Or on numeric operands.
See Also
Reference
And Operator (Visual Basic)
AndAlso Operator
Or Operator (Visual Basic)
OrElse Operator
Not Operator (Visual Basic)
Xor Operator (Visual Basic)
TimeSpan
Concepts
Programming Element Support Changes Summary
Visual Basic Concepts

File Handling for Visual Basic 6.0 Users


Visual Basic 2005 expands file-handling capabilities while providing compatibility with previous versions of Visual Basic file I/O
functions.
Visual Basic 6.0
In Visual Basic 6.0, file handling is accomplished using various file I/O functions such as Open, Input, Output, and Append.
The FileSystemObject object provides an object-oriented method of working with files.
Visual Basic 2005
In Visual Basic 2005, file handling is accomplished through the My.Computer.FileSystem Object. In addition, the
System.IO.File class includes functions that provide compatibility with the older Visual Basic file I/O functions.
The FileStream class provides access to standard input and output files and error devices.
The following table lists members of the My.Computer.FileSystem object available in Visual Basic 2005.
Member Description
CombinePath Returns a properly formatted combined path as a String.

CopyDirectory Copies a directory.

CopyFile Copies a file.

CurrentDirectory Gets or sets the current directory.

CreateDirectory Creates a directory.

DeleteDirectory Deletes a directory.

DeleteFile Deletes a file.

DirectoryExists Returns a Boolean indicating whether a directory exists.

Drives Returns a read-only collection of all available drive names.

FileExists Returns a Boolean indicating whether a file exists.

FindInFiles Returns a read-only collection of strings representing the names of files containing the specified text.

GetDirectories Returns a String collection representing the path names of subdirectories within a directory.

GetDirectoryInfo Returns a DirectoryInfo object for the specified path.

GetDriveInfo Returns a DriveInfo object for the specified path.

GetFileInfo Returns a FileInfo object for the specified path.

GetFiles Returns a read-only String collection representing the names of files within a directory.

GetParentPath Returns a String representing the absolute path of the parent of the provided path.

GetTempFileName Creates a uniquely named zero-byte temporary file on disk and returns the full path of that file.
MoveDirectory Moves a directory to the specified location.

MoveFile Moves a file to the specified location.


OpenTextFieldParser Opens a TextFieldParser.

OpenTextFileReader Opens a TextReader.

OpenTextFileWriter Opens a TextWriter.

ReadAllBytes Reads from a binary file.

ReadAllText Reads from a text file.

RenameDirectory Renames a directory.

RenameFile Renames a file.

SpecialDirectories Gets an object that provides properties for accessing commonly referenced directories.

WriteAllBytes Writes to a binary file.

WriteAllText Writes to a text file.

See Also
Reference
System.IO Namespace
My.Computer.FileSystem Object
My.Computer.FileSystem.SpecialDirectories Object
Concepts
Parsing Text Files with the TextFieldParser Object
File Encodings
Programming Element Support Changes Summary
Other Resources
Reading from Files in Visual Basic
Writing to Files in Visual Basic
Creating, Deleting, and Moving Files and Directories in Visual Basic
File, Directory, and Drive Properties in Visual Basic
Visual Basic Concepts

Module Changes for Visual Basic 6.0 Users


A syntax change affects the declaration of private modules.
Option Private Module Statement
Visual Basic 6.0
In Visual Basic 6.0, the Option Private Module statement indicates that the entire module is private, and its components are
not accessible outside its project.
Visual Basic 2005
Visual Basic 2005 does not support the Option Private Module statement. You cannot declare a module to be private. You
can, however, declare any or all of its members to be private.
Unlike modules, classes can be private. If you need the functionality of the module itself being private, declare a class instead.
See Also
Reference
Module Statement
Class Statement (Visual Basic)
Private (Visual Basic)
Visual Basic Concepts

Procedure Changes for Visual Basic 6.0 Users


The following topics describe changes to procedures between Visual Basic 6.0 and Visual Basic 2005.
In This Section
Parameter Passing Mechanism for Visual Basic 6.0 Users
Describes passing arguments to procedures.
Procedure Calling Sequence for Visual Basic 6.0 Users
Discusses procedure calls and returns.
Procedure Declaration for Visual Basic 6.0 Users
Describes optional procedure arguments and static local variables.
Related Sections
Programming Element Support Changes Summary
Provides an alphabetical list of programming elements that have changed or are no longer supported in Visual Basic 2005,
and includes their replacements.
Language Changes for Visual Basic 6.0 Users
Provides an overview of new and changed features in Visual Basic 2005.
Visual Basic Concepts

Parameter Passing Mechanism for Visual Basic 6.0 Users


Visual Basic 2005 introduces several changes affecting how arguments are passed to procedures.
Default Passing Mechanism
Visual Basic 6.0
In Visual Basic 6.0, if you do not specify ByVal or ByRef for a procedure parameter, the passing mechanism defaults to ByRef.
This allows the variable passed into the procedure to be modified in the calling program.
Exposing a variable to modification can lead to a pitfall. In the following example, the passing mechanism defaults to ByRef,
the value of elapsedSeconds gets altered by minutesPastHour, and elapsedSeconds is displayed incorrectly by MsgBox.

Function minutesPastHour(seconds As Integer) As Integer


Dim hours As Integer = seconds \ 3600
seconds = seconds Mod 3600
Return seconds \ 60
End Function
Sub showSecondsAndMinutes()
Dim elapsedSeconds, extraMinutes As Integer
elapsedSeconds = CInt(Timer()) ' Integer seconds since midnight.
extraMinutes = minutesPastHour(elapsedSeconds)
MsgBox "Total seconds: " & elapsedSeconds & _
"; minutes past hour: " & extraMinutes
End Sub

Passing an argument ByRef allows a procedure to change it in the calling program, which can lead to unexpected behavior.
And if that procedure calls another procedure and passes the same argument ByRef, the chances of unintentionally changing
the original variable are increased.
Visual Basic 2005
When you declare a procedure in Visual Basic 2005, the passing mechanism defaults to ByVal for every parameter. This
protects arguments against modification. The declaration in the preceding example can be rewritten as follows.
VB
Function MinutesPastHour(ByVal Seconds As Integer) As Integer

Passing seconds by value prevents the procedure from accessing the variable in the calling program, and helps avoid the pitfall
just described.
Although ByVal is the default mechanism, specifying it explicitly for every parameter removes uncertainty and makes your
code easier to read.
ByRef Property Arguments
Visual Basic 6.0
In Visual Basic 6.0, a property passed to a procedure as a ByRef argument is copied into the procedure but not copied out. This
means that any modification to such a property argument is not reflected back to the original property in the calling program,
even though it was passed ByRef.
Visual Basic 2005
In Visual Basic 2005, a property argument passed ByRef is copied both into and out of the procedure. The following example
demonstrates how a property can be changed by a procedure.
VB
Sub Reduce(ByRef Height As Single)
' ... ... ... ... ... ... ... ' Code to modify Height argument.
End Sub
VB
Dim Sq As Square = New Square ' Square has property Side of type Single.
Reduce(Sq.Side) ' Side is changed when Reduce returns.

When a procedure modifies a property argument, the value of the original property is not changed immediately in the calling
program. Instead, it is copied out when the procedure returns.
ParamArray Arguments
Visual Basic 6.0
In Visual Basic 6.0, a procedure can specify the ParamArray keyword on the last of its arguments to accept an array of Variant
arguments. You cannot declare the passing mechanism of these arguments. They are always passed ByRef.
Visual Basic 2005
In Visual Basic 2005, ParamArray arguments are always passed ByVal. The arguments in the array must all be of the data
type of the ParamArray argument.
See Also
Reference
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
ByVal
ByRef
ParamArray
Concepts
Procedure Declaration for Visual Basic 6.0 Users
Procedure Calling Sequence for Visual Basic 6.0 Users
Parameter Arrays
Programming Element Support Changes Summary
Visual Basic Concepts

Procedure Calling Sequence for Visual Basic 6.0 Users


Visual Basic 2005 introduces several changes affecting procedure calling sequences. These changes improve syntax
consistency.
Parentheses in Procedure Calls
Visual Basic 6.0
In Visual Basic 6.0, parentheses are required around the argument list in Function calls. In Sub calls, they are required if you
use the Call statement and forbidden if you do not. The following example shows valid calling statements:
y = Sqrt(x)
Call displayCell(2, 14, cellValue)
displayCell 2, 14, cellValue ' Variation on previous statement.
Visual Basic 2005
In Visual Basic 2005, parentheses are always required around a non-empty argument list in any procedure call. In Sub calls, the
Call statement is optional. The preceding example can be rewritten as follows:
VB
Y = Math.Sqrt(X)
... DisplayCell(2, 14, Value)

If you are calling a procedure without supplying any arguments, you can include empty parentheses or leave them out
altogether.
Return Statement
Visual Basic 6.0
In Visual Basic 6.0, you use the Return statement only to branch back to the code following a GoSub statement. Both
statements must be in the same procedure.
Visual Basic 2005
In Visual Basic 2005, the GoSub statement is not supported, and you can use the Return statement to return control to the
calling program from a Function or Sub procedure.
See Also
Reference
Return Statement (Visual Basic)
Call Statement (Visual Basic)
Concepts
Declaration Syntax for Visual Basic 6.0 Users
Procedure Declaration for Visual Basic 6.0 Users
Parameter Passing Mechanism for Visual Basic 6.0 Users
Control Statement for Visual Basic 6.0 Users
Programming Element Support Changes Summary
Visual Basic Concepts

Procedure Declaration for Visual Basic 6.0 Users


Visual Basic 2005 introduces several changes related to the declaration of procedures.
Optional Arguments
Visual Basic 6.0
In Visual Basic 6.0, you can declare a procedure parameter as Optional without specifying a default value. If an optional
parameter is of the Variant type, the procedure code can use the IsMissing function to determine whether the calling code
passed an argument to that parameter.
Visual Basic 2005
In Visual Basic 2005, every optional parameter must declare a default value, which is passed to the procedure if the calling
program does not supply that argument. The IsMissing function is not needed to detect a missing argument, and it is not
supported. The following example shows an optional argument declaration:
VB
Sub Calculate(Optional ByVal Switch As Boolean = False)

Static Local Variables


Visual Basic 6.0
In Visual Basic 6.0, you can declare a procedure with the Static modifier. This causes every local variable within the procedure
to be static and to retain its value between calls.
Visual Basic 2005
In Visual Basic 2005, the Static keyword is not supported in a Function or Sub statement. You must individually declare each
local variable you want to be Static.
See Also
Reference
Optional (Visual Basic)
Static (Visual Basic)
Concepts
Procedure Calling Sequence for Visual Basic 6.0 Users
Parameter Passing Mechanism for Visual Basic 6.0 Users
Programming Element Support Changes Summary
Visual Basic Concepts

Property Changes for Visual Basic 6.0 Users


The following topics describe changes to properties between Visual Basic 6.0 and Visual Basic 2005.
In This Section
Default Property Changes for Visual Basic 6.0 Users
Covers changes to default property support.
Property Procedure Changes for Visual Basic 6.0 Users
Covers changes to property procedures and arguments.
Related Sections
Programming Element Support Changes Summary
Provides an alphabetical list of programming elements that have changed or are no longer supported in Visual Basic 2005,
and includes their replacements.
Language Changes for Visual Basic 6.0 Users
Provides an overview of new and changed features in Visual Basic 2005.
Visual Basic Concepts

Default Property Changes for Visual Basic 6.0 Users


Visual Basic 2005 updates default property support for simplification and improved readability.
Visual Basic 6.0
In Visual Basic 6.0, default properties are supported on objects. On a Label control, for example, Caption is the default
property, and the two assignments in the following example are equivalent.

Dim lbl As Label


lbl = "Important"
lbl.Caption = "Important"

While default properties enable a certain amount of shorthand in writing Visual Basic code, they have several drawbacks:
They can make code more difficult to read. In the preceding example, if you are not familiar with the Label control, you
cannot tell from the first assignment whether the string "Important" is being stored directly in the variable lbl or in a
default property.
Given an object that you plan to use in your code, it is not always easy to discover whether it has a default property, and
if so, which property that is.
Default properties make the Set statement necessary in the Visual Basic language. The following example shows how Set
is needed to indicate that an object reference, rather than a default property, is to be assigned.

Dim lbl1 As Label, lbl2 As Label


lbl1 = "Saving" ' Assign a value to lbl1's Caption property.
lbl2 = lbl1 ' Replace lbl2's Caption property with lbl1's.
Set lbl2 = lbl1 ' Replace lbl2 with an object reference to lbl1.

Visual Basic 2005


In Visual Basic 2005, default properties are not supported unless they take arguments. Because of this syntax change, the Let
and Set statements are not needed to specify what is to be assigned, and they are not used in assignment statements. The Text
property replaces the Caption property on the Label control, and the preceding example can be rewritten as follows.
VB
Dim L1, L2 As New Label ' Both become type Label
' in the new version of Visual Basic.
L1.Text = "Saving" ' Assign Text property.
L2.Text = L1.Text ' Copy Text property.
L2 = L1 ' Copy object reference.

Let is still a reserved word in Visual Basic 2005, even though it has no syntactical use. This helps avoid confusion with its
former meanings. Visual Basic 2005 uses the Set statement for property procedures that set the value of a property.
Parameterized Properties
Default properties that take arguments are not ambiguous, and they are supported in Visual Basic 2005. Default properties
appear most commonly on collection classes. In the System.Windows.Forms namespace, for example, the Form class supports
the following hierarchy:
Form object
Controls property (returns a ControlCollection object for this form)
ControlCollection object (default property is Item)
Item property (returns a Control object for one item in the collection)
Control object
The Controls property returns a ControlCollection object, and the Item property returns a Control object. The following
example shows both valid and invalid use of default properties in Visual Basic 2005.
VB
Dim F As New Form ' Assume F has been created and initialized.

VB
F.Controls.Item(0).Text = "Stop" ' Valid -- no default properties used.
F.Controls(0).Text = "Stop" ' Valid -- Item is parameterized.

VB
'F(0).Text = "Stop" ' INVALID -- Form does not have a default property.
'F.Controls(0) = "Stop" ' INVALID -- No default property on Control.

Default Property Declaration


In Visual Basic 2005, you specify a property as the default property by beginning its declaration with the Default keyword. If
you overload the property name, you must specify Default in every overload declaration. You cannot declare a default
property to be Shared or Private.
See Also
Reference
Set Statement (Visual Basic)
Default (Visual Basic)
Text
Label
System.Windows.Forms
Form
ControlCollection
Control
Concepts
Property Procedure Changes for Visual Basic 6.0 Users
Programming Element Support Changes Summary
Visual Basic Concepts

Property Procedure Changes for Visual Basic 6.0 Users


Visual Basic 2005 updates the declaration of property procedures and parameters for simplification and interoperability with
other programming languages.
Visual Basic 6.0
In Visual Basic 6.0, you use the Property Get, Property Let, and Property Set statements to get and set property values.
You can declare a property parameter to be ByRef. Passing a variable to such a parameter allows a procedure to change that
variable in the calling code.
Visual Basic 2005
Visual Basic 2005 introduces a unified property declaration syntax that includes the procedures for getting and setting the
property's value. This guarantees consistency of property attributes such as access level and overloading. The following
example shows the declaration of a property that does not take parameters.
VB
Private monthNum As Integer = 1
Property month() As Integer
Get
Return monthNum
End Get
Set(ByVal Value As Integer)
If Value < 1 Or Value > 12 Then
' Error processing for invalid value.
Else
monthNum = Value
End If
End Set
End Property

You can use any name you want for the parameter for Set. If you do not supply an argument, Value is automatically generated.
This syntax change makes the Property Get and Property Set statements unnecessary, and they are not supported. Because
Visual Basic 2005 does not allow default properties without parameters, Property Let and Property Set are not needed to
distinguish whether an object reference or a default property is to be assigned. Therefore, the Property Let statement also is
not supported.
Visual Basic 2005 does not support ByRef property parameters. If a property procedure had a ByRef parameter and changed
the variable underlying the corresponding argument, the property could behave in an unexpected manner. Therefore, all
declarations of parameterized properties must specify ByVal for the parameters.
See Also
Reference
ByVal
Concepts
Default Property Changes for Visual Basic 6.0 Users
Programming Element Support Changes Summary
Visual Basic Concepts

Control Flow Changes for Visual Basic 6.0 Users


The following topics describe changes to control flow between Visual Basic 6.0 and Visual Basic 2005.
In This Section
Control Statement for Visual Basic 6.0 Users
Covers changes to statements controlling execution flow.
Exception Handling for Visual Basic 6.0 Users
Discusses new support for structured exception handling, and continued support for unstructured exception handling.
Related Sections
Programming Element Support Changes Summary
Provides an alphabetical list of programming elements that have changed or are no longer supported in Visual Basic 2005,
and includes their replacements.
Language Changes for Visual Basic 6.0 Users
Provides an overview of new and changed features in Visual Basic 2005.
Visual Basic Concepts

Control Statement for Visual Basic 6.0 Users


Visual Basic 2005 updates several statements controlling the flow of execution.
Visual Basic 6.0
In Visual Basic 6.0, the GoSub statement calls a sub-procedure within a procedure. The On ... GoSub and On ... GoTo
constructions, also known as computed GoSub and computed GoTo, provide compatibility with early versions of BASIC.
The While ... Wend construction loops through code while a specified condition is true.
Visual Basic 2005
In Visual Basic 2005, you can call procedures with the Call statement, and the GoSub statement is not supported. You can
perform multiple branching with Select...Case statements, and the On ... GoSub and On ... GoTo constructions are not
supported. However, Visual Basic 2005 still supports the On Error statement.
Visual Basic 2005 retains the While ... Wend construction, but replaces the Wend keyword with the End statement. The
Wend keyword is not supported.
See Also
Reference
Call Statement (Visual Basic)
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
Return Statement (Visual Basic)
Select...Case Statement (Visual Basic)
On Error Statement (Visual Basic)
End Statement
Concepts
Procedure Calling Sequence for Visual Basic 6.0 Users
Programming Element Support Changes Summary
Visual Basic Concepts

Exception Handling for Visual Basic 6.0 Users


Visual Basic 2005 adds support for structured exception handling, and continues support for unstructured exception handling.
Visual Basic 6.0
In Visual Basic 6.0, you use unstructured exception handling to deal with errors in your code. Placing the On Error statement at
the beginning of a block of code handles any errors that occur within that block. Unstructured exception handling also employs
the Error and Resume statements.
Visual Basic 2005
In Visual Basic 2005, structured exception handling code detects and responds to errors during execution by combining a
control structure with exceptions, protected blocks of code, and filters. Structured exception handling is done through a Try
statement, which is made up of three kinds of blocks: Try, Catch, and Finally. A Try block is a statement block that contains
the statement to be executed. A Catch block is a statement block that handles an exception. A Finally block contains
statements to be run when the Try statement is exited, regardless of whether an exception has occurred. The Throw statement,
used in conjunction with a Catch block, raises an exception that is represented by an instance of a type derived from the
Exception class.
See Also
Reference
Throw Statement (Visual Basic)
On Error Statement (Visual Basic)
Error Statement
Resume Statement
Exception
Concepts
Structured Exception Handling Overview for Visual Basic
Unstructured Exception Handling Overview
Programming Element Support Changes Summary
Visual Basic Concepts

Object-Oriented Programming for Visual Basic 6.0 Users


Visual Basic 6.0 supports object-oriented language elements and has support for objects distributed in libraries. Visual Basic
2005 extends the support for object-oriented programming by supporting all of its language properties.
Conceptual Differences
The sections below list object-oriented features in Visual Basic 2005, comparing them with the Visual Basic 6.0 implementation
where applicable. For each feature, links are provided to in-depth Help pages that can help you learn more.
Access Levels
In Visual Basic 6.0, the keywords Private, Friend, Public, and Static are used to set access levels for declared elements.
In Visual Basic 2005, the keywords Private, Friend, Public, and Static, plus the new keywords Protected and Protected
Friend are used to set access levels for declared elements. The access level of a declared element is the extent of the ability to
access it— that is, what code has permission to read it or write to it.
For more information, see Access Levels in Visual Basic and Scope in Visual Basic.
Attributes
In Visual Basic 6.0, limited support for embedded attributes is provided through tools such as the Procedure Attributes in the
Visual Basic IDE.
In Visual Basic 2005, an Attribute is a descriptive tag that can be used to annotate type and type member statements, thereby
modifying their meaning or customizing their behavior. For example, class statements and class method statements can be
annotated with attributes.
Your application and other applications, such as the Visual Basic compiler, can use reflection to access attributes to determine
how types and type members can be used.
Attributes can be used to perform Aspect Oriented Programming (AOP) with Visual Basic. An aspect is a part of a program that
cross-cuts its business logic. In other words, it is needed to complete the program, but is not necessarily specific to the domain
that the program is written for. Isolating such aspects as logging and persistence from business logic is the aim of the aspect-
oriented programming paradigm.
For more information, see Attributes Overview in Visual Basic, Attributes Used in Visual Basic, and
Common Uses for Attributes.
Binary Compatibility
In Visual Basic 6.0, the Binary Compatibility option allows you to automatically retain class and interface identifiers from a
previous version of a component when you compile a new version.
In Visual Basic 2005, the Binary Compatibility option is not supported; instead binary compatibility is accomplished with
attributes. This gives you direct control over the information placed in your compiled component, such as class and interface
identifiers, virtual table offsets, and any appropriate COM attributes.
For more information, see Binary Compatibility Changes for Visual Basic 6.0 Users.
Class Modules
In Visual Basic 6.0, a class is defined in a class module. A single class module is stored in a special type of file that has a .cls file
extension.
In Visual Basic 2005, a class is defined in a Class statement that specifies the name and the members of a class. Class
statements are stored in source files. The entire source file can be viewed as plain text.
Multiple Class statements as well as other type statements can be stored in single source file. Visual Basic does not require the
name of the source file to match a Class or type defined in the source file.
For more information, see Class Statement (Visual Basic).
Class Constructor Methods
In Visual Basic 6.0, the class Initialize event handler named Class_Initialize is used to execute code that needs to be executed
at the moment that an object is created.
In Visual Basic 2005, one or more constructors are added to a class to execute code and initialize variables. Constructors are
the methods in a class that are named New. The New method can be overloaded to provide multiple constructors with the
name New within the same class statement.
For more information, see New (Visual Basic) or Using Constructors and Destructors.
Class Destructor Methods
In Visual Basic 6.0, the Nothing keyword is used to disassociate an object variable from an actual object. The Set statement is
used to assign Nothing to an object variable.
In Visual Basic 2005, for the majority of the objects that your application creates, you can rely on the garbage collector to
automatically perform the necessary memory management tasks. However, unmanaged resources require explicit cleanup. The
most common type of unmanaged resource is an object that wraps an operating system resource, such as a file handle,
window handle, or network connection.
When you create an object that encapsulates an unmanaged resource, it is recommended that you provide the necessary code
to clean up the unmanaged resource in a public Dispose method. By providing a Dispose method, you enable users of your
object to explicitly free its memory when they are finished with the object.
When you use an object that encapsulates an unmanaged resource, you should be aware of Dispose and call it as necessary.
For more information, see Cleaning Up Unmanaged Resources or Automatic Memory Management.
Class_Initialize
In Visual Basic 6.0, a class Initialize event can be handled by a Class_Initialize method to execute code that needs to be
executed at the moment an object is created. For example, the values of class data variables can be initialized.
In Visual Basic 2005, The Initialize event and the Class_Initialize handler are not supported. To provide class initialization,
add one or more constructor methods to the classes and structures you define.
For more information, see Class_Initialize Changes for Visual Basic 6.0 Users.
Data Classes
In Visual Basic 6.0, data source and complex data consumer classes are used to work with external data such as Microsoft SQL
Server databases. A data source class provides data from an external source. A data consumer class can be bound to an
external source of data such as a Data Source class.
In Visual Basic 2005, data source, simple data consumer, complex data consumer, and binding classes are used to work with
external and internal data.
For more information, see Data Binding and Windows Forms.
Default Property
In Visual Basic 6.0, any class property can be defined as the default property of the class.
In Visual Basic 2005, the default member of a class or structure can only be a property that takes one or more arguments.
Default property members are defined by including the Default keyword in one property declaration statement in a class or
structure.
For more information, see Default Property Changes for Visual Basic 6.0 Users.
Delegates
In Visual Basic 6.0, delegate types are not supported.
In Visual Basic 2005, a delegate type is a form of object-oriented method pointer that allows a method to be invoked indirectly
by way of a reference to the method. Delegates can be used to hook up event handlers and to pass a method from one method
to another.
Delegates can be used to implement the asynchronous design pattern. For example, using an asynchronous delegate, a
program can call a method, which enumerates a large list, while the main program continues to execute. When the
enumeration is complete, a callback is made, and the program addresses it.
For more information, see Delegates in Visual Basic or How to: Pass Procedures to Another Procedure in Visual Basic.
Error Handling
In Visual Basic 6.0, the On Error statement is used for unstructured exception handling.
In Visual Basic 6.0, the On Error statement is used for unstructured exception handling.
In Visual Basic 2005, both unstructured and structured exception handling are supported. Structured exception handling is a
control structure containing exceptions, isolated blocks of code, and filters to create an exception-handling mechanism.
For more information, see Structured Exception Handling in Visual Basic or
Choosing When to Use Structured and Unstructured Exception Handling.
Events
In Visual Basic 6.0, the Event, RaiseEvent, and WithEvents keywords are used to declare, raise, and handle events.
In Visual Basic 2005, the Event, RaiseEvent, and WithEvents keywords plus the new AddHandler, RemoveHandler, and
Handles keywords are used to declare, raise, and handle events.
The AddHandler and RemoveHandler keywords allow you to dynamically add, remove, and change the event handler
associated with an event.
The Handles keyword allows you to define a Handles clause on a method. Handles declares that a procedure handles a
specified event.
Events in the .NET Framework are based on the delegate model. The delegate model is based on the object-oriented observer
design pattern.
For more information, see How to: Write Event Handlers.
Generics
In Visual Basic 6.0, generic types are not supported.
In Visual Basic 2005, generics are used to implement parametric polymorphism in a Visual Basic program. Generic code is
written without mention of any specific type and thus can be used transparently with any number of new types.
Visual Basic 2005 supports type parameters on generic classes, structures, interfaces, procedures, and delegates. A
corresponding type argument specifies at compilation time the data type of one of the elements in the generic type.
For more information, see Generic Types in Visual Basic.
Global Classes
In Visual Basic 6.0, the value of the Instancing property of a class determines whether a class is private — that is, for use only
within one component, or available for other applications to use. It also determines how other applications create instances of
the class and how other applications call the class members.
In Visual Basic 2005, the Instancing property is no longer supported.
You can apply the Public keyword to class statements in an assembly to expose classes in that assembly to other assemblies.
You can reference an external assembly such as a class library to enable code in your application to use the Public classes
from that class library.
You can use the Imports keyword to import namespace names from referenced projects and assemblies. The Imports
keyword can also import namespace names defined within the same project as the file in which the statement appears.
You can apply the Shared keyword to field, property, and method members of classes and structures to implement shared
members. Shared members are properties, procedures, and fields that are shared by all instances of a class or structure. The
shared members of a class can be accessed without instantiating the class.
For more information, see Access Levels in Visual Basic, References and the Imports Statement, or
Shared Members in Visual Basic.
Implementation Inheritance
In Visual Basic 6.0, implementation inheritance is not supported.
In Visual Basic 2005, you can implement ad-hoc polymorphism through implementation inheritance. This allows you to define
classes that can be used interchangeably by client code at run time, but with functionally different (yet identically named)
methods or properties.
You can define base classes that serve as the basis for derived classes. Derived classes inherit, and can extend, the properties,
methods, and events of the base class. Derived classes can also override inherited methods with new implementations.
For more information, see Inheritance Basics or When to Use Inheritance.
Interface Inheritance
Visual Basic 6.0 provides polymorphism through multiple ActiveX interfaces. In the Component Object Model (COM) that
forms the infrastructure of the ActiveX specification, multiple interfaces allow systems of software components to evolve
without breaking existing code.
In Visual Basic 2005, you can implement ad-hoc polymorphism with the .NET Framework's Interface keyword.
Multiple classes may implement the same Interface, and a single class may implement one or more interfaces. Interfaces are
essentially definitions of how a class needs to respond. An interface defines the methods, properties, and events that a class
needs to implement, and the type of parameters each member needs to receive and return, but leaves the specific
implementation of these members up to the implementing class.
Multiple interfaces have the advantage of allowing systems of software components to evolve without breaking existing code.
For more information, see Interface-Based Polymorphism or How to: Create and Implement Interfaces.
Methods: ByVal and ByRef Parameters
In Visual Basic 6.0, arguments are passed to a method by value or by reference. Unless method parameters are explicitly
specified by the ByVal or ByRef keyword, arguments are implicitly passed by reference (ByRef).
In Visual Basic 2005, arguments are passed to a method by value or by reference. Unless method parameters are explicitly
specified by the ByVal or ByRef keyword, arguments are implicitly passed by value (ByVal).
For more information, see Argument Passing By Value and By Reference.
Methods: Overloading
In Visual Basic 6.0, method overloading is not supported.
In Visual Basic 2005, Method overloading is used to implement ad-hoc polymorphism in a Visual Basic program. A method is
overloaded when more than one version of the method is defined in a class. The overloaded versions differ in their parameters
and returns types.
For more information, see Overloaded Properties and Methods and How Visual Basic Provides Polymorphism.
Methods: Overriding
In Visual Basic 6.0, methods can not be overridden.
In Visual Basic 2005, you can use the Overrides keyword to override a method in a derived class to provide a different
implementation of a method from the derived class's base class.
For more information, see Overriding Properties and Methods.
Methods: Returning Results
In Visual Basic 6.0, a Function method's name is used as the name of a variable to return the Function method's result.
In Visual Basic 2005, you use the Return keyword to return a Function method's result.
Use the Return to return control to the code that called a Sub, Function, or Property method.
For more information, see Return Statement (Visual Basic).
My
In Visual Basic 2005, the new My feature enables rapid object-oriented programming with Visual Basic by providing entry
points to frequently used .NET Framework classes and functions. My provides new high-level .NET Framework classes that pull
together related functionality into task-based APIs.
For more information, see Development with My.
MyBase, MyClass, and Me Keywords
In Visual Basic 6.0, the Me keyword behaves like an implicitly declared variable. When a class has more than one instance, Me
provides a way to refer to the specific instance of the class where the code is executing.
In Visual Basic 2005, the MyBase keyword provides a way to refer to the base class of the current class instance.
The MyClass keyword provides a way to refer to the current class instance without overrides.
The Me keyword provides a way to refer to the specific instance of a class or structure in which the code is currently executing.
For more information, see Me, My, MyBase, and MyClass in Visual Basic.
New Keyword
In Visual Basic 6.0, using the New keyword inappropriately can cause some unusual re-initializing behavior that could result in
errors and excessive memory usage.
In Visual Basic 2005, the New keyword simply allocates space for the object; it does not cause any unusual re- initializing
behavior.
Use a New clause in a declaration statement or an assignment statement. When the statement is executed, it calls a constructor
method of the specified class, passing any arguments supplied in the New clause. This means that you can enforce data
constraints from the time the object is instantiated.
A class has one or more constructors. Constructors are the methods in a method named New. Multiple constructors are
defined by overloading the New method in the class. Overloaded constructor methods are described as parameterized
constructors.
For more information, see New (Visual Basic).
Object Lifetime
In Visual Basic 6.0, object lifetime is deterministic; every object instance maintains a reference count. When the last reference to
an instance is released and the count equals zero, the object is terminated immediately.
In Visual Basic 2005, object lifetime is non-deterministic; a destructor is not necessarily called as soon as the last reference is
released. This is because the common language runtime maintains a reference tree instead of individual reference counts.
The garbage collector traces the reference tree in the background. If it finds an object or group of objects that have no
references from any currently executing code, it calls the destructors of all such objects.
It is impossible to predict either the order of this destruction or the time it takes the garbage collector to trace the reference
tree.
For more information, see Lifetime in Visual Basic or Object Lifetime: How Objects Are Created and Destroyed.
Operator Overloading
In Visual Basic 6.0, operator overloading is not supported.
In Visual Basic 2005, operator overloading allows the behavior of a standard operator (such as *, <>, or And) to be defined for
a user-defined class or structure.
For more information, see How to: Define a Conversion Operator.
Option Strict
In Visual Basic 6.0, permissive type checking is used at run time.
In Visual Basic 2005, you can use the OPTION STRICT ON statement to enable strict type checking at design time rather than
permissive type checking at run time. By default OPTION STRICT OFF is used.
When converting between data types, the Visual Basic compiler can operate under strict or permissive type semantics. If strict
type semantics are in effect (OPTION STRICT ON), only widening conversions are permitted implicitly, and narrowing
conversions must be explicit. Under permissive type semantics (OPTION STRICT OFF), you can attempt all widening and
narrowing conversions implicitly. Type semantics apply to conversions between all data types, including object types.
For more information, see Type Checking in Visual Basic.
Property Syntax
In Visual Basic 6.0, the Property Get, Property Let, and Property Set statements are used to get and set property values.
In Visual Basic 2005, a unified property declaration syntax is used that includes the procedures for getting and setting the
property's value. This guarantees consistency of property attributes such as access level and overloading.
For more information, see Property Changes for Visual Basic 6.0 Users.
Public Interfaces
In Visual Basic 6.0, a class's public interface is the set of its public members.
In Visual Basic 2005, a class's public interface is the set of its public members, but an abstract class may be used to implement
sub-typing polymorphism in a Visual Basic program.
An abstract class is similar to the .NET Framework's Interface. An abstract class is one that is designed only to serve as a base
class for derived classes. Abstract classes are often used to represent abstract concepts or entities.
An abstract class cannot be instantiated itself; it must be inherited. Some or all members of the class might be unimplemented,
and it is up to the inheriting class to provide that implementation. Members that are implemented might still be overridden,
and the inheriting class can still implement additional interfaces or other functionality.
For more information, see MustInherit.
Read Only Properties
In Visual Basic 6.0, excluding the Set method in a Property procedure creates a read-only property.
In Visual Basic 2005, you must both apply the ReadOnly keyword to a property and exclude the property Set clause to make a
property read-only.
You can also apply the ReadOnly keyword to a field to make it read-only.
For more information, see ReadOnly (Visual Basic).
Reflection
In Visual Basic 6.0, reflection is not supported.
In Visual Basic 2005, the classes in the .NET Framework class library System.Reflection namespace can be used to obtain
information about types such as classes, interfaces, and value types at run time and to create type instances to invoke and
access them.
For more information, see Reflection Namespaces in Visual Studio.
Shared Class and Structure Members
In Visual Basic 2005, the new Shared keyword can be applied to Property, Sub, Dim, Function, Operator, and Event
statements to share them with all instances of a class or structure. The shared members of a class can be accessed without
instantiating the class.
You can access shared members through a class's name rather than through an instance of the class.
For more information, see Shared Members in Visual Basic.
Source Files
In Visual Basic 2005, programs consist of one or more source files. Source files are stored in a special type of file that has a .vb
file extension. Type statements for types such as classes, structures, interfaces, enumerations, and delegates, as well as
statements for standard modules, are stored in program source-code files. Visual Basic does not limit a source file to defining
only one type nor does it require the name of the source file to match a type defined in the source file.
Partial-type statements allow a class, or a structure, to be defined across multiple source files. When a multi-source-file
program is compiled, all of the source files are processed together as if all the source files were concatenated into one file
before being processed.
For more information, see Structure of a Visual Basic Program or Partial (Visual Basic).
User Defined Types
In Visual Basic 6.0, the Type statement is used to combine variables of several different types into one user defined type or
UDT.
In Visual Basic 2005, the Structure and Enum statements are used to define user defined value types.
Use the Class, Interface, and Delegate statements to define user defined reference types.
For more information, see Structures: Your Own Data Types.
Variable Declaration
In Visual Basic 6.0, you can declare variables of different types in the same statement. If you do not specify the data type of a
variable in the statement, it defaults to Variant.
In Visual Basic 2005, you can declare multiple variables of the same data type without having to specify the data type of each
variable in the statement.
For more information, see Variable Declaration in Visual Basic.
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, object-oriented code constructs are converted to their
nearest Visual Basic 2005 equivalent in the most expedient manner. The resulting code should not be taken as an example of
how to do object-oriented programming in Visual Basic 2005.
If you intend to extend an upgraded application to use Visual Basic 2005 object-oriented constructs, you may first want to
modify the upgraded code. The following pages should help you get started.
Classes for Visual Basic 6.0 Users
Classes are the building blocks of an object-oriented application.
How to: Convert a Custom Collection to a Visual Basic Typed Collection
Visual Basic 2005 provides several options for creating typed classes from Visual Basic 6.0 custom collections.
How to: Convert a User-Defined Type to a Visual Basic Structure
The Type statement of Visual Basic 6.0 is upgraded to the Structure statement of Visual Basic 2005.
How to: Convert Implements Code to a New Form of Inheritance
Newer versions of Visual Basic offer two types of inheritance, using the Implements statement and the Inherits statement.
See Also
Tasks
Object-Oriented Programming Sample
Concepts
Classes for Visual Basic 6.0 Users
Object-Oriented Changes for Modules in Visual Basic
Interface Changes for Visual Basic 6.0 Users
Inheritance for Visual Basic 6.0 Users
Other Resources
Language Changes for Visual Basic 6.0 Users
Help for Visual Basic 6.0 Users
Visual Basic Concepts

Classes for Visual Basic 6.0 Users


Classes are the building blocks of an object-oriented application. A class is a programming construct that represents an object
in the system. Designing an application requires designing the objects involved, the information contained by the objects, and
what the objects can do. For more information on classes and object-oriented programming, see
Object-Oriented Programming in Visual Basic.
Class Modules
Visual Basic 6.0
Visual Basic 6.0 provides support for defining classes through the class module. The definition of a class is stored in a special
file type, the .cls file. One class is defined in each class module. Some of the definition of the class is embedded in the .cls file
and only editable through the project system.
Visual Basic 2005
In Visual Basic 2005, a class is defined by the Class Statement (Visual Basic), not by a file name. Classes in Visual Basic 2005 are
defined in the source code files, .vb files. Multiple classes may be defined in one file. The entire class definition is visible as plain
text in the source code.
Global Classes
Visual Basic 6.0
When you create a new class in Visual Basic 6.0, the allowable values of the Instancing property include GlobalSingleUse
and GlobalMultiUse. These indicate that other components can invoke the properties and methods of the new class as if they
were shared members. An instance of the class is implicitly created the first time one of its members is called.
Visual Basic 2005
Visual Basic 2005 does not support the Instancing property. Visual Basic 2005 provides the same functionality by allowing
you to expose standard module members. You can access shared properties and methods of a class using the Imports
statement. You can achieve the effect of GlobalMultiUse with Public class access and the appropriate constructor access.
Data Classes
Visual Basic 6.0
Visual Basic 6.0 also supports Data Source and Complex Data Consumer classes.
Visual Basic 2005
There is no direct equivalent in Visual Basic 2005. For information about classes that manipulate data, see
How to: Connect to Data in an Object.
Default Members
Visual Basic 6.0
In Visual Basic 6.0, you can specify that any particular method or data member is the default member of a class.
Visual Basic 2005
In Visual Basic 2005, a default member of a class or structure can only be a property that takes one or more arguments. This
enables interoperability with other programming languages. For more information, see
How to: Declare and Call a Default Property in Visual Basic.
Object Lifetime
Visual Basic 6.0
Object lifetime is determined by the creation and termination of the object instance. The program determines the creation time
of the objects it declares, but termination involves a more complex mechanism.
In Visual Basic 6.0, every object instance maintains a reference count. When the last reference to an instance is released and the
count goes to zero, the object is terminated immediately.
Visual Basic 2005
In Visual Basic 2005, a destructor is not necessarily called as soon as the last reference is released. This is because the common
language runtime maintains a reference tree instead of individual reference counts. The garbage collector traces the reference
tree in the background. If it finds an object or group of objects that have no reference from any currently executing code, it calls
the destructors of all such objects. It is impossible to predict either the order of this destruction or the time it takes the garbage
collector to trace the reference tree. Therefore, the lifetime of an object is indeterminate. For more information, see
Object Lifetime: How Objects Are Created and Destroyed and Garbage Collection.
Upgrade Options
The Upgrade Wizard creates a straightforward upgrade of class modules with minimal changes to the code. In addition to the
changes listed above, Visual Basic programmers have several new constructs to choose from that are particularly relevant for
object-oriented programming. A few are listed here.
Constructors Constructors replace the use of Class_Initialize of Visual Basic 6.0. For more information, see
Class_Initialize Changes for Visual Basic 6.0 Users.
Default indexed properties Default indexed properties are used extensively throughout the .NET Framework for
accessing collection items. For more information, see Default Property Changes for Visual Basic 6.0 Users.
ReadOnly In Visual Basic 6.0, a property is implicitly read-only if there is no Get procedure. Visual Basic 2005 requires
the ReadOnly keyword to explicitly declare this behavior. For more information see Property Statement.
Late-binding Since Visual Basic 6.0 provides late-binding by default, the most likely way to upgrade the code without
errors is to set Option Strict to Off. Changing Option Strict to On enforces type-safety at compile time, and can expose
subtle errors during compilation rather than at run time. For more information see Option Strict Statement.
Method overloading Method overloading reduces the number of named members of a class. This makes the class
more readable and easier to program against. For more information, see Procedure Changes for Visual Basic 6.0 Users.
File name Visual Basic 6.0 requires the class name and file name to match. In Visual Basic 2005, the programmer
controls both and can define several classes in one source file. How many classes belong in one file is typically covered
by a coding standard.
ByRef The default for parameters in Visual Basic 6.0 is ByRef, so the safest upgrade is ByRef. For more information see
ByVal.
Return keyword In Visual Basic 6.0, the function name is used as a variable to return the value of the function. Visual
Basic 2005 provides the explicit Return keyword for returning function values. For more information, see
Return Statement (Visual Basic) .
Operator overloading You can now define the meaning of addition (+), subtraction (-), and other operators for the
classes you define. For more information, see Operator Statement.
New operators The += operator can shorten and simplify a line of code. For more information see
Arithmetic Operators (Visual Basic) .
Inline definition of new values Syntax in Visual Basic 2005 allows declaring and setting the value of a new variable
all in one line of code. This means that you can enforce data constraints from the time the object is instantiated. For more
information, see Dim Statement (Visual Basic).
Rewriting the code is not without risks. Any time the code is changed it needs to be tested again. Also, some keywords in Visual
Basic 2005 do not act as exactly as they do in Visual Basic 6.0. For more information, see
Upgrading Applications Created in Previous Versions of Visual Basic.
See Also
Reference
Structure Statement
Property Statement
Option Strict Statement
Return Statement (Visual Basic)
'ByVal' and 'ByRef' cannot be combined
ByRef
Concepts
Early and Late Binding
Class_Initialize Changes for Visual Basic 6.0 Users
Other Resources
Creating and Using Objects
Understanding Classes
Visual Basic Concepts

Class_Initialize Changes for Visual Basic 6.0 Users


A constructor is a method that is run when an object is created. Constructors are new to Visual Basic. They combine the
behavior of the New statement and the Class_Initialize method of Visual Basic 6.0, yet offer more flexibility and control in
creating class instances. For more information on object creation, see Creating and Using Objects.
Class_Initialize
Visual Basic 6.0
Visual Basic 6.0 provides support for the constructor concept through the Class_Initialize method. This method is private and
allows no parameters. This method is called automatically when a new instance of the class is created. A call to the New
keyword calls the Class_Initialize method, if it exist.
Suppose you want to specify the yearly growth of a tree with a default of five years. The class code would look something like
this:

' Visual Basic 6.0


Private mvarYearlyGrowth As Integer

Public Property Get YearlyGrowth() As Integer


YearlyGrowth = mvarYearlyGrowth
End Property

Public Property Let YearlyGrowth(ByVal newValue As Integer)


mvarYearlyGrowth = newValue
End Property

Private Sub Class_Initialize()


mvarHeight = 5
End Sub

The code to create a tree and set the property would look like this:

Dim growingTree As New Tree


growingTree.YearlyGrowth = 10

Visual Basic 2005


Visual Basic 2005 supports constructors through the New keyword. In this case, the additional code to set the YearlyGrowth
property is not required. A call to the New keyword calls one of the overloaded New methods in the class. If the class contains
no New method, then one without parameters is created by the compiler.
VB
Option Strict On

VB
Public Class Tree
Private yearlyGrowthValue As Integer = 5
Public Property YearlyGrowth() As Integer
Get
Return yearlyGrowthValue
End Get
Set(ByVal Value As Integer)
yearlyGrowthValue = Value
End Set
End Property

Public Sub New(ByVal newYearlyGrowth As Integer)


Me.YearlyGrowth = newYearlyGrowth
End Sub
End Class

The code to create a tree and set the property would look like this:
VB
Dim growingTree As New Tree(10)

In this example, it is not possible to create a Tree without specifying the yearly growth. To allow that, you could add another
New method to the class that has no parameters. This is called overloading the constructor.

New Keyword
Visual Basic 6.0
In Visual Basic 6.0, this line of code is generally not recommended:

Dim growingTree As New Tree

This is because whenever the growingTree variable is accessed, the compiler checks if the value is Nothing. If so, a new
instance is created and assigned to growingTree. This is not only inefficient, but leads to programming errors.
Visual Basic 2005
In Visual Basic 2005, the instance is not checked and no new instances are created. The only way to create a new instance is to
execute a line of code with the New or As New keywords. In effect, the line of code above is now the recommended way to
handle creating a new instance.
Upgrade Suggestions
The Upgrade Wizard upgrades the Class_Initialize method to this:
VB
'UPGRADE_NOTE: Class_Initialize was upgraded to Class_Initialize_Renamed. Click for more: m
s-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="vbup1061"'

Private mvarHeight As Short


Private Sub Class_Initialize_Renamed()
mvarHeight = 0
End Sub
Public Sub New()
MyBase.New()
Class_Initialize_Renamed()
End Sub

You may be able to eliminate the call to Class_Initialize_Renamed and move the code directly into the constructor. This could
make your code more readable as it eliminates an unneeded call to a procedure. If each call to New is commonly followed by
setting a particular group of properties, consider adding a constructor that sets those properties. The Visual Basic 6.0 code
could be replaced by this code in Visual Basic 2005:
VB
Public Sub New(ByVal newYearlyGrowth As Integer)
Me.YearlyGrowth = newYearlyGrowth
End Sub

See Also
Tasks
How to: Use the New Keyword
Other Resources
Creating and Using Objects
Visual Basic Concepts

Property Changes for Visual Basic


Fields and properties operate together to provide access to the data of a class. Fields are the variables in a class definition and
hold the data of the object. Properties provide Get and Set methods to allow access to class instance data. For more
information, see Properties and Property Procedures.
Property Syntax
Visual Basic 6.0
The Property construct is a combination of a Get method and a Set method. In Visual Basic 6.0, these two methods are
separate:

' Visual Basic 6.0


Private mvarYearlyGrowth As Integer
Public Property Get YearlyGrowth() As Integer
YearlyGrowth = mvarYearlyGrowth
End Property

Public Property Let YearlyGrowth(ByVal newValue As Integer)


mvarYearlyGrowth = newValue
End Property

Visual Basic 2005


The property changes from Visual Basic 6.0 to Visual Basic 2005 are primarily syntactic. The Visual Basic 2005 syntax moves
the Get and Set methods into one code block for the property, instead of two independent methods. Visual Basic 2005 makes
no distinction between properties that are reference types and properties that are value types, so there is only a Set method,
and there is no longer a Let method. The field and property for YearlyGrowth would look like this in Visual Basic 2005:
VB
Private yearlyGrowthValue As Integer = 5

Public Property YearlyGrowth() As Integer


Get
Return yearlyGrowthValue
End Get
Set(ByVal Value As Integer)
yearlyGrowthValue = Value
End Set
End Property

In both Visual Basic 6.0 and Visual Basic 2005, the class contains a field, mvarYearlyGrowth or yearlyGrowthValue that holds
the data.
Upgrade Suggestions
The Upgrade Wizard will upgrade a property to this:
VB
Private mvarYearlyGrowth As Short
Public Property YearlyGrowth() As Short
Get
YearlyGrowth = mvarYearlyGrowth
End Get
Set(ByVal Value As Short)
mvarYearlyGrowth = Value
End Set
End Property
The Visual Basic 6.0 Integer is upgraded to the Short in Visual Basic 2005. This could cause some type incompatibility
problems when other code tries to assign an Integer in Visual Basic 2005 to the property. You may need to review the
converted types for fields and properties to avoid other type-safety conflicts.
See Also
Reference
Dim Statement (Visual Basic)
Property Statement
Other Resources
Property Changes for Visual Basic 6.0 Users
Visual Basic Concepts

Method Changes for Visual Basic 6.0 Users


A method is a Sub or Function procedure declaration. Methods make a class do things. Together with properties, they expose
the behavior and data of a class.
Method Declarations
Visual Basic 6.0
In Visual Basic 6.0 class definitions can contain Sub and Function methods. Those methods can be Public, Private, or Friend.
Here are two examples:

Public Sub Draw(theForm As Form)


' Add code here to draw a tree on the form.
End Sub

Public Function GrowOneYear() As Integer


mvarHeight = mvarHeight + 10
GrowOneYear = mvarHeight
End Function

Visual Basic 2005


Visual Basic 2005 also supports Sub and Function methods that are Public, Private, and Friend. Either ByRef or ByVal is
required on all method parameters. If not explicitly added, ByVal is added by the Code Editor.
Code upgraded from Visual Basic 6.0 will be upgraded to ByRef, as this was the default in Visual Basic 6.0:
VB
Public Sub Draw(ByRef theForm As System.Windows.Forms.Form)
' Add code here to draw a tree on the form.
End Sub

Method Overloading
Visual Basic 6.0
In Visual Basic 6.0, a class can only contain one method with a given name.
Visual Basic 2005
In Visual Basic 2005, methods can be overloaded. A method is overloaded when more than one version of the method is
defined in the class. The overloaded versions differ in their parameters and returns types. This can simplify the interface of an
object by making it smaller. The following example shows two overloads of the Draw method. For more information, see
Overloaded Properties and Methods.
VB
Public Sub Draw(ByRef theForm As System.Windows.Forms.Form)
' Add code here to draw a tree on the form.
End Sub

VB
Public Sub Draw(ByVal surface As System.Drawing.Graphics)
' Add code here to draw a tree on the graphics surface.
End Sub

Return Keyword
Visual Basic 6.0
In Visual Basic 6.0, the function name is used as a variable to return the value of the function.
Public Function GrowOneYear() As Integer
heightValue = heightValue + 10
GrowOneYear = heightValue
End Function

Visual Basic 2005


Visual Basic 2005 includes the explicit Return statement for returning function values. The GrowOneYear function in Visual
Basic 2005 looks like this:
VB
Public Function GrowOneYear() As Integer
heightValue += 10
Return heightValue
End Function

For more information, see Return Statement (Visual Basic).


Upgrade Suggestions
The Upgrade Wizard produces this code from the Draw method:
VB
Public Sub Draw(ByRef theForm As System.Windows.Forms.Form)
' Add code here to draw a tree on the form.
End Sub

Some techniques to consider in upgraded methods include:


Consider using overloaded methods for methods that have similar names and similar behavior, but vary by parameter
and return types.
Verify the conversion of method scope (Public, Private, Friend) and return type (Short, Integer, and so forth).
Consider using the Return statement instead of the function name to return the function value.

See Also
Reference
Sub Statement (Visual Basic)
Function Statement (Visual Basic)
Return Statement (Visual Basic)
Visual Basic Concepts

Inheritance for Visual Basic 6.0 Users


Inheritance allows you to create new classes from existing classes. Inheritance can simplify the design of the application by
providing a relationship structure between the various classes. It also supports code reuse, because only the new or different
class behavior must be coded.
Interface Inheritance
Visual Basic 6.0
Visual Basic 6.0 supports interface inheritance, covered in more detail in Interface Changes for Visual Basic 6.0 Users.
Visual Basic 2005
Visual Basic 2005 supports interface inheritance with the Interface Statement (Visual Basic) and Implements Statement. For
more information on interfaces, see Interfaces in Visual Basic.
Implementation Inheritance
When a new class is created through implementation inheritance, the new class automatically gains all the members and
implementation of the base class. The existing class is called the "base class." The new class is the "derived class." Additional
members can be added to the class. The behavior of the base class can be changed by writing code in the new class. This
technique is called overriding.
You can create classes by inheriting from the classes you create, from classes in references you add to your project, or from
objects in the .NET Framework. Many classes of the .NET Framework are related by inheritance. For example, the TextBox class
inherits from the System.Windows.Forms.TextBoxBase class.
Visual Basic 6.0
Visual Basic 6.0 does not support implementation inheritance.
Visual Basic 2005
Inheritance is declared in Visual Basic 2005 by the Inherits statement. In this example, the derived class Oak inherits from a
base class Tree.
VB
Public Class Oak
Inherits Tree
' Add code here to extend or
' modify the behavior of the Tree class.
End Class

MustInherit and NotInheritable


Visual Basic 6.0
In interface inheritance in Visual Basic 6.0, any class can act as an interface base class. There is no syntax for preventing any
class to act as an interface base class. Likewise, there is no syntax to demand that a class act only as an interface base class.
Visual Basic 2005
Along with implementation inheritance, Visual Basic 2005 defines two class modifiers, MustInherit and NotInheritable. These
modifiers let the programmer control the inheritance relationships in an application.
The MustInherit modifier on a class declaration indicates a class that cannot be instantiated:
VB
Public MustInherit Class BaseClass
End Class

This means that BaseClass cannot appear after the New keyword. Only classes that inherit from BaseClass and that do not
also have the MustInherit modifier can be instantiated. In object-oriented literature and in other object-oriented languages, a
MustInherit class is called an abstract class. A class that is not a MustInherit class, one that can be instantiated, is called a
concrete class.
A related concept is the sealed class, a class that cannot serve as a base class. The NotInheritable keyword on a class
definition indicates this status:
VB
Public NotInheritable Class DerivedClass
End Class

A NotInheritable class marks the edge of an inheritance hierarchy.


For more information, see Inheritance in Visual Basic.
Upgrade Suggestions
Classes acting as interfaces in Visual Basic 6.0 are upgraded to interfaces in Visual Basic 2005. Consider this example of a base
class and derived class from Visual Basic 6.0:

' Contents of class BaseClass


Public Sub BaseMethod()
End Sub

' Contents of class DerivedClass


Implements BaseClass
Private Sub BaseClass_BaseMethod()
End Sub

The Upgrade Wizard produces this upgraded code:


VB
Option Strict Off
Option Explicit On
Interface _BaseClass
Sub BaseMethod()
End Interface

Friend Class BaseClass


Implements _BaseClass
Public Sub BaseMethod() Implements _BaseClass.BaseMethod
End Sub
End Class

Friend Class DerivedClass


Implements _BaseClass
Private Sub BaseClass_BaseMethod() Implements _BaseClass.BaseMethod
End Sub
End Class

Using inheritance instead of interfaces, the upgraded code can be modified to:
VB
Friend Class BaseClass
Public Sub BaseMethod()
' Add code here to define BaseMethod.
End Sub
End Class

Friend Class DerivedClass


Inherits BaseClass
End Class
This eliminates one level of indirection, _BaseClass. Also, it eliminates one method definition, BaseClass_BaseMethod, because
the method is inherited from the base class and does not need to be coded again. If the programmer wanted a different
behavior for the derived class, the BaseMethod can be overridden as shown:
VB
Friend Class BaseClass
Public Overridable Sub BaseMethod()
' Add code here to define BaseMethod.
End Sub
End Class
Friend Class DerivedClass
Inherits BaseClass
Public Overrides Sub BaseMethod()
' Add code here to define behavior for DerivedClass.
End Sub
End Class

Some techniques to consider in upgraded interfaces include:


Replace Interface statements with Inherits statements.
Implement the base class as an interface, rather than as a class that implements an interface. For more information see
Interface Changes for Visual Basic 6.0 Users.
Implement base classes as MustInherit classes.
Implement derived classes as NotInheritable.

See Also
Other Resources
Inheritance in Visual Basic
Interfaces in Visual Basic
Visual Basic Concepts

Event and Exception Changes for Visual Basic 6.0 Users


Events and exceptions are class members that are used to signal changes in the class to the client code. Typically, an event
signals an expected change, and the client code can choose to respond or not. Exceptions signal an error state, and the client
code ignores this at its own risk. For more information, see Structured Exception Handling in Visual Basic.
Events
Visual Basic 6.0
The syntax for declaring an event has not changed from Visual Basic 6.0:

Public Event StateChanged()

Visual Basic 2005


The class library of the .NET Framework introduces a new coding convention for events. Events typically have two parameters,
an Object parameter named sender, and an EventArgs parameter named e. When the event is raised, the object raising the
event passes a reference to itself as the sender parameter. The EventArgs parameter may be an EventArgs object, or an
instance of a class that derives from EventArgs. The derived class carries information specific to the event that can be useful to
the client code. An example follows:
VB
Public Event StateChanged(ByVal sender As Object, ByVal e As EventArgs)

Exceptions
Visual Basic 6.0
Exceptions are not supported in Visual Basic 6.0, but raising an error is. Errors are caught using On Error GoTo statements in
conjunction with labeled statements.
Visual Basic 2005
Raising an error is supported in Visual Basic 2005. For more information, see Unstructured Exception Handling Overview.
Exceptions are new in Visual Basic 2005. The Exception class serves as a base class for all exceptions. (For more information,
see Exception Class and Properties.) Rather than creating error numbers, as in Visual Basic 6.0, the programmer creates derived
classes. This can make the code more readable. Instead of GoTo statements and labeled statements, the
Try...Catch...Finally Statement (Visual Basic) block structure is used to respond to exceptions. An example is shown below.
VB
Dim big As Integer = Integer.MaxValue
Dim bigger As Integer = Integer.MaxValue
Try
Dim biggest As Integer = big + bigger
Catch ex As Exception
MsgBox("Addition did not succeed.")
End Try

For more information, see Structured Exception Handling Overview for Visual Basic.
Upgrade Suggestions
Code that raises errors in Visual Basic 6.0 is converted to code that raises errors in Visual Basic 2005. Here is an example of
converted code that raises an error:
VB
Private mvarAge As Short
Public Property Age() As Short
Get
Age = mvarAge
End Get
Set(ByVal Value As Short)
If Value >= 0 Then
mvarAge = Value
Else
Err.Raise(vbObjectError + 2, Me, _
"Age must be greater than or equal to zero.")
End If
End Set
End Property

Using an exception instead requires only replacing the Err.Raise call with a Throw Statement (Visual Basic). Another benefit is
that the error number can be eliminated.
When upgrading events and exceptions to Visual Basic 2005, consider:
Replacing On Error GoTo statements with Try statements.
Replacing Err.Raise with Throw
Using the parameter conventions for events (Public Event StateChanged(ByVal sender As Object, ByVal e As
EventArgs)).

Creating custom exceptions and EventArgs classes through inheritance.


See Also
Reference
Throw Statement (Visual Basic)
EventArgs
Concepts
Structured Exception Handling Overview for Visual Basic
Other Resources
Exception and Error Handling in Visual Basic
Visual Basic Concepts

Interface Changes for Visual Basic 6.0 Users


An interface, as defined in Visual Basic, is a type that defines a list of public members. An Interface type cannot be instantiated
or implemented.
Interface and Classes
The interface of a class is its list of public members. The Interface statement, in Visual Basic 2005, allows you to declare a type
that defines a list of public members. When a class includes the Implements statement, it adds the members of the interface
by implementing each member of the interface. This is in contrast to implementation inheritance using the Inherits keyword.
In implementation inheritance, the members are inherited from the base class and do not have to be implemented in the
derived class.
In the .NET Framework, interfaces are often used by classes to provide support for some service in the application. As an
example, the .NET Framework provides that if a class implements the System.IComparable interface, then the runtime will sort
instances of the class if they are contained in an ArrayList.
For more information on using interfaces in Visual Basic 2005, see Interfaces in Visual Basic.
Visual Basic 6.0
In Visual Basic 6.0, any class can act as an interface. Any other class can implement the interface of another class, using the
Implements Statement, as shown below.

' Contents of class BaseClass


Public Sub BaseMethod()
End Sub

' Contents of class DerivedClass


Implements BaseClass
Private Sub BaseClass_BaseMethod()
End Sub

While individual members of the class do not have to contain any code, they may do so.
Visual Basic 2005
Visual Basic 2005 makes a clear distinction between classes and interfaces. One is declared in a Class statement; the other is
declared in an Interface statement. A class cannot act as an interface. To act as an interface, the type must be declared using
Interface. Members of an interface are not implemented. In fact, the syntax does not allow such lines of code as End Sub in an
interface definition. Members of an interface are implemented in the class that declares an interface using the Implements
statement:
VB
Interface Printable
Sub Print()
Property Mode() As Integer
End Interface
Public Class Tree
Implements Printable

Private modeValue As Integer


Public Property Mode() As Integer Implements Printable.Mode
Get
Return modeValue
End Get
Set(ByVal Value As Integer)
modeValue = Value
End Set
End Property
Public Sub Print() Implements Printable.Print
' Add code to print a tree.
End Sub
End Class

Upgrade Suggestions
The only option for implementing inheritance in Visual Basic 6.0 is by using the Implements statement and a base class. In
newer versions of Visual Basic, there are two types of inheritance: implementation inheritance and interface inheritance. The
type you should select depends on your application. Issues to consider include:
Implementation inheritance, using the Inherits Statement, allows you to create new classes without writing more code.
You only add code when you want to modify the base class behavior. With interface inheritance, you have to add code
for every base class member.
Interfaces can be used when you want to inherit from more than one class. Visual Basic 2005 only supports inheriting
from one class, but a class can implement multiple interfaces.
The .NET Framework defines several interfaces that simplify common programming tasks. Examples include
IComparable, ISerializable, and IFormattable.
For many .NET Framework interfaces, the .NET Framework also supplies a class that implements the interface. An
example is the Component class that implements the IComponent interface. By inheriting from Component using the
Inherits Statement, a class gains all the features of the IComponent interface without having to write any code.
See Also
Reference
Interface Statement (Visual Basic)
Class Statement (Visual Basic)
Inherits Statement
Visual Basic Concepts

Object-Oriented Changes for Modules in Visual Basic


Shared members are class members, such as properties and procedures, that are available for all the instances of a class, but
not associated with any particular instance of a class. For more information on shared members, see
Shared Members in Visual Basic.
Instance Data and Shared Data
Instance data is the set of data created when the New keyword is executed. By contrast, the shared data of a class is created
independently of any execution of the New keyword.
Visual Basic 6.0
Visual Basic 6.0 does not support shared data in class definitions. To share data across class instances, a global variable in a
module is used.
Visual Basic 2005
Shared data is declared by adding the Shared (Visual Basic) modifier to the variable declaration statement, as shown.
VB
Private Shared totalInstances As Integer

Shared Methods
Visual Basic 6.0
Visual Basic 6.0 does not support shared class members. Similar functionality is available from modules. The runtime only
creates one instance of the data in a module. The data and methods of a module have a project-wide scope. Here is an example
of a library implemented in a module:

Public Sub GetTitle(wordXml As String)


' Add code here to find title in Xml string.
End Sub

Public Sub ReplaceTitle(wordXml As String, newTitle As String)


' Add code here to replace title.
End Sub

Visual Basic 2005


A more object-oriented approach to modules is to use shared class members, if the members are related to each other as a
library, or if the members are related to an existing class. The design will determine if all the members are shared, or whether a
class has a mix of shared and instance members. If the class has only shared members, adding only a private constructor will
prevent the class from being instantiated by client code. The following example shows a class that cannot be instantiated by
client code and the client code that calls one of the members.
VB
Public Class WordLibrary
Public Shared Sub GetTitle(ByVal wordXml As String)
' Add code here to find title in Xml string.
End Sub

Public Shared Sub ReplaceTitle(ByVal wordXml As String, _


ByVal newTitle As String)
' Add code here to replace title.
End Sub
Private Sub New()
' This prevents instantiation of the class in the client.
End Sub
End Class
VB
' Code that calls the library method.
Sub ChangeTheTitle()
WordLibrary.ReplaceTitle("Old Title", "New Title")
End Sub

Some advantages of using a class over a module for this library are:
The library has a name, WordLibrary, that is explicitly called out in the code.
The methods are grouped into one class, indicating their relationship to each other.
The use of a private constructor makes it clear that this class provides a set of utility methods.
The client code uses the library name, making the project organization clear to the reader.
In the .NET Framework, shared methods are commonly used to provide functionality that is related to a class, but does not
require an instance of the class. One example is the Parse method that is supported by many of the data types in the .NET
Framework. The Integer Data Type (Visual Basic) supports a Parse method that takes a string as parameter. The Parse method
returns the integer represented by the string. It does not make sense for the Parse method to be a member method. There is
no integer value to manipulate, only a string.
Accessing Shared Members
Visual Basic 6.0
Visual Basic 6.0 does not support shared class members.
Visual Basic 2005
Shared members can be accessed using the class name or instance name, as shown.
VB
WordLibrary.ReplaceTitle("Old Title", "New Title")

Shared methods cannot access any instance data unless a reference to an instance of the class is passed to the shared method.
Upgrade Suggestions
The Visual Basic 6.0 WordLibrary module is upgraded to the following code:
VB
Module WordLibrary
Public Sub GetTitle(ByRef wordXml As String)
' Add code here to find title in Xml string.
End Sub

Public Sub ReplaceTitle(ByRef wordXml As String, _


ByRef newTitle As String)
' Add code here to replace title.
End Sub
End Module

When upgrading module code from Visual Basic 6.0 to Visual Basic 2005, consider the following:
Organizing module methods and data into classes as shared data and methods.
Moving module methods into existing classes as shared methods, when the method is related to the class.
See Also
Concepts
Shared Members in Visual Basic
Visual Basic Concepts

Binary Compatibility Changes for Visual Basic 6.0 Users


Visual Basic 2005 updates the mechanism for preserving compatibility with older versions of a component.
Binary Compatibility
Visual Basic 6.0
In Visual Basic 6.0, the Binary Compatibility option allows you to automatically retain class and interface identifiers from a
previous version of a component when you compile a new version. The new version contains both the old identifiers and the
new identifiers, and client applications can continue using the old interface to your component without having to be updated.
Visual Basic 2005
In Visual Basic 2005, binary compatibility is accomplished using attributes. This gives you direct control over the information
placed in your compiled component, such as class and interface identifiers, virtual table offsets, and any appropriate COM
attributes. Because you can explicitly select attributes for preservation, the Binary Compatibility option of Visual Basic 6.0 is
not supported.
See Also
Reference
ComClassAttribute Class
Concepts
Attributes Overview in Visual Basic
Attributes Used in Visual Basic
Global Attributes in Visual Basic
Programming Element Support Changes Summary
Visual Basic Concepts

How to: Convert a Custom Collection to a Visual Basic Typed


Collection
A Visual Basic 6.0 custom collection limits the contents of a collection to one particular class. This is also known as a typed
collection. Visual Basic 2005 provides several options for creating typed classes from Visual Basic 6.0 custom collections. This
topic contains three procedures, each showing a different option.
This topic assumes that the Visual Basic 6.0 custom collection has been created using the Class Builder Utility. Such a
collection has the following members:
Add Adds a new instance of the custom class to the collection.
Item Returns an instance from the collection based on an index into the collection.
Count Returns the number of instances in the collection.
Remove Removes an instance from the collection based on an index into the collection.
Enumeration Supports enumeration using the For Each syntax.
To use the Upgrade Wizard to create a collection
Open the Visual Basic 6.0 project in Visual Basic 2005. For a collection class named Forest that contains instances of the
Tree class, the upgraded code is shown below. The advantage of this method is that no changes to the code are required.

VB
' For this example, the Tree class has no members.
Option Strict Off
Option Explicit On
Friend Class Tree
End Class

Friend Class Forest


Implements System.Collections.IEnumerable
'local variable to hold collection
Private mCol As Collection

Public Function Add(Optional ByRef sKey As String = "") As Tree


'create a new object
Dim objNewMember As Tree
objNewMember = New Tree
'set the properties passed into the method
If Len(sKey) = 0 Then
mCol.Add(objNewMember)
Else
mCol.Add(objNewMember, sKey)
End If
'return the object created
Add = objNewMember
'UPGRADE_NOTE: Object objNewMember may not be destroyed until it is garbage collec
ted. Click for more: 'ms-help://MS.MSDNQTR.80.en/commoner/redir/redirect.htm?keyword="
vbup1029"'

objNewMember = Nothing
End Function

Default Public ReadOnly Property Item(ByVal vntIndexKey _


As Object) As Tree
Get
'used when referencing an element in the collection
'vntIndexKey contains either the Index or Key to the collection,
'this is why it is declared as a Variant
'Syntax: Set foo = x.Item(xyz) or Set foo = x.Item(5)
Item = mCol.Item(vntIndexKey)
End Get
End Property

Public ReadOnly Property Count() As Integer


Get
'used when retrieving the number of elements in the
'collection. Syntax: Debug.Print x.Count
Count = mCol.Count()
End Get
End Property

'UPGRADE_NOTE: NewEnum property was commented out. Click for more: 'ms-help://MS.MSD
NQTR.80.en/commoner/redir/redirect.htm?keyword="vbup1054"'

'Public ReadOnly Property NewEnum() As stdole.IUnknown


'Get
'this property allows you to enumerate
'this collection with the For...Each syntax
'NewEnum = mCol._NewEnum
'End Get
'End Property

Public Function GetEnumerator() As System.Collections.IEnumerator _


Implements System.Collections.IEnumerable.GetEnumerator
'UPGRADE_TODO: Uncomment and change the following line to return the collection en
umerator. Click for more: 'ms-help://MS.MSDNQTR.80.en/commoner/redir/redirect.htm?keyw
ord="vbup1055"'

'GetEnumerator = mCol.GetEnumerator
End Function

Public Sub Remove(ByRef vntIndexKey As Object)


'used when removing an element from the collection
'vntIndexKey contains either the Index or Key, which is why
'it is declared as a Variant
'Syntax: x.Remove(xyz)
mCol.Remove(vntIndexKey)
End Sub

'UPGRADE_NOTE: Class_Initialize was upgraded to Class_Initialize_Renamed. Click for


more: 'ms-help://MS.MSDNQTR.80.en/commoner/redir/redirect.htm?keyword="vbup1061"'

Private Sub Class_Initialize_Renamed()


'creates the collection when this class is created
mCol = New Collection
End Sub
Public Sub New()
MyBase.New()
Class_Initialize_Renamed()
End Sub

'UPGRADE_NOTE: Class_Terminate was upgraded to Class_Terminate_Renamed. Click for mo


re: 'ms-help://MS.MSDNQTR.80.en/commoner/redir/redirect.htm?keyword="vbup1061"'
Private Sub Class_Terminate_Renamed()
'destroys collection when this class is terminated
'UPGRADE_NOTE: Object mCol may not be destroyed until it is garbage collected. Cli
ck for more: 'ms-help://MS.MSDNQTR.80.en/commoner/redir/redirect.htm?keyword="vbup1029
"'

mCol = Nothing
End Sub
Protected Overrides Sub Finalize()
Class_Terminate_Renamed()
MyBase.Finalize()
End Sub
End Class

The .NET Framework and Visual Basic 2005 offer several generic collections. The advantage to using generic classes is that very
little code is required to implement the class.
To create a collection using generic collections
1. Create the class definition. Here is an example of a Tree class:
VB
Public Class Tree
Public Species As String
End Class

2. Create a generic list class from the .NET Framework. This declaration essentially replaces the entire Forest class in the
procedure above named "To use the Upgrade Wizard to create a collection."
VB
Dim forest As New System.Collections.Generic.List(Of Tree)

3. Write code to access the list object. The following code adds five instances of the Tree class to the collection and then
prints them out.
VB
For count As Integer = 1 To 5
Dim sapling As New Tree
sapling.Species = "oak"
Forest.Add(sapling)
Next

For Each sapling As Tree In Forest


MsgBox(sapling.Species)
Next

The .NET Framework includes the CollectionBase class. Typed collections are created by inheriting from CollectionBase. This
method uses less code than the Upgrade Wizard method, but more than the generics solution. It is more flexible than the
generics solution, because the programmer can add additional members to the collection class.
To create a collection from the CollectionBase class
1. Create the class definition. Here is an example of a Tree class:
VB
Public Class Tree
Public Species As String
End Class

2. Create a class that inherits from the CollectionBase class. At a minimum, add an Add method and an Item property.
These make the collection class strongly-typed.
VB
Class TreeCollection
Inherits System.Collections.CollectionBase

Public Sub Add(ByVal value As Tree)


Me.List.Add(value)
End Sub

Default Public Property Item(ByVal index As Integer) As Tree


Get
Return CType(Me.List(index), Tree)
End Get
Set(ByVal value As Tree)
If index <= Me.Count - 1 Then
Me.List(index) = value
Else
Throw New IndexOutOfRangeException()
End If
End Set
End Property
End Class

3. Write code to access the list object. The following code adds five instances of the Tree class to the collection and then
prints them out.
VB
Dim forest As New TreeCollection

VB
For count As Integer = 1 To 5
Dim sapling As New Tree
sapling.Species = "oak"
Forest.Add(sapling)
Next

For Each sapling As Tree In Forest


MsgBox(sapling.Species)
Next

See Also
Reference
List
CollectionBase
Ienumerable
Visual Basic Concepts

How to: Convert a User-Defined Type to a Visual Basic


Structure
The Type statement of Visual Basic 6.0 is upgraded to the Structure statement of Visual Basic 2005. Two other options for
upgrading the type are also discussed in this topic: converting to a class and converting to an interface.
The following Visual Basic 6.0 type is discussed in the procedures that follow:

Type Customer
Dim FirstName As String
Dim LastName As String
Dim Id As Long
End Type

Private Function FormatFullName(aCustomer As Customer) As String


FormatFullName = aCustomer.FirstName & " " & aCustomer.LastName
End Function

The Upgrade Wizard automatically upgrades a Visual Basic 6.0 type to a Visual Basic 2005 structure. The Structure is a type
that supports members, such as methods and properties.
To upgrade a type to a structure
1. Run the Upgrade Wizard.
Note
The Upgrade Wizard is a tool used to upgrade a Visual Basic 6.0 application to Visual Basic 2005. It is automatically la
unched when you open a Visual Basic 6.0 project in Visual Basic 2005. For more information, see
How to: Upgrade a Project with the Visual Basic Upgrade Wizard.

2. If you are interested in taking advantage of other features of the Structure type, look for methods that more properly
belong in the structure. In this example, the FormatFullName method could be converted to a FormatFullName method in
the structure:
VB
Structure Customer
Dim FirstName As String
Dim LastName As String
Dim Id As Integer

Public Function FormatFullName() As String


Return FirstName & " " & LastName
End Function
End Structure

The Upgrade Wizard will automatically upgrade a Visual Basic 6.0 type to a Visual Basic 2005 structure. The Class type
supports the same members as a Structure, but is a reference type. A class can serve as a base class, while a structure cannot.
To upgrade to a class
1. Run the Upgrade Wizard.
2. Replace Structure with Class.
3. If you are interested in taking advantage of other features of the Class type, look for methods that more properly belong
in the structure. The following code shows the incorporation of FormatFullName into the class, and the Id property.
VB
Class Customer
Dim FirstName As String
Dim LastName As String
Private idValue As Integer

Public Property Id() As Integer


Get
Return idValue
End Get
Set(ByVal Value As Integer)
idValue = Value
End Set
End Property

Public Function FormatFullName() As String


Return FirstName & " " & LastName
End Function
End Class

A third option is to convert the structure to an interface.


To upgrade to an interface
1. Run the Upgrade Wizard.
2. Replace Structure with Interface.
3. Replace variables with property declarations. Do not include the implementation.
4. Add methods, but remove the implementation.
5. The code might look like this:
VB
Interface Customer
Property FirstName() As String
Property LastName() As String
Property Id() As String

Function FormatFullName() As String


End Interface

6. The Interface can then be implemented by another class. The definition is shown below.
VB
Class NewCustomer
Implements Customer

Public Property FirstName() As String Implements Customer.FirstName


Get
' Add code here.
End Get
Set(ByVal Value As String)
' Add code here.
End Set
End Property
Public Property Id() As String Implements Customer.Id
Get
' Add code here.
End Get
Set(ByVal Value As String)
' Add code here.
End Set
End Property

Public Property LastName() As String Implements Customer.LastName


Get
' Add code here.
End Get
Set(ByVal Value As String)
' Add code here.
End Set
End Property

Public Function FormatFullName() As String _


Implements Customer.FormatFullName
' Add code here.
End Function
End Class

See Also
Tasks
How to: Upgrade a Project with the Visual Basic Upgrade Wizard
Reference
Structure Statement
Class Statement (Visual Basic)
Interface Statement (Visual Basic)
Visual Basic Concepts

How to: Convert Implements Code to a New Form of


Inheritance
Visual Basic 6.0 uses the Implements statement for interface inheritance. Newer versions of Visual Basic offer two types of
inheritance, using the Implements Statement and the Inherits Statement. This topic demonstrates how to convert code using
these two options.
The following Visual Basic 6.0 code is considered on this page:

' Account class.


Private mvarBalance As Currency
Private mvarOwner As String

Public Property Let Owner(ByVal vData As String)


mvarOwner = vData
End Property

Public Property Get Owner() As String


Owner = mvarOwner
End Property

Public Function Deposit(ByVal amount As Currency) As Currency


End Function

' Savings class.


Private mvarBalance As Currency
Private mvarOwner As String 'local copy

Public Property Let Owner(ByVal vData As String)


mvarOwner = vData
End Property

Public Property Get Owner() As String


Owner = mvarOwner
End Property

Public Function Deposit(ByVal amount As Currency) As Currency


End Function

To convert using a common interface


1. Run the Upgrade Wizard.
Note
The Upgrade Wizard is a tool used to upgrade a Visual Basic 6.0 application to Visual Basic 2005. It is automatically la
unched when you open a Visual Basic 6.0 project in Visual Basic 2005. For more information, see
How to: Upgrade a Project with the Visual Basic Upgrade Wizard.

The wizard will convert the Account class to an interface (_Account), and create two classes that implement the interface
(Account and Savings.)
VB
Interface _Account
Property Owner() As String
Function Deposit(ByVal amount As Decimal) As Decimal
End Interface
Friend Class Account
Implements _Account
Private mvarBalance As Decimal
Private mvarOwner As String

Public Property Owner() As String Implements _Account.Owner


Get
Owner = mvarOwner
End Get
Set(ByVal Value As String)
mvarOwner = Value
End Set
End Property

Public Function Deposit(ByVal amount As Decimal) _


As Decimal Implements _Account.Deposit
End Function
End Class

Friend Class Savings


Implements _Account

Private Function Account_Deposit(ByVal amount As Decimal) _


As Decimal Implements _Account.Deposit
End Function

Private Property Account_Owner() As String _


Implements _Account.Owner
Get
End Get
Set(ByVal Value As String)
End Set
End Property

Public Function AddInterest() As Object


End Function
End Class

2. The code to create and use an instance of the Savings account could look like this.
VB
Dim savings As _Account
savings = New Savings
savings.Owner = "Jeff Pike"

If you want Account to be the base class, you can modify the wizard output.
To convert with Interface and Implements
1. Run the Upgrade Wizard.
2. Delete the Account class.
3. Rename the _Account class to Account.
4. In the Savings class, replace _Account with Account.
VB
Friend Class Savings
Implements Account
Private Function Account_Deposit(ByVal amount As Decimal) _
As Decimal Implements Account.Deposit
End Function

Private Property Account_Owner() As String Implements Account.Owner


Get
End Get
Set(ByVal Value As String)
End Set
End Property

Public Function AddInterest() As Object


End Function
End Class

5. The code to create and use an instance of the Savings account could look like this.
VB
Dim savings As Account
savings = New Savings
savings.Owner = "Jeff Pike"

If you want the Account class to be a base class, you can modify the wizard output.
To convert with Class and Inherits
1. Run the Upgrade Wizard.
2. Delete the _Account interface.
3. In the Account class, remove references to the _Account in Implements statements.
VB
Friend Class Account
Private mvarBalance As Decimal
Private mvarOwner As String

Public Property Owner() As String


Get
Owner = mvarOwner
End Get
Set(ByVal Value As String)
mvarOwner = Value
End Set
End Property

Public Function Deposit(ByVal amount As Decimal) As Decimal


End Function
End Class

4. In the Savings class, replace Implements _Account with Inherits Account.

5. In the Savings class, remove the Owner and Deposit members.


VB
Friend Class Savings
Inherits Account

Public Function AddInterest() As Object


End Function
End Class

6. The code to create and use an instance of the Savings account could look like this.
VB
Dim savings As Account
savings = New Savings
savings.Owner = "Jeff Pike"

See Also
Tasks
How to: Upgrade a Project with the Visual Basic Upgrade Wizard
Reference
Class Statement (Visual Basic)
Inherits Statement
Interface Statement (Visual Basic)
Implements Statement
Other Resources
Inheritance in Visual Basic
Interfaces in Visual Basic
Visual Basic Concepts

Web Programming for Visual Basic 6.0 Users


Visual Basic 6.0 supports Web programming directly; in Visual Basic 2005, Web programming is done using Visual Web
Developer and the Visual Basic language.
Conceptual Differences
Visual Basic 6.0 includes several features that support programming for the Web: Internet Information Services (IIS)
applications (Web classes), DHTML applications, ActiveX documents, and ActiveX controls that can be downloaded to Web
pages.
In Visual Basic 2005, Web programming is no longer directly supported. Instead, you can use Visual Web Developer and the
Visual Basic language to create ASP.NET Web sites, ASP.NET Web services, and much more. You can create Web controls in
Visual Basic 2005 that can be used in Visual Web Developer, and you can consume ASP.NET Web services from a Visual Basic
2005 application or component.
ASP and ASP.NET
In Visual Basic 6.0, IIS (Internet Information Services) applications use the Active Server Pages (ASP) model to create
applications that run on IIS. ASP.NET technology allows you to create a Web site using Web Forms pages; ASP.NET Web-site
applications are also hosted on IIS.
DHTML Applications
Visual Basic 6.0 DHTML applications use the Dynamic HTML object model and Visual Basic code to create applications that can
respond to actions performed by the user in a browser. Visual Web Developer Web Forms expand upon the DHTML model,
providing richer dynamic user-interface capabilities as well as client-side validation.
ActiveX Documents and Controls
Visual Basic 6.0 ActiveX documents are not supported in Visual Basic 2005. You can still interoperate with ActiveX documents
from your Visual Web Developer Web-site applications, but development should be maintained in Visual Basic 6.0.
Visual Basic 2005 also allows you to create ActiveX controls that can be downloaded to Web pages, or to use existing ActiveX
controls in your Visual Basic 2005 applications.
See Also
Concepts
Working with Both Visual Basic 6.0 and the Current Version of Visual Basic
Other Resources
Visual Web Developer
Help for Visual Basic 6.0 Users
Web Namespaces in Visual Studio
Programming the Web with XML Web Services
Visual Basic Concepts

WebClasses for Visual Basic 6.0 Users


For the most part, the concepts and techniques for programming an ASP.NET Web site in Visual Basic 2005 are considerably
different from those for creating Web classes in Visual Basic 6.0.
Conceptual Differences
In Visual Basic 6.0, WebClass projects (also known as IIS Application projects) are used to create Web applications based on
ASP page technology.
In Visual Basic 2005, ASP.NET Web-site projects are used to create Web applications based on the newer ASP.NET technology.
For more information, see Guided Tour of Creating Web Sites in Visual Web Developer.
State Management
In Visual Basic 6.0, WebClass projects have a StateManagement property that can be used to keep an instance of the
WebClass alive between requests. This is done by setting the StateManagement property to 2 or wcRetainInstance at
design time; there is also a ReleaseInstance method that can be used to terminate an instance.
In Visual Basic 2005, ASP.NET Web applications do not have a StateManagement property. The model for managing
application state differs considerably, and any code related to state management needs to be replaced. For more information,
see ASP.NET State Management.
Upgrade Notes
When a Visual Basic 6.0 WebClass project is upgraded to Visual Basic 2005, it is converted to an ASP.NET Web-site project.
Declarations are added to your project: one for the WebClass and one for each of the WebItems and Templates in the
WebClass project. A Page_Load event procedure is added to the project, creating first a WebClass object and then WebItem
objects for each of the WebItems and Templates associated with the Visual Basic 6.0 WebClass project. Finally, in the
Page_Load event procedure, you will see a call to the WebClass Compatibility runtime: WebClass.ProcessEvents. This allows
the runtime to render the WebItem specified in the Request URL. This code is the only new code added to your upgraded
project and only serves to emulate the underlying behavior of the Visual Basic 6.0 WebClass runtime.
Function and Sub procedures in your Visual Basic 6.0 code (for example, ProcessTags or Respond) will have their scope
changed from Private to Public to allow the WebClass Compatibility runtime to execute them.
Certain Visual Basic 6.0 WebClass events are not supported in ASP.NET (for example, Initialize, BeginRequest, EndRequest,
and Terminate). These event procedures will be upgraded but will not be called at runtime. After upgrading, you will need to
move any code in these events to equivalent ASP.NET events.
Note
There are a number of behavioral differences for properties, methods, and events between ASP and ASP.NET objects. Before
upgrading a WebClass to ASP.NET, you should understand these differences so you know how to modify your code. For mor
e information, see Guided Tour of Creating Web Sites in Visual Web Developer.

See Also
Reference
WebClass event is not supported
Concepts
Upgrading WebClass Projects to Visual Basic 2005
Other Resources
ASP.NET Web Pages Introduction (Visual Studio)
Visual Basic Concepts

Data Access for Visual Basic 6.0 Users


In Visual Basic 6.0, data access is accomplished using ActiveX Data Objects (ADO). In Visual Basic 2005, data access is
accomplished using ADO.NET, which is a part of the .NET Framework. There are a number of differences, both conceptually and
in terms of tasks, between the two technologies. For more information on conceptual differences between ADO and ADO.NET,
see Comparison of ADO.NET and ADO.
Note
Visual Basic 6.0 also provides backward compatibility support for Remote Data Objects (RDO) and Data Access Objects (DAO
). These technologies are supported in Visual Basic 2005 only as COM objects; applications that use RDO or DAO data bindin
g cannot be upgraded to Visual Basic 2005. For more information, see
Upgrading Applications Created in Previous Versions of Visual Basic.

In Visual Basic 6.0, there are two common methods of implementing data access in an application: at design time, by binding to
an ADODC (ADO data control) or by using a Data Environment, or at run time by creating and interacting with Recordset
objects programmatically.
In Visual Basic 2005, there are two analogous methods of implementing data access: at design time by using data adapters and
datasets, or at run time by adding code to create data adapters and datasets programmatically. For more information, see
Creating Data Adapters.
In Visual Basic 6.0, data binding is accomplished by setting the binding-related properties of a control: DataChanged,
DataField, DataFormat, DataMember, and DataSource. In most cases, the display property of a control (for example, the
Text property of a TextBox control) is bound to a field in a data source.
In Visual Basic 2005, data binding has a much broader definition—you can bind any property of any control to any structure
that contains data. Binding in Windows Forms is accomplished by means of a DataBindings property that contains a
collection of Binding objects for the control. For more information, see Data Binding and Windows Forms.
Note
ADO data binding is supported for backward compatibility with the Microsoft Visual Basic 2005 Compatibility Data Runtime.

In Visual Basic 6.0, data-bound forms are automatically created by dragging database elements from a Data Environment onto
a form.
See Also
Other Resources
Creating Client Data Applications
Connecting to Data with Server Explorer/Database Explorer
Visual Database Tools
Help for Visual Basic 6.0 Users
Data Namespaces in Visual Studio
Visual Basic Concepts

Component Authoring for Visual Basic 6.0 Users


Although both Visual Basic 6.0 and Visual Basic 2005 provide capabilities for creating components, there are some important
differences in component authoring.
Conceptual Differences
In Visual Basic 6.0, component authoring is all about creating COM components: ActiveX Controls, ActiveX DLLs, and ActiveX
EXEs that can be used in COM applications.
In Visual Basic 2005, components are based on the .NET Framework; you create components that can be used in applications
built using the .NET Framework. Components built with Visual Basic 2005 are based on inheritance—every component derives
from either the Component or Control base class. For more information, see Component Classes.
Multithreaded Components
Visual Basic 6.0 provides two models for threading—components can either be single threaded or apartment threaded.
Visual Basic 2005 supports true multithreaded components. For more information, see Multithreading in Components.
Component Instancing
In Visual Basic 6.0, the Instancing property of a class controls the access level and the way a component can be created.
In Visual Basic 2005, setting the access modifier and access level in the constructor for a component class controls instancing.
For more information, see Component Instancing Changes in Visual Basic.
Binary Compatibility and Versioning
Binary compatibility for components is important in Visual Basic 6.0 in order to prevent version conflicts; it is controlled by the
Version Compatibility property for the component project.
In Visual Basic 2005, versioning is built into the assemblies for components; you no longer need to worry about setting binary
compatibility. For more information, see Programming with Components.
ActiveX Controls
In Visual Basic 6.0, you can create ActiveX controls (also referred to as user controls) that can be used in Windows-based
applications.
In Visual Basic 2005, you can create user controls for Windows Forms, or you can inherit from existing controls to add
functionality. For more information, see Developing Windows Forms Controls at Design Time.
Messaging
In Visual Basic 6.0, you can create components that use Microsoft Message Queuing (MSMQ) to pass information between
applications.
In Visual Basic 2005, messaging is built into the .NET Framework. For more information, see Using Messaging Components.
Transactions
In Visual Basic 6.0, you can create MTS components that work with Microsoft Transaction Server (MTS) to participate in
transactions.
With Visual Basic 2005, transactions are handled by the .NET Framework by adding a transactional component to your project
or by adding a Transaction attribute to an existing class.
See Also
Concepts
User Controls for Visual Basic 6.0 Users
Inheritance for Visual Basic 6.0 Users
Other Resources
Component Authoring
Help for Visual Basic 6.0 Users
Component Model Namespaces in Visual Studio
Visual Basic Concepts

User Controls for Visual Basic 6.0 Users


Visual Basic 6.0 and Visual Basic 2005 both allow you to create controls; however there are several differences you should be
aware of.
Conceptual Differences
In Visual Basic 6.0, UserControl projects (also known as ActiveX Control projects) are used to create ActiveX controls. After
they are compiled, UserControl objects can be hosted in any container that supports ActiveX, including Visual Basic 6.0 forms
and Internet Explorer.
In Visual Basic 2005, Windows Control Library projects are used to create controls that can be hosted in Windows Forms
applications.
Design Time Behavior
In Visual Basic 6.0, before adding a UserControl object to a form at design time, you have to close the UserControl Designer;
this step automatically compiles (builds) the control. When subsequent changes are made to the UserControl object, they are
not reflected in the instance of UserControl on the form until the application is run; if open, the UserControl Designer
automatically closes.
In Visual Basic 2005, a UserControl object can be added to a form without closing the UserControl Designer; however, the
user control must be built before it can be added to a form. Simply closing the UserControl Designer does not build the
control. Any subsequent changes to the user control are not reflected on the form designer until the UserControl object is
rebuilt; a UserControl object is automatically rebuilt each time you debug your test application.
Persisting Values
In Visual Basic 6.0, the ReadProperties and WriteProperties events are used to retrieve or save a UserControl object's
values to a PropertyBag object.
In Visual Basic 2005, the PropertyBag object is no longer supported, and the ReadProperties and WriteProperties events
no longer exist. Instead, serialization is used to save and retrieve properties in either a binary or SOAP format. For more
information, see Walkthrough: Persisting an Object in Visual Basic
Upgrade Notes
When a Visual Basic 6.0 UserControl project is upgraded to Visual Basic 2005, it is upgraded to a Windows Control Library;
the resulting control can no longer be hosted in Internet Explorer.
See Also
Tasks
Walkthrough: Persisting an Object in Visual Basic
Concepts
PropertyBag Equivalents for Visual Basic 6.0 Users
Other Resources
Developing Windows Forms Controls at Design Time
Visual Basic Concepts

PropertyBag Equivalents for Visual Basic 6.0 Users


The Visual Basic 6.0 PropertyBag object is replaced by the My.Settings object in Visual Basic 2005.
Conceptual Differences
In Visual Basic 6.0, the PropertyBag object is used to persist an object's data between instances, allowing you to store values
and retrieve them the next time the object is instantiated. Although you can set an object's properties to a default value at
design time, any values entered at run time are lost when the object is destroyed. The Visual Basic 6.0 PropertyBag object
allows a copy of the object to be persisted in a binary format and retrieved for later reuse. For example, an application used to
calculate loans might use a PropertyBag object to persist an interest rate between instances, rather than requiring a user to
enter it each time the application is run.
In Visual Basic 2005, the PropertyBag object no longer exists, but you can still persist an object's data by using the
My.Settings object. The My.Settings object provides access to a component's or application's settings, and it allows you to
dynamically store and retrieve property settings and other information at design time and run time. For more information, see
Managing Application Settings.
Note
The My.Settings object can only be used to persist data in types defined by the .NET Framework. For custom data types, you
can use serialization to persist the data. For more information, see Walkthrough: Persisting an Object in Visual Basic.

See Also
Concepts
User Controls for Visual Basic 6.0 Users
Visual Basic Concepts

Windows Forms for Visual Basic 6.0 Users


In Visual Basic 6.0 (and all earlier versions of Visual Basic), Windows-based applications were created using forms that were an
integral part of the Visual Basic Runtime. In Visual Basic 2005, Windows-based applications are created using Windows Forms,
which are provided by the .NET Framework.
Windows Forms and Windows Forms controls provide a richer, more extensible architecture for developing Windows-based
applications; however, there are a number of differences between Windows Forms and controls and Visual Basic 6.0 Forms and
controls. The following topics are designed to help you discover the differences.
In This Section
Forms Tasks for Visual Basic 6.0 Users
Describes differences in common tasks for working with forms.
Windows Forms Controls for Visual Basic 6.0 Users
Provides links to topics describing the differences between Visual Basic 6.0 and Windows Forms controls and objects.
Control Property, Method, and Event Changes for Visual Basic 6.0 Users
Provides links to topics describing differences in properties, methods, and events for forms, controls, and other objects.
Control Arrays for Visual Basic 6.0 Users
Describes the differences in control arrays between Visual Basic 6.0 and Visual Basic 2005.
Form Positioning for Visual Basic 6.0 Users
Describes differences in setting a form's screen location between Visual Basic 6.0 and Visual Basic 2005.
Menu Object for Visual Basic 6.0 Users
Describes differences in creating menus between Visual Basic 6.0 and Visual Basic 2005.
MDI for Visual Basic 6.0 Users
Describes differences in multiple-document interface (MDI) applications between Visual Basic 6.0 and Visual Basic 2005.
Dialog Box Changes for Visual Basic 6.0 Users
Describes differences in creating dialog boxes between Visual Basic 6.0 and Visual Basic 2005.
Color Behavior for Visual Basic 6.0 Users
Describes differences in color handling between Visual Basic 6.0 and Visual Basic 2005.
Help Support for Visual Basic 6.0 Users
Describes differences in implementing Help between Visual Basic 6.0 and Visual Basic 2005.
Printing Changes for Visual Basic 6.0 Users
Describes differences in printing support for applications between Visual Basic 6.0 and Visual Basic 2005.
Related Sections
Events and Event Handling for Visual Basic 6.0 Users
Describes differences in writing event handlers between Visual Basic 6.0 and Visual Basic 2005.
Drag and Drop for Visual Basic 6.0 Users
Describes differences in implementing drag-and-drop operations between Visual Basic 6.0 and Visual Basic 2005.
Graphics for Visual Basic 6.0 Users
Describes changes in graphics methods between Visual Basic 6.0 and Visual Basic 2005.
Windows Forms Overview
Introduces basic concepts related to forms.
What's New in Windows Forms and Windows Forms Controls
Describes new features for Windows Forms.
Windows Applications Namespaces in Visual Studio
Introduces the namespaces related to Windows Forms.
Help for Visual Basic 6.0 Users
Provides links to additional topics describing differences between Visual Basic 6.0 and Visual Basic 2005.
Visual Basic Concepts

Windows Forms Controls for Visual Basic 6.0 Users


New controls and objects in Visual Basic 2005 replace the intrinsic controls, objects, and collections in Visual Basic 6.0. In some
cases, the names have changed; in many cases, the properties, methods, and events are different.
In This Section
The following topics present mappings between Visual Basic 6.0 controls and objects and their Visual Basic 2005 equivalents:
App Object for Visual Basic 6.0 Users
CheckBox Control for Visual Basic 6.0 Users
Clipboard Object for Visual Basic 6.0 Users
ComboBox Control for Visual Basic 6.0 Users
CommandButton Control for Visual Basic 6.0 Users
CommonDialog Control for Visual Basic 6.0 Users
Controls Collection for Visual Basic 6.0 Users
Data Control for Visual Basic 6.0 Users
DataGrid Control for Visual Basic 6.0 Users
DirListBox Control for Visual Basic 6.0 Users
DriveListBox Control for Visual Basic 6.0 Users
FileListBox Control for Visual Basic 6.0 Users
Font Object for Visual Basic 6.0 Users
Form Object for Visual Basic 6.0 Users
Forms Collection for Visual Basic 6.0 Users
Frame Control for Visual Basic 6.0 Users
HScrollBar Control for Visual Basic 6.0 Users
Image Control for Visual Basic 6.0 Users
Label Control for Visual Basic 6.0 Users
Line Control for Visual Basic 6.0 Users
ListBox Control for Visual Basic 6.0 Users
ListView Control for Visual Basic 6.0 Users
MaskEdBox Control for Visual Basic 6.0 Users
MDIForm Object for Visual Basic 6.0 Users
Menu Object for Visual Basic 6.0 Users
OLE Container Control for Visual Basic 6.0 Users
OptionButton Control for Visual Basic 6.0 Users
PictureBox Control for Visual Basic 6.0 Users
Printer Object for Visual Basic 6.0 Users
Printers Collection for Visual Basic 6.0 Users
ProgressBar Control for Visual Basic 6.0 Users
RDO Data Control for Visual Basic 6.0 Users
RichTextBox Control for Visual Basic 6.0 Users
Screen Object for Visual Basic 6.0 Users
Shape Control for Visual Basic 6.0 Users
StatusBar Control for Visual Basic 6.0 Users
TextBox Control for Visual Basic 6.0 Users
ToolBar Control for Visual Basic 6.0 Users
Timer Control for Visual Basic 6.0 Users
TreeView Control for Visual Basic 6.0 Users
User Controls for Visual Basic 6.0 Users
VBControlExtender Object for Visual Basic 6.0 Users
VScrollBar Control for Visual Basic 6.0 Users
WebBrowser Control for Visual Basic 6.0 Users
Related Sections
Windows Forms Controls
Provides links to topics about the controls designed specifically to work with Windows Forms.
Control Property, Method, and Event Changes for Visual Basic 6.0 Users
Provides links to topics describing differences in properties, methods, and events for forms, controls, and other objects.
Controls and Programmable Objects Compared in Different Languages and Libraries
Provides a comparison of various different controls and objects.
What's New in Windows Forms and Windows Forms Controls
Describes new features for Windows Forms.
Visual Basic Concepts

App Object for Visual Basic 6.0 Users


This topic compares the Visual Basic 6.0 App object with its equivalent in Visual Basic 2005.
The App object in Visual Basic 6.0 is a global object used to set or retrieve information about the application. There is no direct
equivalent for the App object in Visual Basic 2005. However, most of the properties, methods, and events can be mapped to
equivalent members in the .NET Framework.
Conceptual Differences
Version Information Properties
The App object's Version Information properties are replaced by Assembly attributes in Visual Basic 2005. Version
Information properties are set in the Project Properties dialog box. Assembly attributes are set in the Assembly
Information dialog box, which is available by clicking the Application Information button on the Application tab of the
Project Designer.
Note
Version Information properties are stored in the Project (.vbp) file, which you can edit using a text editor such as Notepad.
Assembly attributes are stored in the AssemblyInfo.vb file and can be edited in the Code Editor.

File Description Property


The Visual Basic 6.0 App object has both FileDescription and Title properties; FileDescription determines the description
text that appears in Windows Explorer.
In Visual Basic 2005, there is no FileDescription attribute. Instead, the Title attribute determines the descriptive text that
appears in Windows Explorer.
HelpFile Property
The HelpFile property in Visual Basic 6.0 specifies a Help file at the application level.
In Visual Basic 2005, Help files are specified on a per-form basis using a HelpProvider component. For more information, see
Help Support for Visual Basic 6.0 Users.
Version Properties
The Major, Minor, and Revision properties in Visual Basic 6.0 are used to return a three-part version number for an
application.
In Visual Basic 2005, version information also includes a Build property, and the complete four-part version number can be
retrieved using a single Version property. For more information, see Version Numbering for Visual Basic 6.0 Users.
Title Property
The Title property of the App object in Visual Basic 6.0 can be changed programmatically; doing so determines the name that
appears in the Windows Task Manager.
In Visual Basic 2005, the Title attribute is read-only. The Text property of the application's main form determines the name
that is shown in the Task Manager. You can set the Text property programmatically, but the text in the title bar of the form
will change as well.
TaskVisible Property
In Visual Basic 6.0, the TaskVisible property of the App object determines whether an application appears in the Windows
Task List (Windows 9x) or the Task Manager Applications tab (Windows 2000 or later). The property is commonly used to
prevent a user from closing an application that was designed to run as a background task. In most cases, the TaskVisible
property is used with applications that do not display user interfaces.
In Visual Basic 2005, there is no equivalent for the TaskVisible property; however, you can create a Windows Service or a
Console Application that will not show up in the task list.
PrevInstance Property
The PrevInstance property in Visual Basic 6.0 determines if an instance of the application is already running. Typically you call
PrevInstance on application startup and abort the application if it returns true.
There is no direct equivalent for PrevInstance in Visual Basic 2005. You control whether or not multiple instances of an
application are allowed by setting the Multiple Instance property on the Application tab of the Project Designer. At run
time, a NextInstanceStarted event is raised when a user tries to start another instance of the application. You can add code to
this event handler to activate the first instance of the application.
Additional Differences
There are a number of App object properties in Visual Basic 6.0 that concern ActiveX components, OLE automation, and other
technologies that are now obsolete and are not supported in Visual Basic 2005. They are noted in the App Object Property
Equivalencies table later in this topic.
Code Changes for the App Object
The following code examples illustrate the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005 for
some common uses of the App object.
Code changes for displaying an application's version number
The following example demonstrates retrieving an application's version number and displaying it in a label.

' Visual Basic 6.0


Label1.Caption = "Version: " & App.Major & "." & App.Minor & "." _
& App.Revision

VB
' Visual Basic 2005
Label1.Text = My.Application.Info.Version.ToString()

Code changes for determining an application's path


The following example demonstrates how to display an image file that is stored in the application's folder by retrieving the
path to the executing application.

' Visual Basic 6.0


Picture1.Picture = LoadPicture(App.Path & "\Logo.jpg")

VB
' Visual Basic 2005
PictureBox1.Image = System.Drawing.Bitmap.FromFile( _
My.Application.Info.DirectoryPath & "\Logo.jpg")

Code changes for preventing a second instance of an application from running


The following example demonstrates implementing a single-instance application.

' Visual Basic 6.0


Private Sub Form_Load()
If App.PrevInstance = True Then
MsgBox("The application is already running!")
End If
End Sub

VB
' Visual Basic 2005
' Assumes that the Make Single Instance Application checkbox in the
' Project Designer has been checked.

Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, _


ByVal e As Microsoft.VisualBasic.ApplicationServices. _
StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
MsgBox("The application is already running!")
End Sub
App Object Property Equivalents
The following table lists all properties and methods of the Visual Basic 6.0 App object and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
Comments My.Application.Info.Description Property

CompanyName My.Application.Info.CompanyName Property

EXEName My.Application.Info.AssemblyName Property

FileDescription My.Application.Info.Title Property

HelpFile New implementation. Use a HelpProvider component. For more information, see
Help Support for Visual Basic 6.0 Users.

HInstance GetHINSTANCE

LegalCopyright My.Application.Info.Copyright Property

LegalTrademarks My.Application.Info.Trademark Property

LogEvent metho WriteEntry Method (My.Application.Log and My.Log)


d

LogMode New implementation. For more information, see Logging Information from the Application.
LogPath

Major My.Application.Info.Version Property


Note
The format for version numbers is different in Visual Basic 2005. For more information, see
Version Numbering for Visual Basic 6.0 Users.

Minor My.Application.Info.Version Property


Note
The format for version numbers is different in Visual Basic 2005. For more information, see
Version Numbering for Visual Basic 6.0 Users.

NonModalAllow New implementation. This is a read-only property related to ActiveX .dll files. The common language runti
ed me automatically manages this behavior.
OleRequestPendi No equivalent. These properties relate to OLE automation, which is not supported by Visual Basic 2005.
ngMsgText
OleRequestPendi
ngMsgTitle
OleRequestPendi
ngTimeout
OleServerBusyMs
gText
OleServerBusyMs
gTitle
OleServerBusyRa
iseError
OleServerBusyTi
meout

Path My.Application.Info.DirectoryPath Property

PrevInstance IsSingleInstance
Note
The IsSingleInstance property is a Protected property. It can only be set at design time in the Project
Designer by checking or clearing the Multiple Instance check box.

ProductName My.Application.Info.ProductName Property

RetainedProject New implementation. Visual Basic 2005 cannot retain a project in memory.

Revision My.Application.Info.Version Property


Note
The format for version numbers is different in Visual Basic 2005. For more information, see
Version Numbering for Visual Basic 6.0 Users.

StartLogging met New implementation. For more information, see Logging Information from the Application.
hod

StartMode No equivalent. This property concerns creating ActiveX components, which is not supported in Visual Basic
2005.

TaskVisible New implementation. To create an application that does not appear in the Task Manager, create a Windo
ws Service or Console Application project.

ThreadID New implementation. This property returned the ID of the executing thread; the threading model is signific
antly different in Visual Basic 2005.

Title My.Application.Info.Title Property

UnattendedApp New implementation. For unattended applications in Visual Basic 2005, create a Console Application pro
ject.

Upgrade Notes
When an application is upgraded from Visual Basic 6.0, only the Major and Minor properties are upgraded; Visual Basic 2005
assigns new values to the Revision and Build properties.
See Also
Reference
My.Application Object
Concepts
Help Support for Visual Basic 6.0 Users
Version Numbering for Visual Basic 6.0 Users
Visual Basic Concepts

CheckBox Control for Visual Basic 6.0 Users


This topic compares the Visual Basic 6.0 CheckBox control with its equivalent in Visual Basic 2005.
The CheckBox control in Visual Basic 6.0 is replaced by the Windows Forms CheckBox control in Visual Basic 2005. The names
of some properties, methods, events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
Click Event
In Visual Basic 6.0, the Click event is raised when the CheckBox state is changed programmatically. In Visual Studio 2005 you
use the CheckStateChanged event, not the Click event.
Additional Differences
In addition, there are numerous conceptual differences that apply to all controls, including differences in data binding, font
handling, drag-and-drop, Help support, and more. For more information, see Windows Forms Overview and
What's New in Windows Forms and Windows Forms Controls.
Code Changes for the CheckBox Control
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Responding to CheckBox Clicks
The following code demonstrates changing the text of a CheckBox control when a user checks or unchecks the control. The
Visual Basic 6.0 Value property is replaced by the Visual Basic 2005 Checked property, and the Caption property is replaced
by the Text property. Notice that the Visual Basic 2005 example uses the CheckStateChanged event to duplicate the behavior
of the Visual Basic 6.0 Click event.

' Visual Basic 6.0


Private Sub Check1_Click()
If Check1.Value = 1 Then
Check1.Caption = "Checked"
Else
Check1.Caption = "Unchecked"
End If
End Sub

VB
' Visual Basic 2005
Private Sub CheckBox1_CheckStateChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles CheckBox1.CheckStateChanged
If CheckBox1.Checked = True Then
CheckBox1.Text = "Checked"
Else
CheckBox1.Text = "Unchecked"
End If
End Sub

Code Changes for Determining the State of a CheckBox


The following example demonstrates checking the state of a CheckBox control at run time.

' Visual Basic 6.0


Select Case Check1.Value
Case vbUnchecked
Check1.Caption = "Unchecked"
Case vbChecked
Check1.Caption = "Checked"
Case vbGrayed
Check1.Caption = "Disabled"
End Select
VB
' Visual Basic 2005
Select Case CheckBox1.CheckState
Case CheckState.Unchecked
CheckBox1.Text = "Unchecked"
Case CheckState.Checked
CheckBox1.Text = "Checked"
Case CheckState.Indeterminate
CheckBox1.Text = "Disabled"
End Select

CheckBox Control Property, Method, and Event Equivalents


The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents. Those
properties, methods, and events that have the same names and behaviors are not listed. Where applicable, constants are
indented beneath the property or method. All Visual Basic 2005 enumerations map to the System.Windows.Forms namespace
unless otherwise noted.
Links are provided as necessary to topics explaining differences in behavior. Where there is no direct equivalent in Visual Basic
2005, links are provided to topics that present alternatives.
Properties
Visual Basic 6. Visual Basic 2005 Equivalent
0 Property
Alignment CheckAlign
0 (Left Justify) MiddleLeft enumeration value
1 (Right Justify) MiddleRight enumeration value

Appearance FlatStyle enumeration


0 (Flat) Flat enumeration value
1 (3D) Standard enumeration value

BackColor BackColor
Note
For a list of color constants, see Color Handling for Visual Basic 6.0 Users.

Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.

Caption Text

Container Parent

DataChanged New implementation. For more information, see Data Access for Visual Basic 6.0 Users.
DataField
DataFormat
DataMember
DataSource
DisabledPictu New implementation. For more information, see
re How to: Emulate a Visual Basic 6.0 Tri-state Control in an Upgraded Application.
DownPicture

DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode

Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Handling for Visual Basic 6.0 Users.
FontSize
FontStrikethr
ough
FontUnderlin
e

ForeColor ForeColor
Note
For a list of color constants, see Color Handling for Visual Basic 6.0 Users.

Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.

Height Height , Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpContextI New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
D

HWnd Handle

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

MaskColor New implementation. For more information, see MaskColor for Visual Basic 6.0 Users.

MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.
MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

OLEDropMod New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
e

Parent FindForm method

Picture Image

RightToLeft RightToLeft
True Yes enumeration value
No enumeration value

Style Appearance
0 (Standard) Normal enumeration value
1 (Graphical) Button enumeration value
Note
There are differences in how the Graphical style is handled in Visual Basic 2005. For more information, see
How to: Emulate a Visual Basic 6.0 Tri-state Control in an Upgraded Application.

Tag Tag

ToolTipText ToolTip component


For more information, see ToolTip Support for Visual Basic 6.0 Users.

Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

UseMaskColo New implementation. For more information, see MaskColor for Visual Basic 6.0 Users.
r

Value CheckState
0 (vbUncheck Unchecked enumeration value
ed)
Checked enumeration value
1 (vbChecked)
Indeterminate enumeration value
2 (vbGrayed)

WhatsThisHel New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
pID
Width Width , Size
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Methods
Visual Basic 6.0 Me Visual Basic 2005 Equivalent
thod
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

SetFocus Focus

ShowWhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.

ZOrder BringToFront, SendToBack


0 (vbBringToFront)
1 (vbSendToBack)
Events
Visual Basi Visual Basic 2005 Equivalent
c 6.0 Event
Click CheckStateChanged
Note
In Visual Basic 6.0, the Click event is raised when the CheckBox state is changed programmatically. In Visual B
asic 2005, the Click event is not raised; therefore, you should use the CheckStateChanged event.

DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

GotFocus Enter

LostFocus Leave
OLECompl New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
eteDrag
OLEDragDr
op
OLEDragO
ver
OLEGiveFe
edback
OLESetDat
a
OLEStartDr
ag

Validate Validating

Upgrade Notes
When upgrading a Visual Basic 6.0 application using the Upgrade wizard, CheckBox controls are upgraded to Windows Forms
CheckBox controls, and code is updated to use equivalent properties, methods, and events. Where there are no equivalents or
where there are potential behavioral differences, comments are inserted into the code with a link to a Help topic.
See Also
Reference
CheckBox Control Overview (Windows Forms)
Concepts
Data Access for Visual Basic 6.0 Users
Style Property for Visual Basic 6.0 Users
Font Handling for Visual Basic 6.0 Users
Coordinate System for Visual Basic 6.0 Users
Control Arrays for Visual Basic 6.0 Users
Help Support for Visual Basic 6.0 Users
MousePointer for Visual Basic 6.0 Users
ToolTip Support for Visual Basic 6.0 Users
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts

Clipboard Object for Visual Basic 6.0 Users


The Clipboard object in Visual Basic 6.0 is replaced by a similar Clipboard object in Visual Basic 2005.
Conceptual Differences
In Visual Basic 6.0, the Clipboard object is used to store and retrieve text, images, and data to and from the system Clipboard.
Visual Basic 2005 has a Clipboard object in the My.Computer namespace with some new methods and some methods that
are slightly different.
Clipboard Data Formats
In Visual Basic 6.0, constants are provided to define the type of data being passed to or retrieved from the Clipboard.
Visual Basic 2005 uses a DataFormats object to define the data type; several new data formats are supported. A list of Visual
Basic 6.0 Clipboard format constants and their Visual Basic 2005 equivalents is provided later in this topic.
Code Changes for the Clipboard Object
The following example demonstrates storing and retrieving text using the Clipboard.

' Visual Basic 6.0


Clipboard.Clear
Clipboard.SetText "Hello", vbCFText
If Clipboard.GetFormat(vbCFText) Then
Text1.Text = Clipboard.GetText(vbCFText)
End If

VB
' Visual Basic 2005
My.Computer.Clipboard.Clear()
My.Computer.Clipboard.SetText("Hello")
If My.Computer.Clipboard.ContainsText Then
TextBox1.Text = My.Computer.Clipboard.GetText
End If

Clipboard Constant Equivalencies


Visual Basic 6.0 Visual Basic 2005 Equivalent
vbCFBitmap Bitmap

vbCFDIB Dib

vbCFEMetafile EnhancedMetafile

vbCFFiles FileDrop

vbCFLink No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.

vbCFMetafile MetafilePict

vbCFPalette Palette

vbCFRTF Rtf

vbCFText Text
Note
The DataFormats object is a part of the System.Windows.Forms namespace. In addition to the formats listed above, DataFo
rmats supports several clipboard formats that were not supported in Visual Basic 6.0.

See Also
Tasks
How to: Clear the Clipboard in Visual Basic
How to: Read from the Clipboard in Visual Basic
How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
How to: Save an Audio Stream to the Clipboard in Visual Basic
How to: Retrieve an Image from the Clipboard in Visual Basic
How to: Write to the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard Object Members
Visual Basic Concepts

ComboBox Control for Visual Basic 6.0 Users


The ComboBox control in Visual Basic 6.0 is replaced by the Windows Forms ComboBox control in Visual Basic 2005. The
names of some properties, methods, events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
Change Event
In Visual Basic 6.0, the Change event of the ComboBox control is raised when the text of the control is modified. The Change
event is not raised when an item is selected from the list portion of the control. Programmatically changing the text of an item
in the list does not raise the Change event.
In Visual Basic 2005, the Change event no longer exists; the TextChanged event is raised every time the text changes for any
reason, such as:
When the text-entry portion is modified
When an item is selected from the list
When a list item is modified programmatically
When the AddItem method is called
ItemData Property
In Visual Basic 6.0, the ItemData property for a ComboBox control can be set at design time in the Properties window to
associate an Integer with a ComboBox item.
In Visual Basic 2005, the ItemData property no longer exists. The Microsoft.VisualBasic.Compatibility library contains a
SetItemData function that can be used to associate an Integer with an item; the GetItemData function can be used to
retrieve the item.
Locked Property
In Visual Basic 6.0, the Locked property of a ComboBox control determines whether the text-box portion of the control can be
edited.
In Visual Basic 2005, the Locked property prevents a control from being moved at design time. There is no direct equivalent
for the Visual Basic 6.0 Locked property; however, you can achieve the same effect by setting the DropDownStyle property of
the ComboBox control to DropDownList.
Note In Visual Basic 6.0, setting the Locked property to True also prevents the selection from being changed. You can
duplicate this behavior by canceling the selection in the MouseDown event.
NewIndex Property
In Visual Basic 6.0, the NewIndex property was used to retrieve the index of the item most recently added to a ComboBox
control.
In Visual Basic 2005, the NewIndex property no longer exists. You can use the return value from the Item.Add method to
retrieve the index of an item as it is added.
TopIndex Property
In Visual Basic 6.0, the TopIndex property is used to return or set a value that specifies which item in a ComboBox or ListBox
control is displayed in the topmost position. This property is commonly used to scroll the list without selecting an item.
In Visual Basic 2005, the ComboBox control no longer supports the TopIndex property. In most cases this should not present
a problem, because setting the TopIndex property has no visible effect unless the Style property is set to 1 - SimpleCombo.
In this case, you can emulate this behavior by using a ListBox control and a TextBox control; the ListBox control still supports
the TopIndex property.
Scroll Event
The Scroll event in Visual Basic 6.0 is used in conjunction with the TopIndex property to perform actions when the list is
scrolled. Visual Basic 2005 does not support the Scroll event; however, in most cases the SelectedIndexChanged event is a
suitable replacement.
Other Differences
In addition, there are numerous conceptual differences that apply to all controls, including differences in data binding, font
In addition, there are numerous conceptual differences that apply to all controls, including differences in data binding, font
handling, drag-and-drop operations, Help support, and more. For more information, see
Windows Forms Concepts for Visual Basic 6.0 Users.
Code Changes for the ComboBox Control
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Making a ComboBox Control Read-Only
The following code demonstrates how to prevent a user from adding new items to a ComboBox control.

' Visual Basic 6.0


Combo1.Locked = True

VB
' Visual Basic 2005
ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList

Code Changes for Selecting the Most Recently Added Item in a ComboBox Control
The following code demonstrates how to set the selection to an item that has been added programmatically to a ComboBox
control.

' Visual Basic 6.0


Combo1.AddItem "This is a new item"
Combo1.ListIndex = Combo1.NewIndex

VB
' Visual Basic 2005
Dim i As Integer
i = ComboBox1.Items.Add("This is a new item")
ComboBox1.SelectedIndex = i

Private Sub Code Changes for Associating ItemData


The following code demonstrates how to associate an employee number with each employee listed in a ComboBox control
then how to retrieve that number at run time.

' Visual Basic 6.0


Private Sub Form_Load
Combo1.AddItem "Nancy Davolio"
Combo1.ItemData(Combo1.NewIndex) = 12345
Combo1.AddItem "Judy Phelps"
Combo1.ItemData(Combo1.NewIndex) = 67890
End Sub
Private Sub Combo1_Click()
Label1.Caption = "Empoyee #" & _
CStr(Combo1.ItemData(Combo1.ListIndex))
End Sub

VB
' Visual Basic 2005
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load

ComboBox1.Items.Add("Nancy Davolio")
Microsoft.VisualBasic.Compatibility.VB6. _
SetItemData(ComboBox1, ComboBox1.Items.Count() - 1, 12345)

ComboBox1.Items.Add("Judy Phelps")
Microsoft.VisualBasic.Compatibility.VB6. _
SetItemData(ComboBox1, ComboBox1.Items.Count() - 1, 67890)
End Sub

VB
' Visual Basic 2005
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged

Label1.Text = "Employee #" & CStr( _


Microsoft.VisualBasic.Compatibility.VB6. _
GetItemData(ComboBox1, ComboBox1.SelectedIndex))
End Sub

ComboBox Control Property, Method, and Event Equivalencies


The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents. Those
properties, methods, and events that have the same name and behavior are not listed. Where applicable, constants are
indented beneath the property or method. All Visual Basic 2005 enumerations map to the System.Windows.Forms namespace
unless otherwise noted.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties
Visual Ba Visual Basic 2005 Equivalent
sic 6.0
Appearan New implementation. For more information, see Appearance and BorderStyle Properties for Visual Basic 6.0 Users.
ce

BackColo BackColor
r
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.

Container Parent

DataChan New implementation. For more information, see Data Control for Visual Basic 6.0 Users.
ged
DataField
DataForm
at
DataMem
ber
DataSour
ce

DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMod
e
Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontNam Font Handling for Visual Basic 6.0 Users.
e
FontSize
FontStrik
ethrough
FontUnde
rline
ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.

Height Height, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpCont New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
extID

HWnd Handle

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

ItemData New implementation. For more information, see ItemData property cannot be upgraded.

Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information,
Coordinate System for Visual Basic 6.0 Users.

List Items

ListCount Count

ListIndex SelectedIndex

Locked DropDownStyle = DropDownList


Note
In Visual Basic 6.0, setting the Locked property to True also prevents the selection from being changed. In Visual
Basic 2005, you can duplicate this behavior by canceling the selection in the MouseDown event.
MouseIco New implementation. For more information, see Cannot set a custom MousePointer.
n

MousePo Cursor
inter
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

NewInde New implementation. For more information, see NewIndex property cannot be upgraded.
x

OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Mode

OLEDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Mode

Parent FindForm method

RightToL RightToLeft
eft

SelLengt SelectionLength
h

SelStart SelectionStart

SelText SelectedText

Style DropDownStyle

ToolTipT ToolTip component


ext
For more information, see ToolTip Support for Visual Basic 6.0 Users.

Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

TopIndex New implementation. For more information, see TopIndex Property and Scroll Event for Visual Basic 6.0 Users.

WhatsThi New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
sHelpID

Width Width, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Methods
Visual Basic 6 Visual Basic 2005 Equivalent
.0
AddItem Add
AddRange
Insert
Clear Clear

Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

OLEDrag Drag and Drop for Visual Basic 6.0 Users.

RemoveItem Items.Remove

SetFocus Focus

ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his

ZOrder BringToFront SendToBack functions


Events
Visual Basic 6 Visual Basic 2005 Equivalent
.0
Change TextChanged
Note
The behavior of the TextChanged event is slightly different. For more information, see
ComboBox Control Change Event for Visual Basic 6.0 Users.

Click SelectedIndexChanged

DblClick New implementation. Use the SelectedIndexChanged or TextChanged events.

DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

GotFocus Enter

LostFocus Leave
OLEComplete New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Drag
OLEDragDrop
OLEDragOver
OLEGiveFeed
back
OLESetData
OLEStartDrag

Scroll New implementation. For more information, see TopIndex Property and Scroll Event for Visual Basic 6.0 Users.

Validate Validating

Upgrade Notes
When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, the Change event of the ComboBox control is mapped to
the TextChanged event of the Visual Basic 2005 ComboBox control. The behavior of the TextChanged event differs from
that of the Change event; this difference may cause unintended results in your code.
Any code that references the ItemData, Locked, NewIndex, or TopIndex properties or any code in the Scroll event
procedure is not upgraded; warning comments are added to the code and the code must be removed or modified before
compiling the application.
See Also
Reference
ComboBox Control Overview (Windows Forms)
Concepts
Color Behavior for Visual Basic 6.0 Users
Font Object for Visual Basic 6.0 Users
MousePointer for Visual Basic 6.0 Users
ToolTip Support for Visual Basic 6.0 Users
Visual Basic Concepts

CommandButton Control for Visual Basic 6.0 Users


The CommandButton control in Visual Basic 6.0 is replaced by the Windows Forms Button control in Visual Basic 2005. The
names of some properties, methods, events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
Default and Cancel Properties
In Visual Basic 6.0, the Boolean Default and Cancel properties of a CommandButton control determine if the control
responds to the ENTER or ESC keys, respectively.
In Visual Basic 2005, the Button control no longer has Default or Cancel properties. The Form object has AcceptButton and
CancelButton properties that provide the same functionality; these properties take the name of a Button control as an
argument.
Value Property
In Visual Basic 6.0, the Boolean Value property of a CommandButton control indicates whether the control has been chosen;
setting the property to True invokes the button's Click event.
In Visual Basic 2005, the Button control no longer has a Value property. You can use the GotFocus event to determine if the
control is chosen; the PerformClick method can be used to invoke the Click event.
Style, Picture, DownPicture, and DisabledPicture Properties
In Visual Basic 6.0, setting the Style property of a CommandButton control to 1 – Graphical changes the appearance of the
control to display images. The Picture, DownPicture, and DisabledPicture properties are used to assign images to be
displayed in response to state changes. For example, when a CommandButton control is clicked, the DownPicture image is
displayed; if the control is disabled, the DisabledPicture image is displayed.
Visual Basic 2005 no longer supports the Style, Picture, DownPicture, or DisabledPicture properties. The Style property is
no longer necessary; assigning a picture to the Image property has the same effect as setting the Style property to Graphical.
The Picture property is replaced by the Image property. The functionality of the DownPicture and DisabledPicture
properties can be emulated using an ImageList control that contains multiple images.
MaskColor Property
In Visual Basic 6.0, the MaskColor property of a CommandButton control is used to define a color that becomes transparent,
allowing a background image to show through. To use this property, the Style property has to be set to Graphical, the
UseMaskColor property has to be set to True, and a bitmap has to be assigned to the Picture property.
In Visual Basic 2005, there is no direct equivalent for the MaskColor property. You can, however, set transparency on a control
using the MakeTransparent method of a Bitmap object.
Other Differences
In addition, there are numerous conceptual differences that apply to all controls, including differences in data binding, font
handling, drag and drop, Help support and more. For more information, see
Windows Forms Controls for Visual Basic 6.0 Users.
Code Changes for the CommandButton Control
The following code examples illustrate the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Setting Default and Cancel Buttons
The following example demonstrates setting two buttons to be the default and cancel buttons for a form.

' Visual Basic 6.0


' Set the first button to respond to the Enter key.
Command1.Default = True
' Set the second button to respond to the Esc key.
Command2.Cancel = True

VB
' Visual Basic 2005
' Set the first button to respond to the Enter key.
Me.AcceptButton = Button1
' Set the second button to respond to the Esc key.
Me.CancelButton = Button2

Code Changes for Adding Transparency to a Button


The following example demonstrates methods for defining a transparent region on a button that contains an image; any
portion of the image that is white will become transparent.

' Visual Basic 6.0


' Assumes a picture has been assigned to the Picture property
' and that the Style property has been set to Graphical.
Command1.UseMaskColor = True
Command1.MaskColor = vbWhite

VB
' Visual Basic 2005
' Assumes a picture has been assigned to the BackgroundImage property.
Dim ButtonBitmap As New System.Drawing.Bitmap(Button1.BackgroundImage)
ButtonBitmap.MakeTransparent(System.Drawing.Color.White)
Button1.BackgroundImage = ButtonBitmap

CommandButton Control Property, Method, and Event Equivalencies


The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents. Those
properties, methods, and events that have the same names and behaviors are not listed. Where applicable, constants are
indented beneath the property or method. All Visual Basic 2005 enumerations map to the System.Windows.Forms namespace
unless otherwise noted.
These tables list links to topics explaining differences in behavior. Where there is no direct equivalent in Visual Basic 2005, links
are provided to alternatives.
Properties
Visual Basic Visual Basic 2005 Equivalent
6.0
Appearance New implementation. For more information, see
Appearance and BorderStyle Properties for Visual Basic 6.0 Users.

BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.

Cancel CancelButton (Form object)

Caption Text

Container Parent

Default AcceptButton (Form object)

DisabledPict New implementation. For more information, see Style Property for Visual Basic 6.0 Users.
ure
DownPicture
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethr
ough
FontUnderli
ne

Height Height, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpContext New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
ID

HWnd Handle

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

MaskColor New implementation. For more information, see MaskColor for Visual Basic 6.0 Users.

MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePoint Cursor
er
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

OLEDropMo New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
de

Parent FindForm method

Picture Image

RightToLeft RightToLeft

Style New implementation. For more information, see Style Property for Visual Basic 6.0 Users.
ToolTipText ToolTip component
For more information, see ToolTip Support for Visual Basic 6.0 Users.

Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

UseMaskCol New implementation. For more information, see MaskColor for Visual Basic 6.0 Users.
or

Value New implementation. The PerformClick method is the same as setting the Value to True; for any other use of
the Value property there is no equivalent.

WhatsThisHe New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
lpID

Width Width, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Methods
Visual Basic 6 Visual Basic 2005 Equivalent
.0
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

SetFocus Focus

ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his

ZOrder BringToFront or SendToBack function


Events
Visual Basic 6.0 Visual Basic 2005 Equivalent
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

GotFocus Enter
LostFocus Leave

OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag

Upgrade Notes
When upgrading a Visual Basic 6.0 application using the Upgrade Wizard, any CommandButton controls are upgraded to
Windows Forms Button controls and code is updated to use the equivalent properties, methods, and events. Where there are
no equivalents or where there are potential behavioral differences, comments are inserted in the code with links to Help topics.
When an application is upgraded to Visual Basic 2005, if the Style property is set to 1 – Graphical, the FlatStyle property of
the upgraded control is set to Standard, and any image assigned to the Picture property at design time is assigned to the
Image property of the upgraded control.

If the DownPicture or DisabledPicture properties were set at design time or at run time, you will need to modify your
upgraded application to use an ImageList control. For more information, see
How to: Emulate a Visual Basic 6.0 Tri-state Control in an Upgraded Application.
The Upgrade Wizard does not upgrade code that uses the MaskColor property. Upgrade warnings will be inserted into your
code. You will need to modify the code before running the application.
See Also
Concepts
MaskColor for Visual Basic 6.0 Users
Visual Basic Concepts

CommonDialog Control for Visual Basic 6.0 Users


The Visual Basic 6.0 CommonDialog control is replaced by several specialized components in Visual Basic 2005.
Conceptual Differences
In Visual Basic 6.0, the CommonDialog ActiveX control is used to display various common dialogs (Open, Save, Color, Font,
Print, and Help) to your application.
In Visual Basic 2005, the CommonDialog control is replaced by individual components for displaying dialogs — the
OpenFileDialog, SaveFileDialog, ColorDialog, FontDialog, and PrintDialog components.
Note
There is no direct equivalent for showing a Help dialog in Visual Basic 2005. The CommonDialog control only supported Wi
ndows Help; Visual Basic 2005 only supports HTML Help. Visual Basic 2005 uses the HelpProvider component to display help
for your application. For more information, see Help Support for Visual Basic 6.0 Users.

Code Changes for the CommonDialog Control


The following examples illustrate the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005 for some
common uses of the CommonDialog control.
Code Changes for Displaying a File Open Dialog Box
The following code demonstrates displaying a File Open dialog box, initialized to the Program Files directory.

' Visual Basic 6.0


' Uses a CommonDialog control.
CommonDialog1.InitDir = "C:\Program Files"
CommonDialog1.ShowOpen

VB
' Visual Basic 2005
' Uses a OpenFileDialog component.
OpenFileDialog1.InitialDirectory = "C:\Program Files"
OpenFileDialog1.ShowDialog()

Code changes for Displaying a File Save Dialog Box


The following code demonstrates displaying a File Save dialog box, saving the file to the application's folder.

' Visual Basic 6.0


' Uses a CommonDialog control.
CommonDialog1.InitDir = App.Path
CommonDialog1.ShowSave

VB
' Visual Basic 2005
' Uses a SaveFileDialog component.
SaveFileDialog1.InitialDirectory = My.Application.Info.DirectoryPath
SaveFileDialog1.ShowDialog()

Code changes for Displaying a Print Dialog Box


The following code demonstrates displaying a Print dialog box, printing a file located in the application's folder.

' Visual Basic 6.0


' Uses a CommonDialog control.
CommonDialog1.FileName = App.Path & "MyFile.txt"
CommonDialog1.ShowPrinter

VB
' Visual Basic 2005
' Uses PrintDocument and PrintDialog components.
PrintDocument1.DocumentName = My.Application.Info.DirectoryPath _
& "MyFile.txt"
PrintDialog1.Document = PrintDocument1
PrintDialog1.ShowDialog()

Code changes for Displaying Help


The following code demonstrates displaying a Help file from your application, opening it to the table of contents.

' Visual Basic 6.0


' Uses a CommonDialog control.
CommonDialog1.HelpFile = "C:\Windows\Help\calc.hlp"
CommonDialog1.HelpCommand = cdlHelpContents
CommonDialog1.ShowHelp

VB
' Visual Basic 2005
' Uses the Help.ShowHelp method.
Help.ShowHelp(Me, "file://C:\Windows\Help\calc.chm", _
HelpNavigator.TableOfContents)

CommonDialog Control Property and Method Equivalencies


The following tables list Visual Basic 6.0 properties and methods and their Visual Basic 2005 equivalents. Properties and
methods with the same names and behaviors are not listed. Where applicable, constants are indented beneath the property or
method. All Visual Basic 2005 enumerations map to the System.Windows.Forms namespace unless otherwise noted.
Links are provided as necessary to topics explaining differences in behavior. Where there is no direct equivalent in Visual Basic
2005, links are provided to topics that present alternatives.
Properties
Visual Ba Visual Basic 2005 Equivalent
sic 6.0
Action New implementation. The Visual Basic 6.0 Action property determines which dialog to display; Visual Basic 2005 u
ses a separate component for each dialog.

CancelErr Cancel
or

Copies Copies

DialogTit Title (OpenFileDialog and SaveFileDialog components only)


le
New implementation for the other components. Standard Windows titles (Color, Font, and Print) are displayed an
d cannot be overridden.

FileName FileNames

FileTitle New implementation. The Visual Basic 6.0 FileTitle property returns the FileName without the path; you can parse
the FileNames property to get the name without the path.
Flags The Visual Basic 6.0 Flags property provides constants for setting various attributes of the different common dialo
gs. Rather than using constants, the dialog components provide properties for setting the attributes.

Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontNam Font Handling for Visual Basic 6.0 Users.
e
FontSize
FontStrik
ethrough
FontUnd
erline

FromPag FromPage
e

hDC New implementation. For more information see Graphics for Visual Basic 6.0 Users.

HelpCom HelpNavigator
mand

HelpFile HelpNamespace

HelpKey The parameter parameter of the ShowHelp method.

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

InitDir InitialDirectory

Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Max MaxSize (FontDialog component)


MaximumPage (PrintDialog component)

Min MinSize (FontDialog component)


MinimumPage (PrintDialog component)

MaxFileSi New implementation. This property Visual Basic 6.0 allocates memory for extremely long file names; it is no longer
ze necessary in managed code.

Orientati Landscape
on

Parent FindForm method


PrinterDe New implementation. This Visual Basic 6.0 property is used in conjunction with the hDC property to print using gra
fault phic device interface methods; this is no longer supported.

Top P:System.Windows.Forms.Control.Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

ToPage ToPage

Methods
Visual Basi Visual Basic 2005 Equivalent
c 6.0
AboutBox New implementation. The AboutBox property displayed an About box for the CommonDialog control, which w
as created for Microsoft by a third party.

ShowColor ShowDialog (ColorDialog component)

ShowFont ShowDialog (FontDialog component)

ShowHelp ShowHelp

ShowOpen ShowDialog (OpenFileDialog component)

ShowPrint ShowDialog (PrintDialog component)


er

ShowSave ShowDialog (SaveFileDialog component)

Upgrade Notes
When upgrading an application from Visual Basic 6.0 to Visual Basic 2005, any CommonDialog controls are upgraded to
their equivalent dialog component (OpenFileDialog, SaveFileDialog, ColorDialog, FontDialog or PrintDialog).
There is no direct equivalent for showing a Help dialog in Visual Basic 2005. If a CommonDialog control is being used as a
Help dialog, a warning will be issued and it will not be upgraded. For more information, see
Help Support for Visual Basic 6.0 Users.
A single CommonDialog control could be used to display different types of dialogs. In this case it will be upgraded to a
OpenFileDialog component; a warning will be issued and you will need to add the other dialog components manually.
In addition, where a CommonDialog control was used as a variable you may need to change it to refer to a specific dialog
component after upgrade.
See Also
Reference
FontDialog Component Overview (Windows Forms)
HelpProvider Component Overview (Windows Forms)
Other Resources
ColorDialog Component (Windows Forms)
OpenFileDialog Component (Windows Forms)
SaveFileDialog Component (Windows Forms)
PrintDialog Component (Windows Forms)
PrintDocument Component (Windows Forms)
Visual Basic Concepts

Controls Collection for Visual Basic 6.0 Users


The Visual Basic 6.0 Controls collection is replaced by the ControlCollection class in Visual Basic 2005.
Conceptual Differences
In Visual Basic 6.0, the Controls collection is a collection with elements that represent the controls on a form or container
control.
In Visual Basic 2005, the ControlCollection class replaces the Controls collection. Forms have a default ControlCollection
class that can be accessed using the syntax Me.Controls.
Add Method
In Visual Basic 6.0, the Add method of the Controls collection is late-bound; controls are created in the Add method by
specifying the Control class as an argument.
In Visual Basic 2005, the Add method of the ControlCollection class requires that the controls were created using the New
keyword before being added to the collection.
Remove Method
The Remove method of the Visual Basic 6.0 Controls collection could only be used for controls that were added using the
Add method; the Visual Basic 2005 ControlCollection class does not have this restriction.
Timer and Menu Controls
In Visual Basic 6.0, the Timer and Menu controls are members of the Controls collection. In Visual Basic 2005, these controls
are replaced by the Timer and MainMenu or ContextMenu components; components are not members of the
ControlCollection class.
Contained Controls
The Visual Basic 6.0 Controls collection includes controls that are children of a container control (for example, controls sited on
a Frame control); the Visual Basic 2005 ControlCollection class does not. To iterate through all the controls on a form, you
must recursively iterate through the Controls class of each container control.
Code Changes for the Controls Collection
The following examples illustrate the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Adding and Removing Controls
The following code illustrates differences between the Visual Basic 6.0 Controls collection and the Visual Basic
2005 ControlCollection class.

' Visual Basic 6.0


Private Sub Command1_Click()
' Declare a new Control variable.
Dim c As Control
' Create and add the new control.
Set c = Controls.Add("VB.TextBox", "Text1")
' Make the new control visible.
c.Visible = True
' Set the initial text.
c.Text = "Hello"
' Retrieve the text from the new TextBox.
If Controls.Count > 1 Then
MsgBox (Controls("Text1").Text)
End If
' Remove the new control.
Controls.Remove (Text1)
' The following line causes a compilation error.
' You cannot remove controls added at design time.
Controls.Remove (Command1)
End Sub

VB
' Visual Basic 2005
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handl
es Button1.Click
' Create a new TextBox control.
Dim TextBox1 As New System.Windows.Forms.TextBox
TextBox1.Name = "TextBox1"
' Add the new control to the form's Controls collection.
Me.Controls.Add(TextBox1)
' No need to set Visible property.
' Set the initial text.
TextBox1.Text = "Hello"
' Retrieve the text from the new TextBox.
If Me.Controls.Count > 1 Then
MsgBox(Me.Controls("TextBox1").Text)
End If
' Remove the new control.
Me.Controls.Remove(TextBox1)
' Remove the control added at design time.
Me.Controls.Remove(Button1)
End Sub

Code Changes for Iterating Through the Controls Collection


The following code illustrates a function for iterating through all the controls on a form and then clearing all CheckBox
controls. This example assumes that the CheckBox controls are situated on GroupBox or Panel controls rather than on the
form. In the Visual Basic 2005 example, since the form's Controls collection only includes controls situated directly on the form,
the function recursively calls itself for any control that has children.

' Visual Basic 6.0


Private Sub ClearChecks()
For Each Control in Me.Controls
If TypeOf Control Is CheckBox Then
Control.Value = vbUnchecked
End If
Next
End Sub

VB
' Visual Basic 2005
Private Sub ClearChecks(ByVal Container As Control)
Dim ctl As Control
Dim chk As CheckBox
For Each ctl In Container.Controls
If TypeOf ctl Is CheckBox Then
chk = ctl
chk.Checked = False
End If
' Recursively call this function for any container controls.
If ctl.HasChildren Then
ClearChecks(ctl)
End If
Next
End Sub

Upgrade Notes
Because of differences between Visual Basic 6.0 and the Visual Basic 2005 Controls collections, calls to the Add method are
not upgraded. You must add code to recreate the behavior of your application using the new Add method.
See Also
Reference
Control.Controls Property
Form.ControlCollection Class
Visual Basic Concepts

Data Control for Visual Basic 6.0 Users


The Visual Basic 6.0 Data control is used as a mechanism for binding controls to a database using DAO. Visual Basic 2005 has
no equivalent for the Data control; the data-binding architecture has changed and DAO is no longer supported. For more
information, see Data Access for Visual Basic 6.0 Users.
The Data control also provides an interface for navigating data, with buttons for moving back and forth through rows in a
database table. Visual Basic 2005 has an equivalent control, the BindingNavigator control, which also contains buttons for
adding and deleting rows.
See Also
Reference
BindingNavigator Control Overview (Windows Forms)
Concepts
Things to Consider Before Upgrading
Data Access for Visual Basic 6.0 Users
Visual Basic Concepts

DataGrid Control for Visual Basic 6.0 Users


The DataGrid control in Visual Basic 6.0 is replaced by the Windows Forms DataGridView control in Visual Basic 2005. The
names of some properties, methods, events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
Data Binding
The Visual Basic 2005 DataGridView control does not need data-specific methods or events because all actions are performed
through the data source. Because of this separation of presentation and data functionality, the data source can be changed with
or without user interface input. Also, multiple controls bound to the same data source will always stay in sync.
Navigation
Properties for viewing and navigation in the DataGrid control (such as TabAction, EnterAction, AllowArrows,
WrapCellPointer, and Scrollable) are no longer needed. For example, the grid functions as though the Scrollable property is
set to True: If more data exists than can be displayed, a scroll bar appears automatically. Excel-style navigation through the grid
is the default, allowing the user to move forward with the TAB key and backward with the SHIFT+TAB key combination. For
more information, see Default Keyboard and Mouse Handling in the Windows Forms DataGridView Control.
Caption Property
In Visual Basic 6.0, the Caption property is used to display a title bar above the grid; if the Caption property is left empty, no
title bar is displayed.
The Visual Basic 2005 DataGridView control does not support a title bar. However, you can achieve the same effect using a
Label control.
Data Formatting
In Visual Basic 6.0, formatting data in the DataGrid control is handled using the DataFormat property and a StdDataFormat
object. Formatting is applied on a column-by-column basis.
In the Visual Basic 2005 DataGridView control, formatting is accomplished using the Format property of a
DataGridViewCellStyle object. Formatting can be applied to individual cells, columns, or rows. For more information, see
Data Formatting in the Windows Forms DataGridView Control.
hWndEditor Property
In Visual Basic 6.0, the hWndEditor property is used to pass the window handle assigned to a DataGrid control's editing
window to a Windows API call.
The Visual Basic 2005 DataGridView control does not have a separate window handle when in edit mode; instead, use the
Handle property of the DataGridView control or any embedded edit controls.
MarqueeStyle Property
In Visual Basic 6.0, the MarqueeStyle property controls the appearance of a selected cell or row by changing the border style,
inverting the foreground and background colors, or invoking an edit window.
There is no direct equivalent for the Visual Basic 2005 DataGridView control. However, you can achieve the same effect
through a combination of the SelectionMode, CellBorderStyle, and Format properties. For more information, see
Selection Modes in the Windows Forms DataGridView Control.
SelLength, SelStart, SelText Properties
In the Visual Basic 6.0 DataGrid control, when a cell enters edit mode, the SelLength, SelStart, and SelText properties can be
used to set the initial position of the caret or to highlight a portion of the text in the cell.
In the Visual Basic 2005 DataGridView control, these properties no longer exist. The cells in the DataGridView control are
based on the TextBox control; by adding code to the EditingControlShowing event handler you can access the SelectionLength,
SelectionStart, and SelectedText properties of the underlying control.
Split Views
The Visual Basic 6.0 DataGrid control supports a split view, allowing the user to display the same data side-by-side. The Split
object and the Split, Splits, and TabAcrossSplits properties control the ability to display a split view.
In the Visual Basic 2005 DataGridView control, these properties no longer exist. However, you can achieve the same effect
using one or more SplitContainer controls and multiple DataGridView controls. To duplicate the functionality of the
TabAcrossSplits property, you can use the StandardTab property of the DataGridView control.
Code Changes for the DataGrid Control
The following code demonstrates the differences between Visual Basic 6.0 and Visual Basic 2005 by showing how, in each
version, to highlight the text in a cell when a user selects the cell in a DataGridView control.

' Visual Basic 6.0


Private Sub DataGrid1_Click()
DataGrid1.SelStart = 1
DataGrid1.SelLength = DataGrid1.Text
MsgBox("The selected text is " & DataGrid1.SelText)
End Sub

VB
' Visual Basic 2005
Private Sub DataGridView1_EditingControlShowing( _
ByVal sender As Object, ByVal e As System.Windows.Forms. _
DataGridViewEditingControlShowingEventArgs) _
Handles DataGridView1.EditingControlShowing
CType(e.Control, TextBox).SelectionStart = 0
CType(e.Control, TextBox).SelectionLength = Len(CType(e.Control, _
TextBox).Text)
MsgBox("The selected text is " & CType(e.Control, _
TextBox).SelectedText)
End Sub

DataGrid Control Property, Method, and Event Equivalencies


The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents. Those
properties, methods, and events that have the same name and behavior are not listed. All Visual Basic 2005 enumerations map
to the System.Windows.Forms namespace unless otherwise noted.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties
Visual Ba Visual Basic 2005 Equivalent
sic 6.0
AddNew New implementation. Data operations are handled in the data source. For more information, see
Mode Displaying Data in the Windows Forms DataGridView Control.

Align Dock and Anchor

AllowAdd AllowNew (BindingSource)


New

AllowArr No longer an adjustable property; arrow navigation always allowed. For more information, see
ows Default Keyboard and Mouse Handling in the Windows Forms DataGridView Control.

AllowDel AllowRemove (BindingSource)


ete

AllowRo AllowUserToResizeRows
wSizing

AllowUpd AllowEdit (BindingSource)


ate
Appearan New implementation. For more information, see Appearance and BorderStyle Properties for Visual Basic 6.0 Users.
ce

ApproxCo New implementation. Data operations are handled in the data source. For more information, see
unt Displaying Data in the Windows Forms DataGridView Control.

BackColo BackgroundColor
r
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.

Bookmar New implementation. You can now directly access any item.
k

Caption New implementation. Use a Label control to simulate a title bar.

Col SelectedColumns

ColumnH ColumnHeadersVisible
eaders

Container Parent; inherited from Control.

CurrentCe IsCurrentCellDirty, IsCurrentCellInEditMode


llModifie
d

CurrentCe CurrentCell
llVisible
Note
If the CurrentCell property is set to a cell that is not visible, the grid scrolls to show that cell (similar to setting C
urrentCellVisible = True).

DataChan IsCurrentCellDirty, IsCurrentRowDirty


ged

DataForm DataGridViewCellStyle.object.
ats
Note
Formatting can be set for an individual cell, column, or row.

DefColWi Width DataGridViewColumn object.


dth

DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMod
e

EditActiv IsCurrentCellInEditMode
e
FirstRow FirstDisplayedScrollingRowIndex

Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontNam Font Handling for Visual Basic 6.0 Users.
e
FontSize
FontStrik
ethrough
FontUnde
rline

ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.

HeadFont DataGridViewCellStyle object.


Note
Fonts are handled differently in Visual Basic 2005. For more information, see
Font Object for Visual Basic 6.0 Users.

HeadLine No direct equivalent. Use the WrapMode property of the DataGridViewCellStyle object in combination with
s ColumnHeadersHeight.

Height Height, inherited from Control class.


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpCont New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
extID

hWnd Handle

hWndEdit New implementation. Use Handle.


or

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

Left Left, inherited from Control class.


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
LeftCol FirstDisplayedScrollingColumnIndex

Marquee No direct equivalent. Use the SelectionMode, CellBorderStyle, and Format properties.
Style

RecordSel RowHeadersVisible
ectors
Row SelectedRows

RowDivid GridColor, CellBorderStyle, RowHeadersBorderStyle, ColumnHeadersBorderStyle properties.


erStyle

RowHeig Height
ht

SelBook New implementation. You can now directly access any item.
marks

SelEndCo SelectedCells, SelectedColumns


l
SelStartC
ol

SelLength No direct equivalent. Use the SelectionLength property in the EditingControlShowing event handler.

SelStart No direct equivalent. Use the SelectionStart property in the EditingControlShowing event handler.

SelText No direct equivalent. Use the SelectedText property in the EditingControlShowing event handler.

Split New implementation. Split views are not directly supported; use a SplitContainer control.
Splits
TabAcros
sSplits

TabActio StandardTab
n

Tag New implementation.

Text CurrentCell.Value
Note
The Value property returns an Object; use CStr or ToString to convert it to a String.

ToolTipTe ToolTip component


xt
For more information, see ToolTip Support for Visual Basic 6.0 Users.
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

VisibleCo DisplayedColumnCount method.


ls
Note
In Visual Basic 6.0, partially visible columns are always included in the count; the DisplayedColumnCount meth
od uses a Boolean includePartialColumns parameter to determine whether partially visible columns are includ
ed.

VisibleRo DisplayedRowCount method.


ws
Note
In Visual Basic 6.0, partially visible rows are always included in the count; the DisplayedRowCount method uses
a Boolean includePartialRows parameter to determine whether partially visible rows are included.

WhatsThi New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
sHelpID

Width Width, inherited from Control class.


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

WrapCell No longer an adjustable property; default behavior is WrapCellPointer = True.


Pointer
Methods
Visual Basic 6 Visual Basic 2005 Equivalent
.0
CaptureImag New implementation. Capturing the contents of a DataGridView control to a PictureBox control is not suppo
e rted.

ClearFields New implementation. Column formatting is automatic when re-binding.

ClearSelCols ClearSelection

ColContainin IndexOf (DataGridViewColumnCollection)


g

Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users..

GetBookmar New implementation. Bookmarks are no longer supported.


k

HoldFields New implementation. Column formatting is preserved when rebinding.


Move SetBounds, inherited from Control class.
Note
Coordinates are handled differently in Visual Basic 2005. For more information,
seeCoordinate System for Visual Basic 6.0 Users.

Rebind ResetBindings, inherited from Control class.

RowBookmar New implementation. Bookmarks are no longer supported.


k

RowContaini IndexOf (DataGridViewColumnCollection)


ng

RowTop GetContentBounds (DataGridViewCell)

Scroll New implementation method. Use the CurrentCell property.

SetFocus Focus

ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his

SplitContaini New implementation. Split views are not directly supported; use a SplitContainer control.
ng

ZOrder BringToFront()or SendToBack()functions


Events
Visual Basic Visual Basic 2005 Equivalent
6.0
AfterColEdit CellEndEdit

AfterColUpd New implementation. Data operations are handled in the data source. For more information, see
ate Displaying Data in the Windows Forms DataGridView Control.
AfterDelete

AfterUpdate RowsAdded

BeforeColEd CellBeginEdit
it

BeforeColUp New implementation. Data operations are handled in the data source. For more information, see
date Displaying Data in the Windows Forms DataGridView Control.
BeforeDelet
e
BeforeInsert
BeforeUpdat
e

ButtonClick Click (Button control)


Change TextChanged
Note
The behavior of the TextChanged event is slightly different. For more information, see
ComboBox Control Change Event for Visual Basic 6.0 Users.

Click SelectedIndexChanged

ColEdit CellBeginEdit

ColResize ColumnWidthChanged

DblClick CellMouseDoubleClick

DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

Error DataError

HeadClick ColumnHeaderMouseClick

MouseDown CellMouseDown

MouseMove CellMouseMove

MouseUp CellMouseUp

OLEComplet New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
eDrag
OLEDragDro
p
OLEDragOve
r
OLEGiveFee
dback
OLESetData
OLEStartDra
g

OnAddNew RowsAdded

RowColChan CurrentCellChanged
ge

RowResize RowHeightChanged

SelChange SelectionChanged

SplitChange New implementation. Split views are not directly supported; use a SplitContainer control.

Validate Validating
Upgrade Notes
When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, the Change event of the DataGrid control is mapped to the
TextChanged event of the Visual Basic 2005 DataGridView control. The behavior of the TextChanged event differs from
that of the Change event; this difference may cause unintended results in your code.
Any code related to data-specific methods or events is not upgraded. Warning comments are added to the code, and the code
must be removed or modified before compiling the application.
See Also
Reference
DataGridView Control Overview (Windows Forms)
Controls and Programmable Objects Compared in Different Languages and Libraries
Concepts
DataGridView Control Technology Summary (Windows Forms)
What's New in Windows Forms and Windows Forms Controls
Other Resources
DataGridView Control (Windows Forms)
Windows Forms Controls for Visual Basic 6.0 Users
Windows Forms Data Binding
Visual Basic Concepts

DirListBox Control for Visual Basic 6.0 Users


The Visual Basic 6.0 DirListBox control has been rendered obsolete by the OpenFileDialog and SaveFileDialog components in
Visual Basic 2005.
Conceptual Differences
The Visual Basic 6.0 DirListBox control was typically used to display directories and paths in a File Open or Save dialog box.
In Visual Basic 2005, the Windows Forms OpenFileDialog and SaveFileDialog components provide the ability to create
standard Windows dialog boxes for working with files, in most cases eliminating the need for the DirListBox control.
Note
We recommend that you use the OpenFileDialog and SaveFileDialog components to provide a consistent and familiar us
er experience. If you find it necessary to create your own file dialog boxes, Visual Basic 2005 does provide a DirListBox contr
ol as part of the Microsoft Visual Basic Compatibility Runtime library. For more information, see
How to: Add Visual Basic 6.0 File System Controls to Your Application.

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any existing DirListBox controls are upgraded to the
VB6.DirListBox control that is provided as a part of the compatibility library (Microsoft.VisualBasic.Compatibility).
See Also
Tasks
How to: Add Visual Basic 6.0 File System Controls to Your Application
Reference
OpenFileDialog Component Overview (Windows Forms)
SaveFileDialog Component Overview (Windows Forms)
Visual Basic Concepts

DriveListBox Control for Visual Basic 6.0 Users


The Visual Basic 6.0 DriveListBox control has been rendered obsolete by the OpenFileDialog and SaveFileDialog components
in Visual Basic 2005.
Conceptual Differences
The Visual Basic 6.0 DriveListBox control was typically used to display a list of drives in a File Open or File Save dialog box.
In Visual Basic 2005, the Windows Forms OpenFileDialog and SaveFileDialog components enable you to create standard
Windows dialog boxes to work with files, in most cases eliminating the need for the DriveListBox control.
Note
Using the OpenFileDialog and SaveFileDialog components provides a consistent and familiar user experience. If you need
to create your own file dialog boxes, Visual Basic 2005 does provide a DriveListBox control as part of the Microsoft Visual B
asic Compatibility Runtime library. For more information, see
How to: Add Visual Basic 6.0 File System Controls to Your Application.

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any existing DriveListBox controls are upgraded to the
VB6.DriveListBox control that is part of the Microsoft.VisualBasic.Compatibility library.
See Also
Tasks
How to: Add Visual Basic 6.0 File System Controls to Your Application
Reference
OpenFileDialog Component Overview (Windows Forms)
SaveFileDialog Component Overview (Windows Forms)
Visual Basic Concepts

FileListBox Control for Visual Basic 6.0 Users


The Visual Basic 6.0 FileListBox control has been rendered obsolete by the OpenFileDialog and SaveFileDialog components in
Visual Basic 2005.
Conceptual Differences
The Visual Basic 6.0 FileListBox control was typically used to select files in a File Open or File Save dialog box.
In Visual Basic 2005, the Windows Forms OpenFileDialog and SaveFileDialog components provide the ability to create
standard Windows dialog boxes for working with files, in most cases eliminating the need for the FileListBox control.
Note
We recommend that you use the OpenFileDialog and SaveFileDialog components to provide a consistent and familiar us
er experience. If you find it necessary to create your own file dialog boxes, Visual Basic 2005 does provide a FileListBox cont
rol as part of the Microsoft Visual Basic Compatibility Runtime library. For more information, see
How to: Add Visual Basic 6.0 File System Controls to Your Application.

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any existing FileListBox controls are upgraded to the
VB6.FileListBox control, which is provided as a part of the Microsoft.VisualBasic.Compatibility library.
See Also
Tasks
How to: Add Visual Basic 6.0 File System Controls to Your Application
Reference
OpenFileDialog Component Overview (Windows Forms)
SaveFileDialog Component Overview (Windows Forms)
Visual Basic Concepts

Font Object for Visual Basic 6.0 Users


Visual Basic 6.0 provides two ways to set Font properties; in Visual Basic 2005 there is a single Font class.
Conceptual Differences
In Visual Basic 6.0, Font properties can be set by means of a stdFont object rather than setting the properties directly. The
Visual Basic 6.0 stdFont object is replaced in Visual Basic 2005 by the Font class; there is no direct mapping of the properties
and methods. For more information, see Font Handling for Visual Basic 6.0 Users.
See Also
Concepts
Font Handling for Visual Basic 6.0 Users
Visual Basic Concepts

Form Object for Visual Basic 6.0 Users


The Form object in Visual Basic 6.0 is replaced by the Form class in Visual Basic 2005. The names of some properties, methods,
events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
Activate and Deactivate Events
In Visual Basic 6.0, the Activate and Deactivate events are raised only when switching between forms.
In Visual Basic 2005, the Activated and Deactivate events are also raised when switching to or from other applications.
QueryUnload Event
In Visual Basic 6.0, the QueryUnload event takes two arguments, Cancel and UnloadMode. By querying the UnloadMode
argument you can determine why the form is being unloaded and then cancel if necessary.
In Visual Basic 2005, the QueryUnload event is replaced by the FormClosing event; UnloadMode is replaced by CloseReason.
Picture Property
In Visual Basic 6.0, an image assigned to the Picture property is displayed in the top left corner of the form if the bitmap is
smaller than the form.
In Visual Basic 2005, the Picture property is replaced by the BackgroundImage property; if the image assigned to the
BackgroundImage property is smaller than the form, it will be tiled by default.
Moveable Property
In Visual Basic 6.0, the Moveable property of a form can be set to False to prevent a user from moving the form at run time.
Windows Forms in Visual Basic 2005 do not have an equivalent property.
Although it is generally considered bad user interface design, you can achieve similar behavior in Visual Basic 2005 by setting
the FormBorderStyle property to None and the ControlBox property to False.
ValidateControls Method
In Visual Basic 6.0, the ValidateControls method is used to force the Validate event for the control that has focus when a
form is closed; if the Validate event fails, an error is raised.
In Visual Basic 2005, the ValidateControls method is replaced by the Validate method, which returns True or False.
Mouse Events for MDI Forms
In Visual Basic 6.0, MDI Forms supports mouse events. In Visual Basic 2005, the Click, MouseDown, MouseMove, and
MouseUp events are no longer supported for MDI Forms, because the MDI Form has no client area to receive mouse events.
Code Changes for the Form Object
The following examples illustrate the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Determining Why a Form Closes
The following code can help you determine why a form closes and then how to act depending on the reason. In the Visual Basic
6.0 example, the UnloadMode argument of the QueryUnload event is used. In the Visual Basic 2005 example, the argument is
replaced by the CloseReason parameter in the FormClosing event handler.

' Visual Basic 6.0


Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
If UnloadMode = vbFormControlMenu Then
Cancel = True
End If
End Sub

VB
' Visual Basic 2005
Private Sub Form1_FormClosing(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles _
MyBase.FormClosing
If e.CloseReason.UserClosing Then
e.Cancel = True
End If
End Sub

Code Changes for Validating a Control on Form Close


The following code demonstrates how to force the validation of the control that has focus when the form closes. This example
assumes that the CausesValidation property of the TextBox control is set to the default value of True.

' Visual Basic 6.0


Private Sub Text1_Validate(Cancel As Boolean)
If Text1.Text = "" Then
MsgBox ("Please enter a name")
Cancel = True
End If
Private Sub Form_Unload(Cancel As Integer)
OnError GoTo ERR_HANDLER
Me.ValidateControls

ERR_HANDLER:
' If validation failed cancel the Unload event.
If Err.Number = 380 Then
Cancel = True
End If
End Sub

VB
' Visual Basic 2005
Private Sub TextBox1_Validating(ByVal sender As Object, ByVal e As _
System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
If TextBox1.Text = "" Then
MsgBox("Please enter a name")
e.Cancel = True
End If
End Sub

VB
Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e _
As System.Windows.Forms.FormClosingEventArgs) Handles _
MyBase.FormClosing
' If validation failed cancel the Closing event.
If Me.Validate = False Then
e.Cancel = True
End If
End Sub

Form Object Property, Method, and Event Equivalencies


The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 properties. Those
properties, methods, and events that have the same name and behavior are not listed. Where applicable, constants are
indented beneath the property or method. All Visual Basic 2005 enumerations map to the System.Windows.Forms namespace
unless otherwise noted.
Links are provided as necessary to topics explaining differences in behavior. Where there is no direct equivalent in Visual Basic
2005, links are provided to topics that present alternatives.
Form Properties
Visual Basic 6. Visual Basic 2005 Equivalent
0
Appearance New implementation. For more information, see
Appearance and BorderStyle Properties for Visual Basic 6.0 Users.

AutoRedraw New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.

BorderStyle FormBorderStyle

Caption Text

ClipControls New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

Controls Controls
Note
There are differences in the Controls collection in Visual Basic 2005. For more information, see
Controls Collection for Visual Basic 6.0 Users.

Count Count
Note
There are differences in the Controls collection in Visual Basic 2005. For more information, see
Windows Forms Controls for Visual Basic 6.0 Users.

CurrentX New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
CurrentY

DrawMode New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
DrawStyle
DrawWidth

FillColor New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
FillStyle
Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethro
ugh
FontUnderline

ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.

HasDC New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

HDC New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

Height Height, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpContextID New implementation. For more information, see Help Support for Visual Basic 6.0 Users.

HWnd Handle

Image New implementation. The Image property in Visual Basic 6.0 returned a handle to a bitmap; images in Visual
Basic 2005 do not have handles.

Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

LinkMode No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkTopic

MaxButton MaximizeBox

MDIChild MdiParent
Note
MDI behavior is different in Visual Basic 2005. For more information, see MDI for Visual Basic 6.0 Users.
MinButton MinimizeBox

MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

Moveable New implementation. For more information, see Moveable Property for Visual Basic 6.0 Users.

Name Name

NegotiateMen New implementation. For more information, see Menu Object for Visual Basic 6.0 Users.
us

OLEDropMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

Palette New implementation. For more information, see Palettes for Visual Basic 6.0 Users.
PaletteMode

Picture BackgroundImage
Note
In Visual Basic 6.0, the Picture was displayed in the top left corner of the form; in Visual Basic 2005, the Ba
ckgroundImage is tiled.

RightToLeft: RightToLeft
True Yes enumeration value
False

ScaleHeight New implementation. For more information, see Coordinate System for Visual Basic 6.0 Users.
ScaleLeft
ScaleMode
ScaleTop
ScaleWidth

StartUpPositio StartPosition
n:
Manual enumeration value
0 – Manual
CenterParent enumeration value
1 – CenterOwn
er CenterScreen enumeration value

2 – CenterScre WindowsDefaultLocation enumeration value


en
3 – Windows D
efault
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

WhatsThisButt HelpButton
on
Note
There are differences in Help behavior in Visual Basic 2005. For more information, see
Help Support for Visual Basic 6.0 Users.

WhatsThisHelp New implementation. For more information, see Help Support for Visual Basic 6.0 Users.

Width Width, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Form Methods
Visual Basic 6.0 Visual Basic 2005 Equivalent
Circle New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

Cls New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

Line New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

PaintPicture New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

Point New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

PopupMenu New implementation. For more information, see Menu Object for Visual Basic 6.0 Users.

PrintForm New implementation. For more information, see Printing Changes for Visual Basic 6.0 Users.

Pset New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

Scale New implementation. For more information, see Coordinate System for Visual Basic 6.0 Users.
ScaleX
ScaleY

SetFocus Activate
Show Show or ShowDialog

TextHeight New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

TextWidth New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

ValidateControl Validate
s
Note
The Validate method returns True or False; ValidateControls raised an error if validation failed.

WhatsThisMode New implementation. For more information, see Help Support for Visual Basic 6.0 Users.

ZOrder: BringToFront or SendToBack function


0 – vbBringToFr BringToFront
ont
SendToBack
1 - vbSendToBa
ck

Form Events
Visual Bas Visual Basic 2005 Equivalent
ic 6.0
Activate Activated
Note
In Visual Basic 6.0, the Activate event is raised only when switching between forms in the application; in Visual
Basic 2005, the Activated event also is raised when switching from other applications.

Click Click
Note
The Click event is not supported for MDI Forms.

DblClick DoubleClick

Deactivat Deactivate
e
Note
In Visual Basic 6.0, the Deactivate event is raised only when switching between forms in the application; in Visu
al Basic 2005, it also is raised when switching to other applications.

DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

GotFocus Enter
Initialize New method
Note
The behavior of the New method is different than the Initialize event. For more information, see
Forms Tasks for Visual Basic 6.0 Users.

LinkClose No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkError
LinkExecu
te
LinkOpen

MouseDo MouseDown
wn
Note
The MouseDown event is not supported for MDI Forms.

MouseMo MouseMove
ve
Note
The MouseMove event is not supported for MDI Forms.

MouseUp MouseUp
Note
The MouseUp event is not supported for MDI Forms.

OLECompl New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
eteDrag
OLEDragD
rop
OLEDragO
ver
OLEGiveF
eedback
OLESetDa
ta
OLEStartD
rag

QueryUnl FormClosing
oad
Note
In Visual Basic 6.0, QueryUnload takes two arguments, Cancel and UnloadMode. In Visual Basic 2005, Cancel is
replaced by Cancel; UnloadMode is replaced by CloseReason.
Terminate Dispose method
Note
The behavior of the Dispose method is different than the Terminate event. For more information, see
Form Events for Visual Basic 6.0 Users.

Unload FormClosing
Note
The behavior of the FormClosing event is different than the Unload event. For more information, see
Form Events for Visual Basic 6.0 Users.

See Also
Concepts
Forms Tasks for Visual Basic 6.0 Users
Other Resources
Windows Forms
Visual Basic Concepts

Forms Collection for Visual Basic 6.0 Users


The Visual Basic 6.0 Forms collection is replaced by the My.Application.OpenForms Property property in Visual Basic 2005.
Conceptual Differences
A Visual Basic 6.0 Forms collection is a collection whose elements represented each loaded form in an application. The
collection includes the application's MDI form, MDI child forms, and non-MDI forms. The Forms collection has a single
property, Count, which specifies the number of elements in the collection.
The Visual Basic 2005 OpenForms property returns a FormCollection object that contains all of the application's open forms.
The behavior is the same as the Forms collection, and it can be used in the same ways.
Code Changes for the Forms Collection
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Getting a Count of Open Forms
The following code demonstrates how to return the number of forms currently open in an application.

' Visual Basic 6.0


MsgBox Forms.Count

VB
' Visual Basic 2005
MsgBox(CStr(My.Application.OpenForms.Count))

Code Changes for Setting Properties of All Open Forms


The following code demonstrates how to change the title of each open form in an application.

' Visual Basic 6.0


For Each Form in Forms
Forms(i).Caption = "Hello"
Next

VB
' Visual Basic 2005
For Each f As Form In My.Application.OpenForms
f.Text = "Hello"
Next

See Also
Tasks
How to: Access All Open Forms of an Application
Reference
My.Application.OpenForms Property
Concepts
Form Object for Visual Basic 6.0 Users
Visual Basic Concepts

Frame Control for Visual Basic 6.0 Users


The Visual Basic 6.0 Frame control is replaced by two controls in Visual Basic 2005: the GroupBox control and the Panel
control.
Conceptual Differences
In Visual Basic 6.0, the Frame control is used as a container for grouping controls. In Visual Basic 2005, the Frame control is
replaced by either the GroupBox control or the Panel control.
The GroupBox control is the equivalent of a Frame control with a BorderStyle property of 1 – Fixed Single. It has a visible
border and optionally a caption.
The Panel control is the equivalent of a Frame control with a BorderStyle property of 0 – None. It has no border or caption.
In addition, there are numerous conceptual differences that apply to all controls, including differences in data binding, font
handling, drag and drop, Help support and more. For more information, see
Windows Forms Controls for Visual Basic 6.0 Users.
Frame Control Property, Method, and Event Equivalencies
The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents. Those
properties, methods, and events that have the same name and behavior are not listed. Where applicable, constants are
indented beneath the property or method. All Visual Basic 2005 enumerations map to the System.Windows.Forms namespace
unless otherwise noted.
Links are provided as necessary to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic
2005, links are provided to topics that present alternatives
Frame Properties
Visual Basic 6.0 Visual Basic 2005 Equivalent
Appearance FlatStyle (GroupBox control only)

BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.

BorderStyle BorderStyle (GroupBox control only)

Caption Text (GroupBox control only)


Note
The Panel control does not have a Text property.

ClipControls New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

Container Parent

DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethro
ugh
FontUnderline

ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.

Height Height, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpContextID New implementation. For more information, see Help Support for Visual Basic 6.0 Users.

HWnd Handle

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

OLEDropMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

Parent FindForm method

RightToLeft RightToLeft

ToolTipText ToolTip component


For more information, see ToolTip Support for Visual Basic 6.0 Users.
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

WhatsThisHelp New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
ID

Width Width, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Frame Methods
Visual Basic 6 Visual Basic 2005 Equivalent
.0
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his

ZOrder BringToFront or SendToBack function


Frame Events
Visual Basic 6.0 Visual Basic 2005 Equivalent
Click Click (Panel only; GroupBox has no equivalent)

DblClick DoubleClick (Panel only; GroupBox has no equivalent)

DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver
OLECompleteDrag
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, Frame controls that have their BorderStyle property set
to 0 - None are upgraded to Panel controls; all other Frame controls are upgraded to GroupBox controls.
See Also
Reference
GroupBox Control Overview (Windows Forms)
Concepts
Introduction to the Panel Control
Visual Basic Concepts

HScrollBar Control for Visual Basic 6.0 Users


The HScrollBar control in Visual Basic 6.0 is replaced by the Windows Forms HScrollBar control in Visual Basic 2005. The
names of some properties, methods, events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
Change Event
In Visual Basic 6.0, when the Value property of an HScrollBar control is changed, the Change event is raised.
In Visual Basic 2005, the Change event is not raised; the ValueChanged event is raised instead.
Value Property
In Visual Basic 6.0, when the Scroll or Change event of an HScrollBar control is raised, the current scroll value is assigned to
the Value property.
When the Scroll or ValueChanged event is raised in Visual Basic 2005, the control's Value property has not yet been updated.
If you need to emulate Visual Basic 6.0 behavior, you can create a helper function to retrieve the value. For more information,
see Code was changed from an event to a procedure.
LargeChange Property
In Visual Basic 6.0, the LargeChange property determines the amount of change to the Value property setting in a scroll bar
control when the user clicks the area between the scroll box and scroll arrow.
In Visual Basic 2005, the default value of the LargeChange property is 10; in Visual Basic 6.0 it is 1.
Max Property
In Visual Basic 6.0, the Max property determines the maximum Value property setting in a scroll bar control.
In Visual Basic 2005, the Max property is replaced by the Maximum property; the default value is 100, in Visual Basic 6.0 it is
32767.
Min Property
In Visual Basic 6.0, the Min property determines the minimum Value property setting in a scroll bar control. The Min property
can be set to a value greater than that of the Max property.
In Visual Basic 2005, the Min property is replaced by the Minimum property, the value of which must always be less than that
of the Maximum property.
Other Differences
In addition, there are numerous conceptual differences that apply to all controls, including differences in data binding, font
handling, drag-and-drop functionality, Help support, and more.
HScrollBar Control Property, Method and Event Equivalencies
The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents. Those
properties, methods, and events that have the same name and behavior are not listed. Where applicable, constants are
indented beneath the property or method. All Visual Basic 2005 enumerations map to the System.Windows.Forms namespace
unless otherwise noted.
Necessary links are provided to explain behavior differences. Where there is no direct equivalent in Visual Basic 2005, links are
provided to topics that present alternatives.
HScrollBar Properties
Visual Basi Visual Basic 2005 Equivalent
c 6.0
Container Parent

DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
Height Height, Size
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpConte New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
xtID

HWnd Handle

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

LargeChan LargeChange
ge
Note
The default value in Visual Basic 6.0 was 1, in Visual Basic 2005 the default value is 10.

Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Max Maximum
Note
The default value in Visual Basic 6.0 was 32767, in Visual Basic 2005 the default value is 100.

Min Minimum
Note
In Visual Basic 6.0 Min can be set to a value greater than Max; in Visual Basic 2005 the Minimum property can
not be set to a value greater than the Maximum property.

MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePoin Cursor
ter
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

Parent FindForm method

RightToLef RightToLeft
t:
Yes enumeration value
True
No enumeration value
False
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Value Value
Note
In Visual Basic 6.0, when the Value is changed, the Change event is raised. In Visual Basic 2005 the Change ev
ent is not raised; use the ValueChanged event instead.

WhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
HelpID

Width Width, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HScrollBar Methods
Visual Basic 6.0 Visual Basic 2005 Equivalent
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

SetFocus Focus

ShowWhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.

ZOrder: BringToFront or SendToBack function


0 – vbBringToFr BringToFront
ont
SendToBack
1 - vbSendToBa
ck
HScrollBar Events
Visual Basi Visual Basic 2005 Equivalent
c 6.0
Change ValueChanged
Note
The behavior of the Change and Scroll events have changed in Visual Basic 2005. For more information, see
Code was changed from an event to a procedure.
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

GotFocus Enter

LostFocus Leave

Scroll Scroll
Note
The behavior of the Change and Scroll events have changed in Visual Basic 2005. For more information, see
Code was changed from an event to a procedure.

Validate Validating

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any code in the Change or Scroll event handlers for the
HScrollBar or VScrollBar controls is changed to a procedure due to a difference in the sequence of events. For more
information, see Code was changed from an event to a procedure.
See Also
Reference
HScrollBar and VScrollBar Controls Overview (Windows Forms)
Visual Basic Concepts

Image Control for Visual Basic 6.0 Users


The Image control in Visual Basic 6.0 has no direct equivalent in Visual Basic 2005. The Image control is a lightweight control;
Visual Basic 2005 does not support lightweight controls.
Upgrading the Stretch Property
The properties, methods, and events for the Image control are a subset of those for the PictureBox control (with the
exception of the Stretch property). For more information, see PictureBox Control for Visual Basic 6.0 Users.
The following table shows the mapping between the Stretch property and the equivalent for the Visual Basic 2005 PictureBox
control.
Stretch Property Equivalents
Visual Basic 6.0 Visual Basic 2005 Equivalent
Stretch = False PictureBoxSizeMode = Normal

Stretch = True PictureBoxSizeMode = StretchImage

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any Image controls are upgraded to PictureBox
controls.
See Also
Reference
PictureBox Control Overview (Windows Forms)
Concepts
PictureBox Control for Visual Basic 6.0 Users
Visual Basic Concepts

ImageList Control for Visual Basic 6.0 Users


The ImageList control in Visual Basic 6.0 is replaced by the Windows Forms ImageList component in Visual Basic 2005. The
names of some properties, methods, events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
BackColor
In Visual Basic 6.0, the ImageList control has a BackColor property; however, it has no effect because the control is not visible
at run time.
In Visual Basic 2005, the new ImageList component no longer has a BackColor property.
Left, Top Properties
In Visual Basic 6.0, the ImageList control has Left and Top properties that set the control's location on a form.
In Visual Basic 2005, the ImageList component is located in the Component Tray instead of on the form; as such there is no
need for Left or Top properties.
UseMaskColor Property
In Visual Basic 6.0, the UseMaskColor property determines whether the color assigned in the MaskColor property is used as
a mask.
In Visual Basic 2005, the ImageList component no longer has a UseMaskColor property, and the MaskColor property is
replaced by a TransparentColor property. To prevent the color defined in the TransparentColor property from being used as
a mask, set it to Color.Transparent.
Overlay Method
In Visual Basic 6.0, the Overlay method of an ImageList control allows you to create a composite third image out of two
ListImage objects. For example, you might define a mask for one image so that part of the second image shows through.
In Visual Basic 2005, the ImageList component no longer supports the Overlay method. To achieve the same effect you will
need to create the composite image using a graphics program and then add that image to the ImageList.
Code Changes for the ImageList Control
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Setting a MaskColor
The following code demonstrates how to specify a color to be used for a mask and how to toggle it on and off.

' Visual Basic 6.0


' Specify the color to be used as a mask.
ImageList1.MaskColor = vbWhite
' Use the mask.
ImageList1.UseMaskColor = True
' Don't use the mask.
ImageList1.UseMaskColor = False

VB
' Visual Basic 2005
' Specify the color to be used as a mask and use the mask.
ImageList1.TransparentColor = Color.White
' Don't use the mask.
ImageList1.TransparentColor = Color.Transparent

ImageList Control Property and Method Equivalencies


The following tables list Visual Basic 6.0 properties and methods, along with their Visual Basic 2005 equivalents. Those
properties and methods that have the same name and behavior are not listed. All Visual Basic 2005 enumerations map to the
System.Windows.Forms namespace unless otherwise noted.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties
Visual Basic 6.0 Visual Basic 2005 Equivalent
BackColor New implementation. ImageList is a component.

hImageList Handle

ImageHeight ImageSize
ImageWidth

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

Left New implementation. ImageList is a component.

ListImage Image (ImageCollection class)

ListImages ImageCollection

MaskColor TransparentColor

Parent FindForm method

Top New implementation. ImageList is a component.

UseMaskColor New implementation. Set TransparentColor to Transparent.


Methods
Name Visual Basic 2005 Equivalent
Overlay New implementation.

Upgrade Notes
When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, any ImageList controls are upgraded to Windows Forms
ImageList components. Where properties, methods, and events have no equivalent or have differences in behavior, upgrade
notes or warnings will be added to your code.
See Also
Reference
ImageList Component Overview (Windows Forms)
Other Resources
ImageList Component (Windows Forms)
Visual Basic Concepts

Label Control for Visual Basic 6.0 Users


This topic compares the Visual Basic 6.0 Label control with its equivalent in Visual Basic 2005.
The Label control in Visual Basic 6.0 is replaced by the Windows Forms Label control in Visual Basic 2005. The names of some
properties, methods, events, and constants are different, and in some cases there are behavior differences.
Conceptual Differences
BackStyle Property
In Visual Basic 6.0, the BackStyle property of the Label control determines whether the label had a transparent background.
Setting the BackStyle property to 0 – Transparent allows any background image to show through the label. If the label is
placed over other controls, the controls also show through.
In Visual Basic 2005, the BackStyle property no longer exists and the transparency behavior is slightly different. To emulate
the transparent behavior in Visual Basic 2005, set the BackColor property to Transparent. This will allow the background image
to show through. If the label is placed over other controls, the controls will show through only if they are higher in the z-order.
Note
The ZOrder method no longer exists in Visual Basic 2005. At design time you can use the Bring to Front or Send to Back c
ommand on the Format menu; at run time you can use the BringToFront or SendToBack function.

WordWrap Property
In Visual Basic 6.0, the WordWrap property determines if text wraps to multiple lines when it is too long to fit in a label.
In Visual Basic 2005, the text in a Label control automatically wraps. The only way to prevent wrapping is to make the height of
the Label control equivalent to a single line of text.
Other Differences
In addition, there are numerous conceptual differences that apply to all controls, including differences in data binding, font
handling, drag-and-drop functionality, Help support and more. For more information, see
Windows Forms Concepts for Visual Basic 6.0 Users.
Code Changes for the Label Control
The following code example illustrates the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Making a Label Transparent
The following example demonstrates making the background of a label control transparent. In Visual Basic 6.0, if there are
other controls behind the Label, those controls show through. In the Visual Basic 2005 example, any controls behind the Label
can optionally show through using the BringToFront and SendToBack functions.

' Visual Basic 6.0


Private Sub MakeTransparent()
Label1.BackStyle = vbTransparent
End Sub

VB
' Visual Basic 2005
Private Sub MakeTransparent()
Label1.BackColor = System.Drawing.Color.Transparent
' Let controls behind the label show through.
Label1.SendToBack()
' Make the portion of controls behind the label transparent
Label1.BringToFront()
End Sub

Label Control Property, Method, and Event Equivalencies


The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents. Those
properties, methods, and events that have the same name and behavior are not listed. Where applicable, constants are
indented beneath the property or method. All Visual Basic 2005 enumerations map to the System.Windows.Forms namespace
unless otherwise noted.
This table provides necessary links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic
2005, links are provided to alternatives.
Label Properties
Visual Basic 6.0 Visual Basic 2005 Equivalent
Alignment: TextAlign
0 - Left Justify MiddleLeft enumeration value
1 - Right Justif MiddleRight enumeration value
y

Appearance New implementation. For more information, see


Appearance and BorderStyle Properties for Visual Basic 6.0 Users.

AutoSize AutoSize

BackColor BackColor
Note For a list of constants, see Color Handling for Visual Basic 6.0 Users.
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.

BackStyle New implementation. For more information, see Conceptual Differences above.

Caption Text

Container Parent

DataChanged New implementation. For more information, see Data Access for Visual Basic 6.0 Users.
DataField
DataFormat
DataMember
DataSource

DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode

Font Font
FontBold Note Fonts are handled differently in Visual Basic 2005. For more information, see
Font Handling for Visual Basic 6.0 Users.
FontItalic
FontName
FontSize
FontStrikethro
ugh
FontUnderline
ForeColor ForeColor
Note
For a list of constants, see Color Handling for Visual Basic 6.0 Users.

Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.

Height Height, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

LinkItem No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkMode
LinkTimeOut
LinkTopic

MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

OLEDropMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

Parent FindForm method

RightToLeft: RightToLeft
True Yes enumeration value
False No enumeration value

ToolTipText ToolTip component


For more information, see ToolTip Support for Visual Basic 6.0 Users.
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

WhatsThisHelp New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
ID

Width Width, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

WordWrap New implementation.


Note
Text in the Visual Basic 2005 Label control wraps by default and cannot be changed.

Label Methods
Visual Basic 6.0 Visual Basic 2005 Equivalent
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

LinkExecute No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkPoke
LinkRequest
LinkSend

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

ShowWhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.

ZOrder: BringToFront or SendToBack method


0 – vbBringToFr BringToFront
ont
SendToBack
1 - vbSendToBa
ck
Label Events
Visual Basic 6.0 Visual Basic 2005 Equivalent
Change TextChanged
DblClick DoubleClick

DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

LinkClose No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkError
LinkNotify
LinkOpen

OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any Label controls are upgraded to Windows Forms
Label controls, and properties, methods and events are upgraded to their equivalent. Where there may be differences in
behavior, upgrade comments are inserted into the code.
See Also
Concepts
Introduction to the Label Control
Visual Basic Concepts

Line Control for Visual Basic 6.0 Users


The Line control in Visual Basic 6.0 has no equivalent in Visual Basic 2005. However, you can use graphics methods to achieve
the same results.
Conceptual Differences
In Visual Basic 6.0, the Line control provides an easy way to draw lines on a form at design time. The Line control is a
"lightweight control"- that is, it does not have a Windows handle, also called an HWnd.
In Visual Basic 2005, there is no equivalent for the Line control and lightweight controls are no longer supported. There are,
however, ways to draw lines on a form both at design time and at run time.
At design time, you can draw a vertical or horizontal line on a form by adding a Label control and setting the Text property to
an empty string, the BorderStyle property to None, and the Width or Height to 1.
At run time, you can draw vertical, horizontal, or diagonal lines in a form's Paint event handler by creating a new Graphics
object and calling its methods.
In Visual Basic 6.0, you can us a Line control to draw a line on top of a container control such as a PictureBox or Frame
control by adding a Line control to the container.
In Visual Basic 2005, you can achieve the same effect by calling the DrawLine method in the Paint event of the container
control.
Code Changes for the Line Control
The following examples illustrate the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Drawing Horizontal or Vertical Lines
The following code demonstrates how to draw horizontal and vertical lines on a form at run time. In the Visual Basic 6.0
example, the Line control is used; it assumes that two Line controls were added at design time. The Visual Basic 2005 example
demonstrates two methods - using a Label control and using Graphics methods.
Note
In Visual Basic 6.0 the default unit of measurement was twips; in Visual Basic 2005 it is pixels.

' Visual Basic 6.0


Private Sub Form_Load()
' Draw a horizontal line 200 twips from the top of the form.
Line1.X1 = 0
Line1.X2 = Me.Width
Line1.Y1 = 200
Line1.Y2 = 200
Line1.BorderColor = vbRed
Line1.BorderWidth = 1
' Draw a vertical line 200 twips from the left of the form.
Line1.Y1 = 0
Line1.Y2 = Me.Height
Line1.X1 = 200
Line1.X2 = 200
Line1.BorderColor = vbBlue
Line1.BorderWidth = 1

VB
' Visual Basic 2005
' Using Label controls.
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Dim Line1 As New System.Windows.Forms.Label
Dim Line2 As New System.Windows.Forms.Label
' Draw a horizontal line 14 pixels from the top of the form.
Line1.Location = New System.Drawing.Point(0, 14)
Line1.Size = New System.Drawing.Size(Me.Width, 1)
Line1.BorderStyle = BorderStyle.None
Line1.BackColor = System.Drawing.Color.Red
Line1.Text = ""
Controls.Add(Line1)
' Draw a vertical line 14 pixels from the left of the form.
Line2.Location = New System.Drawing.Point(14, 0)
Line2.Size = New System.Drawing.Size(1, Me.Height)
Line2.BorderStyle = BorderStyle.None
Line2.BackColor = System.Drawing.Color.Blue
Line2.Text = ""
Controls.Add(Line2)
End Sub

VB
' Visual Basic 2005
' Using Graphics methods
Private Sub Form1Paint(ByVal sender As Object, _
ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
' Draw a horizontal line 28 pixels from the top of the form.
e.Graphics.DrawLine(Pens.Red, 0, 28, Me.Width, 28)
' Draw a vertical line 28 pixels from the left of the form.
e.Graphics.DrawLine(Pens.Blue, 28, 0, 28, Me.Height)
End Sub

Drawing a Diagonal Line


The following code demonstrates drawing a diagonal line on a form at run time. In the Visual Basic 6.0 example, the Line
control is used; it assumes that a Line control was added at design time. The Visual Basic 2005 example uses Graphics
methods.
Note
In Visual Basic 6.0 the default unit of measurement was twips; in Visual Basic 2005 it is pixels.

' Visual Basic 6.0


Private Sub Form_Load()
' Draw a diagonal line from the top left to the lower right.
Line1.X1 = 0
Line1.X2 = Me.ScaleWidth
Line1.Y1 = 0
Line1.Y2 = Me.ScaleHeight
Line1.BorderColor = vbBlack
Line1.BorderWidth = 1
End Sub

VB
' Visual Basic 2005
Private Sub FormPaint(ByVal sender As Object, _
ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
' Draw a diagonal line from the top left to the lower right.
e.Graphics.DrawLine(Pens.Black, 0, 0, Me.ClientSize.Width, _
Me.ClientSize.Height)
End Sub

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, vertical or horizontal Line controls are replaced with the
Windows Forms Label control, with the Text property set to an empty string, the BorderStyle property set to None, and the
BackColor, Width, and Height properties set to match the original control.
Line controls that were not vertical or horizontal are not upgraded. You can replace the Line control using the Graphics
functions built into the .NET Framework.
See Also
Concepts
Graphics for Visual Basic 6.0 Users
Visual Basic Concepts

ListBox Control for Visual Basic 6.0 Users


The ListBox control in Visual Basic 6.0 is replaced by either the ListBox control or the CheckedListBox control in Visual Basic
2005. The names of some properties, methods, events, and constants are different, and in some cases there are differences in
behavior.
Conceptual Differences
Checked ListBox
In Visual Basic 6.0, the Style property of a ListBox control determines whether a check box is displayed next to each text item.
Multiple items in the ListBox can be selected by selecting the check box beside them even if the MultiSelect property is set to
False. There is no way to programmatically determine the checked state of an item; if you required this capability, you have to
use a ListView control instead.
In Visual Basic 2005, the new CheckedListBox control displays check boxes next to each item; you can no longer display check
boxes in the ListBox control. The CheckedListBox control allows you to programmatically determine the checked state of
each item through a CheckedItemCollection collection.
Columns Property
In Visual Basic 6.0, the Columns property took an integer specifying the number of columns to display.
In Visual Basic 2005, the MultiColumn property takes a Boolean value, and the ColumnWidth property takes an integer
specifying the width in pixels. If the width of the ListBox control is changed at run time, you may also need to set the
ColumnWidth property for each column.
ItemCheck Event
In the Visual Basic 6.0 ListBox control, when the ItemCheck event was raised, the check state was already changed.
In the Visual Basic 2005 CheckedListBox control, when the ItemCheck event is raised the check state has not yet changed. You
can get the pending value from the ItemCheckEventArgs argument passed to the event.
Code Changes for the ListBox Control
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Adding and Removing Items in a ListBox Control
The following code demonstrates how to add and remove ListBox items.

' Visual Basic 6.0


' Add an item at the end of the list.
List1.AddItem "Tokyo"
' Insert an item at the top of the list.
List1.AddItem "Copenhagen", 0
' Remove the first item.
List1.RemoveItem 0

VB
'Visual Basic 2005
' Add an item at the end of the list.
ListBox1.Items.Add("Tokyo")
' Insert an item at the top of the list.
ListBox1.Items.Insert(0, "Copenhagen")
' Remove the first item.
ListBox1.Items.RemoveAt(0)

Code Changes for Accessing Specific Items in a ListBox Control


The following code demonstrates how to return the value of a ListBox item.

' Visual Basic 6.0


Private Function GetItemText(i As Integer) As String
' Return the text of the item using the index:
GetItemText = ListBox1.List(1)
End Function

VB
' Visual Basic 2005
Private Function GetItemText(ByVal i As Integer) As String
' Return the text of the item using the index:
GetItemText = CStr(ListBox1.Items(i))
End Function

Code Changes for Determining Checked Items in a CheckedListBox Control


The following code demonstrates how to determine the checked state of items in a CheckedListBox control.

' Visual Basic 6.0


' The Visual Basic 6.0 ListBox control didn't support this scenario,
' a ListView control had to be used instead.
Dim s As String
Dim i As Integer
' Loop through all items
For i = 1 To ListView1.ListItems.Count
' If an item is checked, add it to the string
If ListView1.ListItems(i).Checked = True Then
s = s & "Checked Item" & CStr(i) & " = " & _
ListView1.ListItems(i) & vbCrLf
End If
Next
' Determine if any items are checked.
If s <> "" Then
MsgBox s
End If

VB
' Visual Basic 2005
' Determine if there are any items checked.
If CheckedListBox1.CheckedItems.Count <> 0 Then
' If so, loop through all checked items and print results.
Dim x As Integer
Dim s As String = ""
For x = 0 To CheckedListBox1.CheckedItems.Count - 1
s = s & "Checked Item " & CStr(x + 1) & " = " & _
CStr(CheckedListBox1.CheckedItems(x)) & ControlChars.CrLf
Next x
MessageBox.Show(s)
End If

ListBox Control Property, Method, and Event Equivalencies


The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents. Those
properties, methods, and events that have the same name and behavior are not listed. Where applicable, constants are
indented beneath the property or method. All Visual Basic 2005 enumerations map to the System.Windows.Forms namespace
unless otherwise noted.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties
Visual Basic 6. Visual Basic 2005 Equivalent
0
Appearance New implementation. For more information, see
Appearance and BorderStyle Properties for Visual Basic 6.0 Users.

BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.

Columns MultiColumn and ColumnWidth

Container Parent

DataChanged New implementation. For more information, see Data Access for Visual Basic 6.0 Users.
DataField
DataFormat
DataMember
DataSource

DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode

Font Font Font


FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethro
ugh
FontUnderline

ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.

Height Height, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpContextI New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
D

HWnd Handle
Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

IntegralHeigh IntegralHeight
t

ItemData New implementation. For more information, see ItemData property cannot be upgraded.

Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

List Items

ListCount Count (List.Count)

ListIndex SelectedIndex

MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

MultiSelect SelectionMode

NewIndex New implementation. For more information, see NewIndex property cannot be upgraded.

OLEDragMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDropMode

Parent FindForm method

SelCount Count (SelectedItem.Count)

Selected GetSelected, SetSelected (ListBox control)


GetItemChecked, SetItemChecked (CheckedListBox control)

Style New implementation property. 0 – Standard maps to the CheckedListBox control, 1 – Checkbox maps to t
he CheckedListBox control.

ToolTipText ToolTip component


For more information, see ToolTip Support for Visual Basic 6.0 Users.

Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
WhatsThisHel New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
pID

Width Width, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Methods
Name Visual Basic 2005 Equivalent
AddItem Add
AddRange
Insert

Clear Clear

Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

RemoveItem Remove

SetFocus Focus

ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his

ZOrder BringToFront or SendToBack method


Events
Visual Basic 6.0 Visual Basic 2005 Equivalent
DblClick DoubleClick

DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

GotFocus Enter

ItemCheck ItemCheck (CheckedListBox only)

LostFocus Leave
OLECompleteDra New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
g
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag

Scroll New implementation. For more information, see


TopIndex Property and Scroll Event for Visual Basic 6.0 Users.

Validate Validating

Upgrade Notes
During upgrade, if the Style property of a Visual Basic 6.0 Listbox is set to 1 – Checkbox, it is upgraded to the
CheckedListBox control; otherwise, it is upgraded to the ListBox control.
See Also
Reference
ListBox Control Overview (Windows Forms)
ListBox Control Overview (Windows Forms)
CheckedListBox Control Overview (Windows Forms)
Visual Basic Concepts

ListView Control for Visual Basic 6.0 Users


The ListView control in Visual Basic 6.0 is replaced by the ListView control in Visual Basic 2005. The names of some properties,
methods, events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
DropHighlight Property
In Visual Basic 6.0, when the cursor moves over a ListItem object in a ListView control, the DropHighlight property is used
to highlight the ListItem object with the system highlight color . This property is commonly used in drag-and-drop operations.
In Visual Basic 2005, the DropHighlight property no longer exists; you can achieve the same effect by ownerdrawing (also
known as custom drawing) the highlight in the MouseEnter and MouseLeave events. For more information, see
Controls with Built-In Owner-Drawing Support.
FlatScrollBar Property
In Visual Basic 6.0, the FlatScrollBar property determines whether the scroll bar in a ListView control has a flat (two-
dimensional) appearance.
In Visual Basic 2005, the FlatScrollBar property no longer exists; scroll bars in the ListView control always have a three-
dimensional appearance.
HideColumnHeaders Property
In Visual Basic 6.0, the HideColumnHeaders property determines whether ColumnHeader objects in a ListView control are
hidden in Report view.
In Visual Basic 2005, the HideColumnHeaders property no longer exists; you can control the visibility of the column headers
by setting the HeaderStyle property.
ItemClick Event
The Visual Basic 6.0 ListView control has both a Click and an ItemClick event. The ItemClick event takes a ListItem object as
an argument.
In Visual Basic 2005, there is no longer an ItemClick event. Instead you can use the Click event and the
EventSender.FocusedItem argument to determine which ListViewItem was clicked.
Sorting
In Visual Basic 6.0, sorting of a ListView control is accomplished using a combination of the Sorted, SortKey, and SortOrder
properties. Sorted determines whether sorting is enabled, SortOrder determines if sorting is ascending or descending, and
SortKey specifies a sub-item to be used for sorting instead of the text.
In Visual Basic 2005, sorting is accomplished using the Sorting property, which enables sorting and sets the sort order in a
single step. The SortKey property is replaced by the ListViewItemSorter property.
View Property
In Visual Basic 6.0, the View property determines how items in a ListView control are displayed—as large icons with text
(lvwIcon), as small icons with text (lvwSmallIcon), as a list (lvwList), or as a list with sub-items (lvwReport).
In Visual Basic 2005, the View property still exists, but the enumerations are different. lvwIcon is replaced by LargeIcon,
lvwSmallIcon by SmallIcon, lvwList by List, and lvwReport by Details. In addition, there is a new view, Tile, where each item
appears as a full-sized icon with the item label and sub-item information to the right of it.
Code Changes for the ListView Control
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Determining the Selected Item in a ListView Control
The following code example assigns the selected ListView item to a variable.

' Visual Basic 6.0


Dim theItem As ListItem
theItem = ListView1.SelectedItem
VB
' Visual Basic 2005
Dim theItem As ListViewItem
If ListView1.SelectedItems.Count > 0 Then
theItem = ListView1.SelectedItems(0)
Else
theItem = Nothing
End If

Code Changes for Determining All Selected Items in a ListView Control


The following code example displays a message box with the text of each selected item in a ListView control.

' Visual Basic 6.0


For i = 1 To ListView1.ListItems.Count
If ListView1.ListItems(i).Selected = True Then
MsgBox(ListView1.SelectedItem
End If
Next i

VB
' Visual Basic 2005
For Each selectedItem As ListViewItem In ListView1.SelectedItems
MsgBox(selectedItem.Text)
Next

ListView Control Property, Method, and Event Equivalencies


The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents. Those
properties, methods, and events that have the same name and behavior are not listed. All Visual Basic 2005 enumerations map
to the System.Windows.Forms namespace unless otherwise noted.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties
Visual Basic 6.0 Visual Basic 2005 Equivalent
Appearance New implementation. For more information, see
Appearance and BorderStyle Properties for Visual Basic 6.0 Users.

Arrange Alignment

BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.

ColumnHeaderIc ImageIndex, ImageKey


ons

ColumnsHeader Columns
s

Container Parent
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode

DropHighlight New implementation.

FlatScrollBar New implementation.

Font Font Font


FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethrou
gh
FontUnderline

Height Height, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpContextID New implementation. For more information, see Help Support for Visual Basic 6.0 Users.

HWnd Handle

Icons LargeImageList

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

ListItems Items

MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

OLEDragMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDropMode

Parent FindForm method

Picture BackgroundImage
PictureAlignme BackgroundImageTiled
nt

SelectedItem SelectedItems

SmallIcons SmallImageList

Sorted Sorting
SortOrder

SortKey ListViewItemSorter

TextBackground BackColor

ToolTipText ToolTip component.


For more information, see ToolTip Support for Visual Basic 6.0 Users.

Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

WhatsThisHelpI New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
D

Width Width, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Methods
Name Visual Basic 2005 Equivalent
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

FindItem FindItemWithText

GetFirstVisibl TopItem
e

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

Refresh RedrawItems
SetFocus Focus

ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his

StartLabelEdi BeginEdit
t

ZOrder BringToFront or SendToBack method


Events
Visual Basic 6.0 Visual Basic 2005 Equivalent
DblClick DoubleClick

DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

GotFocus Enter

ItemClick No direct equivalent.

LostFocus Leave

OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag

Validate Validating

Upgrade Notes
When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, any ListView controls are upgraded to Windows Forms
ListView controls. Where properties, methods, and events have no equivalent or have differences in behavior, upgrade notes
or warnings are added to your code.
See Also
Other Resources
ListView Control (Windows Forms)
Visual Basic Concepts

MaskEdBox Control for Visual Basic 6.0 Users


The MaskEdBox control in Visual Basic 6.0 is replaced by the Windows Forms MaskedTextBox control in Visual Basic 2005.
The names of some properties, methods, events, and constants are different, and in some cases there are differences in
behavior.
Conceptual Differences
In Visual Basic 6.0, the AutoTab property determines whether the next control in the TAB order receives focus as soon as the
Text property of a MaskEdBox control is filled with valid data.
In Visual Basic 2005, there is no equivalent for the AutoTab property. You can achieve the same effect by monitoring and
validating the input, and setting the focus to the next control yourself.
In Visual Basic 6.0, the PasswordChar property is of type String; in Visual Basic 2005 it is of type Char.
In addition, there are numerous conceptual differences that apply to all controls, including differences in data binding, font
handling, drag-and-drop, Help support and more. For more information, see
Windows Forms Concepts for Visual Basic 6.0 Users.
MaskedEdBox Control Property, Method, and Event Equivalencies
The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents. Those
properties, methods, and events that have the same name and behavior are not listed. All Visual Basic 2005 enumerations map
to the System.Windows.Forms namespace unless otherwise noted.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties
Visual Basic 6. Visual Basic 2005 Equivalent
0
AllowPrompt AllowPromptAsInput

Appearance New implementation. For more information, see


Appearance and BorderStyle Properties for Visual Basic 6.0 Users.

AutoTab New implementation.

BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.

ClipMode SkipLiterals

ClipText Text
Note
The Visual Basic 6.0 ClipText property excludes literals; in Visual Basic 2005 literals are included unless Ski
pLiterals is set to true.

Container Parent
DataBinding New implementation. For more information, see Data Access for Visual Basic 6.0 Users.
DataChanged
DataField
DataFormat

DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode

Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethro
ugh
FontUnderline

ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.

Format New implementation. Use formatting functions such as FormatNumber Function (Visual Basic) or
FormatDateTime Function (Visual Basic).

FormattedTex Text
t
Note
The Visual Basic 6.0 ClipText property excludes literals; in Visual Basic 2005 literals are included unless Ski
pLiterals is set to true.

Height Height, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpContextI New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
D

HWnd Handle

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

OLEDragMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDropMod
e

Parent FindForm method

PromptInclud TextMaskFormat
e

SelLength SelectionLength

SelStart SelectionStart

SelText SelectedText

ToolTipText ToolTip component.


For more information, see ToolTip Support for Visual Basic 6.0 Users.

Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

WhatsThisHel New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
pID

Width Width, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Methods
Visual Basic 6 Visual Basic 2005 Equivalent
.0
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.

OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

SetFocus Focus

ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his

ZOrder BringToFront or SendToBack function


Events
Visual Basic 6.0 Visual Basic 2005 Equivalent
Change TextChanged

DblClick DoubleClick

DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

GotFocus Enter

LostFocus Leave

OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag

Validate Validating

ValidationError MaskInputRejected

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any MaskEdBox controls are upgraded to Windows
Forms MaskedTextBox controls, and properties, methods and events are upgraded to their equivalents. Where there may be
differences in behavior, upgrade comments are inserted into the code.
See Also
Tasks
Walkthrough: Working with the MaskedTextBox Control
MaskedTextBox Control Sample
How to: Bind Data to the MaskedTextBox Control
Other Resources
MaskedTextBox Control (Windows Forms)
Visual Basic Concepts

MDIForm Object for Visual Basic 6.0 Users


In Visual Basic 6.0, an MDIForm was a special type of form that acted as a container for an MDI (Multiple Document Interface)
application. In Visual Basic 2005, any form with its IsMdiContainer property set to true can act as an MDI container.
Conceptual Differences
Child Forms and Multiple MDI Forms
In Visual Basic 6.0, setting the MDIChild property on a child form identifies it as a child of the MDI form; an MDI application
can have only one MDI form.
In Visual Basic 2005, the MdiParent property replaces the MDIChild property and identifies the MDI form that will contain the
child form; MDI applications can have multiple MDI containers.
BackColor and Picture Properties
In Visual Basic 6.0, the background color of an MDIForm can be changed by setting the BackColor property, and a
background picture can be displayed by setting the Picture property.
In Visual Basic 2005, it is not possible to change the background color or display a picture on an MDI form. Although you can
set the BackColor and BackgroundImage properties on the form, setting the IsMdiContainer property to true invalidates
these settings.
AutoShowChildren Property
In Visual Basic 6.0, the AutoShowChildren property of an MDI form is used to automatically show an MDI child form when it
is loaded. Standard forms do not have this behavior; calling the Load method loads but does not show the form.
In Visual Basic 2005, you must explicitly call the Show method in order to display an MDI child form.
Controls and Graphics on MDI Forms
In Visual Basic 6.0, it is not possible to add most controls to an MDIForm. You can only add docked controls such as the Menu,
StatusBar, or ToolBar control. In addition, graphics methods such as Circle or Line cannot be used on an MDIForm.
In Visual Basic 2005, you can add any control to an MDI form; however the behavior may not be what you would expect. Any
controls on a form with the IsMdiContainer property set to true will "float" on top of any MDI child forms. Although you can
make calls to graphics methods in the Paint event, the graphics will not appear at run time.
Code Changes for MDI Forms
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Showing MDI Child Forms
The following code demonstrates how to display five instances of an MDI child form.

' Visual Basic 6.0


Dim F(1 To 4) As New Form1
Private Sub MDIForm_Load()
Dim i As Integer
Load Form1
For i = 1 To 4
F(i).Caption = "Form" & i + 1
F(i).Show
Next I
End Sub

VB
' Visual Basic 2005
Private Sub MDIForm1_Load(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles MyBase.Load
Dim i As Integer = 0
For i = 0 To 4
Dim F As New FormChild
F.Text = "Form " & CStr(i + 1)
F.Show()
Next
End Sub

Code Changes for Arranging MDI Child Windows


The following code demonstrates how to write code to change the arrangement of windows in an MDI application. It assumes
that you have created menu items for each option.

' Visual Basic 6.0


Private Sub menuCascade_Click()
Me.Arrange vbCascade
End Sub
Private Sub menuTileHorizontally_Click()
Me.Arrange vbHorizontal
End Sub
Private Sub menuTileVertically_Click()
Me.Arrange vbVertical
End Sub

VB
' Visual Basic 2005
Private Sub CascadeToolStripMenuItem_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles CascadeToolStripMenuItem.Click
Me.LayoutMdi(MdiLayout.Cascade)
End Sub

VB
' Visual Basic 2005
Private Sub TileVerticleToolStripMenuItem_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles TileVerticalToolStripMenuItem.Click

Me.LayoutMdi(MdiLayout.TileVertical)
End Sub

VB
' Visual Basic 2005
Private Sub TileHorizontalToolStripMenuItem_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles TileHorizontalToolStripMenuItem.Click

Me.LayoutMdi(MdiLayout.TileHorizontal)
End Sub

MDI Form Property and Method Equivalencies


The following table lists Visual Basic 6.0 properties and methods and their Visual Basic 2005 equivalents. Only properties and
methods that are unique to the MDIForm object are listed — for other properties, methods, and events see
Form Object for Visual Basic 6.0 Users.
MDIForm Properties and Methods
Visual Basic 6.0 Visual Basic 2005 Equivalent
ActiveForm property ActiveMdiChild

Arrange method LayoutMdi

AutoShowChildren property New implementation. For more information, see MDI form Show behavior has changed.
BackColor property New implementation. The background for an MDI form will always be the default (Control).

Picture property New implementation. MDI forms in Visual Basic 2005 cannot directly display pictures.

Upgrade Notes
When upgrading a MDI application from Visual Basic 6.0 to Visual Basic 2005, any MDIForm objects are upgraded to regular
forms and their IsMdiContainer property is set to true.
In Visual Basic 2005, the AutoShowChildren property no longer exists. To emulate the Visual Basic 6.0 behavior, a line of code
is added during upgrade to show each child form if AutoShowChildren is set to true in the original application.
See Also
Concepts
MDI for Visual Basic 6.0 Users
Form Object for Visual Basic 6.0 Users
Forms Tasks for Visual Basic 6.0 Users
Other Resources
Multiple-Document Interface (MDI) Applications
Visual Basic Concepts

Menu Object for Visual Basic 6.0 Users


The Menu object in Visual Basic 6.0 is replaced by either the MenuStrip control or the ContextMenuStrip control in Visual Basic
2005. The names of some properties, methods, events, and constants are different, and in some cases there are differences in
behavior.
Conceptual Differences
In Visual Basic 6.0, a Menu object is created using the Menu Editor. Menu objects are tied to the form for which they are
created, but they can be modified at run time or displayed as context menus. Menus created with the Menu object do not
natively support shading, icons, or embedded controls; only Windows 98 "flat"-style menus can be created.
In Visual Basic 2005, the Menu object is replaced by the MenuStrip and ContextMenuStrip components. Menus may be
created using in-place editing at design time or they may be created in code. The MenuStrip and ContextMenuStrip
components allow you to create modern Office toolbar style menus, with full support for shaded regions, icons, and embedded
controls such as dropdown lists. For more information, see MenuStrip Control Overview (Windows Forms).
Displaying Context Menus
In Visual Basic 6.0, you can display a context menu by calling the PopupMenu method and passing it any top level Menu
object. For example, if you have an Edit menu named mnuEdit with Cut, Copy, and Paste submenus, you can display a context
menu with the Cut, Copy, and Paste commands by calling PopupMenu mnuEdit.
In Visual Basic 2005, context menus are displayed using a separate ContextMenuStrip component. There is no equivalent for
the PopupMenu method, however you can still share commands between a MenuStrip and a ContextMenuStrip by
creating the ContextMenuStrip at design time and sharing event handlers.
Code Changes for the Menu Object
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Displaying Context Menus
The following code demonstrates how to display Cut, Copy, and Paste commands from an existing Edit menu in a context
menu.

' Visual Basic 6.0


Private Sub mnuCut_Click()
MsgBox "You selected Cut"
End Sub
Private Sub mnuCopy_Click()
MsgBox "You selected Copy"
End Sub
Private Sub mnuPaste_Click()
MsgBox "You selected Paste"
End Sub
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Button = vbRightButton Then
PopupMenu mnuEdit
End If
End Sub

VB
' Visual Basic 2005
' You must first add a ContextMenuStrip component to the form at design
' time and add Cut, Copy, and Paste menu items named
' CutContextMenuItem, CopyContextMenuItem, and PasteContextMenuItem.
Private Sub CutToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles CutToolStripMenuItem.Click
MsgBox("Cut")
End Sub
Private Sub CopyToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles CopyToolStripMenuItem.Click
MsgBox("Copy")
End Sub
Private Sub PasteToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles PasteToolStripMenuItem.Click
MsgBox("Paste")
End Sub

VB
Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As _
System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown

If e.Button = Windows.Forms.MouseButtons.Right Then


Me.ContextMenuStrip = ContextMenuStrip1
AddHandler CutContextMenuItem.Click, _
AddressOf CutToolStripMenuItem_Click

AddHandler CopyContextMenuItem.Click, _
AddressOf CopyToolStripMenuItem_Click
AddHandler PasteContextMenuItem.Click, _
AddressOf PasteToolStripMenuItem_Click
End If
End Sub

Menu Property and Method Equivalencies


The following tables list Visual Basic 6.0 properties and methods, along with their Visual Basic 2005 equivalents. Those
properties and methods that have the same name and behavior are not listed. All Visual Basic 2005 enumerations map to the
System.Windows.Forms namespace unless otherwise noted.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties
Visual Basic 6.0 Visual Basic 2005 Equivalent
Caption Text (MenuStripItem)

HelpContextID New implementation. For more information, see Help Support for Visual Basic 6.0 Users.

Index New implementation. See the Index property of the ToolStripItemCollection class.

NegotiatePosition No equivalent. This property was only used for OLE linking and embedding which is no longer supported.

Parent FindForm method

WindowList MdiWindowListItem
Methods
Visual Basic 6.0 Visual Basic 2005 Equivalent
PopupMenu New implementation. Use a ContextMenuStrip component.

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any calls to the PopupMenu method are not upgraded;
you must create context menus to replace these.
See Also
Reference
MenuStrip Control Overview (Windows Forms)
Concepts
Menu Handling for Visual Basic 6.0 Users
Other Resources
Windows Forms Controls for Visual Basic 6.0 Users
Visual Basic Concepts

OLE Container Control for Visual Basic 6.0 Users


In Visual Basic 6.0, the OLE Container control was used to add insertable OLE objects to your forms. There is no OLE
Container control in Visual Basic 2005.
Conceptual Differences
If you need the functionality of the OLE Container control, in some cases you may be able to substitute the Visual Basic
2005 WebBrowser control and use it in the place of an OLE Container.
One of the primary uses of the OLE Container control was to embed Word documents or Excel spreadsheets in a form. The
WebBrowser control encapsulates Internet Explorer, which has the ability to display these types of documents. In addition, you
can use Visual Studio Tools for Office to interact with Office applications directly from Visual Basic 2005.
See Also
Reference
WebBrowser Control Overview
Concepts
Things to Consider Before Upgrading
Other Resources
Visual Studio Tools for Office
Visual Basic Concepts

OptionButton Control for Visual Basic 6.0 Users


The OptionButton control in Visual Basic 6.0 is replaced by the Windows Forms RadioButton control in Visual Basic 2005. The
names of some properties, methods, events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
In Visual Basic 6.0, the Click event of the OptionButton control was raised only when its Value property was changed to
True.
In Visual Basic 2005, the CheckedChanged event of the RadioButton control is raised each time the Checked property value
changes to either True or False.
In addition, there are numerous conceptual differences that apply to all controls, including differences in data binding, font
handling, drag-and-drop functionality, Help support and more. For more information, see
Windows Forms Concepts for Visual Basic 6.0 Users.
Code Changes for the OptionButton Control
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Programmatically Selecting an OptionButton
The following code demonstrates how to select an OptionButton or RadioButton control from a group of two at run time.

' Visual Basic 6.0


If Option1.Value = True Then
Option2.Value = True
Else
Option1.Value = True
End If

VB
' Visual Basic 2005
If RadioButton1.Checked = True Then
RadioButton2.Checked = True
Else
RadioButton1.Checked = True
End If

Code Changes for Determining When an OptionButton is Selected


The following code demonstrates how to handle the Click event for the OptionButton control versus the CheckedChanged
event for the RadioButton control.

' Visual Basic 6.0


' The Click event is only fired when the Value is True
Private Sub Option1_Click()
MsgBox "Option1 was clicked"
End Sub

Private Sub Option2_Click()


MsgBox "Option2 was clicked"
End Sub

VB
' Visual Basic 2005
' The CheckChanged event fires each time the RadioButton's Checked
' value changes to either True or False.
Private Sub RadioButton1_CheckedChanged(ByVal sender As Object, ByVal _
e As System.EventArgs) Handles RadioButton1.CheckedChanged, _
RadioButton2.CheckedChanged
' Only execute if the Checked value is True.
If sender.Checked = True Then
MsgBox(sender.Name & " was clicked")
End If
End Sub

OptionButton Control Property, Method, and Event Equivalencies


The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents. Those
properties, methods, and events that have the same name and behavior are not listed. Where applicable, constants are
indented beneath the property or method. All Visual Basic 2005 enumerations map to the System.Windows.Forms namespace
unless otherwise noted.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties
Visual Basic 6 Visual Basic 2005 Equivalent
.0
Alignment TextAlign

Appearance FlatStyle

BackColor BackColor
Note
For a list of constants, see Color Handling for Visual Basic 6.0 Users.

Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.

Caption Text

Container Parent

DisabledPict New implementation. For more information, see Style Property for Visual Basic 6.0 Users.
ure
DownPicture

DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode

Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethr
ough
FontUnderlin
e
ForeColor ForeColor
Note
For a list of constants, see Color Handling for Visual Basic 6.0 Users.

Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.

Height Height, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpContextI New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
D

HWnd Handle

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

MaskColor New implementation. For more information, see MaskColor for Visual Basic 6.0 Users

MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePointe Cursor
r
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

OLEDropMod New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
e

Parent FindForm method

Picture Image

RightToLeft: RightToLeft
True Yes enumeration value
False No enumeration value
Style Appearance
Note
There are differences in how the Graphical style is handled in Visual Basic 2005. For more information, see
Style Property for Visual Basic 6.0 Users.

ToolTipText ToolTip component


For more information, see ToolTip Support for Visual Basic 6.0 Users.

Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

UseMaskColo New implementation. For more information, see MaskColor for Visual Basic 6.0 Users.
r

Value Checked

WhatsThisHe New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
lpID

Width Width, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Methods
Visual Basic 6 Visual Basic 2005 Equivalent
.0
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

SetFocus Focus

ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his

ZOrder BringToFront or SendToBack method


Events
Visual Basic 6 Visual Basic 2005 Equivalent
.0
Click CheckedChanged
Note
In Visual Basic 6.0, the Click event was raised only when the state was changed to True; in Visual Basic 2005,
it is raised for both True and False.

DblClick DoubleClick

DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

GotFocus Enter

LostFocus Leave

OLEComplete New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
Drag
OLEDragDrop
OLEDragOver
OLEGiveFeed
back
OLESetData
OLEStartDrag

Validate Validating

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any OptionButton controls are upgraded to Windows
Forms RadioButton controls, and properties, methods and events are upgraded to their equivalent. Where there may be
differences in behavior, upgrade comments are inserted into the code.
See Also
Reference
RadioButton Control Overview (Windows Forms)
Visual Basic Concepts

PictureBox Control for Visual Basic 6.0 Users


The PictureBox control in Visual Basic 6.0 is replaced by the Windows Forms PictureBox control in Visual Basic 2005. The
names of some properties, methods, events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
PictureBox as a Container
The Visual Basic 6.0 PictureBox control is a container control; in addition to displaying pictures it can be used to group and
display other controls.
The Visual Basic 2005 PictureBox control is not a container control; it is only used to display pictures. You can use the new
Panel control as a replacement for the PictureBox control where you need a container control.
AutoSize Property
In Visual Basic 6.0, the AutoSize property determines whether a PictureBox control retains its design-time size (AutoSize =
False) or is resized dynamically to fit the dimensions of the picture (AutoSize = True).

In Visual Basic 2005, the AutoSize property is replaced by the SizeMode property; in addition to the Normal and AutoSize
modes, options are also available to center, stretch, or zoom the picture.
Graphics Properties and Methods
In Visual Basic 6.0, various graphics properties and methods can be used to draw lines, shapes, and text on top of a PictureBox
control.
In Visual Basic 2005, controls no longer have graphics properties or methods; you can still draw on top of a PictureBox
control using a T:System.Drawing.Graphics object. For more information, see Graphics for Visual Basic 6.0 Users.
Other Differences
In addition, there are numerous conceptual differences that apply to all controls, including differences in data binding, font
handling, drag-and-drop functionality, Help support, and more. For more information, see
Windows Forms Concepts for Visual Basic 6.0 Users.
Code Changes for the PictureBox Control
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Displaying a Picture
The following code demonstrates how to display a picture in a PictureBox control at run time.

' Visual Basic 6.0


Picture1.Picture = LoadPicture(App.Path & "\somepicture.jpg")

VB
' Visual Basic 2005
PictureBox1.Image = System.Drawing.Bitmap.FromFile( _
My.Application.Info.DirectoryPath & "\somepicture.jpg")

Code Changes for Clearing a PictureBox Control


The following code demonstrates how to clear a PictureBox control at run time so that no image is displayed.

' Visual Basic 6.0


Picture1.Picture = LoadPicture("")

VB
' Visual Basic 2005
If Not (PictureBox1.Image Is Nothing) Then
PictureBox1.Image.Dispose()
PictureBox1.Image = Nothing
End If

Code Changes for Drawing on a PictureBox Control


The following code demonstrates how to draw a 40 pixel diameter red circle in the center of a PictureBox control at run time.

' Visual Basic 6.0


Private Sub Picture1_Paint
Dim x As Integer
Dim y As Integer
Picture1.ScaleMode = vbPixels
x = Picture1.ScaleWidth / 2
y = Picture1.ScaleHeight / 2
Picture1.Circle (x, y), 20, vbRed
End Sub

VB
' Visual Basic 2005
Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e _
As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint
Dim radius As Integer = 20
Dim diameter As Integer = radius * 2
Dim x As Integer = (PictureBox1.Width / 2) - radius
Dim y As Integer = (PictureBox1.Height / 2) - radius
e.Graphics.DrawEllipse(Pens.Red, x, y, diameter, diameter)
End Sub

PictureBox Control Property, Method, and Event Equivalencies


The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents. Those
properties, methods, and events that have the same name and behavior are not listed. Where applicable, constants are
indented beneath the property or method. All Visual Basic 2005 enumerations map to the System.Windows.Forms namespace
unless otherwise noted.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties
Visual Basic 6.0 Visual Basic 2005 Equivalent
Align Dock

Appearance New implementation. For more information, see


Appearance and BorderStyle Properties for Visual Basic 6.0 Users.

AutoRedraw New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

AutoSize SizeMode

BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.
BorderStyle BorderStyle
Note
In Visual Basic 6.0, the default is Fixed Single; in Visual Basic 2005 the default is None.

ClipControls New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

Container Parent

CurrentX New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
CurrentY

DataChanged New implementation. For more information, see Data Access for Visual Basic 6.0 Users.
DataField
DataFormat
DataMember
DataSource

DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode

DrawMode New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
DrawStyle
DrawWidth
FillColor
FillStyle

Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethro
ugh
FontUnderline

ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.

HasDC New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
HDC
Height Height, Size
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpContextID New implementation. For more information, see Help Support for Visual Basic 6.0 Users.

HWnd Handle

Image New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
Note
In Visual Basic 2005, the Image property is not a graphics property. It is the equivalent of the Visual Basic 6
.0 Picture property.

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

LinkItem No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkMode
LinkTimeOut
LinkTopic

MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

OLEDragMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDropMode

Parent FindForm

Picture Image

ScaleHeight New implementation. For more information, see Coordinate System for Visual Basic 6.0 Users.
ScaleLeft
ScaleMode
ScaleTop
ScaleWidth
ToolTipText ToolTip component
For more information, see ToolTip Support for Visual Basic 6.0 Users.

Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

WhatsThisHelp New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
ID

Width Width, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Methods
Visual Basic 6 Visual Basic 2005 Equivalent
.0
Circle New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
Cls

Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

Line New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

LinkExecute No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkPoke
LinkRequest
LinkSend

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

PaintPicture New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
Point
Print
PSet
Scale New implementation. For more information, see Coordinate System for Visual Basic 6.0 Users.
ScaleX
ScaleY

SetFocus Focus

ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his

TextHeight New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
TextWidth

ZOrder BringToFront or SendToBack method


Events
Visual Basic Visual Basic 2005 Equivalent
6.0
Change New implementation. There are individual events (BackgroundImageChanged, SizeChanged, and so forth) that
are raised when some properties are changed.

DblClick DoubleClick

DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

GotFocus Enter

KeyDown New implementation. The Visual Basic 2005 PictureBox control is not a container control and does not receive
keystrokes.
KeyPress
KeyUp

LinkClose No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkError
LinkNotify
LinkOpen

LostFocus Leave

OLEComplet New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
eDrag
OLEDragDro
p
OLEDragOve
r
OLEGiveFee
dback
OLESetData
OLEStartDra
g
Validate Validating

Upgrade Notes
During upgrade, PictureBox controls that contain controls are upgraded to Panel controls. For Visual Basic 6.0 PictureBox
controls that were upgraded to Panel controls, images assigned to the Picture property are mapped to the
BackgroundPicture property of the Panel control.
See Also
Reference
PictureBox Control Overview (Windows Forms)
Visual Basic Concepts

Printer Object for Visual Basic 6.0 Users


The Visual Basic 6.0 Printer object is replaced by the PrintDocument component in Visual Basic 2005. The behavior of the two
is considerably different, but in most cases the functionality can be duplicated.
Conceptual Differences
In Visual Basic 6.0, printing is accomplished by creating a Printer object and using graphics methods to draw text and graphics
onto a virtual page. Properties and methods are used to define printer attributes such as DeviceName, PrintQuality or
Copies; other properties such as Orientation and PaperSize define attributes of the page itself. The EndDoc method sends
the output to the default printer for the application as defined in the Printers collection.
In Visual Basic 2005, the Printer object no longer exists. Instead, you use a PrintDocument component to define the graphics
and text, a PrinterSettings object to define printer attributes, and a PageSettings class to define page attributes.
Printing is no longer tied to a specific device, and the concept of a default printer for an application is no longer valid. Instead
the PrintPage method of the PrintDocument component can be used to print to any device, and the default printer is
system-wide. The PrintDialog, PrintPreviewDialog, and PageSetupDialog components allow you to let the user select a
printer and print options at run time.
ColorMode Property
In Visual Basic 6.0, the ColorMode property controls whether output is printed in monochrome on a color printer.
In Visual Basic 2005, it is now up to the printer to expose this as an advanced option. The SupportsColor property of the
PrinterSettings class can be used to determine the color capabilities of a printer.
DriverName Property
In Visual Basic 6.0, the DriverName property of the Printer object is used to specify a printer driver. In early versions of
Windows, and in MS-DOS, printer drivers were necessary to translate output in a way that each specific brand and model of
printer could understand. By the time of Visual Basic 6.0, this was largely unnecessary, but the property was maintained for
backward compatibility.
In Visual Basic 2005, the DriverName property no longer exists; printer drivers are managed by Windows, and you can no
longer specify different drivers.
hDC property
In Visual Basic 6.0, the hDC property of the Printer object specifies a handle to a device context (a link between a Windows-
based application, a device driver, and an output device, such as a printer).
In Visual Basic 2005, the hDC property no longer exists; an instance of a PrintDocument component is the equivalent of a
device context.
Note
Although handles to device contexts are no longer necessary, graphics objects have GetHdc and ReleaseHdc methods that ca
n be used in advanced scenarios.

Page Property
In Visual Basic 6.0, the Page property returns a count of pages that have been printed since your application started or since
the last time the EndDoc statement was used on the Printer object. This property is often used to add a page number to each
page during printing.
In Visual Basic 2005, page numbers are not tracked; however, you can easily keep a count by setting a variable in the
BeginPrint event and incrementing it in the PrintPage event.
Port Property
In Visual Basic 6.0, the Port property returns the name of the port through which a document is sent to a printer.
In Visual Basic 2005, the Port property no longer exists; the PrintDialog and PrintPreviewDialog controls automatically
manage port information.
RightToLeft Property
In Visual Basic 6.0, the RightToLeft property determines how the Printer object will format output on a bi-directional
platform, such as Arabic Windows 95 or Hebrew Windows 95.
In Visual Basic 2005, the RightToLeft property is no longer necessary; the direction of printing is controlled by the localization
settings in later versions of Windows.
TrackDefault Property
In Visual Basic 6.0, the TrackDefault property determines whether a Printer object always points to the same printer, or
whether it changes the printer it points to if you change the default printer setting in the operating system's Control Panel.
Changing the TrackDefault property setting while a print job is in progress causes printing to halt immediately.
In Visual Basic 2005, the TrackDefault property no longer exists; the IsDefaultPrinter property of the PrinterSettings class
can be used to determine if a printer is the default, but printing is no longer halted if the default printer changes.
Zoom Property
In Visual Basic 6.0, the Zoom property determines the percentage by which printed output is to be scaled up or down. For
example, consider a letter-sized page printed with Zoom set to 50. This page contains as much data as a page of the size 17 by
22 inches because the printed text and graphics on the letter-sized page are scaled to one-half their original height and width.
In Visual Basic 2005, the Zoom property no longer exists; if a printer has zoom capabilities, settings are automatically exposed
in the Print dialog box. You can also use graphics methods to scale the output prior to assigning it to a PrintDocument
component.
Graphics Properties and Methods
In Visual Basic 6.0, various graphics properties and methods can be used to draw lines, shapes, and text on a Printer object.
In Visual Basic 2005, most objects no longer have their own graphics properties or methods; you can still draw lines, shapes,
and text by creating and using a Graphics object. For more information, see Graphics for Visual Basic 6.0 Users.
Code Changes for the Printer Object
Due to the considerable differences in printing models between Visual Basic 6.0 and Visual Basic 2005, a comparison of the
coding techniques is of little value. For an example of printing in Visual Basic 2005, see Printing Sample.
Printer Object Property and Method Equivalencies
The following tables list Visual Basic 6.0 properties and methods, along with their Visual Basic 2005 equivalents. Those
properties and methods that have the same name and behavior are not listed. All Visual Basic 2005 enumerations map to the
System.Windows.Forms namespace unless otherwise noted.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties
Visual Bas Visual Basic 2005 Equivalent
ic 6.0
ColorMod New implementation. The SupportsColor property of the PrinterSettings class can be used to determine the color c
e apabilities of a printer

Copies Copies property of the PrinterSettings class.

CurrentX New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
CurrentY

DeviceNa PrinterName property of the PrinterSettings class.


me

DrawMod New implementation. For details, see Graphics for Visual Basic 6.0 Users.
e
DrawStyle
DrawWidt
h
DriverNa New implementation. No longer needed; printer drivers are managed by Windows.
me

Duplex Duplex property of the PrinterSettings class.

FillColor New implementation. For details, see Graphics for Visual Basic 6.0 Users.
FillStyle

Font New implementation. For details, see Font Handling for Visual Basic 6.0 Users.
FontBold
FontCoun
t
FontItalic
FontNam
e
Fonts
FontSize
FontStrike
Thru
FontTrans
parent
FontUnde
rline

ForeColor New implementation. For details, see Color Handling for Visual Basic 6.0 Users.

hDC No longer necessary. An instance of a PrintDocument component is the equivalent of a device context.

Height PaperSize property of the PageSettings class.

Orientatio Landscape property of the PageSettings class.


n

Page New implementation. The current page number is not tracked; however, you can easily do this by setting a variable
in the BeginPrint event and incrementing it in the PrintPage event.

PaperBin PaperSources property of the PrinterSettings class.

PaperSize PaperSize property of the PageSettings class.

Port No longer necessary. The PrintPreviewDialog control automatically sets port information.

PrintQuali PrinterResolutions property of the PrinterSettings class.


ty

RightToLe No longer necessary. The direction of printing is controlled by the localization settings in Windows.
ft
ScaleHeig New implementation. For details, see Coordinate System for Visual Basic 6.0 Users.
ht
ScaleLeft
ScaleMod
e
ScaleTop
ScaleWidt
h

TrackDefa No direct equivalent. The IsDefaultPrinter property of the PrinterSettings class can be used to determine if a print
ult er is the default.

TwipsPer No longer necessary. Measurements in Visual Basic 2005 are always in pixels.
PixelX
TwipsPer
PixelY

Width PaperSize property of the PageSettings class.

Zoom No longer necessary. If the printer has zoom capabilities, settings are automatically exposed in the Print dialog bo
x.
Methods
Visual Basic 6.0 Visual Basic 2005 Equivalent
Circle New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

EndDoc Print

KillDoc Cancel

Line New implementation. For more information, see Graphics for Visual Basic 6.0 Users.

NewPage HasMorePages

PaintPicture New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
PSet

Scale New implementation. For details, see Coordinate System for Visual Basic 6.0 Users.
ScaleX
ScaleY

TextHeight New implementation. For more information, see Graphics for Visual Basic 6.0 Users.
TextWidth

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any instances of the Printer object are not upgraded, and
an upgrade error is issued. You need to remove the code for the Printer object and re-implement printing using a
PrintDocument component.
See Also
Tasks
Printing Sample
Reference
PageSettings Class
PrinterSettings Class
Concepts
Printing Changes for Visual Basic 6.0 Users
Graphics for Visual Basic 6.0 Users
Other Resources
Windows Forms Print Support
Visual Basic Concepts

Printers Collection for Visual Basic 6.0 Users


The Visual Basic 6.0 Printers collection has no direct equivalent in Visual Basic 2005.
Conceptual Differences
In Visual Basic 6.0, the Printers collection is used to return information about available printers on a system. Typically, you
iterate through the Printers collection to find a printer with certain attributes and then set that printer to be the default printer
for your application. For example, you might choose a laser printer instead of a dot matrix printer.
In Visual Basic 2005, there is no direct equivalent for the Printers collection, and the model has changed: Rather than choosing
a printer for your application, you should allow your users to make their own choices.
A PrintDialog component can be used to present a list of available printers to the user. Properties for the printer selected by the
user can be retrieved using the PrinterSettings class.
The Printers collection in Visual Basic 6.0 has two properties: Item and Count. The PrintDialog component has no equivalent
properties. The PrinterSettings class has an InstalledPrinters collection with Item and Count; however, this is a String
collection and cannot be used to query the attributes of a printer.
Code Changes for the Printers Collection
The following code example illustrates the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Returning a List of Available Printers
The following example demonstrates populating a ListBox control with a list of available printers.

' Visual Basic 6.0


Dim X As Printer
For Each X In Printers
List1.AddItem X.DeviceName
Next

VB
' Visual Basic 2005
Dim i As Integer
Dim pkInstalledPrinters As String
For i = 0 To System.Drawing.Printing.PrinterSettings. _
InstalledPrinters.Count - 1

pkInstalledPrinters = System.Drawing.Printing.PrinterSettings. _
InstalledPrinters.Item(i)
ListBox1.Items.Add(pkInstalledPrinters)
Next

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any instances of the Printers collection are not upgraded
and an upgrade error is issued. You will need to remove the code for the Printers collection and modify your code so that it
uses a PrintDialog component.
See Also
Reference
PrintDialog Component Overview (Windows Forms)
PrinterSettings Class
Concepts
Printing Changes for Visual Basic 6.0 Users
Other Resources
Windows Forms Print Support
Visual Basic Concepts

ProgressBar Control for Visual Basic 6.0 Users


The ProgressBar control in Visual Basic 6.0 is replaced by the Windows Forms ProgressBar control in Visual Basic 2005. The
names of some properties, methods, events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
Negotiate Property
In Visual Basic 6.0, the Negotiate property of a ProgressBar control can be used to automatically hide the control when a
toolbar is displayed.
The Visual Basic 2005 ProgressBar control does not have a Negotiate property; you can achieve the same effect by setting
the Visible property to false at run time.
Orientation Property
In Visual Basic 6.0, a ProgressBar control can be displayed either horizontally or vertically by setting the Orientation property.
The Visual Basic 2005 ProgressBar control can only be displayed horizontally.
ProgressBar Control Property, Method, and Event Equivalencies
The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents.
Properties, methods, and events with the same names and behaviors are not listed. Where applicable, constants are indented
beneath the property or method. All Visual Basic 2005 enumerations map to the System.Windows.Forms namespace unless
otherwise noted.
Links are provided, as necessary, to topics explaining differences in behavior. Where there is no direct equivalent in Visual Basic
2005, links are provided to topics that present alternatives.
Properties
Visual Basi Visual Basic 2005 Equivalent
c 6.0
Align Dock

Appearanc New implementation. For more information, see


e Appearance and BorderStyle Properties for Visual Basic 6.0 Users.
BorderStyle

Container Parent

DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode

Height Height
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HWnd Handle

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

Left Left
Note Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
Max Maximum

Min Minimum
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePoin Cursor
ter
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

Negotiate New implementation.

OLEDropM New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
ode

Orientation New implementation.

Parent FindForm

Scrolling Style

ToolTipTex ToolTip component.


t
For more information, see ToolTip Support for Visual Basic 6.0 Users.

Top Top
Note Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Value Value
Note
In Visual Basic 6.0, when the Value is changed, the Change event is raised. In Visual Basic 2005, the Change e
vent is not raised; use the ValueChanged event instead.

WhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
HelpID

Width Width, Size


Note Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
Methods
Visual Basic 6.0 Visual Basic 2005 Equivalent
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
ShowWhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.

ZOrder: BringToFront or SendToBack function


0—vbBringToF BringToFront
ront
SendToBack
1—vbSendToB
ack

Events
Visual Basic 6.0 Visual Basic 2005 Equivalent
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag

Upgrade Notes
When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, any ProgressBar controls are upgraded to Windows Forms
ProgressBar controls. Where properties, methods, and events have no equivalent or have differences in behavior, upgrade
notes or warnings are added to your code.
See Also
Tasks
How to: Set the Value Displayed by the Windows Forms ProgressBar Control
Other Resources
ProgressBar Control (Windows Forms)
Visual Basic Concepts

RDO Data Control for Visual Basic 6.0 Users


The Visual Basic 6.0 RDO Data Control has no direct equivalent in Visual Basic 2005.
Conceptual Differences
The Visual Basic 6.0 RDO Data Control is used as a mechanism for binding controls to a database using Remote Data Objects
(RDO). In Visual Basic 2005, the data-binding architecture has changed, and RDO is no longer supported. For more
information, see Data Access for Visual Basic 6.0 Users.
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any instances of the RDO Data Control are not upgraded,
and an upgrade error is issued. You will need to either modify your Visual Basic 6.0 application to use ADO (ActiveX Data
Objects) prior to upgrading, or modify any data-binding code in the upgraded application to use the new data architecture.
See Also
Concepts
Things to Consider Before Upgrading
Data Access for Visual Basic 6.0 Users
Visual Basic Concepts

RichTextBox Control for Visual Basic 6.0 Users


The RichTextBox control in Visual Basic 6.0 is replaced by the Windows Forms RichTextBox control in Visual Basic 2005. The
names of some properties, methods, events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
AutoVerbMenu Property
In Visual Basic 6.0, the AutoVerbMenu property of a RichTextBox control is used to display a context menu with a set of
standard commands.
In Visual Basic 2005, the AutoVerbMenu property no longer exists. To provide a context menu for a RichTextBox control, use a
ContextMenuStrip component. For more information, see AutoVerbMenu property was not upgraded.
DisableNoScroll Property
In Visual Basic 6.0, the DisableNoScroll property determines whether scroll bars appear as unavailable when there are too
few lines of text to scroll vertically or too few characters to scroll horizontally in a RichTextBox control.
In Visual Basic 2005, the DisableNoScroll property no longer exists. You can use the ScrollBars property to force the scroll
bars to appear, but you cannot make them appear as unavailable.
FileName Property and LoadFile Method
In Visual Basic 6.0, either the FileName property or the LoadFile method can be used to load an .rtf or text file into a
RichTextBox control.
In Visual Basic 2005, only the LoadFile method is available; you cannot assign a file at design time.
SelPrint Method
In Visual Basic 6.0, the SelPrint method of a RichTextBox control can be used to print the contents of the control. It takes a
single argument, hDC, which specifies the device context of the device.
In Visual Basic 2005, the SelPrint method no longer exists, and device contexts are no longer used for printing. The
RichTextBox control does not provide a method to print its content. However, you can extend the RichTextBox class to use
the EM_FORMATRANGE message. You can then send the content of a RichTextBox to an output device, such as a printer. For
more information, see SelPrint property was not upgraded.
SelTabCount Property
In Visual Basic 6.0, the SelTabCount property determines the number of tab positions in the selected paragraph(s) or in those
paragraphs following the insertion point.
In Visual Basic 2005, the SelTabCount property no longer exists; it is replaced by the Length parameter of the SelectionTabs
property (SelectionTabs.Length).
Span Method
In Visual Basic 6.0, the Span method of a RichTextBox control can be used to select a range of text based on a set of specified
characters.
In Visual Basic 2005, the Span method no longer exists. You can use the Find method with the characterSet() argument to
find a specified character, and then use the SelectedText property to select the range.
Upto Method
In Visual Basic 6.0, the Upto method of a RichTextBox control can be used to move the insertion point up to, but not
including, the first character that is a member of a set of specified characters.
In Visual Basic 2005, the Upto method no longer exists. You can use the Find method with the characterSet() argument to
find a specified character, and then use the SelectionStart property move the insertion point.
Additional Differences
In addition, there are numerous conceptual differences that apply to all controls, including differences in data binding, font
handling, drag-and-drop features, Help support and more. For more information, see
Windows Forms Concepts for Visual Basic 6.0 Users.
Code Changes for the RichTextBox Control
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Searching in a RichTextBox Control
The following code demonstrates how to search from the insertion point to the end of a sentence in a RichTextBox control
and highlight it. The example requires a RichTextBox control with one or more sentences entered into the Text property, and
it requires a Button control. Since the code is being called from the button's Click event, the HideSelection property of the
RichTextBox should be set to False; otherwise the highlighting will not be visible.

' Visual Basic 6.0


' Make sure that HideSelection is set to False.
Private Sub Command1_Click()
RichTextBox1.Span ".?!", True, True
End Sub

VB
' Visual Basic 2005
' Make sure that HideSelection is set to False.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
Dim endChars() As Char = New Char() {".", "!", "?"}
Dim intEnd As Integer
intEnd = RichTextBox1.Find(endChars, RichTextBox1.SelectionStart)
RichTextBox1.SelectionLength = intEnd - RichTextBox1.SelectionStart
End Sub

RichTextBox Control Property, Method, and Event Equivalencies


The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents. Those
properties, methods, and events that have the same name and behavior are not listed. All Visual Basic 2005 enumerations map
to the System.Windows.Forms namespace unless otherwise noted.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties
Visual Basic 6.0 Visual Basic 2005 Equivalent
Appearance New implementation. For more information, see
Appearance and BorderStyle Properties for Visual Basic 6.0 Users.

AutoVerbMenu New implementation. For more information, see AutoVerbMenu property was not upgraded.

BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.

Container Parent
DataBindings New implementation. For more information, see Data Access for Visual Basic 6.0 Users.
DataChanged
DataField
DataFormat
DataMember
DataSource

DisableNoScro New implementation.


ll

DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode

FileName LoadFile method

Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethro
ugh
FontUnderline

ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.

Height Height, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpContextID New implementation. For more information, see Help Support for Visual Basic 6.0 Users.

HWnd Handle

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

OLEDragMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDropMode

Parent FindForm method

SelAlignment SelectionAlignment

SelBold SelectionFont

SelBullet SelectionBullet

SelCharOffset SelectionCharOffset

SelColor SelectionColor

SelFontName SelectionFont

SelFontSize SelectionFont

SelHangingInd SelectionHangingIndent
ent

SelIndent SelectionIndent

SelItalic SelectionFont

SelLength SelectionLength

SelProtected SelectionProtected

SelRightIndent SelectionRightIndent

SelRTF SelectedRtf

SelStart SelectionStart

SelStrikethru SelectionFont

SelTabCount SelectionTabs.Length

SelTabs SelectionTabs

SelText SelectedText

SelUnderline SelectionFont

TextRTF Rtf
ToolTipText ToolTip component
For more information, see ToolTip Support for Visual Basic 6.0 Users.

Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

WhatsThisHelp New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
ID

Width Width, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Methods
Visual Basic 6. Visual Basic 2005 Equivalent
0
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

GetLineFromC GetLineFromCharIndex
har

LinkExecute No equivalent. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkPoke
LinkRequest
LinkSend

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

SelPrint New implementation. For more information, see SelPrint property was not upgraded.

SetFocus Focus

ShowWhatsTh New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
is

Span No direct equivalent. Use the Find method with a characterSet argument.

Upto No direct equivalent. Use the Find method with a characterSet argument.
ZOrder BringToFront or SendToBack function
Events
Visual Basic 6.0 Visual Basic 2005 Equivalent
Change TextChanged

DblClick DoubleClick

DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

GotFocus Enter

LostFocus Leave

OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag

SelChange SelectionChanged

Validate Validating

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any RichTextBox controls are upgraded to Windows
Forms RichTextBox controls, and properties, methods and events are upgraded to their equivalents. Where there may be
differences in behavior, upgrade comments are inserted into the code.
See Also
Reference
RichTextBox Control Overview (Windows Forms)
Other Resources
RichTextBox Control (Windows Forms)
Visual Basic Concepts

Screen Object for Visual Basic 6.0 Users


The Visual Basic 6.0 Screen object has no direct equivalent in Visual Basic 2005, but most of its functionality can be duplicated
using the .NET Framework.
Conceptual Differences
In Visual Basic 6.0, the Screen object provides access to the active form and control in your application, provides information
about the screen where the application is being displayed, and allows you to control the appearance of the cursor.
In Visual Basic 2005, there is no direct equivalent for the Screen object, but most of its functionality can be duplicated using
the .NET Framework.
Note
Visual Basic 2005 does have a Screen property—My.Computer.Screen. Unlike the Visual Basic 6.0 Screen object, My.Com
puter.Screen only returns read-only information about the screen, such as its device name, its working area, and its color de
pth. For more information, see My.Computer.Screen Property

ActiveControl Property
In Visual Basic 6.0, the ActiveControl property of the Screen object is used to determine the control that has focus. The
ActiveControl property can be used in a global capacity, such as in Screen.ActiveControl, where the active control on the
currently selected form is returned. If a specific form is referenced, for example, Form2.ActiveControl, ActiveControl specifies
the control that will have the focus if the referenced form is active.
In Visual Basic 2005, there is no longer a global ActiveControl property; each instance of a form has its own ActiveControl
property. When referencing a specific form, this property works just as it did in Visual Basic 6.0. To determine the active control
on the currently selected form, you must first iterate through the OpenForms collection and check the ContainsFocus
property to determine which form is active.
ActiveForm Property
In Visual Basic 6.0, the ActiveForm property of the Screen object is used to determine which form currently has the focus. If
an MDI parent form has the focus, ActiveForm returns the MDI child form that last had the focus.
In Visual Basic 2005, there is no longer a global ActiveForm property. To determine the active form, you must iterate through
the OpenForms collection and find the form with its ContainsFocus property set to True.
Visual Basic 2005 MDI parent forms (any forms with IsMDIContainer set to True) have an ActiveMDIChild property that can
be used to return the active child form without using the OpenForms collection.
MousePointer Property
In Visual Basic 6.0, the MousePointer property of the Screen object is used to change the appearance of the cursor; once set it
applies to all forms in the application.
In Visual Basic 2005, there is no longer a global MousePointer property; each form has a Cursor property that can be used to
change the appearance of the cursor for that form only.
TwipsPerPixel Properties
In Visual Basic 6.0, the TwipsPerPixelX and TwipsPerPixelY properties of the Screen object are used to convert screen
measurements from a logical twip (the standard unit of measurement in Visual Basic 6.0) to pixels.
In Visual Basic 2005, pixels are the standard unit of measurement; there is no longer any need for conversion.
Code Changes for the Screen Object
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Determining the Active Control
The following code demonstrates copying the text from the currently selected control on the currently selected form to the
Clipboard.

' Visual Basic 6.0


If TypeOf Screen.ActiveControl Is TextBox Then
Clipboard.SetText Screen.ActiveControl.Text
End If

VB
' Visual Basic 2005
Dim i As Integer
For i = 0 To My.Application.OpenForms.Count - 1
If My.Application.OpenForms.Item(i).ContainsFocus Then
If TypeOf (My.Application.OpenForms.Item(i).ActiveControl) _
Is TextBox Then
My.Computer.Clipboard.SetText(My.Application.OpenForms. _
Item(i).ActiveControl.Text)
End If
End If
Next

Code Changes for Determining the Active Form


The following code demonstrates changing the caption of the currently selected form.

' Visual Basic 6.0


Screen.ActiveForm.Caption = "This is the selected form"

VB
' Visual Basic 2005
Dim i As Integer
For i = 0 To My.Application.OpenForms.Count - 1
If My.Application.OpenForms.Item(i).ContainsFocus Then
My.Application.OpenForms.Item(i).Text = _
"This is the selected form"
End If
Next

Code Changes for Determining the Active Form in an MDI Application


The following code demonstrates changing the caption of the currently selected MDI child form.

' Visual Basic 6.0


Screen.ActiveForm.Caption = "This is the selected child form"

VB
' Visual Basic 2005
Me.ActiveMdiChild.Text = "This is the selected child form"

Screen Object Property Equivalencies


The following table lists Visual Basic 6.0 properties and their Visual Basic 2005 equivalents. Links are provided as necessary to
topics explaining differences in behavior. Where there is no direct equivalent in Visual Basic 2005, links are provided to topics
that present alternatives.
Properties
Visual Basic Visual Basic 2005 Equivalent
6.0
ActiveContr My.Application.OpenForms(0).ActiveControl
ol
ActiveForm My.Application.OpenForms(0).ContainsFocus or
ActiveMdiChild (MDI applications)

FontCount New implementation. The behavior for enumerating fonts is different. For more information, see
Font Handling for Visual Basic 6.0 Users.
Fonts

Height My.Computer.Screen.Bounds.Height

MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePoint System.Windows.Forms.Cursor
er

TwipsPerPix New implementation. In Visual Basic 2005, coordinates are in pixels; twips are not used as a unit of measuremen
elX t.
TwipsPerPix
elY

Width My.Computer.Screen.Bounds.Width

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any Screen object properties are upgraded to their
Visual Basic 2005 equivalent. Where there may be differences in behavior, upgrade comments are inserted into the code.
See Also
Reference
My.Application.OpenForms Property
My.Computer.Screen Property
Concepts
App Object for Visual Basic 6.0 Users
Font Handling for Visual Basic 6.0 Users
Visual Basic Concepts

Shape Control for Visual Basic 6.0 Users


The Shape control in Visual Basic 6.0 has no equivalent in Visual Basic 2005. However, you can use Graphics methods to
achieve the same results.
Conceptual Differences
In Visual Basic 6.0, the Shape control provides an easy way to draw rectangles, circles, and other shapes on a form at design
time. The Shape control is a "lightweight" control - meaning that it does not have a Windows handle, also known as an HWnd.
In Visual Basic 2005, there is no equivalent for the Shape control and lightweight controls are no longer supported. There are,
however, ways to draw shapes on a form both at design time and at run time.
At design time, you can draw a square or rectangular shape on a form by adding a Label control and setting the Text property
to an empty string, the BorderStyle property to FixedSingle, and the BackColor, Width, and Height to the desired color and
dimensions.
At run time, you can draw rectangles, ellipses, and complex shapes in a form's Paint event handler by creating a new object
from the Graphics class and calling its methods.
In Visual Basic 6.0, you can use a Shape control to draw a shape on top of a container control such as a PictureBox or Frame
control by adding a Shape control to the container.
In Visual Basic 2005, you can achieve the same effect by calling the Graphics methods in the Paint event of the container
control.
Code Changes for the Shape Control
The following code examples illustrate the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Drawing Rectangular Shapes
The following code demonstrates drawing a filled rectangle on a form at run time. In the Visual Basic 6.0 example, the Shape
control is used; it assumes that a Line control was added at design time. The Visual Basic 2005 example demonstrates two
different methods - using a Label control, and using Graphics methods.
Note
In Visual Basic 6.0 the default unit of measurement was twips; in Visual Basic 2005 it is pixels.

' Visual Basic 6.0


Private Sub Form_Load()
' Show a solid red rectangle 200 twips from the top left.
Shape1.Top = 200
Shape1.Left = 200
Shape1.FillColor = vbRed
Shape1.FillColor= vbFSSolid
Shape1.BorderColor = vbRed
End Sub

VB
' Visual Basic 2005
' Using a Label control
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
Dim Shape1 As New System.Windows.Forms.Label
' Show a solid red rectangle 14 pixels from the top left.
Shape1.Location = New System.Drawing.Point(14, 14)
Shape1.Size = New System.Drawing.Size(200, 100)
Shape1.BorderStyle = BorderStyle.None
Shape1.BackColor = System.Drawing.Color.Red
Shape1.Text = ""
Controls.Add(Shape1)
End Sub
VB
' Visual Basic 2005
' Using Graphics methods
Private Sub Form2_Paint(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
' Draw a solid blue rectangle below the red rectangle.
e.Graphics.FillRectangle(Brushes.Blue, 14, 120, 200, 100)
End Sub

Code Changes for Drawing a Circle


The following code demonstrates drawing a circle on a form at run time. In the Visual Basic 6.0 example, the Shape control is
used; it assumes that a Shape control was added at design time. The Visual Basic 2005 example uses Graphics methods.
Note
In Visual Basic 6.0 the default unit of measurement was twips; in Visual Basic 2005 it is pixels.

' Visual Basic 6.0


Private Sub Form_Load()
Draw a 1000 twip diameter red circle
Shape1.Top = 0
Shape1.Left = 0
Shape1.Height = 1000
Shape1.Width = 1000
Shape1.Shape = vbShapeCircle
Shape1.BorderColor = vbRed
End Sub

VB
' Visual Basic 2005
Private Sub Form3_Paint(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
' Draw a 70 pixel diameter red circle.
e.Graphics.DrawEllipse(Pens.Red, 0, 0, 70, 70)
End Sub

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any Shape controls are replaced with Windows Forms
Label controls, with the BorderStyle property set to FixedSingle, and the BackColor, Width, and Height properties set to
match the original control.
Note
The Label controls may be added to the form in a different order than the original Shape controls. For overlapping shapes, it
may be necessary to call the BringToFront or SendToBack function to achieve the same visual layout.

Shape controls with the Shape property set to 2-Oval or 3-Circle cannot be upgraded and are replaced with a Label control
as a placeholder. You can replace the Shape control using the graphics functions built into the .NET Framework. For more
information, see Graphics for Visual Basic 6.0 Users.
See Also
Concepts
Graphics for Visual Basic 6.0 Users
Visual Basic Concepts

StatusBar Control for Visual Basic 6.0 Users


The StatusBar control in Visual Basic 6.0 is replaced by the Windows Forms StatusStrip control in Visual Basic 2005. The
names of some properties, methods, events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
The Visual Basic 6.0 StatusBar control contains a collection of Panel objects, each of which can display text and images.
The Visual Basic 2005, StatusStrip control is more similar to the ToolStrip control. In addition to panels (now known as
ToolStripStatusLabel controls), StatusStrip controls can contain progress bars, drop down menus, and split buttons. There is
also a Windows Forms StatusBar control, but it is recommended that you use StatusStrip instead.
SimpleText Property
In Visual Basic 6.0, the SimpleText property of a StatusBar control defines the text that is displayed when the Style property
is set to sbrSimple.
The Visual Basic 2005 StatusStrip control does not support a simple style, and there is no longer a SimpleText property.
Style Property
In Visual Basic 6.0, the Style property determines whether a StatusBar control shows multiple panels (sbrNormal) or just one
large panel (sbrSimple). When set to the simple style, the bevel style is raised with no borders.
In Visual Basic 2005, the Style property no longer exists; to emulate the simple style you can add a single ToolStripStatusLabel
object to the StatusStrip control and set its BorderStyle property.
StatusBar Control Property, Method, and Event Equivalencies
The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents.
Properties, methods, and events with the same names and behaviors are not listed. All Visual Basic 2005 enumerations map to
the System.Windows.Forms namespace unless otherwise noted.
Links are provided as necessary to topics explaining differences in behavior. Where there is no direct equivalent in Visual Basic
2005, links are provided to topics that present alternatives.
Properties
Visual Basi Visual Basic 2005 Equivalent
c 6.0
Align Dock

Container Parent

DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode

Font Font
FontBold Note
FontItalic
Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStriket
hrough
FontUnderl
ine
Height Height
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HWnd Handle

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePoin Cursor
ter
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

OLEDropM New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
ode

Panels ToolStripItemCollection

Parent FindForm

ShowTips ToolTip component.


For more information, see ToolTip Support for Visual Basic 6.0 Users.

SimpleText New implementation.

Style New implementation.

ToolTipTex ToolTip component.


t
For more information, see ToolTip Support for Visual Basic 6.0 Users.

Value Value
Note
In Visual Basic 6.0, when the Value property is changed, the Change event is raised. In Visual Basic 2005, the C
hange event is not raised; use the ValueChanged event instead.

WhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
HelpID
Methods
Visual Basic 6.0 Visual Basic 2005 Equivalent
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.
OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

ShowWhatsThi New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
s

ZOrder: BringToFront or SendToBack function


0 – vbBringToFr BringToFront
ont
SendToBack
1 - vbSendToBa
ck
Events
Visual Basic 6.0 Visual Basic 2005 Equivalent
DblClick DoubleClick

DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag

PanelClick Click

PanelDblClick DoubleClick

Upgrade Notes
When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, any StatusBar controls are upgraded to Windows Forms
StatusBar controls. Where properties, methods, and events have no equivalent or have differences in behavior, upgrade notes
or warnings are added to your code.
See Also
Tasks
StatusStrip Control Sample
Reference
StatusStrip
Visual Basic Concepts

TextBox Control for Visual Basic 6.0 Users


The TextBox control in Visual Basic 6.0 is replaced by the Windows Forms TextBox control in Visual Basic 2005. The names of
some properties, methods, events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
In Visual Basic 6.0, the MaxLength property determines the number of characters that can be entered into a TextBox control.
If you attempt to insert text programmatically, the text will be truncated at the length specified by the MaxLength property.
In Visual Basic 2005, the behavior of the MaxLength property no longer applies to text that is added programmatically. To
duplicate the Visual Basic 6.0 behavior, you need to truncate the string yourself.
In Visual Basic 6.0, the PasswordChar property is of type String; in Visual Basic 2005 it is of type Char.
In addition, there are numerous conceptual differences that apply to all controls, including differences in data binding, font
handling, drag-and-drop operations, Help support and more. For more information, see
Windows Forms Concepts for Visual Basic 6.0 Users.
Code Changes for the TextBox Control
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Searching in a TextBox Control
The following code demonstrates how to search for a string in a TextBox control and highlight it.

' Visual Basic 6.0


Private Sub Form_Load ()
Text1.Text = "Two of the peak human experiences"
Text1.Text = Text1.Text & " are good food and classical music."
End Sub
Private Sub Form_Click ()
Dim Search, Where
' Get search string from user.
Search = InputBox("Enter text to be found:")
' Find string in text.
Where = InStr(Text1.Text, Search)
If Where Then
Text1.SetFocus
Text1.SelStart = Where - 1
Text1.SelLength = Len(Search)
Else
MsgBox "String not found."
End If
End Sub

VB
' Visual Basic 2005
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
TextBox1.Text = "Two of the peak human experiences are "
TextBox1.Text = TextBox1.Text & "good food and classical music."
End Sub
Private Sub Form1_Click(ByVal sender As Object, ByVal e As _
System.EventArgs) Handles Me.Click
Dim Search As String
Dim Where As String
' Get search string from user.
Search = InputBox("Enter text to be found:")
' Find string in text.
Where = InStr(TextBox1.Text, Search)
If Where Then
TextBox1.Focus()
TextBox1.SelectionStart = Where - 1
TextBox1.SelectionLength = Len(Search)
Else
MsgBox("String not found.")
End If
End Sub

Code Changes for Limiting the Number of Characters in a TextBox Control


The following code demonstrates how to use the MaxLength property to specify a maximum number of characters.

' Visual Basic 6.0


Private Sub Form_Load()
Text1.MaxLength = 5
End Sub
Private Sub SetText()
' Only the first five characters will be displayed.
Text1.Text = "Hello World"
End Sub

VB
' Visual Basic 2005
Private Sub Form1_Load2(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
TextBox1.MaxLength = 5
End Sub
Private Sub SetText()
' Truncate the string to equal MaxLength.
TextBox1.Text = Strings.Left("Hello World", TextBox1.MaxLength)
End Sub

TextBox Control Property, Method, and Event Equivalencies


The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents. Those
properties, methods, and events that have the same name and behavior are not listed. All Visual Basic 2005 enumerations map
to the System.Windows.Forms namespace unless otherwise noted.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties
Visual Basic 6.0 Visual Basic 2005 Equivalent
Alignment TextAlign

Appearance New implementation. For more information, see


Appearance and BorderStyle Properties for Visual Basic 6.0 Users.

BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.

Container Parent
DataChanged New implementation. For more information, see Data Access for Visual Basic 6.0 Users.
DataField
DataFormat
DataMember
DataSource

DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode

Font Font
FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethro
ugh
FontUnderline

ForeColor ForeColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Handling for Visual Basic 6.0 Users.

Height Height, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpContextID New implementation. For more information, see Help Support for Visual Basic 6.0 Users.

HWnd Handle

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

LinkItem New implementation. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkMode
LinkTimeOut
LinkTopic
Locked ReadOnly

MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

OLEDragMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDropMode

Parent FindForm method.

SelLength SelectionLength

SelStart SelectionStart

SelText SelectedText

ToolTipText ToolTip component.


For more information, see ToolTip Support for Visual Basic 6.0 Users.

Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

WhatsThisHelp New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
ID

Width Width, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Methods
Visual Basic 6 Visual Basic 2005 Equivalent
.0
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

LinkExecute New implementation. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkPoke
LinkRequest
LinkSend
Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

SetFocus Focus

ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his

ZOrder BringToFront or SendToBack function


Events
Visual Basic 6.0 Visual Basic 2005 Equivalent
Change TextChanged

DblClick DoubleClick

DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

GotFocus Enter

LinkClose New implementation. For more information, see Dynamic Data Exchange for Visual Basic 6.0 Users.
LinkError
LinkNotify
LinkOpen

LostFocus Leave

OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag

Validate Validating

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any TextBox controls are upgraded to Windows Forms
TextBox controls, and properties, methods and events are upgraded to their equivalents. Where there may be differences in
behavior, upgrade comments are inserted into the code.
See Also
Reference
TextBox Control Overview (Windows Forms)
Visual Basic Concepts

Timer Control for Visual Basic 6.0 Users


The Timer control in Visual Basic 6.0 is replaced by the Timer component in Visual Basic 2005. The names of some properties
and events are different, and in some cases there are differences in behavior.
Conceptual Differences
The Visual Basic 6.0 Timer control is an actual control that is sited on a form at design time; however it is not visible at run
time.
The Visual Basic 2005 Timer is a component that is added to the tray at design time; as a component it has no Parent
property.
Note
In addition to the Timer component, the .NET Framework also has two timer classes: Timer and Timer.

Interval Property
In Visual Basic 6.0, you can disable a Timer control by setting the Interval property to 0.
In Visual Basic 2005, the lower range for the Interval property is 1. If you set the interval to 0, it throws a run-time exception.
The Visual Basic 2005 Timer component uses the Enabled property to allow you to disable or enable it.
Code Changes for the Timer Control
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Starting and Stopping a Timer Control
The following code demonstrates how to enable and disable a Timer control at run time.

' Visual Basic 6.0


Public Function TimerOn(Interval As Integer)
If Interval > 0 Then
' Start the timer.
Timer1.Interval = Interval
Else
' Stop the timer.
Timer1.Interval = 0
End If
End Function

VB
' Visual Basic 2005
Public Sub TimerOn(ByRef Interval As Short)
If Interval > 0 Then
' Start the timer.
Timer1.Enabled = True
Else
' Stop the timer
Timer1.Enabled = False
End If
End Sub

Timer Control Property and Event Equivalencies


The following table lists Visual Basic 6.0 properties and events, along with their Visual Basic 2005 equivalents. Those properties
and events that have the same name and behavior are not listed.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties and Events
Visual Basic 6. Visual Basic 2005 Equivalent
0
Index property New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users

Interval prope Interval


rty
Note
The behavior of the Interval property has changed. For more information, see
Timer Interval property behavior has changed.

Parent propert New implementation. The Timer is a component and cannot have a parent.
y

Timer event Tick

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any Timer controls are upgraded to Windows Forms
Timer components. If code is found that sets the Interval property to 0, an upgrade warning is added to your code.
See Also
Reference
Timer Component Overview (Windows Forms)
Visual Basic Concepts

ToolBar Control for Visual Basic 6.0 Users


The ToolBar control in Visual Basic 6.0 is replaced by the ToolStrip control in Visual Basic 2005. The names of some properties,
methods, events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
The Visual Basic 6.0 ToolBar control is an ActiveX control that is used to create simple toolbars with buttons and combo boxes.
You can use the Visual Basic 2005 ToolStrip control to create customized toolbars and user-interface elements or to create
toolbars and user-interface elements that have the appearance and behavior of Microsoft Windows XP, Microsoft Office, or
Microsoft Internet Explorer. These user-interface elements support overflow and run-time item reordering. ToolStrip controls
offer a rich design-time experience that includes in-place activation and editing, custom layout, and rafting, which is the ability
of toolbars to share horizontal or vertical space.
Note
Visual Basic 2005 also has a ToolBar control that is carried over from earlier versions; however the ToolStrip control is the r
ecommended choice because of its advanced capabilities.

AllowCustomize Property, Customize Method, Change Event


In Visual Basic 6.0, the AllowCustomize property of a ToolBar control can be used to display a standard Customize Toolbar
dialog box, which allows the user to hide, display, or rearrange toolbar buttons. The Customize method can be used to invoke
the dialog box programmatically. The Change event is raised when the user closes the Customize Toolbox dialog box.
The Visual Basic 2005 ToolStrip control has no equivalent property or method; you must create your own dialog box and
display it using the ShowDialog method. For more information, see ToolStrip Customizing Sample.
DisabledImageList, HotImageList, ImageList Properties
In Visual Basic 6.0, the DisabledImageList, HotImageList and ImageList properties of a ToolBar control are used to
associate the control with ImageList controls. Separate images can be associated for different states: normal (ImageList),
disabled (DisabledImageList), and selected (HotImageList).
The Visual Basic 2005 ToolStrip control has no equivalent properties. The ToolStripButton object has a single Image
property; setting the Enabled property of the ToolStripButton to False automatically renders the image disabled. To emulate
the Visual Basic 6.0 "selected" state behavior, you can either assign a different image or change the BackColor property of the
ToolStripButton at run time.
Style Property
In Visual Basic 6.0, the Style property of a ToolBar control determines where images are displayed in relationship to text;
setting it to tbrTransparent also enables hot tracking.
The Visual Basic 2005 ToolStrip control has no equivalent property. The relationship between image and text is controlled by
setting the TextImageAlign property of the ToolStripItem; unlike Visual Basic 6.0, each item can have a different alignment.
Hot tracking is not directly supported, but you can emulate the behavior by changing the Image property in the MouseEnter
and MouseLeave events.
Wrappable Property
In Visual Basic 6.0, the Wrappable property of a ToolBar control determines whether the toolbar buttons will automatically
wrap when the window is resized.
The Visual Basic 2005 ToolStrip control has no direct equivalent; it supports the use of a dropdown overflow menu instead.
When you add ToolStripItem elements that require more space than is allotted to the ToolStrip, given the form's current
size, a ToolStripOverflowButton automatically appears on the ToolStrip. The ToolStripOverflowButton appears, and
overflow-enabled items are moved into the drop-down overflow menu. You can disable this behavior by setting the
CanOverflow property to False.
In addition, you can specify the overflow behavior for an individual ToolStripItem element by setting its Overflow property.
For more information, see How to: Manage ToolStrip Overflow in Windows Forms.
RestoreToolBar, SaveToolBar Methods
In Visual Basic 6.0, the RestoreToolBar and SaveToolBar methods are used to manage ToolBar configuration. SaveToolBar
saves the configuration to an initialization (.ini) file; RestoreToolBar returns it to its original state after being customized.
The Visual Basic 2005 ToolStrip control has no equivalent methods. You can use the Settings Designer to manage
configurations for the ToolStrip control. For more information, see Managing Application Settings.
ToolBar Control Property and Method Equivalencies
The following tables list Visual Basic 6.0 properties and methods, along with their Visual Basic 2005 equivalents. Those
properties and methods that have the same name and behavior are not listed. All Visual Basic 2005 enumerations map to the
System.Windows.Forms namespace unless otherwise noted.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties
Visual Basic Visual Basic 2005 Equivalent
6.0
Align Dock

AllowCusto New implementation. You must provide your own dialog box.
mize

Appearance New implementation. For more information, see


Appearance and BorderStyle Properties for Visual Basic 6.0 Users.
BorderStyle

ButtonHeig Height, Size (ToolStripButton)


ht

Buttons ToolStripItemCollection

ButtonWidt Height, Size (ToolStripButton)


h

Container Parent

Controls ToolStripItemCollection

DataBindin New implementation. For more information, see Data Access for Visual Basic 6.0 Users.
gs

DisabledIm New implementation. Use the Image property of the ToolStripButton object.
ageList

DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode

Height Height
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpContex New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
tID
HelpFile
HotImageLi New implementation. Use the Image property of the ToolStripButton object.
st

HWnd Handle
ImageList New implementation. Use the Image property of the ToolStripButton object.

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

Left Left
Note Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users

MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePoint Cursor
er
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

OLEDropMo New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
de

Parent FindForm

ShowTips ShowItemToolTips

Style New implementation. Use the TextImageAlign property of the ToolStripItem.

TextAlignm TextAlign (ToolStripItem)


ent

ToolTipText ToolTip component


For more information, see ToolTip Support for Visual Basic 6.0 Users.

Value Value
Note
In Visual Basic 6.0, when the Value is changed, the Change event is raised. In Visual Basic 2005, the Change e
vent is not raised; use the ValueChanged event instead.

WhatsThisH New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
elpID

Width Width, Size


Note Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Wrappable CanOverflow, Overflow


Methods
Visual Basic 6 Visual Basic 2005 Equivalent
.0
Customize New implementation. You must provide your own dialog box.
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

RestoreToolb New implementation. Use the Application Settings feature.


ar
SaveToolbar

ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his

ZOrder: BringToFront or SendToBack function.


Events
Visual Basic 6.0 Visual Basic 2005 Equivalent
Change New implementation. The Customize ToolBox dialog box no longer exists.

DblClick DoubleClick

DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag

Upgrade Notes
When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, any ToolBar controls are upgraded to Windows Forms
ToolStrip controls. Where properties, methods, and events have no equivalent or have differences in behavior, upgrade notes
or warnings will be added to your code.
See Also
Reference
ToolStrip Control Overview (Windows Forms)
Other Resources
ToolStrip Control (Windows Forms)
Visual Basic Concepts

TreeView Control for Visual Basic 6.0 Users


The TreeView control in Visual Basic 6.0 is replaced by the TreeView control in Visual Basic 2005. The names of some
properties, methods, events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
SingleSel Property
In Visual Basic 6.0, the SingleSel property of a TreeView control determines whether a node expands to show its child nodes
when selected. Setting this property to True causes the node to expand when selected and causes the previously selected node
to contract.
In Visual Basic 2005, the SingleSel property no longer exists. By default, a node does not expand when clicked (the default is
equivalent to setting the SingleSel property to False in Visual Basic 6.0). You can use the AfterSelect event to determine when
a node has been selected, and then use the Expand or Collapse method to control the expansion behavior.
Image and SelectedImage Properties
In Visual Basic 6.0, it is possible to assign a SelectedImage property to a TreeView control node without assigning an Image
property.
In Visual Basic 2005, the TreeNode object of a TreeView control cannot have a SelectedImage property unless it also has an
Image property. If you need to emulate Visual Basic 6.0 behavior, you can assign an empty image to the Image property.
Other Differences
In addition, there are numerous conceptual differences that apply to all controls, including differences in data binding, font
handling, drag-and-drop operations, Help support, and more. For more information, see
Windows Forms Concepts for Visual Basic 6.0 Users.
Code Changes for the TreeView Control
The following examples illustrate differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Expanding a Selected Node in a TreeView Control
The following code demonstrates how to expand a TreeView node when a user selects it.

' Visual Basic 6.0


TreeView1.SingleSel = True

VB
' Visual Basic 2005
Private Sub TreeView1_AfterSelect(ByVal sender As Object, ByVal e As _
System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect

TreeView1.SelectedNode.Expand()
End Sub

Code Changes for Adding Nodes in a TreeView Control


The following code demonstrates how to add a new node as a child of the currently selected node.

' Visual Basic 6.0


Dim nodX As Node
Set nodX = TreeView1.Nodes.Add(Node, tvwChild, , "New Node")

VB
' Visual Basic 2005
Dim nodX As TreeNode = New TreeNode("New Node")
TreeView1.SelectedNode.Nodes.Add(nodX)
TreeView Control Property, Method, and Event Equivalencies
The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents. Those
properties, methods, and events that have the same name and behavior are not listed. All Visual Basic 2005 enumerations map
to the System.Windows.Forms namespace unless otherwise noted.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties
Visual Basic 6. Visual Basic 2005 Equivalent
0
Appearance New implementation. For more information, see
Appearance and BorderStyle Properties for Visual Basic 6.0 Users.

BackColor BackColor
Note
Colors are handled differently in Visual Basic 2005. For more information, see
Color Behavior for Visual Basic 6.0 Users.

Container Parent

DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode

Font Font Font


FontBold Note
FontItalic Fonts are handled differently in Visual Basic 2005. For more information, see
FontName Font Object for Visual Basic 6.0 Users.
FontSize
FontStrikethro
ugh
FontUnderline

Height Height, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpContextI New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
D

HWnd Handle

Indentation Indent

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.
Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

LineStyle ShowRootLines

MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePointer Cursor
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

OLEDragMode New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDropMode

Parent FindForm method

Scroll Scrollable

SingleSel New implementation. Use the NodeMouseClick event.

Style New implementation property. 0 or Standard maps to the CheckedListBox control, 1 or Checkbox maps to t
he CheckedListBox control.

ToolTipText ToolTip component


For more information, see ToolTip Support for Visual Basic 6.0 Users.

Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

WhatsThisHel New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
pID

Width Width, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Methods
Name Visual Basic 2005 Equivalent
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

GetVisibleCo VisibleCount property.


unt
HitTest GetNodeAt, GetNodeAt

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

SetFocus Focus

ShowWhatsT New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
his

StartLabelEdi BeginEdit
t

ZOrder BringToFront or SendToBack method


Events
Visual Basic 6.0 Visual Basic 2005 Equivalent
Collapse BeforeCollapse

DblClick DoubleClick

DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

Expand AfterExpand

GotFocus Enter

LostFocus Leave

NodeCheck AfterCheck

NodeClick NodeMouseClick

OLECompleteDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
OLEDragDrop
OLEDragOver
OLEGiveFeedback
OLESetData
OLEStartDrag

Validate Validating

Upgrade Notes
When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, any TreeView controls are upgraded to Windows Forms
TreeView controls. Where properties, methods, and events have no equivalent or have differences in behavior, upgrade notes
or warnings are added to your code.
See Also
Tasks
How to: Add Custom Information to a TreeView or ListView Control (Windows Forms)
How to: Iterate Through All Nodes of a Windows Forms TreeView Control
Other Resources
TreeView Control (Windows Forms)
Visual Basic Reference

VBControlExtender Object for Visual Basic 6.0 Users


The Visual Basic 6.0 VBControlExtender object has no equivalent in Visual Basic 2005, and it is no longer necessary to use a
control extender to host an ActiveX control.
Conceptual Differences
In Visual Basic 6.0, the VBControlExtender object is used to provide access to properties of a host form to an ActiveX control.
The VBControlExtender object is primarily used when dynamically adding a control to the Controls collection using the Add
method. The VBControlExtender object is particularly useful for this purpose because it provides a generic set of properties,
events, and methods to the developer.
In Visual Basic 2005, ActiveX controls can be hosted directly on a Windows form; they no longer require an extender object to
access the properties of the host form. When an ActiveX control is added to a project, a COM interop wrapper is created,
allowing you to use the ActiveX control as you would any other control.
Upgrade Notes
When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, any instances of the VBControlExtender object are ignored.
A COM interop wrapper is created for each ActiveX control; property, method, and events are mapped to their equivalents.
Where there are no equivalents, upgrade warnings are added to the code.
See Also
Tasks
How to: Add ActiveX Controls to Windows Forms
Reference
System.Windows.Forms Namespace
Concepts
Considerations When Hosting an ActiveX Control on a Windows Form
Visual Basic Concepts

VScrollBar Control for Visual Basic 6.0 Users


The VScrollBar control in Visual Basic 6.0 was replaced by the Windows Forms VScrollBar control in Visual Basic 2005. The
names of some properties, methods, events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
Change Event
In Visual Basic 6.0, when the Value property of a VScrollBar control is changed, the Change event is raised.
In Visual Basic 2005, the Change event is not raised; instead, the ValueChanged event is raised.
Value Property
In Visual Basic 6.0, when the Scroll or Change event of a VScrollBar control is raised, the current scroll value is assigned to
the Value property.
When the Scroll event is raised in Visual Basic 2005, the control's Value property has not yet been updated. If you need to
emulate Visual Basic 6.0 behavior, you can create a helper function to retrieve the value. For more information, see
Code was changed from an event to a procedure.
LargeChange Property
In Visual Basic 6.0, the LargeChange property determines the amount of change to the Value property of a scroll bar control
when the user clicks the area between the scroll box and scroll arrow.
In Visual Basic 2005, the default value of the LargeChange property is 10; in Visual Basic 6.0 it is 1.
Max Property
In Visual Basic 6.0, the Max property determines the maximum Value property setting in a scroll bar control.
In Visual Basic 2005, the Max property is replaced by the Maximum property; the default value is 100, in Visual Basic 6.0 it was
32767.
Min Property
In Visual Basic 6.0, the Min property determines the minimum Value property setting in a scroll bar control. The Min property
can be set to a value greater than that of the Max property.
In Visual Basic 2005, the Min property is replaced by the Minimum property, the value of which must always be less than that
of the Maximum property.
Other Differences
In addition, there are numerous conceptual differences that apply to all controls, including differences in data binding, font
handling, drag and drop, Help support, and more. For more information, see
Windows Forms Concepts for Visual Basic 6.0 Users.
VScrollBar Control Property, Method, and Event Equivalencies
The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents.
Properties, methods, and events with the same names and behaviors are not listed. Where applicable, constants are indented
beneath the property or method. All Visual Basic 2005 enumerations map to the System.Windows.Forms namespace unless
otherwise noted.
Links are provided as necessary to topics explaining differences in behavior. Where there is no direct equivalent in Visual Basic
2005, links are provided to topics that present alternatives.
Properties
Visual Basi Visual Basic 2005 Equivalent
c 6.0
Container Parent

DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode
Height Height
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpConte New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
xtID

HWnd Handle

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

LargeChan LargeChange
ge
Note
The default value in Visual Basic 6.0 is 1; in Visual Basic 2005 the default value is 10.

Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Max Maximum
Note
The default value in Visual Basic 6.0 is 32767; in Visual Basic 2005, the default value is 100.

Min Minimum
Note
In Visual Basic 6.0, Min can be set to a value greater than Max; in Visual Basic 2005, this is not allowed.

MouseIcon New implementation. For more information, see Cannot set a custom MousePointer.

MousePoin Cursor
ter
For a list of constants, see MousePointer for Visual Basic 6.0 Users.

Parent FindForm

RightToLef RightToLeft
t:
Yes enumeration value
True
No enumeration value
False
Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Value Value
Note
In Visual Basic 6.0, when the Value is changed, the Change event is raised. In Visual Basic 2005, the Change e
vent is not raised; use the ValueChanged event instead.

WhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
HelpID

Width Width, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Methods
Visual Basic 6.0 Visual Basic 2005 Equivalent
Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

SetFocus Focus

ShowWhatsThis New implementation. For more information, see Help Support for Visual Basic 6.0 Users.

ZOrder: BringToFront or SendToBack function


0 – vbBringToFr BringToFront
ont
SendToBack
1 - vbSendToBa
ck
Events
Visual Basi Visual Basic 2005 Equivalent
c 6.0
Change ValueChanged
Note
The behavior of the Change and Scroll events have changed in Visual Basic 2005. For more information, see
Code was changed from an event to a procedure.
DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

GotFocus Enter

LostFocus Leave

Scroll Scroll
Note
The behavior of the Change and Scroll events have changed in Visual Basic 2005. For more information, see
Code was changed from an event to a procedure.

Validate Validating

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any code in the Scroll event handler for the HScrollBar or
VScrollBar control is changed to a procedure due to a difference in the sequence of events. For more information, see
Code was changed from an event to a procedure.
See Also
Reference
HScrollBar and VScrollBar Controls Overview (Windows Forms)
Visual Basic Concepts

WebBrowser Control for Visual Basic 6.0 Users


The WebBrowser control in Visual Basic 6.0 is replaced by the Windows Forms WebBrowser control in Visual Basic 2005. The
names of some properties, methods, events, and constants are different, and in some cases there are differences in behavior.
Conceptual Differences
The Visual Basic 6.0 WebBrowser control, also known as the Microsoft Internet Controls or Shdocvw.dll, is an ActiveX control
that allows you to host Internet Explorer inside your application.
The Visual Basic 2005 WebBrowser control provides a managed wrapper for the WebBrowser ActiveX control. This lets you
display Web pages in your Windows Forms client applications. You can use the WebBrowser control to duplicate Internet
Explorer Web browsing functionality in your application, or you can disable default Internet Explorer functionality and use the
control as a simple HTML document viewer. You can also use the control to add DHTML-based user-interface elements to your
form and hide the fact that they are hosted in the WebBrowser control. This approach lets you seamlessly combine Web
controls with Windows Forms controls in a single application.
Internet Explorer Object
The Visual Basic 6.0 Microsoft Internet Controls consist of two components: the WebBrowser control and an Internet
Explorer object that allows you to control an instance of Internet Explorer through OLE Automation.
There is no equivalent for the Internet Explorer object in Visual Basic 2005, and its related properties, methods, and events no
longer exist. OLE Automation is no longer supported; you can control an external instance of Internet Explorer using a scripting
language such as VBScript.
Document Property
In Visual Basic 6.0, the Document property returns a string containing the name of an HTML document; in Visual Basic 2005, it
returns the HTML document itself.
Refresh, Refresh2 Methods
The Visual Basic 6.0 Refresh2 method takes a parameter specifying the refresh level; the Visual Basic 2005 Refresh method
has an optional parameter that can be used to specify the refresh level.
WebBrowser Control Property, Method, and Event Equivalencies
The following tables list Visual Basic 6.0 properties, methods, and events, along with their Visual Basic 2005 equivalents. Those
properties, methods, and events that have the same name and behavior are not listed. All Visual Basic 2005 enumerations map
to the System.Windows.Forms namespace unless otherwise noted.
This table provides links to topics explaining behavior differences. Where there is no direct equivalent in Visual Basic 2005,
links are provided to topics that present alternatives.
Properties
Visual Basic 6. Visual Basic 2005 Equivalent
0
AddressBar New implementation. This was a property of the Internet Explorer object.

Application New implementation. This was a property of the Internet Explorer object.

Busy IsBusy

Container Parent

Document Document
Note
In Visual Basic 6.0, the Document property returns a string containing the name of an HTML document; in
Visual Basic 2005, it returns the HTML document itself.
DragIcon New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragMode

FullName New implementation. This was a property of the Internet Explorer object.

Height Height, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

HelpContextI New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
D

HWnd Handle

Index New implementation. For more information, see Control Arrays for Visual Basic 6.0 Users.

Left Left
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

LocationName New implementation. This was a property of the Internet Explorer object.
LocationURL

MenuBar New implementation. This was a property of the Internet Explorer object.

Offline IsOffline

Parent FindForm method

Path New implementation. This was a property of the Internet Explorer object.

RegisterAsBro New implementation. This was a property of the Internet Explorer object.
wser

RegisterAsDro AllowWebBrowserDrop
pTarget

Resizable New implementation. This was a property of the Internet Explorer object.

Silent ScriptErrorsSuppressed

StatusBar New implementation. This was a property of the Internet Explorer object.
StatusText

TheaterMode New implementation. This was a property of the Internet Explorer object.

ToolBar New implementation. This was a property of the Internet Explorer object.
ToolTipText ToolTip component.
For more information, see ToolTip Support for Visual Basic 6.0 Users.

Top Top
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

TopLevelCont New implementation. This was a property of the Internet Explorer object.
ainer

Type DocumentType

WhatsThisHel New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
pID

Width Width, Size


Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Methods
Visual Ba Visual Basic 2005 Equivalent
sic 6.0
ClientTo PointToClient
Window

Drag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

ExecWB New implementation. This was a method of the Internet Explorer object.

GetPrope New implementation. This was a method of the Internet Explorer object.
rty

Move SetBounds
Note
Coordinates are handled differently in Visual Basic 2005. For more information, see
Coordinate System for Visual Basic 6.0 Users.

Navigate New implementation. This was a method of the Internet Explorer object.
2

OLEDrag New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.

PutPrope New implementation. This was a method of the Internet Explorer object.
rty

QuerySta New implementation. This was a method of the Internet Explorer object.
tusWB
Quit New implementation. This was a method of the Internet Explorer object.

Refresh Refresh
Refresh2 Note
The Visual Basic 6.0 Refresh2 method took a parameter specifying the refresh level; the Visual Basic 2005 Refres
h method has an optional parameter that can be used to specify the refresh level.

SetFocus Focus

ShowBro New implementation. This was a method of the Internet Explorer object.
wserBar

ShowWh New implementation. For more information, see Help Support for Visual Basic 6.0 Users.
atsThis

ZOrder BringToFront or SendToBack function


Events
Visual Basic 6.0 Visual Basic 2005 Equivalent
BeforeNavigate Navigating
BeforeNavigate2

ClientToHostWindow New implementation. This was an event of the Internet Explorer object.

CommandStateChanged CanGoBackChanged
CanGoForwardChanged

DblClick DoubleClick

DocumentComplete DocumentCompleted
DownloadBegin
DownloadComplete

DragDrop New implementation. For more information, see Drag and Drop for Visual Basic 6.0 Users.
DragOver

GotFocus Enter

LostFocus Leave

NavigateComplete Navigated
NavigateComplete2

NavigateError New implementation. This was an event of the Internet Explorer object.

NewWindow NewWindow
NewWindow2
NewWindow3
OnFullScreen New implementation. This was an event of the Internet Explorer object.
OnMenuBar
OnQuit
OnStatusBar
OnTheaterMode
OnToolBar
OnVisible

PrintTemplateInstantiation New implementation. This was an event of the Internet Explorer object.
PrintTemplateTearDown
PrivacyImpactedStateChange

ProgressChange ProgressChanged

PropertyChange New implementation. This was an event of the Internet Explorer object.

SetSecureLockIcon EncryptionLevelChanged

StatusTextChange StatusTextChanged

TitleChange DocumentTitleChanged

UpdatePageStatus New implementation. This was an event of the Internet Explorer object.

Validate Validating

WindowClosing New implementation. This was an event of the Internet Explorer object.
WindowSetHeight
WindowSetLeft
WindowSetResizable
WindowSetTop
WindowSetWidth

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any WebBrowser controls are upgraded to Windows
Forms WebBrowser controls, and properties, methods and events are upgraded to their equivalents. Where there may be
differences in behavior, upgrade comments are inserted into the code.
See Also
Tasks
How to: Use the WebBrowser Control in the .NET Compact Framework
Reference
WebBrowser Control Overview
Other Resources
WebBrowser Control (Windows Forms)
Visual Basic Concepts

Control Property, Method, and Event Changes for Visual Basic


6.0 Users
Many of the properties, methods, and events for Visual Basic 6.0 controls and objects are replaced by Visual Basic 2005
properties, methods, and events that have different behaviors.
The following topics describe the changes for selected properties, methods, and events.
In This Section
Appearance and BorderStyle Properties for Visual Basic 6.0 Users
Describes changes to the Appearance and BorderStyle properties of various controls.
ComboBox Control Change Event for Visual Basic 6.0 Users
Describes changes in the behavior of the Change event of the ComboBox control.
Coordinate System for Visual Basic 6.0 Users
Describes changes to the Height and Width properties, the Move method, and ScaleMode settings.
Form Events for Visual Basic 6.0 Users
Describes changes to various form-level events.
MaxLength Property for Visual Basic 6.0 Users
Describes changes to the MaxLength property of the TextBox control.
MousePointer for Visual Basic 6.0 Users
Describes changes to the MousePointer property and constants.
Moveable Property for Visual Basic 6.0 Users
Describes changes to the Moveable property of a form.
Style Property for Visual Basic 6.0 Users
Describes changes to the Style, Picture, Disabled Picture, and DownPicture properties of various controls.
TopIndex Property and Scroll Event for Visual Basic 6.0 Users
Describes changes to the TopIndex property and the Scroll event of ComboBox and ListBox controls.
Related Sections
Windows Forms Concepts for Visual Basic 6.0 Users
Describes general conceptual differences when working with forms and controls.
Windows Forms Controls for Visual Basic 6.0 Users
Compares all Visual Basic 6.0 controls and objects with their Windows Forms equivalents.
Constant Equivalents for Visual Basic 6.0 Users
Lists all Visual Basic 6.0 constants and their Visual Basic 2005 equivalents.
Language Changes for Visual Basic 6.0 Users
Describes differences in the Visual Basic language between Visual Basic 6.0 and Visual Basic 2005.
Help for Visual Basic 6.0 Users
Portal for all topics comparing Visual Basic 6.0 and Visual Basic 2005.
Visual Basic Concepts

Appearance and BorderStyle Properties for Visual Basic 6.0


Users
The Appearance and the BorderStyle properties in Visual Basic 6.0 are used to control the appearance of controls.
Conceptual Differences
The Visual Basic 6.0 Frame, Image, Label, PictureBox, and TextBox controls support both the Appearance and BorderStyle
properties. Setting a combination of the two properties makes the control appear with no border, with a single line for a
border, or with a three-dimensional border.
In Visual Basic 2005, the Appearance property no longer exists for these controls. Its functionality has been combined with the
BorderStyle property to set the appearance in a single step.

The Visual Basic 6.0 CommandButton, ListBox, and ComboBox controls support only the Appearance property.
The Visual Basic 2005 Button control has a FlatStyle property that is equivalent to the Appearance property. The ListBox
control can be made to appear flat by setting the BorderStyle property to FixedSingle. The ComboBox control never actually
supported a flat appearance in Visual Basic 6.0, so there is no equivalent.
Note
Visual Basic 6.0 forms also have a BorderStyle property that supports a different set of values. This is replaced by the
FormBorderStyle property in Visual Basic 2005.

Code Changes for the Appearance and BorderStyle Properties


The following code example illustrates the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code changes for changing the appearance of controls
The following example demonstrates setting properties to change the appearance of controls at run time.

' Visual Basic 6.0


' Give a TextBox a flat look with no border.
Text1.Appearance = 0
Text1.BorderStyle = 0
' Give a TextBox a three-dimensional appearance.
Text1.Appearance = 1
Text1.BorderStyle = 1
' Give a CommandButton a flat look
Command1.Appearance = 0
' Give a ListBox a flat look
List1.Appearance = 0

VB
' Visual Basic 2005
' Give a TextBox a flat look with a single border.
TextBox1.BorderStyle = BorderStyle.None
' Give a TextBox a three-dimensional appearance.
TextBox2.BorderStyle = BorderStyle.Fixed3D
' Give a Button a flat look
Button1.FlatStyle = FlatStyle.Flat
' Give a ListBox a flat look
ListBox1.BorderStyle = BorderStyle.FixedSingle

Appearance and BorderStyle Equivalencies


The following table lists Visual Basic 6.0 Appearance and BorderStyle constants and their Visual Basic 2005 enumeration
equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
BorderStyle = 0 – None None

Appearance = 0 – Flat FixedSingle


BorderStyle = 1 – Fixed Single

Appearance = 1 – 3D Fixed3D
BorderStyle = 1 – Fixed Single

Upgrade Notes
When upgrading a Visual Basic 6.0 application using the Upgrade wizard, Frame controls can be upgraded to either Visual
Basic 2005 GroupBox or Panel controls. Appearance and BorderStyle mappings apply only to those Frame controls that are
upgraded to Panel controls; there is no BorderStyle property for GroupBox controls. For more information, see
Frame Control for Visual Basic 6.0 Users.
When upgrading ComboBox, CommandButton, and ListBox controls, the Appearance property is not mapped. If the
Appearance property is set in code, an upgrade warning will be added.
See Also
Concepts
ComboBox Control for Visual Basic 6.0 Users
CommandButton Control for Visual Basic 6.0 Users
Frame Control for Visual Basic 6.0 Users
Label Control for Visual Basic 6.0 Users
PictureBox Control for Visual Basic 6.0 Users
TextBox Control for Visual Basic 6.0 Users
User Controls for Visual Basic 6.0 Users
Visual Basic Concepts

ComboBox Control Change Event for Visual Basic 6.0 Users


In Visual Basic 6.0, the Change event of the ComboBox control is raised when the text in the text-entry portion of the control
is modified; it is not raised when an item is selected from the list portion of the control. Programmatically changing the text of
an item in the list does not raise the Change event.
When a project is migrated to Visual Basic 2005, the Change event of the ComboBox control is mapped to the TextChanged
event of the Visual Basic 2005 ComboBox control. The behavior of the TextChanged event differs from that of the Change
event; this difference may cause unintended results in your code.
The Visual Basic 2005 TextChanged event is raised every time the text changes for any reason, such as:
When the text-entry portion is modified.
When an item is selected from the list.
When a list item is modified programmatically.
When the Add method is called.
The following example illustrates the behavior differences.

' Visual Basic 6.0


Private Sub Form_Load()
' Does not raise the Change event.
Combo1.AddItem "A"
End Sub
Private Sub Form_Click()
' Does not raise the Change event.
Combo1.List(0) = "B"
End If

VB
' Visual Basic 2005
Private Sub Form1_Load()
' Raises the TextChanged event.
ComboBox1.Items.Add("A")
End Sub
Private Sub Form1_Click(ByVal sender As System.Object, ByVal _
e As System.EventArgs)
' Uses the SetItemString method from the VB6 compatibility library;
' there is no equivalent method in Visual Basic 2005.
' Raises the TextChanged event.
Microsoft.VisualBasic.Compatibility.VB6. _
SetItemString(ComboBox1, ComboBox1.Items.Count, "B")
End Sub

What to do next
Set a breakpoint in the TextChanged event procedure and then run your code to determine where it is raised. Modify
your code as necessary.
See Also
Concepts
ComboBox Control for Visual Basic 6.0 Users
Visual Basic Concepts

Coordinate System for Visual Basic 6.0 Users


The coordinates for forms and controls are expressed differently in Visual Basic 2005 than in Visual Basic 6.0; methods for
sizing and moving forms differ as well.
Conceptual Differences
In Visual Basic 6.0, coordinates for forms and controls are expressed in twips. In Visual Basic 2005, coordinates are expressed in
pixels.
Height and Width Properties
In Visual Basic 6.0, the Height and Width properties are used to change the size of a form or control. Visual Basic 2005
provides a Size property that also allows you to change both height and width in a single step.
Move Method
Visual Basic 6.0 uses the Move method to change the location of a form or control at run time. In Visual Basic 2005, Move is
replaced by the SetBounds method and coordinates are expressed in pixels.
ScaleMode property
Visual Basic 6.0 also provides a ScaleMode property you can use to define a different coordinate system. Visual Basic 2005
only supports a single coordinate system, pixels. ScaleMode and its related properties and methods (Scale, ScaleHeight,
ScaleLeft, ScaleTop, ScaleWidth, ScaleX, ScaleY) are not supported in Visual Basic 2005. For more information, see
ScaleMode is not supported.
Code Changes for Coordinates
The following code illustrates the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Resizing a Form
The following example shows how to change the size of a form at run time.

' Visual Basic 6.0


' Measurements are in twips.
Me.Width = 8000
Me.Height = 6000

VB
' Visual Basic 2005
' Measurements are in pixels.
Me.Size = New System.Drawing.Size(640, 480)

Moving a Control
The following example shows how to move a control at run time.

' Visual Basic 6.0


' Move and retain original size.
CommandButton2.Move 2000, 1000
' Move and resize to 1200 by 800 twips.
CommandButton1.Move 0, 0, 1200, 800

VB
' Visual Basic 2005
' Move and retain original size.
Button2.SetBounds(20, 10, 0, 0, BoundsSpecified.X Or BoundsSpecified.Y)
' Move and resize to 120 by 80 pixels.
Button1.SetBounds(0, 0, 120, 80)
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, the Height and Width properties of forms and controls
are automatically converted to pixels.
If the original application used the ScaleMode property, the upgrade tool assumes that the design-time setting for the
ScaleMode property was twips; if this is not the case, the conversion will be incorrect and must be fixed. For more
information, see ScaleMode is not supported.
See Also
Concepts
Form Object for Visual Basic 6.0 Users
Other Resources
Windows Forms Controls for Visual Basic 6.0 Users
Control Property, Method, and Event Changes for Visual Basic 6.0 Users
Visual Basic Concepts

Form Events for Visual Basic 6.0 Users


There are some differences in form-event behavior between Visual Basic 6.0 and Visual Basic 2005.
Conceptual Differences
Initialize Event
In Visual Basic 6.0, the Initialize event is used to execute code before a form is loaded.
In Visual Basic 2005, initialization code must be added to the form constructor (Sub New()) after the call to
InitializeComponent(), as in the following example:

' Visual Basic 6.0


Private Sub Form_Initialize()
MsgBox("The form is loading")
End Sub

VB
' Visual Basic .NET
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
MsgBox("The form is loading")
End Sub

Note
A common use of the Initialize event is to show a "splash" form to display information while the form is loading. Visual Basi
c 2005 applications have a SplashScreen property that can be used to automatically display a form during application startu
p. For more information, see How to: Specify a Splash Screen for an Application (Visual Basic).

Terminate Event
In Visual Basic 6.0, the Terminate event is used to execute code after a form is unloaded.
In Visual Basic 2005, the Terminate event is no longer supported. Termination code must be executed inside the Dispose
method, before the call to MyBase.Dispose().
Note
The Dispose method is called automatically for the main form in an application; you need to call it explicitly for any other for
m.

The following example demonstrates the differences.

' Visual Basic 6.0


Private Sub Form_Terminate()
MsgBox "The form was terminated"
End Sub

VB
' Visual Basic .NET
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing AndAlso components IsNot Nothing Then
MsgBox("The form was terminated")
components.Dispose()
End If
MyBase.Dispose(disposing)
End Sub

Unload Event
In Visual Basic 6.0, the Unload event has a Cancel argument; in Visual Basic 2005, it is replaced by the Closed event, which
does not have a Cancel argument. If you need to cancel during unloading, use the Closing event instead.
Mouse Events for MDI Forms
In Visual Basic 6.0, MDI Forms support mouse events. In Visual Basic 2005, because an MDI Form has no client area to receive
mouse events, the Click, MouseDown, MouseMove, and MouseUp events are no longer supported for MDI Forms..
See Also
Reference
Form Constructor
Form.Closing Event
Concepts
Form Object for Visual Basic 6.0 Users
Visual Basic Concepts

MaxLength Property for Visual Basic 6.0 Users


In Visual Basic 6.0, the MaxLength property of a TextBox control has absolute control over the length of a string that can be
entered or displayed in the text box. Although you can programmatically enter a longer string, it is automatically truncated to
the length set in the MaxLength property.
In Visual Basic 2005, the length of a string entered programmatically overrides the MaxLength property setting.
The following code illustrates the different behavior.

' Visual Basic 6.0


Text1.MaxLength = 5
Text1.Text = "Longer than five"
MsgBox Text1.Text ' Displays "Longe".

VB
' Visual Basic 2005
Text1.MaxLength = 5
Text1.Text = "Longer than five"
MsgBox(Text1.Text) ' Displays "Longer than five".

What to do next
Review the design of your application to determine if the intended behavior was to always limit the text in the text box to
the length set in the MaxLength property.
If this was the intended behavior, find each occurrence of code that sets the Text property, and add code to
truncate the string, similar to the following example.
VB
' Old code
Text1.Text = SomeString

' Replacement code


If Len(SomeString) > Text1.MaxLength Then
SomeString = Microsoft.VisualBasic.Left(SomeString, Text1.MaxLength)
End If

Text1.Text = SomeString

If it was not the intended behavior, leave the code alone. The user will still be limited by the MaxLength setting,
but you can programmatically assign strings that are longer than the MaxLength setting.
See Also
Concepts
TextBox Control for Visual Basic 6.0 Users
Visual Basic Concepts

MousePointer for Visual Basic 6.0 Users


In Visual Basic 2005, the Visual Basic 6.0 MousePointer property has been replaced by the Cursor property and the names of
the MousePointer constants have changed.
Conceptual Differences
In Visual Basic 6.0, the MousePointer property of a form or control is used to change the appearance of the cursor when it
passes over that form or control.
In Visual Basic 2005, the Cursor property provides the same functionality as the MousePointer.
Custom MousePointers
In Visual Basic 6.0, you can use any icon (.ico) or cursor (.cur) file as a custom MousePointer.
In Visual Basic 2005, only cursor files are supported; you can set a custom cursor at run time by assigning a cursor file to the
Cursor property.
vbIconPointer Constant
Visual Basic 6.0 includes the MousePointer constant vbIconPointer to change the cursor to an icon symbol (a small square
within a square). This constant is provided for legacy purposes only; on newer operating systems it has no effect and the
default cursor is displayed. There is no equivalent in Visual Basic 2005.
Code Changes for the MousePointer Property
The following examples illustrate the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Changing the Cursor Appearance
The following code demonstrates how the cursor changes appearance when it passes over a text box control at run time,
replacing the default arrow with an hourglass cursor. The Visual Basic 6.0 example sets the MousePointer property; in the
Visual Basic 2005 example, the Cursor property is the equivalent of MousePointer. The Visual Basic 2005 example also uses
the new MouseEnter event.

' Visual Basic 6.0


Private Sub Text1_MouseMove(Button As Integer, Shift As Integer, _
X As Single, Y As Single)
Text1.MousePointer = vbHourGlass
End Sub

VB
' Visual Basic 2005
Private Sub TextBox1_MouseEnter(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles TextBox1.MouseEnter
TextBox1.Cursor = System.Windows.Forms.Cursors.WaitCursor
End Sub

Displaying a Custom Cursor


The following code demonstrates the display of a hand cursor when the cursor passes over a text box control. The Visual Basic
6.0 example sets both the MouseIcon and MousePointer properties; the Visual Basic 2005 example sets the Cursor property
to a new instance of a Cursor object.

' Visual Basic 6.0


Private Sub Text1_MouseMove(Button As Integer, Shift As Integer, _
X As Single, Y As Single)
Text1.MouseIcon = LoadPicture("C:\Windows\Cursors\hmove.cur")
Text1.MousePointer = vbHourGlass
End Sub

VB
' Visual Basic 2005
Private Sub TextBox2_MouseEnter(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles TextBox2.MouseEnter
TextBox2.Cursor = New System.Windows.Forms.Cursor _
("C:\mypath\mycursor.cur")
End Sub

MousePointer Constant Equivalencies


The following table lists Visual Basic 6.0 constants and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
0 – vbDefault Default

1 – vbArrow Arrow

2 – vbCrossHair Cross

3 – vbIBeam IBeam

4 – vbIconPointer Obsolete — replaced by Default

5 – vbSizePointer SizeAll

6 – vbSizeNESW SizeNESW

7 – vbSizeNS SizeNS

8 – vbSizeNWSE SizeNWSE

9 – vbSizeWE SizeWE

10 – vbUpArrow UpArrow

11 – vbHourGlass WaitCursor

12 – vbNoDrop No

13 – vbArrowHourGlass AppStarting

14 – vbArrowQuestion Help

15 – vbSizeAll SizeAll

99 – vbCustom No equivalent — for more information, see Cannot set a custom MousePointer

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, the MousePointer property is replaced by the Cursor
property. Code that uses MousePointer constants is modified to use Visual Basic 2005 Cursors enumerations.
If the Visual Basic 6.0 application uses a custom MousePointer, the design-time setting or custom MousePointer code will
not be upgraded and a warning will be issued.
In addition, if the Visual Basic 6.0 application sets the MousePointer to the vbIconPointer constant at either design time or
run time, it will be replaced by the default cursor during upgrade.
See Also
Reference
Cannot set a custom MousePointer
Other Resources
Windows Forms Controls for Visual Basic 6.0 Users
Control Property, Method, and Event Changes for Visual Basic 6.0 Users
Visual Basic Concepts

Moveable Property for Visual Basic 6.0 Users


The Moveable property of a Visual Basic 6.0 form has no equivalent in Visual Basic 2005.
Conceptual Differences
In Visual Basic 6.0, the Moveable property of a form can be set to False to prevent a user from moving the form at run time.
Windows Forms in Visual Basic 2005 does not have an equivalent property.
Although it is generally considered bad user interface design, you can achieve similar behavior in Visual Basic 2005 by setting
the FormBorderStyle property to None and then the ControlBox property to False.
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any design-time or run-time references to the Moveable
property are not upgraded and a warning comment is added to the code.
See Also
Reference
ControlBox
Concepts
Form Object for Visual Basic 6.0 Users
MDIForm Object for Visual Basic 6.0 Users
Visual Basic Concepts

Style Property for Visual Basic 6.0 Users


The procedures for displaying images for Visual Basic 6.0 CommandButton, CheckBox, and OptionButton controls differ
from those used in Visual Basic 2005.
Conceptual Differences
In Visual Basic 6.0, setting the Style property of a CommandButton, CheckBox, or OptionButton control to 1 – Graphical
enables the control to display images. The Picture, DownPicture, and DisabledPicture properties assign images to be
displayed in response to state changes. For example, when a CheckBox control is checked, the DownPicture image is
displayed; if the CheckBox control is disabled, the DisabledPicture image is displayed.
Visual Basic 2005 no longer supports the Style, Picture, DownPicture, and DisabledPicture properties. The Style property
is no longer necessary: Assigning a picture to the Image property has the same effect as setting the Style property to
Graphical. The Picture property is replaced by the Image property. The functionality of the DownPicture and
DisabledPicture properties can be emulated using an ImageList control that contains multiple images.
Upgrade Notes
When you upgrade an application that has the Style property set to 1 – Graphical, the Appearance property of the
upgraded control is set to Button, and any image assigned to the Picture property at design time is assigned to the upgraded
control's Image property.
If the DownPicture or DisabledPicture properties were set at design time or at run time, you need to modify your upgraded
application to use an ImageList control. For more information, see
How to: Emulate a Visual Basic 6.0 Tri-state Control in an Upgraded Application.
See Also
Tasks
How to: Emulate a Visual Basic 6.0 Tri-state Control in an Upgraded Application
Concepts
CheckBox Control for Visual Basic 6.0 Users
CommandButton Control for Visual Basic 6.0 Users
OptionButton Control for Visual Basic 6.0 Users
OptionButton Control for Visual Basic 6.0 Users
Visual Basic Concepts

TopIndex Property and Scroll Event for Visual Basic 6.0 Users
Visual Basic 2005 no longer supports the TopIndex property for a ComboBox control or the Scroll event for ListBox or
ComboBox controls.
Conceptual Differences
TopIndex Property
In Visual Basic 6.0, the TopIndex property is used to return or set a value that specifies which item in a ComboBox or ListBox
control displayed in the topmost position. This property is commonly used to scroll the list without selecting an item.
In Visual Basic 2005, the ComboBox control no longer supports the TopIndex property. In most cases this should not present
a problem as setting the TopIndex property has no visible effect, unless the Style property is set to 1 - SimpleCombo. In this
case, you can emulate the ComboBox's SimpleCombo behavior by using a ListBox control and a TextBox control, as the
ListBox control still supports the TopIndex property.
Scroll Event
The Scroll event in Visual Basic 6.0 is used in conjunction with the TopIndex property to perform actions when the list is
scrolled. Visual Basic 2005 does not support the Scroll event; however, in most cases the SelectedIndexChanged event should
be a suitable replacement.
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any code that references the TopIndex property for a
ComboBox control or any code in the Scroll event procedure for a ComboBox or ListBox control is not upgraded. The
Upgrade wizard inserts a warning comment in the code; the code must be removed for the application to compile.
See Also
Reference
SelectedIndexChanged
SelectedIndexChanged
Concepts
ComboBox Control for Visual Basic 6.0 Users
ListBox Control for Visual Basic 6.0 Users
Visual Basic Concepts

Windows Forms Concepts for Visual Basic 6.0 Users


If you are familiar with forms and controls in Visual Basic 6.0, you will recognize many similarities in Windows Forms in Visual
Basic 2005. There are, however, a few areas that are conceptually different. The following topics will familiarize you with those
differences.
In This Section
The following topics present conceptual differences between working with forms and controls in Visual Basic 6.0 and in Visual
Basic 2005.
Color Handling for Visual Basic 6.0 Users
Control Arrays for Visual Basic 6.0 Users
Dialog Box Changes for Visual Basic 6.0 Users
Drag and Drop for Visual Basic 6.0 Users
Dynamic Data Exchange for Visual Basic 6.0 Users
Font Handling for Visual Basic 6.0 Users
Form Positioning for Visual Basic 6.0 Users
Forms Tasks for Visual Basic 6.0 Users
Graphics for Visual Basic 6.0 Users
Help Support for Visual Basic 6.0 Users
How to: Add Visual Basic 6.0 File System Controls to Your Application
Menu Handling for Visual Basic 6.0 Users
MDI for Visual Basic 6.0 Users
Printing Changes for Visual Basic 6.0 Users
ToolTip Support for Visual Basic 6.0 Users
Version Numbering for Visual Basic 6.0 Users
Related Sections
Windows Forms Controls for Visual Basic 6.0 Users
Describes differences between Visual Basic 6.0 and Windows Forms controls.
Windows Forms Overview
Introduces basic concepts related to forms.
What's New in Windows Forms for Visual Basic 6.0 Users
Describes new features for Windows Forms.
Windows Applications Namespaces in Visual Studio
Introduces the namespaces related to Windows Forms.
Help for Visual Basic 6.0 Users
Provides links to additional topics describing differences between Visual Basic 6.0 and Visual Basic 2005.
Visual Basic Reference

Color Handling for Visual Basic 6.0 Users


This topic compares color handling in Visual Basic 6.0 with equivalents in Visual Basic 2005.
Working with colors in Visual Basic 2005 is similar to working with colors in Visual Basic 6.0; however, there are a few
conceptual differences that you need to know. In addition, the constants used to specify colors in Visual Basic 6.0 are replaced
by new color enumerations in Visual Basic 2005.
Conceptual Differences
In Visual Basic 6.0, colors were represented by a value of type Long; in Visual Basic 2005 colors are of type Color. In Visual
Basic 6.0, constants were provided for eight standard colors; in Visual Basic 2005 there are more than 100 named colors.
Tip
To find an equivalent value for a Visual Basic 6.0 color that is not a standard color, you can use the ColorTranslator class and
pass it the Long value of the Visual Basic 6.0 color.

Color Constants
In Visual Basic 6.0, constants were provided for system colors that could be used to map a color to the user's system
preferences. In Visual Basic 2005, the system colors are of type SystemColors.
BackColor and ForeColor Properties
In Visual Basic 6.0, the BackColor and ForeColor properties of a control had to be explicitly set at design time or at run time;
colors could not be inherited. In Visual Basic 2005, unless a color is explicitly set at design time or at run time, it will inherit the
color setting of its parent. For more information, see Color Behavior for Visual Basic 6.0 Users.
Palette and PaletteMode Properties
In Visual Basic 6.0, the Palette and PaletteMode properties of a form were used to control the set of colors to be used when
displaying images on a 256-color display. Visual Basic 2005 does not support the Palette or PaletteMode properties. For
more information, see Palettes for Visual Basic 6.0 Users.
MaskColor Property
The Visual Basic 6.0 MaskColor property no longer exists for the CheckBox, Button, and RadioButton controls. You can emulate
the MaskColor property by using the graphics methods. For more information, see MaskColor for Visual Basic 6.0 Users.
Code Changes for Color Handling
The following examples illustrate the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Setting a Color to a System Color
The following code sets the BackColor of a form to match the user-selected color for the active title bar.
' Visual Basic 6.0
Me.BackColor = vbActiveTitleBar

VB
' Visual Basic 2005
Me.BackColor = System.Drawing.SystemColors.ActiveCaption

Code Changes for Setting a Color to a Visual Basic 6.0 Value


The following example sets the BackColor property of a TextBox control to match the lightest green (&H00C0FFC0) from the
Visual Basic 6.0 color picker.
' Visual Basic 6.0
textBox1.Text = &H00C0FFC0

VB
' Visual Basic 2005
TextBox1.BackColor = System.Drawing.ColorTranslator.FromOle(&HC0FFC0)
Constant Equivalencies
The following tables list Visual Basic 6.0 constants and their Visual Basic 2005 equivalents.
Color Constant Equivalents
Visual Basic 6.0 Visual Basic 2005 Equivalent
vbBlack Black

vbRed Red

vbGreen Lime

vbYellow Yellow

vbBlue Blue

vbMagenta Magenta

vbCyan Cyan

vbWhite White
System Color Constant Equivalents
Visual Basic 6.0 Visual Basic 2005 Equivalent
vb3DDKShadow ControlDarkDark

vb3DFace Control

vb3DHighlight ControlLightLight

vb3DLight ControlLight

vb3DShadow ControlDark

vbActiveBorder ActiveBorder

vbActiveTitleBar ActiveCaption

vbActiveTitleBarText ActiveCaptionText

vbApplicationWorkspace AppWorkspace

vbButtonFace Control

vbButtonShadow ControlDark

vbButtonText ControlText

vbDesktop Desktop

vbGrayText GrayText
vbHighlight Highlight

vbHighlightText HighlightText

vbInactiveBorder InactiveBorder

vbInactiveCaptionText InactiveCaptionText

vbInactiveTitleBar InactiveCaption

vbInactiveTitleBarText InactiveCaptionText

vbInfoBackground Info

vbInfoText InfoText

vbMenuBar Menu

vbMenuText MenuText

vbScrollBars ScrollBar

vbTitleBarText ActiveCaptionText

vbWindowBackground Window

vbWindowFrame WindowFrame

vbWindowText WindowText
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005 using the upgrade wizard, colors are converted using the
FromOle method.
After upgrade you should search for any code that explicitly sets the BackColor or ForeColor property at run time. If it is being
set for a parent, explicitly set the color of the child controls at design time, otherwise the child controls will inherit the colors
from the parent.
Any code that used the Palette, PaletteMode, or MaskColor properties will need to be rewritten in Visual Basic 2005.
See Also
Concepts
Color Behavior for Visual Basic 6.0 Users
Palettes for Visual Basic 6.0 Users
MaskColor for Visual Basic 6.0 Users
Other Resources
Windows Forms Controls for Visual Basic 6.0 Users
Visual Basic Concepts

Color Behavior for Visual Basic 6.0 Users


The ForeColor and BackColor properties of controls behave differently in Visual Basic 6.0 compared to Visual Basic 2005.
Conceptual Differences
In Visual Basic 6.0, the BackColor and ForeColor properties of a control had to be explicitly set at design time or at run time
and colors could not be inherited. In Visual Basic 2005, unless a color is explicitly set at design time or at run time, it inherits
the color setting of its parent.
Code Changes for Color Behavior
The following example of a form with two CommandButton controls, Command1 and Command2, demonstrates the differences
in behavior.
' Visual Basic 6.0
' Command1's BackColor is left at its default (gray).
' Command2's BackColor is explicitly set.
Command2.BackColor = vbBlack
' Explicitly set the BackColor of the form.
Form1.BackColor = vbRed

After running the above code, Command1's BackColor is still the default (gray), and Command2's BackColor is black.
The following example shows the behavior in Visual Basic 2005. In Visual Basic 2005, CommandButton controls are replaced
by Button controls.
VB
' Visual Basic 2005
' Command1's BackColor is left at its default (gray).
' Command2's BackColor is explicitly set.
Command2.BackColor = System.Drawing.Color.Black
' Explicitly set the BackColor of the form.
Me.BackColor = System.Drawing.Color.Red

After running the above code, Command1's BackColor is red and Command2's BackColor is black. Because the Command1's
BackColor was not explicitly set, red is inherited from the form.
Note
This applies for any parent, not just for forms. If the Button was contained in a Panel control within the form, changing the
color of either the panel or the form would change the color of the Button.

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, the upgrade wizard has no way to determine if colors will
be inherited. After upgrading, search for any code that explicitly sets the BackColor or ForeColor property at run time. If it is
set for a parent, explicitly set the color of the child controls at design time.
See Also
Reference
Color Handling for Visual Basic 6.0 Users
Other Resources
Windows Forms Controls for Visual Basic 6.0 Users
Visual Basic Concepts

MaskColor for Visual Basic 6.0 Users


The MaskColor property in Visual Basic 6.0 has no direct equivalent in Visual Basic 2005, however you can use graphics
methods to achieve the same effect.
Conceptual Differences
In Visual Basic 6.0, the MaskColor property of a CheckBox, CommandButton, or OptionButton control was used to define
a color that would become transparent, allowing a background image to show. To use this property, the Style property had to
be set to Graphical, the UseMaskColor property had to be set to True, and a bitmap had to be assigned to the Picture
property.
In Visual Basic 2005, there is no direct equivalent for the MaskColor property. You can, however, set transparency on a control
using the MakeTransparent method of a Bitmap object.
Code Changes for MaskColor
The following code shows the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
' Visual Basic 6.0
' Assumes a picture has been assigned to the Picture property
' and that the Style property has been set to Graphical.
Command1.UseMaskColor = True
Command1.MaskColor = vbWhite

VB
' Visual Basic 2005
' Assumes a picture has been assigned to the BackgroundImage property.
Dim g As New System.Drawing.Bitmap(Button1.BackgroundImage)
g.MakeTransparent(System.Drawing.Color.White)
Button1.BackgroundImage = g

Upgrade Notes
When upgrading an application from Visual Basic 6.0 to Visual Basic 2005, the upgrade wizard does not upgrade code that
uses the MaskColor property. Upgrade warnings will be inserted into your code. You will need to modify the code before
running the application.
See Also
Reference
Color Handling for Visual Basic 6.0 Users
MakeTransparent
Concepts
CheckBox Control for Visual Basic 6.0 Users
CommandButton Control for Visual Basic 6.0 Users
OptionButton Control for Visual Basic 6.0 Users
Visual Basic Concepts

Palettes for Visual Basic 6.0 Users


The Palette and PaletteMode properties in Visual Basic 6.0 have no equivalent in Visual Basic 2005.
Conceptual Differences
In Visual Basic 6.0, the Palette and PaletteMode properties of a form control the colors used when displaying images on a
256-color display. These properties have no effect on displays that supported more than 256 colors.
Visual Basic 2005 does not support the Palette or PaletteMode properties. Today's display devices typically display
thousands or millions of colors and there is no longer a need to specify a palette for an image.
Note
The Image object in Visual Basic 2005 has a Palette property for rendering images; this is not the same as the Visual Basic 6.0
Palette property.

Upgrade Notes
When upgrading a Visual Basic 6.0 application to Visual Basic 2005, any code that references the Palette or PaletteMode
property is not upgraded. The upgrade wizard inserts a warning in your code; you will need to delete the code that references
these properties.
See Also
Reference
Color Handling for Visual Basic 6.0 Users
Concepts
Form Object for Visual Basic 6.0 Users
Visual Basic Concepts

Control Arrays for Visual Basic 6.0 Users


Although control arrays are no longer supported in Visual Basic 2005, using the event model you can duplicate and expand
upon much of the control array functionality.
Conceptual Differences
In Visual Basic 6.0, control arrays could be used to manage controls on a form; they provided capabilities for sharing event
handlers, iterating through groups of controls, and adding controls at run time.
In Visual Basic 2005, control arrays are no longer supported. Changes to the event model make control arrays unnecessary,
and the .NET Framework provides the same capabilities for working with controls.
Sharing Event Handlers
In Visual Basic 6.0, control arrays could be used to specify a group of controls that shared a set of events. The controls had to
be of the same type, and they had to have the same name.
Visual Basic 2005 allows any event handler to handle events from multiple controls, even controls with different names and of
different types.
For example, you might add two Button controls (Button1 and Button2) and a CheckBox control (CheckBox1) to a form, and
then create an event handler to handle the Click event for all three controls.

Private Sub MixedControls.Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click, Button2.Click, CheckBox1.Click

Iterating Through Controls


Another feature of Visual Basic 6.0 control arrays was the ability to iterate through a group of controls using the Index
property. For example, to clear the text of all TextBox controls in a control array, you could loop through the control array
using the Index property as a loop variable.
Visual Basic 2005 controls do not have an Index property, but you can still iterate through the controls on a form or container
using the ControlCollection of the Control class.
In Visual Basic 6.0, controls in a single control array could be sited on different containers. For example, TextBox controls
contained on two different Frame controls could be part of the same control array.
In Visual Basic 2005, the Controls collection only returns controls sited on a single container. You must iterate through the
controls of each container control separately; this can be done using a recursive function.
Adding Controls at Run Time
In Visual Basic 6.0, controls could be added to a control array at run time using the Load statement. The controls had to be of
the same type as the control array, and the control array had to be created at design time with at lest one element. After adding
the control, the Visible property had to be set to True.
In Visual Basic 2005, controls are added at run time by using the New keyword in a Dim statement, then using the Add
method for the container where you want to add the control.
Adding Event Handlers at Run Time
In Visual Basic 6.0, when you added a control to a control array at run time, the new controls events were automatically
handled by the events for the control array.
In Visual Basic 2005, you need to define event handlers for controls added at run time. This is accomplished using the
AddHandler statement.
Code Changes for Control Arrays
The following code illustrates the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Sharing Event Handlers
The following example demonstrates sharing the Change event handler (TextChanged in Visual Basic 2005) for a group of
three TextBox controls. In Visual Basic 2005, the Handles clause of the event handler specifies which control the event will
handle. The event handler returns a generic Object, so it must be cast to the specific object type (in this case, TextBox) that
you want to handle using the DirectCast method.
' Visual Basic 6.0
Private Sub Text1_Change(Index As Integer)
Select Case Index
Case 0
MsgBox("The text in the first TextBox has changed")
Case 1
MsgBox("The text in the second TextBox has changed")
Case 2
MsgBox("The text in the third TextBox has changed")
End Select
End Sub

VB
' Visual Basic 2005
Private Sub TextBoxes_TextChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles TextBox1.TextChanged, _
TextBox2.TextChanged, TextBox3.TextChanged
Select Case DirectCast(sender, TextBox).Name
Case TextBox1.Name
MsgBox("The text in the first TextBox has changed")
Case TextBox2.Name
MsgBox("The text in the second TextBox has changed")
Case TextBox3.Name
MsgBox("The text in the third TextBox has changed")
End Select
End Sub

Note
The event behavior is slightly different in Visual Basic 2005. The TextChanged event is raised when each control is initialized
(for example in the Form_Load event) as well as when the text is changed at run time. In Visual Basic 6.0, the Change event w
as only raised when the text was changed.

Iterating Through Controls


The following example demonstrates a function for iterating through a group of text-box controls and clearing their text. In the
Visual Basic 6.0 example, the Index property of a control array is used as a loop variable.
In Visual Basic 2005, a Control object is passed as an argument; it has a ControlCollection collection that includes all controls
sited on that control. The Typeof operator is used to determine if each control is of type TextBox.
Note
A Form object is of type Control; you can also pass a Form as an argument.

Because nested controls are not included in the ControlCollection collection, the HasChildren method is used to determine if
each control contains other controls, if so the ClearText function is called recursively.
' Visual Basic 6.0
Private Sub ClearText()
For i = 0 To Text1().UBound
Text1(i).Text = ""
Next
End Sub

VB
' Visual Basic 2005
Private Sub ClearText(ByVal container As Control)
Dim ctrl As Control
For Each ctrl In container.Controls
If TypeOf (ctrl) Is TextBox Then
ctrl.Text = ""
End If
If ctrl.HasChildren Then
ClearText(ctrl)
End If
Next
End Sub

Adding Controls at Run Time


The following example demonstrates adding a text-box control to a form at run time. In Visual Basic 6.0, the control is added to
a control array. In Visual Basic 2005 the control is added to the ControlCollection collection. In Visual Basic 6.0, events for the
new TextBox were automatically handled by the control array. In Visual Basic 2005, you need to hook up event handling
through the AddHandler statement.
Both examples assume that a text-box control is added to the form at design time, and in the Visual Basic 6.0 example that a
single-element control array was created. The Visual Basic 2005 example also assumes that an event handler named
TextChangedHandler exists for the first TextBox control.
' Visual Basic 6.0
Private Sub AddControl()
' Add a TextBox as the second element of a control array.
Load Text1(1)
' Set the location below the first TextBox.
Text1(1).Move Text1(0).Left, Text1(0).Top + 500
' Make the new TextBox visible
Text1(1).Visible = True

VB
' Visual Basic 2005
' Declare a new TextBox.
Dim TextBox2 As New TextBox
' Set the location below the first TextBox
TextBox2.Left = TextBox1.Left
TextBox2.Top = TextBox1.Top + 30
' Add the TextBox to the form's Controls collection.
Me.Controls.Add(TextBox2)
AddHandler TextBox2.TextChanged, AddressOf TextChangedHandler

Upgrade Notes
When an application created with Visual Basic 6.0 is upgraded to Visual Basic 2005, any control arrays are upgraded to special
control-specific control array classes. These classes are contained in the Microsoft.VisualBasic.Compatibility.VB6
namespace and are used by the upgrade tools to emulate Visual Basic 6.0 control array behavior.
Although it is possible to use these control array classes in new Visual Basic 2005 development, we recommend that you use
the .NET Framework event model and functions instead.
See Also
Concepts
Events and Event Handling for Visual Basic 6.0 Users
Other Resources
Windows Forms Controls for Visual Basic 6.0 Users
Visual Basic Concepts

Dialog Box Changes for Visual Basic 6.0 Users


The methods for displaying dialog boxes in Visual Basic 2005 differ from those in Visual Basic 6.0.
Conceptual Differences
In Visual Basic 6.0, a form can be displayed as a modal dialog box by calling the Show method with a parameter of vbModal.
In Visual Basic 2005, the ShowDialog method is used to display a form modally; the Show method is used to display a form
non-modally.
In addition, the Visual Basic 6.0 CommonDialog control provides several predefined dialog boxes. In Visual Basic 2005, this
control is replaced by the ColorDialog control, the FontDialog control, the OpenFileDialog control, the PageSetupDialog
control, the PrintDialog control, the PrintPreviewDialog control, and the SaveFileDialog control.
See Also
Concepts
CommonDialog Control for Visual Basic 6.0 Users
Other Resources
Dialog Boxes in Windows Forms
Dialog-Box Controls and Components (Windows Forms)
Visual Basic Concepts

Drag and Drop for Visual Basic 6.0 Users


The model for implementing drag-and-drop editing in Visual Basic 2005 differs considerably from the Visual Basic 6.0 model.
Conceptual Differences
In Visual Basic 6.0, drag-and-drop editing can be accomplished by two different methods: standard dragging, for dragging
between controls on a form, and OLE dragging, for dragging between forms and applications.
In Visual Basic 2005, a single model for drag-and-drop editing is used. It is similar to OLE dragging, but the names and
parameters for drag-and-drop methods and events are different, and the event model is different.
Code Changes for Drag and Drop
Code Changes for Dragging and Dropping Text
The following example shows the differences in code for dragging text from one TextBox control to another.

' Visual Basic 6.0


Private Sub Text1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
Text1.Text = "Hello World"
' Begin dragging by calling the OLEDrag method.
Text1.OLEDrag
End Sub

Private Sub Text1_OLEStartDrag(Data As DataObject, AllowedEffects As Long)


' Only allow copying.
AllowedEffects = vbDropEffectCopy
Data.Clear
' Populate the Data object with the text to copy and the format.
Data.SetData Text1.Text, vbCFText
End Sub

Private Sub Text2_OLEDragOver(Data As DataObject, Effect As Long, Button As Integer, Shift


As Integer, X As Single, Y As Single, State As Integer)
' Make sure that the format is text.
If Data.GetFormat(vbCFText) Then
' If it is text, enable dropping for the second TextBox.
Text2.OLEDropMode = vbOLEDropManual
End If
End Sub

Private Sub Text2_OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift


As Integer, X As Single, Y As Single)
' Copy the text from the Data object to the second TextBox.
Text2.Text = Data.GetData(vbCFText)
End Sub

VB
' Visual Basic 2005
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles MyBase.Load
' Dropping must be enabled before the dragging occurs.
TextBox2.AllowDrop = True
End Sub
Private Sub TextBox1_MouseDown(ByVal sender As Object, ByVal e _
As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseDown

TextBox1.Text = "Hello World"


' Begin dragging by calling the DoDragDrop method.
' OLEStartDrag is replaced by arguments on the method.
TextBox1.DoDragDrop(TextBox1.Text, DragDropEffects.Copy)
End Sub
Private Sub TextBox2_DragEnter(ByVal sender As Object, ByVal e _
As System.Windows.Forms.DragEventArgs) Handles TextBox2.DragEnter

' Make sure that the format is text.


If (e.Data.GetDataPresent(DataFormats.Text)) Then
' Allow drop.
e.Effect = DragDropEffects.Copy
Else
' Do not allow drop.
e.Effect = DragDropEffects.None
End If
End Sub
Private Sub TextBox2_DragDrop(ByVal sender As Object, ByVal e _
As System.Windows.Forms.DragEventArgs) Handles TextBox2.DragDrop

' Copy the text to the second TextBox.


TextBox2.Text = e.Data.GetData(DataFormats.Text).ToString
End Sub

Upgrade Notes
Drag-and-drop code cannot automatically be upgraded to Visual Basic 2005; it must be rewritten using the new model. Any
drag-and-drop code is marked with upgrade warnings during the upgrade process.
See Also
Other Resources
Drag-and-Drop Operations and Clipboard Support
Visual Basic Concepts

Dynamic Data Exchange for Visual Basic 6.0 Users


Dynamic Data Exchange (DDE) is no longer supported in Visual Basic 2005.
Conceptual Differences
Dynamic Data Exchange (DDE) was an early technology that enabled the exchange of information between applications in
Visual Basic 3.0. DDE was replaced by OLE Automation in later versions of Visual Basic; however, DDE was still supported for
backwards compatibility through Visual Basic 6.0.
With the introduction of Visual Basic .NET 2002, DDE is no longer supported. Visual Basic applications needing to exchange
information with legacy applications that only support DDE should be maintained in Visual Basic 6.0.
The following DDE properties, methods, and events are no longer available:
Category Name
Properties LinkItem
LinkMode
LinkTimeOut
LinkTopic

Methods LinkExecute
LinkPoke
LinkRequest
LinkSend

Events LinkClose
LinkError
LinkExecute
LinkNotify
LinkOpen

In addition, the Clipboard object constant vbCFLink is no longer valid.


Upgrade Notes
When upgrading a Visual Basic 6.0 application to Visual Basic 2005, any code that references DDE properties or methods and
any code in DDE event procedures will not be upgraded and a warning will be added.
See Also
Concepts
Form Object for Visual Basic 6.0 Users
Label Control for Visual Basic 6.0 Users
PictureBox Control for Visual Basic 6.0 Users
TextBox Control for Visual Basic 6.0 Users
Clipboard Object for Visual Basic 6.0 Users
Visual Basic Concepts

Font Handling for Visual Basic 6.0 Users


This topic compares font-handling techniques in Visual Basic 6.0 with their equivalents in Visual Basic 2005.
Conceptual Differences
Fonts in Visual Basic 6.0 are handled in two different ways: as font properties of forms and controls, or as a stdFont object.
In Visual Basic 2005, there is a single Font object: System.Drawing.Font. The Font property of a form or control takes a Font
object as an argument.
Setting Font Properties
In Visual Basic 6.0, font properties can be set at run time, either by assigning a stdFont object or by setting the properties
directly on the control; the two methods can be interchanged.
In Visual Basic 2005, the Font property of a control is read-only at run time—you cannot set the properties directly. You must
instantiate a new Font object each time you want to set a property.
Font Inheritance
In Visual Basic 6.0, font properties have to be set individually for each control or form; using a stdFont object simplifies the
process but still requires code.
In Visual Basic 2005, font properties are automatically inherited from their parent unless they are explicitly set for the child
object. For example, if you have two label controls on a form and change the font property of the form to Arial, the label
control's font also changes to Arial. If you subsequently change the font of one label to Times Roman, further changes to the
form's font would not override the label's font.
Font Compatibility
Visual Basic 6.0 supports raster fonts for backward compatibility; Visual Basic 2005 supports only TrueType and OpenType
fonts.
Enumerating Fonts
In Visual Basic 6.0, you can use the Screen.Fonts collection along with the Screen.FontCount property to enumerate the
available screen fonts.
In Visual Basic 2005, the Screen object no longer exists; in order to enumerate available fonts on the system, you should use
the System.Drawing.FontFamily namespace.
Note
Visual Basic 6.0 enumerates all types of fonts. Visual Basic 2005 supports only TrueType and OpenType fonts; other font type
s are not enumerated. In addition, Visual Basic 6.0 enumerates each character-set version within a font family (for instance, A
rial, Arial Baltic, Arial Greek); Visual Basic 2005 enumerates only the font families.

Code Changes for Fonts


The following code examples illustrate the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Setting Font Properties
The following example demonstrates setting font properties at run time. In Visual Basic 6.0, you can set properties directly on a
control; in Visual Basic 2005, you must create a new Font object and assign it to the control each time you need to set a
property.

' Visual Basic 6.0


' Set font properties directly on the control.
Label1.FontBold = True
' Create a stdFont object.
Dim f As New stdFont
' Set the stdFont object to the Arial font.
f.Name = "Arial"
' Assign the stdFont to the control's font property.
Set Label1.Font = f
' You can still change properties at run time.
Label1.FontBold = True
Label1.FontItalic = True

VB
' Visual Basic 2005
' Create a new Font object Name and Size are required.
Dim f As New System.Drawing.Font("Arial", 10)
' Assign the font to the control
Label1.Font = f
' To set additional properties, you must create a new Font object.
Label1.Font = New System.Drawing.Font(Label1.Font, FontStyle.Bold Or FontStyle.Italic)

Code Changes for Enumerating Fonts


The following example demonstrates filling a ListBox control with a list of the fonts installed on a computer.
Note
Visual Basic 6.0 enumerates all types of fonts. Visual Basic 2005 supports only TrueType and OpenType fonts; other font type
s are not enumerated. In addition, Visual Basic 6.0 enumerates each character-set version within a font family (for instance, A
rial, Arial Baltic, Arial Greek); Visual Basic 2005 enumerates only the font families.

' Visual Basic 6.0


Dim i As Integer
For i = 0 To Screen.FontCount – 1
List1.AddItem Screen.Fonts(i)
Next i

VB
' Visual Basic 2005
Dim ff As FontFamily
For Each ff In System.Drawing.FontFamily.Families
listBox1.Items.Add(ff.Name)
Next

Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any font-handling code is modified to use the new Font
object.
Font inheritance in Visual Basic 2005 can cause unintended changes in the appearance of your application. You should check
your converted application for any code that explicitly sets a font at the form or container level and, if necessary, change the
font for any child controls that should not inherit that font.
During upgrade, raster fonts are converted to the default OpenType font, Microsoft Sans Serif. Formatting such as Bold or Italic
is not preserved. For more information, see Only OpenType and TrueType fonts are supported.
If your application contains code that enumerates fonts, raster fonts will not be enumerated in the upgraded application, and
font families are enumerated rather than individual character-set versions.
See Also
Reference
Font Class
FontFamily.Families Property
Other Resources
Windows Forms Controls for Visual Basic 6.0 Users
Visual Basic Concepts

Form Positioning for Visual Basic 6.0 Users


Setting the position of a form on the screen differs between Visual Basic 6.0 and Visual Basic 2005.
Conceptual Differences
Left and Top Properties
In Visual Basic 6.0, the initial screen location for a form can be set at design time using the Form Layout window or by setting
the Left and Top properties in the Properties window. The Left and Top properties can also be set programmatically.
In Visual Basic 2005, the initial screen location is set at design time by setting the Location property, or programmatically by
setting the Location property to a Point object.
StartUpPosition Property
In addition, Visual Basic 6.0 supports a StartUpPosition property that can be used to allow Windows to automatically set a
location (for example, centered on the screen). The default setting is Manual, meaning that the Left and Top properties take
precedence.
In Visual Basic 2005, the StartPosition property performs the same function. The default setting is now
WindowsDefaultLocation, meaning that the Location property is ignored.
See Also
Tasks
How to: Set the Screen Location of Windows Forms
Visual Basic Concepts

Forms Tasks for Visual Basic 6.0 Users


There are many differences between Windows Forms and Visual Basic 6.0 forms. The following table provides a list of tasks
that can be performed with forms, along with their methodologies. You can use this list to make the transition from your
existing Visual Basic 6.0 Forms projects to the .NET Framework model for Windows Forms.
Task Visual Basic 6.0 Forms Windows Forms
Set the tab indexing for Select each control on the form, From the View menu choose Tab Order. The form displays a numer
all the controls on a for and set its TabIndex property t al next to each control that represents the control's TabIndex propert
m. o the next number in the tab or y setting. Click each control in the desired tab order. For more inform
der for your form. ation, see How to: Set the Tab Order on Windows Forms.

Determine the modifier Use the parameters provided by Compare the form class's ModifierKeys method against the modifier
key (ALT, SHIFT, CTRL) the mouse event handler. key value, found in the Keys enumeration. For more information, see
pressed during keyboar How to: Determine Which Modifier Key Was Pressed
d and mouse events.

Align or size controls b Click each control to align or siz Click each control to align or size. The first control selected is used to
ased on the location an e. The last control selected is us determine the location and size of all controls selected. For more info
d size of a single contro ed to determine the location an rmation, see How to: Align Multiple Controls on Windows Forms.
l. d size of all controls selected.

Change the name of a f Change the name specified in th Click the form's class file in Solution Explorer, and then change the
orm. e Name property of the form in Filename property in the Properties window.
the Properties window.

Change the run-time di Use the Form Layout window t With the form selected in the Windows Forms Designer, set the
splay position of a form o position the form, or set its St StartPosition property in the Properties window.
. artup property in the Propertie
s window.

Display a form as a dial In code, use the Show method a In code, use the ShowDialog method of the form. For more informati
og box. nd specify that the form be displ on, see How to: Display Dialog Boxes for Windows Forms.
ayed modally using the vbMod
al value.

Group or layer controls Layer the controls within the Fr Place the controls within a GroupBox control. Moving the group box
on a form. ame control. To move the contr moves the controls as well.
ols as a group, select them all.

Iterate through the cont Use a control array. Use the Controls Collection. For more information, see
rols on a form. Collections in Visual Basic.

See Also
Reference
Windows Forms Overview
Concepts
Form Object for Visual Basic 6.0 Users
Control Arrays for Visual Basic 6.0 Users
Other Resources
Windows Forms Concepts for Visual Basic 6.0 Users
Visual Basic Concepts

Graphics for Visual Basic 6.0 Users


In Visual Basic 6.0, various graphics methods and properties are used to draw on a Form or PictureBox control. Graphics in
Visual Basic 6.0 are based on the Windows Graphics Device Interface (GDI) APIs.
In Visual Basic 2005, graphics are provided by the System.Drawing namespace, which encapsulates GDI+ APIs. GDI+ expands
on the graphics capabilities of Visual Basic 6.0, although the methods are not compatible.
Conceptual Differences
In Visual Basic 6.0, graphics methods apply only to the Form object and to the PictureBox control.
In Visual Basic 2005, graphics methods apply to forms, plus any control that supports the Paint event, including the PictureBox,
Panel, and GroupBox controls. Additionally, graphics methods apply to any controls that support the OwnerDraw property,
including the ListView, TreeView, and Button controls.
AutoRedraw Property
In Visual Basic 6.0, graphics methods can be called from any event procedure; the AutoRedraw property is used to persist
graphics when graphics methods are called from an event other than the Paint event.
In Visual Basic 2005, graphics methods should only be called from the Paint event procedure, or in the case of some owner-
drawn controls, from the various Draw event procedures (DrawItem, DrawSubItem, etc.). The AutoRedraw property is no
longer supported and is not necessary because the Paint and Draw events automatically persist graphics.
ClipControls Property
In Visual Basic 6.0, the ClipControls property is used to control the painting of a form or control. When set to True, only newly
exposed areas are repainted, in theory, improving performance.
There is no equivalent for the ClipControls property in Visual Basic 2005; performance enhancements in GDI+ and up-to-date
video adapters make it unnecessary.
DrawMode Property
In Visual Basic 6.0, the DrawMode property controls the color of a graphics object when drawing one pattern on top of
another. This property only affects monochrome or low-resolution displays (256 colors or less).
There is no equivalent for the DrawMode property in Visual Basic 2005; it is no longer necessary with current displays.
DrawStyle Property
In Visual Basic 6.0, the DrawStyle property controls the appearance of a line drawn using the Line method. If the DrawWidth
property is set to a value greater than 1, the DrawStyle property has no effect and the line will always be solid.
In Visual Basic 2005, the appearance of a line is controlled by setting the DashStyle property of a System.Drawing.Pen class
used by one of the DrawLine methods; line width has no bearing on this property.
DrawWidth Property
In Visual Basic 6.0, the DrawWidth property determines the thickness of a line in pixels; the DrawWidth property is typically
set before performing a graphics method.
In Visual Basic 2005, the Pen.Width property of a System.Drawing.Pen control determines line thickness; you can set the
Width property as a parameter when you create the Pen, or by setting Pen.Width after the Pen is created. If no Pen.Width
property is specified, the default is 1 pixel.
Image Property
In Visual Basic 6.0 the Image property of a form or PictureBox control returns a handle to a bitmap; the handle can be
assigned to the Picture property or used as a value to pass to Windows API calls.
In Visual Basic 2005, bitmaps no longer have handles; the actual bitmap itself is passed as an object of type Bitmap. A Bitmap
control can be assigned to the Image property of a PictureBox control, but it cannot be passed to Windows API calls.
Line Method
In Visual Basic 6.0, the Line method is used to draw a rectangle by specifying the top left and lower coordinates, along with an
optional argument B. The FillColor property is used to fill a rectangle with a solid color, and the FillStyle property fills the
rectangle with a crosshatch pattern.
In Visual Basic 2005, the DrawRectangles method is used to draw the border of a rectangle, and the FillRectangle method is
used to fill it. FillRectangle takes a Brush object as a parameter. The SolidBrush replaces the FillColor property and members
of the HatchBrush class replace the FillStyle property.
Point Method
In Visual Basic 6.0, the Point method of a form or PictureBox control is used to return a color value for the pixel at a specified
point. Although the Point method can be used for forms or controls that do not contain a picture, it is most often used to
retrieve a color from a bitmap assigned to the Picture property.
In Visual Basic 2005, the Point method no longer exists. You can use the
M:System.Drawing.Bitmap.GetPixel(System.Int32,System.Int32) method to retrieve a color value from a bitmap. For
forms or controls that do not contain a picture, you can query the BackColor property.
Print Method
In Visual Basic 6.0, the Print method is used to display text on a form or PictureBox control. The font used to display the text is
determined by the Font properties of the form or control, and the color is determined by the ForeColor property. The Print
method offers no control for the location of the text and can only display text horizontally.
In Visual Basic 2005, the DrawString method is used to display text. The font is determined by a Font object, and the color is
determined by a Brush object; both are passed as parameters to the DrawString method. The DrawString method also has X
and Y parameters that determine the starting location for the text. There is also an optional Format parameter that takes
a StringFormat object, allowing you to display text vertically.
PSet Method
In Visual Basic 6.0, the PSet method is used to change the color of a pixel on a form or PictureBox control. If the DrawWidth
property is set to a value greater than 1, the PSet method draws a filled circle. An optional parameter is used to specify the
color; if omitted ForeColor is used.
In Visual Basic 2005, there is no equivalent for the PSet method. To change the color of a single pixel on a form or the
PictureBox control, use the DrawEllipse method to draw a circle with a height and width of 1 pixel. To duplicate the
functionality of PSet when DrawWidth is greater than 1, use the FillEllipse method.
Code Changes for Graphics
The following code examples illustrate the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Drawing a Simple Line
The following code demonstrates drawing a line on a form at run time. In the Visual Basic 6.0 example, the Line method is
used; it takes the X and Y coordinates of the starting and ending points and, optionally, a color as arguments. The Visual Basic
2005 example uses the DrawLine method, which takes a Pens object and the X and Y coordinates of the starting and ending
points as arguments.
Note
In Visual Basic 6.0, the default unit of measurement is twips; in Visual Basic 2005, it is pixels.

' Visual Basic 6.0


Private Sub Form_Paint()
' Draw a solid black line 200 twips from the top of the form.
Line (0, 200) - (ScaleWidth, 200), vbBlack
End Sub

VB
' Visual Basic 2005
Private Sub Form1_Paint(ByVal sender As Object, ByVal e _
As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
' Draw a solid black line 25 pixels from the top of the form.
e.Graphics.DrawLine(Pens.Black, 0, 25, Me.Width, 25)
End Sub

Drawing a Dotted Line


The following code demonstrates drawing a dotted line on a form at run time. In the Visual Basic 6.0 example, the DrawStyle
property determines the appearance of the line. The Visual Basic 2005 example uses a Pen object, setting the DashStyle
property to determine the appearance.
Note
In Visual Basic 6.0, the default unit of measurement is twips; in Visual Basic 2005, it is pixels.

' Visual Basic 6.0


Private Sub Form_Paint()
' Draw a dotted line 200 twips from the top of the form.
Me.DrawStyle = vbDot
Line (0, 200) - (ScaleWidth, 200), vbBlack
End Sub

VB
' Visual Basic 2005
Private Sub Form1_Paint1(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint

' Draw a dotted black line 25 pixels from the top of the form.
Dim LPen As New System.Drawing.Pen(System.Drawing.Color.Black)
LPen.DashStyle = Drawing2D.DashStyle.Dot
e.Graphics.DrawLine(LPen, 0, 25, Me.Width, 25)
End Sub

Controlling Line Thickness


The following code demonstrates drawing lines of different thicknesses on a form at run time. In the Visual Basic 6.0 example,
the DrawWidth property is used. The Visual Basic 2005 example uses the Width property of the Pens object.

' Visual Basic 6.0


Private Sub Form_Paint()
' Draw a line with a thickness of 1 pixel.
DrawWidth = 1
Line (0, 200)-(ScaleWidth, 200), vbBlack
' Draw a line with a thickness of 5 pixels.
DrawWidth = 5
Line (0, 400)-(ScaleWidth, 400), vbBlack
' Draw a line with a thickness of 10 pixels.
DrawWidth = 10
Line (0, 600)-(ScaleWidth, 600), vbBlack
End Sub

VB
' Visual Basic 2005
Private Sub Form1_Paint2(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
' Draw a line with a thickness of 1 pixel.
Dim TPen As New System.Drawing.Pen(System.Drawing.Color.Black, 1)
e.Graphics.DrawLine(TPen, 0, 25, Me.Width, 25)
' Draw a line with a thickness of 5 pixels.
TPen.Width = 5
e.Graphics.DrawLine(TPen, 0, 50, Me.Width, 50)
' Draw a line with a thickness of 10 pixels.
TPen.Width = 10
e.Graphics.DrawLine(TPen, 0, 75, Me.Width, 75)
End Sub

Drawing a Circle
The following code demonstrates drawing a circle on a form at run time. In the Visual Basic 6.0 example, the Circle method is
used; it takes the X and Y coordinates of the center point, the radius, and, optionally, a color, as arguments. The Visual Basic
2005 example uses the DrawEllipse method, which takes a Pen object, the X and Y coordinates of the upper-left corner of the
bounding rectangle, and the width and height as arguments.
Note
In Visual Basic 6.0, the default unit of measurement is twips; in Visual Basic 2005, it is pixels.

' Visual Basic 6.0


Private Sub Form_Paint()
' Draw a 1000 twip diameter red circle
Circle (500, 500), 500, vbRed
End Sub

VB
' Visual Basic 2005
Private Sub Form1_Paint3(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint

' Draw a 70 pixel diameter red circle.


e.Graphics.DrawEllipse(Pens.Red, 0, 0, 70, 70)
End Sub

Drawing a Filled Rectangle


The following code demonstrates drawing two rectangles on a form at run time, one with a solid fill and the other with a cross-
hatched pattern. In the Visual Basic 6.0 example, the FillColor and FillStyle properties are used along with the Line method.
Calling the Line method with the B parameter draws a rectangle.
The Visual Basic 2005 example uses the Graphics.Rectangle method to draw the outline, and the Graphics.FillRectangle
method which takes a Brush object as an argument. In this example both SolidBrush and HatchBrush controls are used.
Note
In Visual Basic 6.0, the default unit of measurement is twips; in Visual Basic 2005 it is pixels.

' Visual Basic 6.0


Private Sub Form_Paint()
' Draw a solid red rectangle.
FillColor = vbRed
FillStyle = vbSolid
Line (10, 10)- (1000, 500), vbRed, B
' Draw a rectangle filled with a crosshatch pattern.
FillColor = vbBlack
FillStyle = vbCross
Line (10, 500)- (1000, 1000), vbBlack, B
End Sub

VB
' Visual Basic 2005
Private Sub Form1_Paint4(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint

' Draw a solid red rectangle.


Dim SBrush As New System.Drawing.SolidBrush _
(System.Drawing.Color.Red)
e.Graphics.DrawRectangle(Pens.Red, 2, 2, 70, 40)
e.Graphics.FillRectangle(SBrush, 2, 2, 70, 40)

' Draw a rectangle filled with a crosshatch pattern.


Dim HBrush As New System.Drawing.Drawing2D.HatchBrush( _
System.Drawing.Drawing2D.HatchStyle.Cross, _
System.Drawing.Color.Black, System.Drawing.Color.Transparent)
e.Graphics.DrawRectangle(Pens.Black, 2, 40, 70, 40)
e.Graphics.FillRectangle(HBrush, 2, 40, 70, 40)
End Sub

Displaying an Image on a Form


The following code demonstrates graphics methods for displaying an image on a form at run time. The Visual Basic 6.0
example uses the PaintPicture method. The Visual Basic 2005 example uses the DrawImage method.

' Visual Basic 6.0


Private Sub Form_Paint()
' Create a stdPicture object.
Dim Pict1 As New stdPicture
Pict1 = LoadPicture("C:\Windows\Greenstone.bmp")
PaintPicture Pict1, 0, 0
End Sub

VB
' Visual Basic 2005
Private Sub Form1_Paint5(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint

' Create a Bitmap object.


Dim Pict1 As New Bitmap("C:\Windows\Greenstone.bmp")
e.Graphics.DrawImage(Pict1, 0, 0)
End Sub

Displaying Text on a Form


The following code demonstrates graphics methods for displaying a text string on a form at run time. The Visual Basic 6.0
example uses the Print method. The Visual Basic 2005 example uses the DrawString method.

' Visual Basic 6.0


Private Sub Form_Paint()
Me.Font.Size = 24
Me.Font.Bold = True
Me.ForeColor = vbRed
Print "Hello World!"
End Sub

VB
' Visual Basic 2005
Private Sub Form1_Paint6(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint

Dim TextFont As New System.Drawing.Font("Arial", 24, FontStyle.Bold)


Dim TextBrush As New System.Drawing.SolidBrush(System.Drawing.Color.Red)
e.Graphics.DrawString("Hello World!", TextFont, TextBrush, 10, 10)
TextFont.Dispose()
TextBrush.Dispose()
End Sub

Determining the Height and Width of a String


The following code demonstrates graphics methods for determining the size of a string on a form at run time, and then
drawing a rectangle around it. The Visual Basic 6.0 example uses the TextHeight and TextWidth methods. The Visual Basic
2005 example uses the MeasureString method, which returns a SizeF structure.
' Visual Basic 6.0
Private Sub Form_Paint()
Me.Font.Size = 24
Me.Font.Bold = True
Me.ForeColor = vbRed
Print "Hello World!"
Line (0, 0)-(TextWidth("Hello World!"), _
TextHeight("Hello World!")), vbBlack, B
End Sub

VB
' Visual Basic 2005
Private Sub Form1_Paint7(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint

Dim TextFont As New System.Drawing.Font("Arial", 24, FontStyle.Bold)


Dim TextBrush As New System.Drawing.SolidBrush(System.Drawing.Color.Red)
e.Graphics.DrawString("Hello World!", TextFont, TextBrush, 10, 10)
Dim TextSize As New System.Drawing.SizeF
TextSize = e.Graphics.MeasureString("Hello World!", TextFont)
e.Graphics.DrawRectangle(Pens.Black, 10, 10, TextSize.Width, TextSize.Height)
TextFont.Dispose()
TextBrush.Dispose()
End Sub

Drawing a Single Pixel


The following example demonstrates graphics methods for changing the color of a single pixel on a form at run time. The
Visual Basic 6.0 example uses the PSet method. The Visual Basic 2005 example uses the DrawEllipse method with the Height
and Width parameters set to 1.
Note In Visual Basic 6.0, the default unit of measurement is twips; in Visual Basic 2005 it is pixels.

' Visual Basic 6.0


Private Sub Form_Paint()
Me.DrawWidth = 1
PSet (1000, 1000), vbRed
End Sub

VB
' Visual Basic 2005
Private Sub Form1_Paint8(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint

e.Graphics.DrawEllipse(Pens.Red, 70, 70, 1, 1)


End Sub

Determining the Color of a Single Pixel


The following code demonstrates graphics methods for determining the color of a pixel at a specified location in an image on a
form at run time, and then drawing a rectangle filled with that color. The Visual Basic 6.0 example uses the Point method to
retrieve the color value. The Visual Basic 2005 example uses the GetPixel method.
Note
In Visual Basic 6.0 the default unit of measurement is twips; in Visual Basic 2005, it is pixels.

' Visual Basic 6.0


Private Sub Form_Paint()
Dim PixelColor As Long
Picture1.Picture = LoadPicture("C:\Windows\Greenstone.bmp")
PixelColor = Picture1.Point(10, 10)
FillColor = PixelColor
Line (0, 0)-(100, 500), PixelColor, B
End Sub

VB
' Visual Basic 2005
Private Sub Form1_Paint9(ByVal sender As Object, ByVal e As _
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint

Dim Pict1 As New Bitmap("C:\Windows\Greenstone.bmp")


Picture1.Image = Pict1
Dim PixelColor As Color = Pict1.GetPixel(4, 4)
Dim PixelBrush As New SolidBrush(PixelColor)
e.Graphics.FillRectangle(PixelBrush, 0, 0, 100, 100)
End Sub

Graphics Property and Method Equivalencies


The following table lists Visual Basic 6.0 graphics properties and methods, along with their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
AutoRedraw property New implementation. To persist graphics, put graphics methods in the Paint event.

Circle method DrawEllipse method

ClipControls property New implementation. The ClipControls property is no longer necessary.

Cls method Clear method

CurrentX property The x parameter of various graphics methods. For example, DrawRectangle(pen, x, y, width, hei
ght)

CurrentY property The y parameter of various graphics methods. For example, DrawRectangle (pen, x, y, width,
height)

DrawMode property New implementation. The DrawMode property is no longer necessary.

DrawStyle property DashStyle property

DrawWidth property Width property

FillColor property SolidBrush object

FillStyle property HatchBrush object

HasDC property New implementation. Device contexts are no longer necessary with GDI+.

HDC property New implementation. Device contexts are no longer necessary with GDI+.

Image property New implementation.

Line method DrawLine method

PaintPicture method DrawImage method


Point method No direct equivalent. For bitmaps, use Bitmap.GetPixel. For forms or controls, use the
BackColor property.

Print method DrawString method

Pset method DrawEllipse, FillEllipse methods

TextHeight, TextWidth prope MeasureString method


rties

Upgrade Notes
When an application is upgraded from Visual Basic 6.0 to Visual Basic 2005, graphics methods are not upgraded, and warnings
are inserted into the code. Due to the considerable differences between GDI and GDI+, any existing graphics code will need to
be rewritten.
See Also
Tasks
Custom Drawing User Control Sample
Other Resources
Graphics Overview (Windows Forms)
Getting Started with Graphics Programming
About GDI+ Managed Code
Using Managed Graphics Classes
Visual Basic Concepts

Help Support for Visual Basic 6.0 Users


This topic compares support for implementing help in Visual Basic 6.0 with its equivalent in Visual Basic 2005.
Most applications provide help for users in the form of a Help file, pop-up Help, and / or ToolTips. While both Visual Basic 6.0
and Visual Basic 2005 support all three Help mechanisms, the methods of implementing them differ considerably.
Conceptual Differences
In Visual Basic 6.0, Help could be provided using either HTML Help or the older Windows Help format. In Visual Basic 2005,
only HTML Help is supported.
Help support in Visual Basic 6.0 was implemented on a per-project basis by specifying a Help file name in the Project
Properties dialog box. Each form and control had a HelpContextID property that could be used to link to a specific topic in
the Help file.
Help support in Visual Basic 2005 is implemented on a per-form basis by adding one or more HelpProvider components to a
form. Each form and control has HelpKeyword and HelpNavigator properties that were used to link to a specific topic. For
more information, see How to: Provide Help in a Windows Application.
Pop-up Help
Pop-up Help in Visual Basic 6.0 was implemented using the WhatsThisButton and WhatsThisHelp properties of a form. The
What's This button appeared if WhatsThisButton was True and both the MaxButton and MinButton properties were
False. Setting the WhatsThisMode property in code enabled the button.
Pop-up Help in Visual Basic 2005 is implemented using the HelpButton property of a form. The Help button only appears if the
HelpButton property is set to True and both the MaximizeBox and MinimizeBox properties are set to False; the button is
automatically enabled. For more information, see How to: Display Pop-up Help.
ToolTips
ToolTips in Visual Basic 6.0 were implemented using the ToolTipText property of a control.
ToolTips in Visual Basic 2005 are implemented by adding a ToolTip component to a form. For more information, see
ToolTip Support for Visual Basic 6.0 Users.
ShowHelp Method
In Visual Basic 6.0, Help could also be displayed using a ShowHelp method of a CommonDialog control to open Windows
Help. Windows Help is no longer supported in Visual Basic 2005 and there is no equivalent control for displaying Help.
Code Changes for Help Support
The following code illustrates the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005 for some
common uses of Help properties.
Specifying a Help file
The following example demonstrates how to specify a Help file for your application, assuming that your form has two
OptionButton controls that allow the user to choose between English and French Help files.
' Visual Basic 6.0
If Option1(0).Value = True Then
App.HelpFile = App.Path & "\EnglishHelp.chm"
Else
App.HelpFile = App.Path & "\FrenchHelp.chm"
End If

VB
' Visual Basic 2005
' Assumes a HelpProvider component has been added to the form.
If RadioButton1.Checked = True Then
HelpProvider1.HelpNamespace = My.Application.Info.DirectoryPath & _
"\EnglishHelp.chm"
Else
HelpProvider1.HelpNamespace = My.Application.Info.DirectoryPath & _
"\FrenchHelp.chm"
End If

Displaying a ToolTip
The following demonstrates code to display a ToolTip.
' Visual Basic 6.0
Private Sub Text1_Change()
Text1.ToolTipText = "The text has changed"
End Sub

VB
' Visual Basic 2005
' Assumes a ToolTip component has been added to the form.
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles TextBox1.TextChanged
ToolTip1.SetToolTip(TextBox1, "The text has changed")
End Sub

Help Support Equivalencies


Visual Basic 6.0 Visual Basic 2005
App.HelpFile property HelpProvider component

HelpContextID property SetHelpKeyword method. For more information, see


How to: Provide Help in a Windows Application.

ToolTipText property SetToolTip method. For more information, see ToolTip Support for Visual Basic 6.0 Users.

WhatsThisButton propert HelpButton property


y

WhatsThisHelp property HelpButton property

WhatsThisHelpID propert HelpString property


y

WhatsThisMode property No equivalent. Enabled by default.

Upgrade Notes
When a Visual Basic 6.0 project is upgraded using the upgrade wizard in Visual Basic 2005, any Help-related properties or code
will not be upgraded. You need to reimplement Help support for your application after upgrading. If your Help file was written
using HTML Help, you can reuse the Help file; if it was written using Windows Help it will need to be rewritten.
See Also
Tasks
How to: Provide Help in a Windows Application
How to: Display Pop-up Help
Concepts
ToolTip Support for Visual Basic 6.0 Users
Other Resources
Integrating User Help in Windows Forms
Visual Basic Concepts

Menu Handling for Visual Basic 6.0 Users


The techniques for creating and working with menus in Visual Basic 2005 differ considerably from Visual Basic 6.0
Conceptual Differences
In Visual Basic 6.0, menus were created using the Menu Editor. Menus could not be created programmatically, but could be
changed or added to programmatically.
In Visual Basic 2005, menus are created using a MenuStrip control, which provides a graphical menu designer. Menus can also
be created programmatically.
Context Menus
In Visual Basic 6.0, context menus were created by calling the PopupMenu method of a form or control. Menus could not be
created programmatically; the PopupMenu method required that a menu already existed.
In Visual Basic 2005, context menus are created using ContextMenuStrip controls, which provides a graphical menu designer;
they can also be created programmatically by creating a new instance of the ContextMenuStrip class. For more information,
see ContextMenuStrip Control Overview.
Merging Menus
In Visual Basic 6.0, the NegotiateMenus property of a form determined if a menu from an object on the form would be
merged with the form's menu. This property could only be set at design time.
In Visual Basic 2005, menus can be merged using the AllowMerge property of a MenuStrip or ContextMenuStrip control.
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, any existing menus are upgraded to MainMenu
components. Menus that were used as context menus must be manually changed to use ContextMenuStrip controls.
See Also
Concepts
Menu Object for Visual Basic 6.0 Users
Windows Forms for Visual Basic 6.0 Users
Other Resources
MenuStrip Control (Windows Forms)
Visual Basic Concepts

MDI for Visual Basic 6.0 Users


You can use both Visual Basic 6.0 and Visual Basic 2005 to create multiple-document interface (MDI) applications; however the
techniques for creating them and some of their behaviors differ.
Conceptual Differences
In Visual Basic 6.0, multiple-document interface (MDI) applications are created by adding an MDI form to a project and then
setting the MDIChild property of any child forms.
Visual Basic 2005 does not have an MDI form; any form can be made into an MDI parent by setting the IsMdiContainer
property to True.
Many of the properties and methods that applied to Visual Basic 6.0 MDI forms have changed in Visual Basic 2005. For more
information, see MDIForm Object for Visual Basic 6.0 Users.
The behavior of MDI applications has also changed. In Visual Basic 6.0, an MDI application having a form that is not an MDI
child does not end until that form is closed, even if the MDI parent is closed. In Visual Basic 2005, the application ends when
the startup form is closed, regardless of any non-MDI forms in the application.
See Also
Concepts
MDIForm Object for Visual Basic 6.0 Users
Windows Forms for Visual Basic 6.0 Users
Other Resources
Multiple-Document Interface (MDI) Applications
Help for Visual Basic 6.0 Users
Visual Basic Concepts

Printing Changes for Visual Basic 6.0 Users


Visual Basic 2005 provides greatly improved support for printing through classes that control the printing of documents, that
allow users to modify print settings and choose printers, and that allow print preview.
Conceptual Differences
Printer Object
In Visual Basic 6.0, the Printer object is used for printing; it supports various graphics methods such as Print, Line, and
PaintPicture to control what is printed.
In Visual Basic 2005, the PrintDocument component replaces the Printer object. Equivalent graphics methods include the
DrawString, DrawLine, and DrawImage methods of the Graphics class.
For more information, see Printer Object for Visual Basic 6.0 Users.
Printers Collection
In Visual Basic 6.0, the Printers collection is used to direct the output of a Printer object to a different printer. The Printers
collection contains a list of available printers that match the list displayed in the Windows Print dialog box.
In Visual Basic 2005, the Printers collection is replaced by the PrintDialog control, which provides a standard Windows Print
dialog box.
For more information, see Printers Collection for Visual Basic 6.0 Users.
PrintForm Method
In Visual Basic 6.0, the PrintForm method of a form can be used to send an image of the form to a printer. The PrintForm
method is no longer supported in Visual Basic 2005.
The results of the PrintForm method vary greatly depending on the screen resolution and the resolution of the printer; it is not
the recommended method of printing. If you need to duplicate the functionality of the PrintForm method, you can automate
the screen capture capabilities of a third-party graphics tool to capture and print an image of a form.
Print Preview
In Visual Basic 6.0, implementing print preview is only possible through third-party controls. In Visual Basic 2005, the
PrintPreviewDialog control can be used to provide a standard Windows Print Preview dialog box. For more information, see
PrintPreviewDialog Control Overview (Windows Forms).
Page Setup
In Visual Basic 6.0, no user interface for page setup is provided. In Visual Basic 2005, the PageSetupDialog control can be used
to provide a standard Windows Page Setup dialog box. For more information, see
PageSetupDialog Component Overview (Windows Forms).
Printing From A File
In Visual Basic 6.0, printing text from a file requires a considerable amount of code. In Visual Basic 2005, the StreamReader
class can be used to pass the contents of a text file directly to a PrintDocument component. For more information, see the
Print method of the PrintDocument class.
See Also
Concepts
Printer Object for Visual Basic 6.0 Users
Printers Collection for Visual Basic 6.0 Users
Other Resources
Windows Forms Print Support
Visual Basic Concepts

ToolTip Support for Visual Basic 6.0 Users


The methods for displaying ToolTips differ considerably between Visual Basic 6.0 and Visual Basic 2005.
Conceptual Differences
In Visual Basic 6.0, the ToolTipText property of a control is used to display a ToolTip at run time.
In Visual Basic 2005, a single ToolTip component can be used to control the ToolTips for all controls on a form; the ToolTip
component can be added to a form from the Toolbox. The SetToolTip method is used to set the text for each ToolTip based
on the name of the control.
Hiding ToolTips
In Visual Basic 6.0, if the ToolTipText property contains text, the ToolTip is displayed; if it is empty, no ToolTip is displayed. To
clear the text of multiple ToolTips, you need to loop through the Controls collection and set the ToolTipText property to an
empty string.
In Visual Basic 2005, you can prevent the ToolTip from being displayed by passing an empty string to the SetToolTip method;
you can clear the text of all ToolTips associated with a ToolTip component by setting the Active property to false.
Customizing ToolTips
In Visual Basic 6.0, there is no way to customize a ToolTip without resorting to Windows API calls.
In Visual Basic 2005, there are a number of new properties that allow you to customize the appearance or behavior of a
ToolTip—for example, changing the colors, setting a delay before displaying a ToolTip, or creating multi-line ToolTips.
Code Changes for ToolTips
The following code examples illustrate the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Displaying a ToolTip
The following example demonstrates setting a ToolTip for a Button control in Visual Basic 6.0 and Visual Basic 2005. The
Visual Basic 2005 example assumes that a ToolTip component was added to the form at design time.

' Visual Basic 6.0


Button1.ToolTipText = "Save changes"

VB
' Visual Basic 2005
ToolTip1.SetToolTip(Button1, "Save changes")

Code Changes for Hiding a ToolTip


The following example demonstrates hiding a ToolTip for a Button control in Visual Basic 6.0 and Visual Basic 2005. The Visual
Basic 2005 example assumes that a ToolTip component was added to the form at design time.
Note
The Visual Basic 2005 ToolTip component also has an Active property; setting this property to false will hide the ToolTips f
or all controls associated with that ToolTip component.

' Visual Basic 6.0


' Hide a single ToolTip.
Button1.ToolTipText = ""
' Hide all ToolTips.
For Each Control in Me.Controls
Control.ToolTipText = ""
Next

VB
' Visual Basic 2005
' Hide a single ToolTip.
ToolTip1.SetToolTip(Button1, "")
' Hide all ToolTips.
ToolTip1.Active = False

Upgrade Notes
When a Visual Basic 6.0 is upgraded to Visual Basic 2005, any references to the ToolTipText property at either design time or
run time are not upgraded, and comments are inserted into your code. A ToolTip component named ToolTip1 is added to
your form; you will need to hook up your ToolTips by either setting the ToolTip on ToolTip1 property at design time or
calling the SetToolTip method at run time.
If the Visual Basic 6.0 application uses Windows API calls to customize ToolTips, you should modify your code to take
advantage of the customization features of the ToolTip component.
See Also
Reference
ToolTip Component Overview (Windows Forms)
Other Resources
Windows Forms Controls for Visual Basic 6.0 Users
Visual Basic Concepts

Version Numbering for Visual Basic 6.0 Users


The version numbering scheme for Visual Basic 2005 differs from that used in Visual Basic 6.0, and the methods for setting
and retrieving version numbers differ as well.
Conceptual Differences
In Visual Basic 6.0, setting the Major, Minor, and Revision properties of the App object control the version number for an
application. For example, setting Major to 1, Minor to 2, and Revision to 3 results in a version number of 1.2.0.3. The third
part of the version number (0) cannot be seen in Visual Basic; however it is visible when you look at the properties of a file
compiled by Visual Basic 6.0.
In Visual Basic 2005, the version-number properties are replaced by an AssemblyVersion attribute, which has four parts:
Major, Minor, Build, and Revision. For the above example, the resulting version number would be 1.2.x.4, where x is the build
number. Note that the Revision value is now the fourth part of the version number.
Setting Version Properties
In Visual Basic 6.0, version-number properties are set in the Project Properties dialog box; in Visual Basic 2005 they are set in
the Assembly Information dialog box, available by clicking the Assembly Information button on the Application tab of the
Project Designer.
Note
Visual Basic 6.0 version-number properties are stored in the Project (.vbp) file and can also be edited directly using a text edit
or such as Notepad. Assembly attributes are stored in the AssemblyInfo.vb file and can also be edited directly in the Code Edi
tor.

Code Changes for Version Numbering


The following code example illustrates the differences in coding techniques between Visual Basic 6.0 and Visual Basic 2005.
Code Changes for Displaying an Application's Version Number
The following example demonstrates retrieving an application's version number and displaying it in a label.
' Visual Basic 6.0
Label1.Caption = "Version: " & App.Major & "." & App.Minor & "." _
& App.Revision

VB
'Visual Basic 2005
Label1.Text = My.Application.Info.Version.ToString()

Version Number Property Equivalencies


The following table lists Visual Basic 6.0 version-number properties and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005
No equivalent My.Application.AppInfo.Version.Build

Major My.Application.AppInfo.Version.Major

Minor My.Application.AppInfo.Version.Minor
Revision My.Application.AppInfo.Version.Revision
Note
In Visual Basic 6.0, Revision is the fourth part of the version number; in Visual Basic 2005, it is the third par
t.

Upgrade Notes
When an application is upgraded from Visual Basic 6.0, only the Major and Minor properties are upgraded; Visual Basic 2005
assigns new values for the Revision and Build properties.
See Also
Concepts
App Object for Visual Basic 6.0 Users
Visual Basic Concepts

How to: Add Visual Basic 6.0 File System Controls to Your
Application
We recommend that you use the OpenFileDialog and SaveFileDialog components to provide access to the file system;
however, if you find it necessary to create your own file dialog boxes, Visual Basic 2005 provides DirListBox, DriveListBox,
and FileListBox controls as part of the Microsoft Visual Basic Compatibility Runtime library.
You can add a DirListBox, DriveListBox, or FileListBox to a Windows Application project using the following procedures.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

Adding Controls to Your Project


To add a reference to the Compatibility library
1. On the Project menu, choose Add Reference.
2. In the Add Reference dialog box, click the .NET tab. Under the Component Name list, choose
Microsoft.VisualBasic.Compatibility, and then click OK.
A reference will be added to your project.
To add the controls to the Toolbox
1. On the View menu, choose Toolbox.
2. Expand the All Windows Forms section. Right-click its title bar and then click Choose Items.
3. In the Choose Toolbox Items dialog box, check the DirListBox, DriveListBox, and FileListBox components, and then
click OK.
The controls will be added to the Toolbox; they can be used like any other Windows Forms control.
Note
Once added, the controls will remain in the Toolbox until you explicitly remove them.

See Also
Reference
OpenFileDialog Component Overview (Windows Forms)
SaveFileDialog Component Overview (Windows Forms)
Concepts
DirListBox Control for Visual Basic 6.0 Users
DriveListBox Control for Visual Basic 6.0 Users
FileListBox Control for Visual Basic 6.0 Users
Visual Basic Concepts

Debugging for Visual Basic 6.0 Users


Although the process of debugging an application in Visual Basic 2005 is essentially the same as in Visual Basic 6.0, there are a
few minor differences. In addition, there are several new features related to debugging in Visual Basic 2005. For more
information, see Debugging Your Visual Basic Application.
Conceptual Differences
Setting Watches
In Visual Basic 6.0, watches can be set at design time, or at run time when in break mode. In Visual Basic 2005, watches can be
set only in break mode.
Compilation Errors
In Visual Basic 6.0, compilation errors cause an error-message dialog box to be displayed during debugging.
In Visual Basic 2005, compilation errors are highlighted in the Code Editor window with a blue underline. If you attempt to
debug the application before fixing an error , a build-error warning is displayed and the error appears in the Task List window.
Run Time Exceptions
In Visual Basic 6.0, when an exception occurs during debugging, a modal dialog box is displayed with an error number.
Dismissing the dialog box takes you to the offending line of code in the Code Editor.
In Visual Basic 2005, exceptions cause the non-modal Exception Assistant to be displayed in the Code Editor. The
Exception Assistant shows the type of exception and gives troubleshooting tips and corrective actions. For more information,
see Exception Assistant.
Keyboard Shortcuts for Debugging
In Visual Studio, some of the keyboard shortcuts for debugging are different for different languages; you can customize the
settings to match your preferences.
When you first run Visual Basic 2005, you are asked to choose your development settings. If you choose Visual Basic
Settings, the keyboard shortcuts will match those used in Visual Basic 6.0.
Note
If your keyboard shortcuts do not match the Visual Basic 6.0 settings, you can apply the Visual Basic Settings in the Import
and Export Settings Wizard, available from the Tools menu. For more information, see How to: Change Select Settings.

See Also
Concepts
Debugging Your Visual Basic Application
Integrated Development Environment for Visual Basic 6.0 Users
Other Resources
Help for Visual Basic 6.0 Users
Visual Basic Concepts

Setup and Deployment for Visual Basic 6.0 Users


The methods for deploying applications and components in Visual Basic 2005 are considerably different than in Visual Basic
6.0.
Conceptual Differences
In Visual Basic 6.0, the Package and Deployment Wizard is used to create Setup programs (.exe files) to distribute and
install your application.
Note
Later releases of Visual Studio 6.0 also include the Visual Studio Installer add-in, which can be used to create Windows Install
er files (.msi files). Projects created with Visual Studio Installer are not compatible with Visual Basic 2005.

Visual Basic 2005 provides two different strategies for deploying Windows-based applications: publishing an application using
ClickOnce technologies, or deploying it by means of traditional Setup using Windows Installer technologies
With ClickOnce deployment, you publish the application to a centralized location (usually a Web server or file share), and the
user installs or runs the application from that location. ClickOnce applications can be self-updating—when you publish an
update to the application, end users can automatically download the update— ensuring that everyone is using the same
version. For more information, see ClickOnce Deployment.
With Windows Installer deployment, you use a Setup and Deployment project to package the application in a Setup.exe file and
distribute that file to users, who run the Setup.exe file to install the application. For more information, see
Windows Installer Deployment.
Note
Visual Basic Express Edition only supports ClickOnce deployment.

Prerequisites and Dependencies


In Visual Basic 6.0, information regarding file dependencies for an application is stored in dependency (.dep) files; all
applications require the Visual Basic runtime file as a prerequisite and many require other prerequisites, such as data libraries.
Determining the complete list of dependencies and prerequisites often requires manually editing the Vb6dep.ini file.
In Visual Basic 2005, both ClickOnce deployment and Windows Installer deployment can automatically determine and package
all dependencies for your application. Prerequisites such as the .NET Framework runtime library can also be automatically
installed with either type of deployment, and you can bootstrap (install along with your application) any other prerequisites.
For more information, see Deploying Prerequisites (Visual Studio).
Upgrade Notes
When you upgrade a Visual Basic 6.0 application to Visual Basic 2005, any deployment information is lost. You will need to
implement a new deployment using either ClickOnce or Windows Installer.
See Also
Concepts
Choosing a Deployment Strategy
Other Resources
Deploying Applications and Components
Visual Basic Concepts

Localization and Globalization for Visual Basic 6.0 Users


Both Visual Basic 6.0 and Visual Basic 2005 provide support for international applications. However, the concepts and
techniques for localizing and globalizing an application are different.
Conceptual Differences
Localizing Resources
In Visual Basic 6.0, international versions of an application are created by putting all localizable information, such as strings,
into a separate resource file (.res) for each language. At run time, locale-specific resources are loaded from the resource file by
calling the LoadResString, LoadResPicture, and LoadResData functions.
In Visual Basic 2005, international versions of an application are created by changing the Language property of a form at
design time. A separate resource file (.resx) is automatically created for each locale selected. You no longer need to explicitly
load resources from code; resources are automatically loaded based on the user's locale. For more information, see
Globalizing Windows Forms.
Editing Resources
In Visual Basic 6.0, resource files can be edited using the resource editor add-in or the Visual C++ resource editors.
In Visual Basic 2005, the Resource Editor is built into the IDE as a part of the Project Designer. For more information, see
Managing Application Resources.
Unicode
In Visual Basic 6.0, strings are represented internally as Unicode characters but are displayed using Windows code pages. The
StrConv function, along with binary and Unicode versions of string manipulation functions (for example, ChrB and ChrW), are
necessary to convert between ANSI and DBCS code pages.
In Visual Basic 2005, forms are entirely Unicode-enabled; conversion between code pages is no longer required. For more
information, see Encoding and Windows Forms Globalization.
Date and Currency Formatting
In Visual Basic 6.0, the formatting of dates and currency in code requires special consideration; values entered as text can be
incorrectly interpreted when converted to dates or currency in localized applications.
In Visual Basic 2005, dates and currency are automatically formatted according to the user's culture. You can override the
settings, if necessary, through functions in the System.Globalization namespace. For more information, see
Culture-Specific Classes for Global Windows Forms and Web Forms.
See Also
Tasks
How to: Retrieve Localized Resources in Visual Basic
Concepts
Introduction to International Applications Based on the .NET Framework
Deployment and Localization
Other Resources
Globalizing and Localizing Applications
Globalization and Localization Namespaces in Visual Studio
Visual Basic Concepts

Windows API Programming for Visual Basic 6.0 Users


The use of Windows APIs is generally not necessary in Visual Basic 2005, and the techniques for calling them differ somewhat
from those used in Visual Basic 6.0.
Conceptual Differences
In Visual Basic 6.0, it was often necessary to call Windows APIs in order to provide advanced functionality that Visual Basic
itself did not provide.
Visual Basic 2005 incorporates the .NET Framework; in most cases, Windows API calls are no longer necessary because much
of the functionality of the Windows API is wrapped up in the .NET Framework.
Declaring Windows API's
In Visual Basic 6.0, the Declare statement is used to call the Windows API in order to access functionality not provided by
Visual Basic.
In Visual Basic 2005, you can still use the Declare statement to call an API, but there are some differences to be aware of. For
example, some of the data types in Visual Basic 2005 have no direct equivalent; they must be marshaled in order to be passed
to an API call. For more information, see Walkthrough: Calling Windows APIs.
Upgrade Notes
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, calls to Windows APIs are upgraded in place—they are
not replaced with their.NET Framework equivalents. When data-type issues are encountered, upgrade warnings are added to
your code and to the upgrade report. In most cases you will want to replace these API calls with their .NET Framework
equivalents.
See Also
Reference
Declare Statement
Concepts
Data Type Changes for Visual Basic 6.0 Users
Other Resources
Help for Visual Basic 6.0 Users
Visual Basic Concepts

Registry Access for Visual Basic 6.0 Users


Techniques for accessing the registry in Visual Basic 2005 differ from those used in Visual Basic 6.0.
Conceptual Differences
In Visual Basic 6.0, you can access the registry using the GetSetting or SaveSetting functions, which provide access to a
limited set of registry keys. To access other registry keys, calls to the Windows API are required.
Visual Basic 2005 supplies the My.Computer.Registry object, which provides access to registry keys. For more information,
see Reading from and Writing to the Registry Using My.
In addition, complete access to the registry is provided by means of the Registry class in the .NET Framework.
Note
In Visual Basic 2005, the GetSetting and SaveSetting functions are still supported for limited registry access. For more info
rmation, see Registry Summary.

Registry Access and Deployment


In Visual Basic 6.0, files can be marked for registration during installation by manually editing the Setup.lst file.
In Visual Basic 2005, Setup and Deployment Projects provide full support for working with the registry during installation. For
more information, see Deployment and the Registry.
See Also
Tasks
Walkthrough: Creating a Registry Key and Changing Its Values
Troubleshooting: Manipulating the Registry
Reference
Registry Class
My.Computer.Registry Object
Concepts
Common Registry Tasks
Reading from and Writing to the Registry Using My
Reading from and Writing to the Registry Using the Microsoft.Win32 Namespace
Security and the Registry
Visual Basic Concepts

Constant Equivalents for Visual Basic 6.0 Users


In Visual Basic 6.0, numerous constants were defined in the Visual Basic language. In Visual Basic 2005, most of the constants
are replaced by enumerations in the .NET Framework; in many cases the Visual Basic 6.0 constants may still be used as well.
The following links will take you to topics that show the mappings between Visual Basic 6.0 constants and their Visual Basic
2005 equivalents.
Note
If a constant is not listed, there is no equivalent. For example, DDE (Dynamic Data Exchange) constants are not listed because
DDE is not supported in Visual Basic 2005.

In This Section
Align Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Align constants and their Visual Basic 2005 equivalents.
Alignment Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Alignment constants and their Visual Basic 2005 equivalents.
Arrange Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Arrange constants and their Visual Basic 2005 equivalents.
BorderStyle Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 BorderStyle constants and their Visual Basic 2005 equivalents.
CallType Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 CallType constants and their Visual Basic 2005 equivalents.
CheckBox Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 CheckBox constants and their Visual Basic 2005 equivalents.
Color Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Color constants and their Visual Basic 2005 equivalents.
CompareMethod Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 CompareMethod constants and their Visual Basic 2005 equivalents.
Date Format Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 DateFormat constants and their Visual Basic 2005 equivalents.
DayOfWeek Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 DayOfWeek constants and their Visual Basic 2005 equivalents.
File Attribute Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 FileAttribute constants and their Visual Basic 2005 equivalents.
IMEMode Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 IMEMode constants and their Visual Basic 2005 equivalents.
Key Code Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Key Code constants and their Visual Basic 2005 equivalents.
Mouse Pointer Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Mouse Pointer constants and their Visual Basic 2005 equivalents.
MsgBox Result Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 MsgBox Result constants and their Visual Basic 2005 equivalents.
MsgBox Style Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 MsgBox Style constants and their Visual Basic 2005 equivalents.
MultiSelect Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 MultiSelect constants and their Visual Basic 2005 equivalents.
OLEDropEffect Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 OLEDropEffect constants and their Visual Basic 2005 equivalents.
ScrollBar Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 ScrollBar constants and their Visual Basic 2005 equivalents.
StartUpPosition Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 StartUpPosition constants and their Visual Basic 2005 equivalents.
StrConv Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 StrConv constants and their Visual Basic 2005 equivalents.
Style Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Style constants and their Visual Basic 2005 equivalents.
System Color Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 System Color constants and their Visual Basic 2005 equivalents.
TriState Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 TriState constants and their Visual Basic 2005 equivalents.
Variant Type Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Variant Type constants and their Visual Basic 2005 equivalents.
VarType Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 VarType constants and their Visual Basic 2005 equivalents.
VBA Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Visual Basic for Applications constants and their Visual Basic 2005 equivalents.
WeekOfYear Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 WeekOfYear constants and their Visual Basic 2005 equivalents.
WindowState Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 WindowState constants and their Visual Basic 2005 equivalents.
WindowStyle Constants for Visual Basic 6.0 Users
Lists Visual Basic 6.0 Window Style constants and their Visual Basic 2005 equivalents.
Related Sections
Constants and Enumerations in Visual Basic
Introduces Visual Basic 2005 enumerations.
Windows Forms Controls for Visual Basic 6.0 Users
Provides links to topics describing the differences between Visual Basic 6.0 and Windows Forms controls and objects.
Language Changes for Visual Basic 6.0 Users
Describes changes to the Visual Basic language.
Visual Basic Reference

Align Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 Align constants and values and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
VbAlignNone (0) None

VbAlignTop (1) Top

VbAlignBottom (2) Bottom

VbAlignLeft (3) Left

VbAlignRight (4) Right


See Also
Concepts
PictureBox Control for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

Alignment Constants for Visual Basic 6.0 Users


The following tables show the Visual Basic 6.0 Alignment constants and values and their Visual Basic 2005 equivalents.
CheckBox and OptionButton Alignment Constants
Visual Basic 6.0 Visual Basic 2005
VbLeftJustify (0) MiddleLeft

VbRightJustify (1) MiddleRight


TextBox Alignment Constants
Visual Basic 6.0 Visual Basic 2005
VbLeftJustify (0) Left

VbRightJustify (1) Right

VbCenter (2) Center


Label Alignment Constants
Visual Basic 6.0 Visual Basic 2005
VbLeftJustify (0) TopLeft

VbRightJustify (1) TopRight

VbCenter (2) TopCenter


See Also
Concepts
CheckBox Control for Visual Basic 6.0 Users
OptionButton Control for Visual Basic 6.0 Users
TextBox Control for Visual Basic 6.0 Users
Label Control for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

Arrange Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 Arrange constants and values and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
VbCascade (0) Cascade

VbTileHorizontal (1) TileHorizontal

VbTileVertical (2) TileVertical

VbArrangeIcons (3) ArrangeIcons


See Also
Concepts
MDIForm Object for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

BorderStyle Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 BorderStyle constants and values and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
VbBSNone (0) None

VbFixedSingle (1) FixedSingle

VbSizable (2) Sizable

VbFixedDialog (3) FixedDialog

VbFixedToolWindow (4) FixedToolWindow

VbSizableToolWindow (5) SizableToolWindow


See Also
Concepts
Form Object for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

CallType Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 CallType constants and their Visual Basic 2005 equivalents.
Note
For backward compatibility, you can still use the Visual Basic 6.0 CallType constants in Visual Basic 2005 code. For more info
rmation, see CallType Enumeration.

Visual Basic 6.0 Visual Basic 2005 Equivalent


vbMethod CallType.Method

vbGet CallType.Get

vbSet CallType.Set

vbLet CallType.Let
See Also
Reference
CallByName Function
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

CheckBox Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 CheckBox constants and values and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
vbUnchecked (0) Unchecked

vbChecked (1) Checked

vbGrayed (2) Indeterminate


See Also
Concepts
CheckBox Control for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

Color Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 Color constants and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
vbBlack Black

vbRed Red

vbGreen Lime

vbYellow Yellow

vbBlue Blue

vbMagenta Magenta

vbCyan Cyan

vbWhite White
See Also
Reference
Color Handling for Visual Basic 6.0 Users
System Color Constants for Visual Basic 6.0 Users
Concepts
Color Behavior for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations (Visual Basic)
Visual Basic Reference

CompareMethod Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 Compare constants and their Visual Basic 2005 equivalents.
Note
For backward compatibility, the Visual Basic 6.0 Compare constants can also be used in Visual Basic 2005. For more informa
tion, see CompareMethod Enumeration.

Visual Basic 6.0 Visual Basic 2005 Equivalent


vbBinaryCompare CompareMethod.Binary

vbTextCompare CompareMethod.Text

vbDatabaseCompare No equivalent
See Also
Reference
CompareMethod Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

Date Format Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 Date Format constants and their Visual Basic 2005 equivalents.
Note
For backward compatibility, you can still use Visual Basic 6.0 Date Format constants in Visual Basic 2005 code. For more inf
ormation, see DateFormat Enumeration.

Visual Basic 6.0 Visual Basic 2005 Equivalent


vbGeneralDate DateFormat.GeneralDate

vbLongDate DateFormat.LongDate

vbShortDate DateFormat.ShortDate

vbLongTime DateFormat.LongTime

vbShortTime DateFormat.ShortTime
See Also
Reference
DateFormat Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

DayOfWeek Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 DayOfWeek constants and their Visual Basic 2005 equivalents.
Note
For backward compatibility, the Visual Basic 6.0 DayOfWeek constants can be used in Visual Basic 2005 code. For more info
rmation, see FirstDayOfWeek Enumeration.

Visual Basic 6.0 Visual Basic 2005 Equivalent


VbUseSystemDayOfWeek FirstDayOfWeek.System

vbSunday FirstDayOfWeek.Sunday

vbMonday FirstDayOfWeek.Monday

vbTuesday FirstDayOfWeek.Tuesday

vbWednesday FirstDayOfWeek.Wednesday

vbThursday FirstDayOfWeek.Thursday

vbFriday FirstDayOfWeek.Friday

vbSaturday FirstDayOfWeek.Saturday
See Also
Reference
FirstDayOfWeek Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

File Attribute Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 File Attribute constants and their Visual Basic 2005 equivalents.
Note
For backward compatibility, you can still use Visual Basic 6.0 File Attribute constants in your Visual Basic 2005 code. For mo
re information, see FileAttribute Enumeration.

Visual Basic 6.0 Visual Basic 2005 Equivalent


vbNormal FileAttribute.Normal

vbReadOnly FileAttribute.ReadOnly

vbHidden FileAttribute.Hidden

vbSystem FileAttribute.System

vbVolume FileAttribute.Volume

vbDirectory FileAttribute.Directory

vbArchive FileAttribute.Archive

vbAlias No equivalent
See Also
Reference
FileAttribute Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

IMEMode Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 IMEMode constants and values and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
vbIMEAlphaDbl (7) AlphaFull

vbIMEAlphaSng (8) Alpha

vbIMEDisable (3) Disable

vbIMEHiragana (4) Hiragana

vbIMEKatakanaDbl (5) Katakana

vbIMEKatakanaSng (6) KatakanaHalf

vbIMEModeAlpha (8) Alpha

vbIMEModeAlphaFull (7) AlphaFull

vbIMEModeDisable (3) Disable

vbIMEModeHangul (10) Hangul

vbIMEModeHangulFull (9) HangulFull

vbIMEModeHiragana (4) Hiragana

vbIMEModeKatakana (5) Katakana

vbIMEModeKatakanaHalf (6) KatakanaHalf

vbIMEModeNoControl (0) NoControl

vbIMEModeOff (2) Off

vbIMEModeOn (1) On

vbIMENoOp (0) NoControl

vbIMEOff (2) Off

vbIMEOn (1) On
See Also
Concepts
Form Object for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

Key Code Constants for Visual Basic 6.0 Users


The following tables show the Visual Basic 6.0 Key Code constants and values and their Visual Basic 2005 equivalents.
Key Code Constants
Visual Basic 6.0 Visual Basic 2005 Equivalent
vbKeyLButton (1) LButton

vbKeyRButton (2) RButton

vbKeyCancel (3) Cancel

vbKeyMButton (4) MButton

vbKeyBack (8) Back

vbKeyTab (9) Tab

vbKeyClear (12) Clear

vbKeyReturn (13) Return

vbKeyShift (16) ShiftKey

vbKeyControl (17) ControlKey

vbKeyMenu (18) Menu

vbKeyPause (19) Pause

vbKeyCapital (20) Capital

vbKeyEscape (27) Escape

vbKeySpace (32) Space

vbKeyPageUp (33) PageUp

vbKeyPageDown (34) PageDown

vbKeyEnd (35) End

vbKeyHome (36) Home

vbKeyLeft (37) Left

vbKeyUp (38) Up

vbKeyRight (39) Right

vbKeyDown (40) Down


vbKeySelect (41) Select

vbKeyPrint (42) Print


vbKeyExecute (43) Execute

vbKeySnapshot (44) Snapshot

vbKeyInsert (45) Insert

vbKeyDelete (46) Delete

vbKeyHelp (47) Help

vbKeyNumlock (144) Numlock

vbKeyScrollLock (145) Scroll


Alphabetic Key Code Constants
Visual Basic 6.0 Visual Basic 2005 Equivalent
VbKeyA (65) A

VbKeyB (66) B

VbKeyC (67) C

VbKeyD (68) D

VbKeyE (69) E

VbKeyF (70) F

VbKeyG (71) G

VbKeyH (72) H

VbKeyI (73) I

VbKeyJ (74) J

VbKeyK (75) K

VbKeyL( 76) L

vbKeyM (77) M

VbKeyN (78) N

VbKeyO (79) O

VbKeyP( 80) P

VbKeyQ (81) Q
VbKeyR (82) R

VbKeyS (83) S

VbKeyT (84) T

VbKeyU (85) U

VbKeyV (86) V

VbKeyW (87) W

VbKeyX (88) X

VbKeyY (89) Y

VbKeyZ (90) Z
Numeric Key Constants
Visual Basic 6.0 Visual Basic 2005 Equivalent
vbKey0 (48) D0

vbKey1 (49) D1

vbKey2 (50) D2

vbKey3 (51) D3

vbKey4 (52) D4

vbKey5 (53) D5

vbKey6 (54) D6

vbKey7 (55) D7

vbKey8 (56) D8

vbKey9 (57) D9
Numeric Keypad Key Constants
Visual Basic 6.0 Visual Basic 2005 Equivalent
vbKeyNumpad0 (96) NumPad0

vbKeyNumpad1 (97) NumPad1

vbKeyNumpad2 (98) NumPad2

vbKeyNumpad3 (99) NumPad3

vbKeyNumpad4 (100) NumPad4

vbKeyNumpad5 (101) NumPad5


vbKeyNumpad6 (102) NumPad6

vbKeyNumpad7 (103) NumPad7


vbKeyNumpad8 (104) NumPad8

vbKeyNumpad9 (105) NumPad9

VbKeyMultiply (106) Multiply

VbKeyAdd (107) Add

VbKeySeparator (108) Separator

VbKeySubtract (109) Subtract

VbKeyDecimal (110) Decimal

VbKeyDivide (111) Divide


Function Key Constants
Visual Basic 6.0 Visual Basic 2005 Equivalent
vbKeyF1 (112) F1

vbKeyF2 (113) F2

vbKeyF3 (114) F3

vbKeyF4 (115) F4

vbKeyF5 (116) F5

vbKeyF6 (117) F6

vbKeyF7 (118) F7

vbKeyF8 (119) F8

vbKeyF9 (120) F9

vbKeyF10 (121) F10

vbKeyF11 (122) F11

vbKeyF12 (123) F12

vbKeyF13 (124) F13

vbKeyF14 (125) F14

vbKeyF15 (126) F15

vbKeyF16 (127) F16


See Also
Reference
Keys Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

Mouse Pointer Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 Mouse Pointer constants and values and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
VbDefault (0) Default

VbArrow (1) Arrow

VbCrosshair (2) Cross

VbIbeam (3) IBeam

VbIconPointer (4) Obsolete. Replaced by Default

VbSizePointer (5) SizeAll

VbSizeNESW (6) SizeNESW

VbSizeNS (7) SizeNS

VbSizeNWSE (8) SizeNWSE

VbSizeWE (9) SizeWE

VbUpArrow (10) UpArrow

VbHourglass (11) WaitCursor

VbNoDrop (12) No

VbArrowHourglass (13) AppStarting

VbArrowQuestion (14) Help

VbSizeAll (15) SizeAll

VbCustom (99) Cannot set a custom MousePointer No equivalent. For details, see Cannot set a custom MousePointer
See Also
Concepts
MousePointer for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

MsgBox Result Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 MsgBox Result constants and their Visual Basic 2005 equivalents.
Note
For backward compatibility, you can still use Visual Basic 6.0 MsgBox Result constants in Visual Basic 2005 code. For more i
nformation, see MsgBoxResult Enumeration.

Visual Basic 6.0 Visual Basic 2005 Equivalent


vbOK MsgBoxResult.OK

vbCancel MsgBoxResult.Cancel

vbAbort MsgBoxResult.Abort

vbRetry MsgBoxResult.Retry

vbIgnore MsgBoxResult.Ignore

vbYes MsgBoxResult.Yes

vbNo MsgBoxResult.No
See Also
Reference
MsgBoxResult Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

MsgBox Style Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 MsgBox Style constants and their Visual Basic 2005 equivalents.
Note
For backward compatibility, you can still use Visual Basic 6.0 MsgBox Style constants in Visual Basic 2005 code. For more in
formation, see MsgBoxStyle Enumeration.

Visual Basic 6.0 Visual Basic 2005 Equivalent


vbOKOnly MsgBoxStyle.OKOnly

vbOKCancel MsgBoxStyle.OKCancel

vbAbortRetryIgnore MsgBoxStyle.AbortRetryIgnore

vbYesNoCancel MsgBoxStyle.YesNoCancel

vbYesNo MsgBoxStyle.YesNo

vbRetryCancel MsgBoxStyle.RetryCancel

vbCritical MsgBoxStyle.Critical

vbQuestion MsgBoxStyle.Question

vbExclamation MsgBoxStyle.Exclamation

vbInformation MsgBoxStyle.Information

vbDefaultButton1 MsgBoxStyle.DefaultButton1

vbDefaultButton2 MsgBoxStyle.DefaultButton2

vbDefaultButton3 MsgBoxStyle.DefaultButton3

vbDefaultButton4 No equivalent

vbApplicationModal MsgBoxStyle.ApplicationModal

vbSystemModal MsgBoxStyle.SystemModal

vbMsgBoxHelpButton MsgBoxStyle.MsgBoxHelp

vbMsgBoxRight MsgBoxStyle.MsgBoxRight

vbMsgBoxRtlReading MsgBoxStyle.MsgBoxRtlReading

vbMsgBoxSetForeground MsgBoxStyle.MsgBoxSetForeground
See Also
Reference
MsgBoxStyle Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

MultiSelect Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 MultiSelect constants and values and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
vbMultiSelectNone (0) One

vbMultiSelectSimple (1) MultiSimple

vbvbMultiSelectExtended (2) MultiExtended


See Also
Concepts
ListBox Control for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

OLEDropEffect Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 OLEDropEffect constants and values and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
VbDropEffectNone (0) None

VbDropEffectCopy (1) Copy

VbDropEffectMove (2) Move

VbDropEffectScroll (&H80000000) Scroll


See Also
Concepts
Drag and Drop for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

ScrollBar Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 ScrollBar constants and values and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
vbSBNone (0) None

vbHorizontal (1) Horizontal

vbVertical (2) Vertical

vbBoth (3) Both


See Also
Concepts
Form Object for Visual Basic 6.0 Users
PictureBox Control for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

StartUpPosition Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 StartUpPosition constants and values and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
vbStartUpManual (0) Manual

vbStartUpOwner (1) CenterParent

vbStartUpScreen (2) CenterScreen

vbStartUpWindowsDefault (3) WindowsDefaultLocation


See Also
Concepts
Form Object for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

StrConv Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 StrConv constants and their Visual Basic 2005 equivalents.
Note
For backward compatibility, you can still use Visual Basic 6.0 StrConv constants in Visual Basic 2005 code. For more informa
tion, see VbStrConv Enumeration.

Visual Basic 6.0 Visual Basic 2005 Equivalent


vbUpperCase VbStrConv.UpperCase

vbLowerCase VbStrConv.LowerCase

vbProperCase VbStrConv.ProperCase

vbWide VbStrConv.Wide

vbNarrow VbStrConv.Narrow

vbKatakana VbStrConv.Katakana

vbHiragana VbStrConv.Hiragana

vbUnicode No equivalent constant. You can achieve the same functionality by using the Convert method.

vbFromUnicode No equivalent
See Also
Reference
VbStrConv Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

Style Constants for Visual Basic 6.0 Users


The following tables show the Visual Basic 6.0 Style constants and values and their Visual Basic 2005 equivalents.
ComboBox Style Constants
Visual Basic 6.0 Visual Basic 2005 Equivalent
vbComboDropdown (0) DropDown

vbComboSimple (1) Simple

vbComboDropdownList (2) DropDownList


CheckBox and OptionButton Style Constants
Visual Basic 6.0 Visual Basic 2005 Equivalent
VbButtonStandard (0) Normal

VbButtonGraphical (1) Button


Note
In Visual Basic 6.0, Style constants are also defined for CommandButton and ListBox controls. There are no equivalents in
Visual Basic 2005. For details, see How to: Emulate a Visual Basic 6.0 Tri-state Control in an Upgraded Application or
ListBox Control for Visual Basic 6.0 Users.

See Also
Concepts
ComboBox Control for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

System Color Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 System Color constants and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
vb3DDKShadow ControlDarkDark

vb3DFace Control

vb3DHighlight ControlLightLight

vb3DLight ControlLight

vb3DShadow ControlDark

vbActiveBorder ActiveBorder

vbActiveTitleBar ActiveCaption

vbActiveTitleBarText ActiveCaptionText

vbApplicationWorkspace AppWorkspace

vbButtonFace Control

vbButtonShadow ControlDark

vbButtonText ControlText

vbDesktop Desktop

vbGrayText GrayText

vbHighlight Highlight

vbHighlightText HighlightText

vbInactiveBorder InactiveBorder

vbInactiveCaptionText InactiveCaptionText

vbInactiveTitleBar InactiveCaption

vbInactiveTitleBarText InactiveCaptionText

vbInfoBackground Info

vbInfoText InfoText

vbMenuBar Menu

vbMenuText MenuText
vbScrollBars Scrollbar

vbTitleBarText ActiveCaptionText

vbWindowBackground Window

vbWindowFrame WindowFrame

vbWindowText WindowText
See Also
Reference
Color Handling for Visual Basic 6.0 Users
Color Constants for Visual Basic 6.0 Users
Concepts
Color Behavior for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

TriState Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 TriState constants and their Visual Basic 2005 equivalents.
Note
For backward compatibility, the Visual Basic 6.0 TriState constants can still be used in Visual Basic 2005. For more informati
on, see TriState Enumeration.

Visual Basic 6.0 Visual Basic 2005 Equivalent


vbTrue TriState.True

vbFalse TriState.False

vbUseDefault TriState.UseDefault
See Also
Reference
TriState Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

Variant Type Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 VarType constants and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
vbVEmpty VariantType.Empty

vbVNull VariantType.Null

vbVInteger VariantType.Short

vbVLong VariantType.Integer

vbVSingle VariantType.Single

vbVDouble VariantType.Double

vbVCurrency VariantType.Decimal

vbVDate VariantType.Date

vbVString VariantType.String
See Also
Reference
VariantType Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations (Visual Basic)
Visual Basic Reference

VarType Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 VarType constants and their Visual Basic 2005 equivalents in the
VariantType Enumeration.
Note
For backward compatibility, the Visual Basic 6.0 VarType constants can still be used in Visual Basic 2005. For more informati
on, see VariantType Enumeration.

Visual Basic 6.0 Visual Basic 2005 Equivalent


vbEmpty VariantType.Empty

vbNull VariantType.Null

vbInteger VariantType.Short

vbLong VariantType.Integer

vbSingle VariantType.Single

vbDouble VariantType.Double

vbCurrency VariantType.Decimal

vbDate VariantType.Date

vbString VariantType.String

vbObject VariantType.Object

vbError VariantType.Error

vbBoolean VariantType.Boolean

vbVariant VariantType.Variant

vbDataObject VariantType.DataObject

vbDecimal VariantType.Decimal

vbByte VariantType.Byte

vbUserDefinedType VariantType.UserDefinedType

vbArray VariantType.Array
See Also
Reference
VariantType Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

VBA Constants for Visual Basic 6.0 Users


The following table shows the Microsoft Visual Basic for Applications (VBA) constants for Visual Basic 6.0 and their Visual Basic
2005 equivalents.
Note
For backward compatibility, the Visual Basic 6.0 VBA constants can also be used in Visual Basic 2005.

Visual Basic 6.0 Visual Basic 2005 Equivalent


vbBack ControlChars.Back

vbCr ControlChars.Cr

vbCrLf ControlChars.CrLf

vbFormFeed ControlChars.FormFeed

vbLf ControlChars.Lf

vbNewLine ControlChars.NewLine

vbNullChar ControlChars.NullChar

vbNullString Nothing keyword

vbObjectError vbObjectError

vbTab ControlChars.Tab
See Also
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

WeekOfYear Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 WeekOfYear constants and their Visual Basic 2005 equivalents.
Note
For backward compatibility, you can still use Visual Basic 6.0 WeekOfYear constants in Visual Basic 2005. For more informat
ion, see FirstWeekOfYear Enumeration.

Visual Basic 6.0 Visual Basic 2005 Equivalent


vbUseSystem FirstWeekOfYear.System

VbFirstJan1 FirstWeekOfYear.Jan1

vbFirstFourDays FirstWeekOfYear.FirstFourDays

vbFirstFullWeek FirstWeekOfYear.FirstFullWeek
See Also
Reference
FirstWeekOfYear Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

WindowState Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 WindowState constants and values and their Visual Basic 2005 equivalents.
Visual Basic 6.0 Visual Basic 2005 Equivalent
vbNormal (0) Normal

vbMinimized (1) Minimized

vbMaximized (2) Maximized


See Also
Concepts
Form Object for Visual Basic 6.0 Users
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Reference

WindowStyle Constants for Visual Basic 6.0 Users


The following table shows the Visual Basic 6.0 WindowStyle constants and their Visual Basic 2005 equivalents.
Note
For backward compatibility, you can still use Visual Basic 6.0 WindowStyle constants in Visual Basic 2005. For more inform
ation, see AppWinStyle Enumeration.

Visual Basic 6.0 Visual Basic 2005 Equivalent


vbHide AppWinStyle.Hide

vbNormalFocus AppWinStyle.NormalFocus

vbMinimizedFocus AppWinStyle.MinimizedFocus

vbMaximizedFocus AppWinStyle.MaximizedFocus

vbNormalNoFocus AppWinStyle.NormalNoFocus

vbMinimizedNoFocus AppWinStyle.MinimizedNoFocus
See Also
Reference
AppWinStyle Enumeration
Other Resources
Constant Equivalents for Visual Basic 6.0 Users
Constants and Enumerations in Visual Basic
Visual Basic Concepts

Object Libraries and Namespaces for Visual Basic 6.0 Users


Namespaces may at first seem to be a new concept in Visual Basic 2005. However, conceptually, they are similar to object
libraries in Visual Basic 6.0.
In Visual Basic 6.0, various libraries contain objects that are used to build an application. For example, the Visual Basic library
contains the form objects and intrinsic control objects that were the foundation of a Windows-based application. You could see
the objects contained in a given library by viewing it in the Object Browser.
In Visual Basic 2005, objects are contained in assemblies that are part of the .NET Framework class library. Each assembly
represents a namespace. For example, form and control objects are contained in the System.Windows.Forms namespace. As
in Visual Basic 6.0, namespaces can be inspected in the Object Browser.
Tip
Of special interest to Visual Basic 6.0 users is the Microsoft.VisualBasic namespace, which contains many objects and const
ants that allow you to continue using Visual Basic 6.0 syntax in Visual Basic 2005.

See Also
Concepts
Introduction to the .NET Framework Class Library in Visual Studio
Visual Basic Concepts

Run Time Libraries for Visual Basic 6.0 Users


Applications created with Visual Basic 6.0 or with Visual Basic 2005 require that a run-time library be installed on the user's
computer.
Conceptual Differences
For applications created with Visual Basic 6.0, the Visual Basic run-time file (Msvbvm60.dll) has to be installed on a client
computer in order for the application to run. This file was often included in Setup packages so that it could be installed along
with the application if necessary
In Visual Basic 2005, applications require the .NET Framework common language runtime, a run-time environment that
manages the execution of code on a client computer. The common language runtime files can be pre-installed on a target
computer using either ClickOnce or Windows Installer deployment. For more information, see
Deploying Prerequisites (Visual Studio).
See Also
Concepts
Setup and Deployment for Visual Basic 6.0 Users
Other Resources
Deploying Applications and Components
Redistributing the .NET Framework
Visual Basic Concepts

Upgrading Applications in Visual Basic


In the following sections, you can learn how to upgrade programs created with Visual Basic 6.0 to Visual Basic 2005.
In This Section
What's New in Upgrading
New features related to upgrading your Visual Basic 6.0 projects.
Upgrading from Visual Basic 6.0
Converting applications to the new version of Visual Basic.
Visual Basic 6.0 Upgrading Reference
Diagnostic messages for the tool that upgrades projects to Visual Basic 2005.
Related Sections
Help for Visual Basic 6.0 Users
A series of topics that compare Visual Basic 6.0 objects, concepts, and techniques with their Visual Basic 2005 equivalents.
Introduction to Solutions, Projects, and Items
Describes the core concepts underlying application development in the integrated development environment (IDE). This topic
provides background information about managing upgraded projects and performing project-related tasks.
Product Support and Accessibility
Provides information about installation, editions, product support, and customizing the IDE.
Visual Basic Concepts

What's New in Upgrading


Visual Basic 2005 includes several new features for upgrading Visual Basic 6.0 applications and code to Visual Basic 2005.
What's New in Visual Basic 2005
Feature Description
Support for MT You can now upgrade Visual Basic 6.0 projects that used Microsoft Transaction Server (MTS) or COM+ compo
S and COM+ u nents.
pgrades

Support for Act You can now upgrade many Visual Basic 6.0 ActiveX controls to their Visual Basic 2005 equivalents. Support is
iveX control up included for these controls: WebBrowser, ToolBar, ImageList, TreeView, ListView, RichTextBox, ProgressBar,
grades StatusBar, CommonDialog, and MaskedTextBox.

Enhancements You will find a number of enhancements to code upgrades in Visual Basic 2005, including:
to code upgrad
es Upgrade code that uses string-based-keys in forms control collections.
Upgrade code that changes the key value in the KeyPress event.
Other enhancements let you:
Upgrade the Visual Basic 6.0 App object to the new My.Application object.
Upgrade the UnloadMode parameter of QueryUnload event to the ClosingReason argument of the For
mClosing event.
Upgrade forms to use the new Partial Type format.
Upgrade Visual Basic 6.0 default instances to use support for default instances provided in Visual Basic 2
005.
Upgrade the Forms collection to the Visual Basic 2005 System.Windows.Forms collection.
Upgrade Visual Basic 6.0 Clipboard object to the new My.Computer.Clipboard object.
Upgrade the LoadResString, LoadResData, and LoadResPicture methods to the new My.Resources
object.

See Also
Concepts
What's New in the Visual Basic Language
Visual Basic Concepts

Upgrading from Visual Basic 6.0


Visual Basic 2005 improves on previous versions of Visual Basic, with a new development environment, an updated
programming language, and a new forms package making development easier than ever. Moving from Visual Basic 6.0 to
Visual Basic 2005 takes less effort than you might think—enhancements to the integrated development environment and Help
system ease the task of successfully upgrading your code by mapping your knowledge of Visual Basic 6.0 to Visual Basic 2005
equivalents.
As you learn about Visual Basic 2005, you will likely want to upgrade some of your Visual Basic 6.0 projects. Although there are
differences between the two versions, the tools provided can help you successfully upgrade your projects.
The following documentation will help you upgrade your applications and quickly learn about changes in Visual Basic 2005.
In This Section
Upgrading Applications Created in Previous Versions of Visual Basic
Describes how to upgrade your applications to Visual Basic 2005.
Working with Both Visual Basic 6.0 and the Current Version of Visual Basic
Describes compatibility between the two versions of Visual Basic.
Walkthrough: Upgrading a Visual Basic 6.0 Application to the Current Version of Visual Basic
Compares a Visual Basic 6.0 sample application to a Visual Basic 2005 equivalent.
Related Sections
What's New for Visual Basic 6.0 Users
Describes new features in Visual Basic 2005.
Help for Visual Basic 6.0 Users
A series of topics that compare Visual Basic 6.0 objects, concepts, and techniques with their Visual Basic 2005 equivalents.
Language Changes for Visual Basic 6.0 Users
Describes changes to Visual Basic.
Visual Basic Concepts

Upgrading Applications Created in Previous Versions of Visual


Basic
With Visual Basic 2005, you are able to upgrade applications created in Visual Basic 6.0 so you can continue development,
taking advantage of the benefits of the .NET Framework. When you first open a Visual Basic 6.0 project file (.vbp), the Upgrade
Wizard appears. You can also upgrade projects outside of the development environment with the provided command-line tool.
The upgrading tools modify code within your project to comply with Visual Basic 2005 syntax and replace any forms and
controls with Visual Basic 2005 equivalents. Due to the differences between Visual Basic 6.0 and Visual Basic 2005, some parts
of your project may not map directly—in these cases, you receive an upgrade report to guide you through the process of
modifying your application.
Some Visual Basic 6.0 applications may not benefit from being upgraded to Visual Basic 2005. You can prepare those
applications you do choose to upgrade so that upgrading goes smoothly.
The following topics will help you better understand the upgrade process.
In This Section
Why Upgrading Is Necessary
Discusses the differences between Visual Basic 6.0 and Visual Basic 2005.
Things to Consider Before Upgrading
Discusses the limitations of and considerations for upgrading.
Preparing a Visual Basic 6.0 Application for Upgrading
Describes how to make sure that your application is ready to be upgraded.
Language Recommendations for Upgrading
Provides recommendations you can follow when preparing a Visual Basic 6.0 application for upgrade, or when developing
Visual Basic 6.0 applications that might later be upgraded.
Visual Basic 6.0 Compatibility Library
Describes a mechanism provided for backward compatibility.
Visual Basic Upgrade Wizard
Provides an overview of upgrading a Visual Basic 6.0 project to Visual Basic 2005 with the Upgrade Wizard.
How to: Upgrade a Project with the Visual Basic Upgrade Wizard
Describes how to use the Upgrade Wizard.
How to: Upgrade Visual Basic 6.0 Code with the Upgrade Visual Basic 6 Code Dialog Box
Explains how to upgrade Visual Basic 6.0 code to Visual Basic 2005 code.
Upgrade Visual Basic 6 Code Dialog Box
Describes the user interface for upgrading Visual Basic 6.0 code to Visual Basic 2005 code.
Upgrading WebClass Projects to Visual Basic 2005
Explains how to upgrade WebClass projects (also known as IIS Applications) to ASP.NET Web Application projects.
Completing the Upgrading Process
Describes what to do next after the Upgrade Wizard has finished running.
Visual Basic Upgrade Report
Describes the format and purpose of the upgrade report.
How to: View the Upgrade Report
Explains how to open the upgrade report.
How to: Upgrade a Project from the Command Line
Describes how to use the command-line upgrading tool.
Troubleshooting Applications Upgraded from Visual Basic 6.0
Lists some known issues that are not detected by the upgrading tools and explains how to address them.
Related Sections
What's New in Visual Basic
Describes the new features in Visual Basic 2005.
Help for Visual Basic 6.0 Users
Lists the differences between Visual Basic 6.0 and Visual Basic 2005.
Working with Both Visual Basic 6.0 and the Current Version of Visual Basic
Describes compatibility between the two versions of Visual Basic.
Visual Basic Concepts

Why Upgrading Is Necessary


The designers of Visual Basic 2005 had two options—retrofit the existing code base to run on top of the .NET Framework, or
build from the ground up, taking full advantage of the .NET Framework. The right decision was to build from the ground up.
The result is a product that:
Delivers the features most requested by customers (for example, inheritance and threading).
Provides full and unconstrained access to the .NET Framework.
Ensures that Visual Basic moves forward into the next generation of Web applications.
For example, many of the new features found in Windows Forms (the new forms package) could have been added to the
existing code base as new controls or more properties. However, had this been done, developers would not get the benefits of
all the other great features inherent to Windows Forms, such as security and visual inheritance.
One of the major goals of Visual Basic 2005 was to ensure that Visual Basic code could fully interoperate with code written in
other languages, such as C# or C++. Another goal was to enable Visual Basic developers to harness the power of the .NET
Framework simply, without resorting to the programming workarounds traditionally required to make Windows APIs work.
Visual Basic now has the same variable types, arrays, user-defined types, classes, and interfaces as Visual C++ and any other
language that targets the common language runtime; however, some features such as fixed-length strings had to be removed
from the language.
Visual Basic is now a true object-oriented language; some unintuitive and inconsistent features like GoSub/Return and DefInt
have been removed from the language.
The result is a re-energized Visual Basic, which will continue to be the most productive tool for creating Windows-based
applications and is now positioned to be the best tool for creating the next-generation Web sites. The tradeoff is that Visual
Basic 6.0 applications must be upgraded to conform to the new language and forms features, breaking compatibility with
earlier versions.
See Also
Concepts
Preparing a Visual Basic 6.0 Application for Upgrading
Things to Consider Before Upgrading
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts

Things to Consider Before Upgrading


Visual Basic 2005 represents a major shift from previous versions of Visual Basic. Because it was designed from the ground up
to take advantage of the .NET Framework, there are many areas where compatibility with previous versions is broken.
Note
Visual Basic 2005 and Visual Basic 6.0 can be installed on the same computer and run at the same time. Applications written i
n Visual Basic 2005 and Visual Basic 6.0 can be installed and executed on the same computer. Components written in Visual
Basic 2005 can interoperate with COM components written in earlier versions of Visual Basic and other languages.

In most cases you will want to upgrade your Visual Basic 6.0 applications to Visual Basic 2005 so that you can take
advantage of the benefits of the .NET Framework as you continue development. There are, however, situations where you
may wish to continue development in Visual Basic 6.0 rather than upgrading. Some of the factors in deciding to upgrade
an application include features that aren't supported in Visual Basic 2005, and the amount of rework needed due to
incompatibility and architectural considerations.
Unsupported Features
The following features from Visual Basic 6.0 are no longer supported in Visual Basic 2005. For more information, see
Preparing a Visual Basic 6.0 Application for Upgrading.
OLE Container Control There is no equivalent in Visual Basic 2005. Applications that depend on this control should be
left in Visual Basic 6.0.
Dynamic Data Exchange (DDE) DDE methods are no longer supported. Applications that depend on DDE should either
be revised to use another method of inter-application communication or left in Visual Basic 6.0.
DAO or RDO Data Binding Data binding to a DAO or RDO data source isn't supported in Visual Basic 2005; the Data
control and the RemoteData control have no equivalent. DAO and RDO can only be accessed using code. Applications
that rely on DAO or RDO data binding should either be updated to use ADO or left in Visual Basic 6.0.
Visual Basic 5.0 Controls Visual Basic 6.0 included the Visual Basic 5.0 versions of the Windows Common controls and
the Data-Bound Grid control. These controls are incompatible with Visual Basic 2005. Applications that rely on these
controls should either be updated to use the 6.0 versions or left in Visual Basic 6.0.
DHTML Applications There is no equivalent in Visual Basic 2005. However, DHTML applications can interoperate with
Visual Basic 2005 technologies.
ActiveX Documents There is no equivalent in Visual Basic 2005. However, DHTML applications can interoperate with
Visual Basic 2005 technologies. ActiveX documents should either be rewritten as user controls or left in Visual Basic 6.0.
Property Pages There is no equivalent in Visual Basic 2005. If your application depends heavily on property pages, it
should be left in Visual Basic 6.0.
Determining the Amount of Rework Required
Due to the many differences between Visual Basic 6.0 and Visual Basic 2005, most applications will require some rework for
items that can't be mapped directly or are otherwise incompatible. The amount of rework required depends on a number of
factors, including the type of application, features, and the language constructs used.
The easiest way to determine the amount of rework required is to run the Upgrade Wizard and view the list of issues in the
Upgrade Report. When an application is upgraded a new copy is created; the original application is left intact. If, after viewing
the report, you decide not to upgrade, you can simply delete the new project and continue development in Visual Basic 6.0.
The following are additional considerations that may factor into your upgrade decision.
Single-tier Database Applications Because data binding to DAO isn't supported, simple applications using controls
bound directly to a local database (such as one created with Microsoft Access) may require a significant amount of
rework.
Visual Basic Add-ins Because Visual Basic 2005 uses the Visual Studio integrated development environment, the object
model for extensibility is significantly different than that of Visual Basic 6.0. Add-ins will require a considerable amount of
rework.
Games Applications relying on specific performance characteristics of Visual Basic 6.0, such as arcade games, will
require rework because Visual Basic 2005 has different performance characteristics.
Graphics There is no support for the graphics methods of forms or for the shape and line controls. Applications that use
these features extensively to draw on forms will require considerable rework.
Drag-and-Drop Functionality The models for drag-and-drop functionality are significantly different; any code
performing drag-and-drop actions will need to be rewritten.
Variants When an application is upgraded, the Variant data type is converted to Object. If an application is heavily
dependent on variants, this conversion can introduce some subtle differences in the application's behavior. For example,
in Visual Basic 6.0 the expression IsObject(Variant) evaluates to false; in Visual Basic 2005 it changes to
IsObject(Object), which evaluates to true.

Windows APIs Due to language changes, many calls to Windows APIs will need to be revised or replaced with .NET
Framework functions.
See Also
Concepts
Preparing a Visual Basic 6.0 Application for Upgrading
Why Upgrading Is Necessary
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts

Preparing a Visual Basic 6.0 Application for Upgrading


Although the process of upgrading a Visual Basic 6.0 application to Visual Basic 2005 is for the most part automatic, there are a
number of things you can do to optimize your upgrade with a little bit of preparation.
By following the recommendations in this topic, you can minimize and, in some cases, eliminate the changes needed after
upgrading your project to Visual Basic 2005. In most cases, the recommendations simply represent good programming
practices; however, some also identify the objects and methods which have no equivalents, and which should be used
sparingly if you intend to upgrade your project to Visual Basic 2005.
General Recommendations
This may seem obvious, but if your project doesn't compile and run under Visual Basic 6.0, it will not be upgraded successfully.
We recommend that you install Visual Basic 6.0 on the computer that you will be using for upgrading. In addition to allowing
you to test the application, this will ensure that all necessary controls, components, and type libraries are available during
upgrade.
Visual Basic 2005 allows you to upgrade Visual Basic 6.0 projects; if you have a project written in Visual Basic version 1 to 5,
you should first load it into Visual Basic 6.0 (choosing to upgrade Microsoft ActiveX controls), compile, and save the project
before upgrading it to Visual Basic 2005.
Considerations for Forms and Controls
Visual Basic 2005 has a new forms package, Windows Forms. Windows Forms is largely compatible with the forms package
found in Visual Basic 6.0; however, there are some key differences that are outlined below:
Visual Basic 2005 does not support the OLE container control; you should avoid using this control in your Visual Basic 6.0
applications.
There is no shape control in Visual Basic 2005. Square and rectangular shapes will be upgraded to labels, while ovals and
circles cannot be upgraded. You should avoid using these in your applications.
There is no line control in Visual Basic 2005. Horizontal and vertical lines are upgraded to labels. Diagonal lines are not
upgraded, and you should avoid using them.
Visual Basic 2005 has a new set of graphics commands that replace the Form methods Circle, CLS, PSet, Line, and
Point. Because the new object model is quite different from Visual Basic 6.0, these methods cannot be upgraded.
For the Timer control, setting the Interval property to 0 does not disable the timer; instead the interval is reset to 1. In
your Visual Basic 6.0 projects, you should set Enabled to False instead of setting the Interval to 0.
Visual Basic 2005 has two menu controls, MenuStrip and ContextMenuStrip, whereas Visual Basic 6.0 has one menu
control that can be opened as either a MainMenu or a ContextMenu control. All menu controls are upgraded to a
single MenuStrip component containing MenuItems for each menu control; you will have to recreate your context
menus and delete the extra MenuStrip controls.
Visual Basic 2005 has no support for Dynamic Data Exchange (DDE).
Visual Basic 2005 does not support the Form.PrintForm method.
Although Visual Basic 2005 has support for drag-and-drop functionality, the object model is different from the one in
Visual Basic 6.0. Therefore, the Visual Basic 6.0 drag-and-drop properties and methods cannot be upgraded.
Visual Basic 2005 has an improved Clipboard object (My.Computer.Clipboard) that offers more functionality and
supports more Clipboard formats than the Visual Basic 6.0 Clipboard object. However, because of differences between
object models, Clipboard statements cannot be automatically upgraded.
Visual Basic 2005 does not support the Name property for forms and controls at run time; therefore you should not
write code that iterates the Controls collection looking for a control with a certain name. (This functionality is now
available using the .NET Framework System.Reflection classes.)
Data Recommendations
Visual Basic 2005 introduces an enhanced version of ADO called ADO.NET that is optimized to work with data in distributed
applications and that provides performance improvements over ADO when used in distributed applications.
RDO and ADO can still be used in code from Visual Basic 2005, with some trivial modifications. However, Visual Basic 2005
does not support DAO and RDO data binding to controls, data controls, or RDO User connection. We recommend that if your
applications contain DAO or RDO data binding you either leave them in Visual Basic 6.0 or upgrade the DAO or RDO data
binding to ADO before upgrading your project to Visual Basic 2005, as ADO data binding is supported in Windows Forms.
Information on how to upgrade DAO or RDO to ADO in Visual Basic 6.0 is available in the Visual Basic 6.0 Help.
Web Architecture Recommendations
Visual Basic 2005 introduces ASP.NET, an enhanced version of ASP, and adds to the architecture with Web Forms, a technology
for producing Web pages with a Visual Basic-like event model. The architecture is server-based.
Web-based applications that meet the following criteria will be the easiest to upgrade:
Follow Microsoft multitier architectural guidelines.
Use Active Server Pages.
Use Visual Basic 6.0 or Visual C++ 6.0 COM objects for business logic.
ASP is fully supported in Visual Basic 2005, and you can continue to extend your application using ASP, ASP.NET, and Web
Forms. The Visual Basic 6.0 and Visual C++ 6.0 business objects can either be used without modification or upgraded to Visual
Basic 2005.
Webclasses no longer exist in Visual Basic 2005. Existing Webclass applications can interoperate with Visual Basic 2005 Web
Forms and ASP applications, or they can be upgraded to Web Forms applications.
See Also
Concepts
Things to Consider Before Upgrading
Why Upgrading Is Necessary
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Language Recommendations for Upgrading
Visual Basic Concepts

Language Recommendations for Upgrading


Because there are language differences between Visual Basic 6.0 and Visual Basic 2005, you may need to change some code
when you upgrade an application.
Use the following recommendations when preparing a Visual Basic 6.0 application for upgrade or when developing Visual
Basic 6.0 applications that might later be upgraded.
In This Section
Upgrade Recommendation: Use Early Binding and Explicit Conversions
Provides recommendations for variable declaration and data type conversion in Visual Basic 6.0 applications.
Upgrade Recommendation: Use the Date Data Type for Storing Dates
Provides recommendations for date handling in Visual Basic 6.0 applications.
Upgrade Recommendation: Resolve Parameterless Default Properties
Provides recommendations for referencing default properties in Visual Basic 6.0 applications.
Upgrade Recommendation: Avoid Null Propagation
Provides recommendations for handling null values in Visual Basic 6.0 applications.
Upgrade Recommendation: Use Zero-Bound Arrays
Provides recommendations for creating arrays in Visual Basic 6.0 applications.
Upgrade Recommendation: Use Constants Instead of Underlying Values
Provides recommendations for referencing constants in Visual Basic 6.0 applications.
Upgrade Recommendation: Avoid Arrays and Fixed-Length Strings in User-Defined Types
Provides recommendations for User-Defined Types in Visual Basic 6.0 applications.
Upgrade Recommendation: Avoid Legacy Keywords
Provides recommendations for the use of obsolete keywords in Visual Basic 6.0 applications.
Upgrade Recommendation: Adjust Data Types for Win32 APIs
Provides recommendations for calling Windows APIs in Visual Basic 6.0 applications.
Related Sections
Preparing a Visual Basic 6.0 Application for Upgrading
Describes how to make sure your application is ready to be upgraded.
Things to Consider Before Upgrading
Discusses the limitations of and considerations for upgrading.
Upgrading Applications Created in Previous Versions of Visual Basic
Discusses upgrading your Visual Basic 6.0 applications.
Visual Basic Concepts

Upgrade Recommendation: Use Early Binding and Explicit


Conversions
Both Visual Basic 6.0 and Visual Basic 2005 support using late-bound objects, which is the practice of declaring a variable as
the Object data type and assigning it to an instance of a class at run time. However, during the upgrade process, late-bound
objects can introduce problems when resolving default properties, or in cases where the underlying object model has changed
and properties, methods, and events need to be converted. For example, suppose you have a form called Form1 with a label
called Label1; the following Visual Basic 6.0 code would set the caption of the label to "SomeText":

Dim o As Object
Set o = Me.Label1
o.Caption = "SomeText"

In Visual Basic 2005, the Caption property of a label control is replaced by the Text property. When your code is upgraded, all
instances of the Caption property are changed to Text, but because a late-bound object is typeless, Visual Basic cannot detect
what type of object it is, or if any properties should be translated. In such cases, you will need to change the code yourself after
upgrading.
If you rewrite the code using early-bound objects, it will be upgraded automatically:

Dim o As Label
Set o = Me.Label1
o.Text = "SomeText"

Where possible, you should declare variables of the appropriate object type rather than simply declaring them as the Object
data type.
In the cases where you do use Object and Variant variables in your Visual Basic 6.0 code, we recommend you use explicit
conversions when you assign the variables, perform operations on the variables, or pass the variables to a function. For
example, the intention of the '+' operation in the following code is unclear:

Dim Var1 As Variant


Dim Var2 As Variant
Dim Var3 As Variant
Var1 = "3"
Var2 = 4
'BAD: Should Var1 and Var2 be added as strings or integers?
Var3 = Var1 + Var2

The above example may result in a run-time error in Visual Basic 2005. Rewriting the final line to use explicit conversions
ensures the code will work:

'GOOD: explicit conversion


Var3 = CInt(Var1) + CInt(Var2)

Visual Basic 2005 supports overloading functions based on parameter type. For example, the Environ function now has two
forms:

Environ( Expression As Integer) As String


Environ( Expression As String ) As String

Visual Basic 2005 determines which function to call based on the parameter type. If you pass an integer to Environ(), the
integer version is called; if you pass a string, then the string version is called. Code that passes a Variant or Object data type
to an overloaded function may cause a compiler error or run-time error. Using an explicit conversion, as in the following
example, will mean your code will work as intended after it is upgraded to Visual Basic 2005:

Dim a As String
Dim v As Variant
v = "Path"
'GOOD: explicit conversion
a = Environ(CStr(v))

Using explicit conversions of late-bound objects is good coding practice. It makes the intention of the code easy to determine,
and makes it easier for you to upgrade your project to Visual Basic 2005.
See Also
Other Resources
Language Recommendations for Upgrading
Visual Basic Concepts

Upgrade Recommendation: Use the Date Data Type for Storing


Dates
Earlier versions of Visual Basic support using the Double data type to store and manipulate dates. You should not do this in
Visual Basic 2005, because dates are not internally stored as doubles. For example, the following is valid in Visual Basic 6.0, but
may cause a compile error in Visual Basic 2005:

Dim dbl As Double


Dim dat As Date
dat = Now
'BAD: Date can't be assigned to a double
dbl = dat
'BAD: Double can't be used in date functions
dbl = DateAdd("d", 1, dbl)
'BAD: CDate can't convert a double to a date
dat = CDate(dbl)

The .NET Framework provides the ToOADate and FromOADate functions to convert between doubles and dates. However,
when your project is upgraded to Visual Basic 2005, it is difficult to determine the intention of code that uses doubles to store
dates. To avoid unnecessary modifications to your code in Visual Basic 2005, always use the Date data type to store dates.
See Also
Other Resources
Language Recommendations for Upgrading
Visual Basic Concepts

Upgrade Recommendation: Resolve Parameterless Default


Properties
In Visual Basic 6.0, many objects expose default properties, which can be omitted as a programming shortcut. For example,
TextBox has a default property of Text, so instead of writing:

MsgBox Form1.Text1.Text

you use the shortcut:

MsgBox Form1.Text1

The default property is resolved when the code is compiled. In addition, you can also use default properties with late-bound
objects, as in the following example:

Dim obj As Object


Set obj = Form1.Text1
MsgBox obj

In the late-bound example, the default property is resolved at run time, and the MsgBox displays the value of the default
property of the TextBox as Text1.
Visual Basic 2005 does not support parameterless default properties, and consequently does not allow this programming
shortcut. When your project is upgraded, Visual Basic 2005 resolves the parameterless default properties, but late-bound
usages that rely on run-time resolution cannot be automatically resolved. In these cases, you will have to change the code
yourself. An additional complication is that many libraries implement default properties using a property called _Default.
_Default acts as a proxy, passing calls to the real default property. So, when your project is upgraded, some default properties
will be resolved to _Default. The code will still work as usual, but it will be less understandable than code written explicitly
using the actual property. For these reasons, try to avoid using parameterless default properties in your Visual Basic 6.0 code.
Instead of writing:

Dim obj As Object


Set obj = Me.Text1
'BAD: Relying on default property
MsgBox obj
'BAD: Relying on default property
MsgBox Me.Text1

use:

Dim obj As TextBox


Set obj = Me.Text1
'GOOD: Default property is resolved
MsgBox obj.Text
'GOOD: Default property is resolved
MsgBox Me.Text1.Text

While parameterless default properties are not supported in Visual Basic 2005, default properties with parameters are
supported. To understand the difference between the two types, consider that parameterized default properties always have an
index. An example is the default property of ADO recordset: the Fields collection. The code:

Dim rs As ADODB.Recordset
rs("CompanyName") = "SomeCompany"
rs!CompanyName = "SomeCompany"

is actually a shortcut for:


Dim rs As ADODB.Recordset
rs.Fields("CompanyName").Value = "SomeCompany"
rs.Fields!CompanyName.Value = "SomeCompany"

In this case, the Fields property is parameterized, and so the usage is valid in Visual Basic 2005; however, the default property
of the Fields property, Value, is parameterless, so the correct usage in Visual Basic 2005 is:

Dim rs As ADODB.Recordset
rs("CompanyName").Value = "SomeCompany"
rs!CompanyName.Value = "SomeCompany"

This example and most other default properties are resolved for you when the project is upgraded, so resolving them in Visual
Basic 6.0 is simply a good programming practice. However, you should avoid using default properties with the Object and
Variant data types, as these cannot be resolved and you will have to fix the code yourself in the upgraded project.
See Also
Other Resources
Language Recommendations for Upgrading
Visual Basic Concepts

Upgrade Recommendation: Avoid Null Propagation


Previous versions of Visual Basic support Null propagation. Null propagation supports the premise that when Null is used in
an expression, the result of the expression will itself be Null. In each case in the following example, the result of V is always Null.

Dim V
V = 1 + Null
V = Null + Right$("SomeText", 1)
V = Right("SomeText", 0)

Null propagation is not supported in Visual Basic 2005. The statement 1+Null will generate a type mismatch in Visual Basic
2005. Additionally, where Visual Basic 6.0 had two versions of the Left function — Left$ returning a string, Left returning a
variant which could be Null — Visual Basic 2005 only has one version, Left, which always returns a string.
In order to be compatible with both Visual Basic 6.0 and Visual Basic 2005, you should always write code to test for Null
instead of relying on Null propagation. Furthermore, in Visual Basic 2005, the following functions will no longer return Null:
Chr, Command, CurDir, Date, Environ, Error, Hex, LCase, LTrim, Oct, Right, RTrim, Space, Str, Time, Trim, UCase
Null propagation is commonly used in database applications, where you need to check if a database field contains Null. In
these cases you should check results using the function IsNull() and perform the appropriate action.
See Also
Other Resources
Language Recommendations for Upgrading
Visual Basic Concepts

Upgrade Recommendation: Use Zero-Bound Arrays


Visual Basic 6.0 allows you to define arrays with lower and upper bounds of any whole number. You can also use ReDim to
reassign a variant as an array. To enable interoperability with other languages, arrays in Visual Basic 2005 must have a lower
bound of zero, and ReDim cannot be used unless the array variable was previously declared with the Dim keyword. Although
this restricts the way arrays can be defined, it does allow you to pass arrays between Visual Basic 2005 and any other .NET
Framework language. The following example shows the restriction:

'BAD: LBound must be 0


Dim a(1 To 10) As Integer
'BAD: Can't use ReDim without Dim
ReDim v(10)
'OK: Creates an array of 11 integers
Dim b(10) As Integer
'OK: Can ReDim previously Dimed variable
ReDim b(5) As Integer

A side effect is that the Option Base statement is removed from the language.
When your project is upgraded to Visual Basic 2005, any option base statements are removed from your code. If the array is
zero-bound, it is left unchanged. However, if an array is non-zero–bound, then the lower bound is removed and a warning is
inserted into the code, as in the following example:

Dim a(1 To 10) As Integer

changes to:

' UPGRADE_WARNING: Lower bound of an array was changed from 1 to 0.


Dim a(10) As Integer

In many cases, the upgraded code will work as it did before. However, if your application logic relies on the lower bound being
1, then you will need to make some modifications. Dim, ReDim, and LBound statements are marked with warnings to help
you review the changes.
For this reason, you should use zero-bound arrays in your Visual Basic 6.0 code, avoid using ReDim as an array declaration,
and avoid using Option Base 1.
See Also
Other Resources
Language Recommendations for Upgrading
Visual Basic Concepts

Upgrade Recommendation: Use Constants Instead of


Underlying Values
When writing code, try to use constants rather than relying on their underlying values. For example, if you are maximizing a
form at run time, use:

' GOOD: Constant name


Me.WindowState = vbMaximized

rather than:

'BAD: Underlying value


Me.WindowStyle = 2
'BAD: Variable
Me.WindowStyle = X

Likewise, use True and False instead of -1 and 0.


In Visual Basic 2005, the values and in some cases the names of some properties and constants have changed. When your
project is upgraded to Visual Basic 2005, most constants are changed automatically for you; however, if you use underlying
values or variables instead of the constant names, many cases cannot be upgraded automatically. Using constant names
minimizes the number of modifications you have to do.
See Also
Other Resources
Language Recommendations for Upgrading
Visual Basic Concepts

Upgrade Recommendation: Avoid Arrays and Fixed-Length


Strings in User-Defined Types
Due to changes made which allow Visual Basic 2005 arrays and structures (formerly known as user-defined types) to be fully
compatible with other Visual Studio languages, fixed-length strings are no longer supported in the language. In most cases this
is not a problem, because there is a compatibility class which provides fixed-length string behavior, so the code:

Dim FixedLengthString As String * 100

upgrades to the following:

Dim FixedLengthString As New VB6.FixedLengthString(100)

However, fixed-length strings do cause a problem when used in structures. The problem arises because the fixed-length string
class is not automatically created when the structure is created. Likewise, fixed-size arrays are not created when the structure is
created.
When your code is upgraded, user-defined types with fixed-length strings or arrays will be converted to structures and marked
with a comment telling you to initialize the fixed-length string or array before referencing the structure in code. However, you
can shield yourself from this modification by changing your Visual Basic 6.0 user-defined types to use strings instead of fixed-
length strings, and uninitialized arrays instead of fixed-size arrays. For example:

Private Type uType


anArray(5) As Integer
aFixedString As String * 100
End Type
Sub SomeFunction()
Dim aVariable As uType
End Sub

can be changed to:

Private Type uType


anArray() As Integer
aFixedString As String
End Type
Sub SomeFunction()
Dim aVariable As uType
ReDim aVariable.anArray(5) As Integer
aVariable.aFixedString = String$(100, " ")
End Sub

See Also
Other Resources
Language Recommendations for Upgrading
Visual Basic Concepts

Upgrade Recommendation: Avoid Legacy Keywords


Because they have been removed from the language, you should avoid using the following keywords in Visual Basic 6.0
projects that may be upgraded to Visual Basic 2005.
Keyw Explanation
ord
Def< t In previous versions of Visual Basic, DefBool, DefByte, DefInt, DefLng, DefCur, DefSng, DefDbl, DefDec, DefDate,
ype > DefStr, DefObj and DefVar are used in the declarations section of a module to define a range of variables as a certain
type. For example, DefInt A-C defines all variables beginning with the letter A, B, or C as an integer. Instead of using D
ef<type> statements, you should explicitly declare variables.

Comp Computed GoTo/GoSub statements take this form:


uted G
oTo/G On x GoTo 100, 200, 300
oSub
These are not supported in Visual Basic 2005. Instead, you should use If statements, or Select Case constructs.

GoSu GoSub and Return statements are not supported in Visual Basic 2005. In most cases you can replace these with functi
b/Ret ons and procedures.
urn

Optio The Option Base statement was used to specify the default lower bound of an array as either 0 or 1. This statement ha
n Bas s been removed from the language since Visual Basic 2005 natively only supports arrays with a zero lower bound. Non
e 0|1 -zero lower bound arrays are supported through the Compatibility library.

VarPt VarPtr, VarPtrArray, VarPtrStringArray, ObjPtr and StrPtr are undocumented functions used to get the underlying
r, Obj memory address of variables. These functions are not supported in Visual Basic 2005.
Ptr, St
rPtr

LSet In Visual Basic 6.0, the LSet statement can be used to assign a variable of one user-defined type to another variable of
a different user-defined type. This functionality is not supported in Visual Basic 2005.

See Also
Other Resources
Language Recommendations for Upgrading
Visual Basic Concepts

Upgrade Recommendation: Adjust Data Types for Win32 APIs


Many APIs can be used exactly as they were in Visual Basic 6.0, with the caveat that you have to adjust your data types
accordingly. The Visual Basic 6.0 Long data type is now the Visual Basic 2005 Integer data type, and the Visual Basic 6.0
Integer data type is now the Visual Basic 2005 Short data type. During the upgrade, these changes are made for you, and
simple APIs work exactly the same as they did in Visual Basic 6.0. For example:

Private Declare Function GetVersion Lib "kernel32" () As Long


Function GetVer()
Dim Ver As Long
Ver = GetVersion()
MsgBox ("System Version is " & Ver)
End Function

changes to:

Private Declare Function GetVersion Lib "kernel32" () As Integer


Function GetVer()
Dim Ver As Integer
Ver = GetVersion()
MsgBox("System Version is " & Ver)
End Function

In addition to numeric data type upgrades, Visual Basic 6.0 has a fixed-length string data type which is not supported in Visual
Basic 2005, and which is upgraded to a fixed-length string wrapper class. In many cases in Visual Basic 6.0 you can perform the
same action using a normal string. For example:

Private Declare Function GetUserName Lib "advapi32.dll" Alias _


"GetUserNameA" (ByVal lpBuffer As String, ByRef nSize As Long) As Long
Function GetUser()
Dim Ret As Long
Dim UserName As String
Dim Buffer As String * 25
Ret = GetUserName(Buffer, 25)
UserName = Left$(Buffer, InStr(Buffer, Chr(0)) - 1)
MsgBox (UserName)
End Function

can be better written using a normal string explicitly set to length 25 instead of a fixed-length string:

Dim Buffer As String


Buffer = String$(25, " ")

This is upgraded to Visual Basic 2005 as follows:

Declare Function GetUserName Lib "advapi32.dll" Alias _


"GetUserNameA" (ByVal lpBuffer As String, ByRef nSize As Integer) As Integer
Function GetUser()
Dim Ret As Integer
Dim UserName As String
Dim Buffer As String
Buffer = New String(CChar(" "), 25)
Ret = GetUserName(Buffer, 25)
UserName = Left(Buffer, InStr(Buffer, Chr(0)) - 1)
MsgBox(UserName)
End Function

In some cases, Visual Basic 2005 better handles passing strings to APIs, since you can optionally declare how you want strings
to be passed using the ANSI and UNICODE keywords.
There are three cases where you may need to make some changes. The first is passing user-defined types that contain fixed-
length strings or byte arrays to APIs. In Visual Basic 2005 you may need to change your code, adding the MarshallAs attribute
(from the System.Runtime.InteropServices namespace) to each fixed-length string or byte array in the user-defined type. The
second case is using the As Any variable type in a Declare statement. This is not supported in Visual Basic 2005. Variables of
type As Any were often used to pass a variable that was either a string or Null; you can replace this Visual Basic 6.0 usage by
declaring two forms of the API, one with longs, one with strings. For example, the GetPrivateProfileString API has a
parameter lpKeyName of type As Any:

Private Declare Function GetPrivateProfileString Lib "kernel32" Alias _


"GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal _
lpKeyName As Any, ByVal lpDefault As String, ByVal lpReturnedString _
As String, ByVal nSize As Long, ByVal lpFileName As String) As Long

You can remove the "As Any" by replacing the Declare with two versions, one that accepts a long, and one that accepts a
string:

Private Declare Function GetPrivateProfileStringKey Lib "kernel32" Alias _


"GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal _
lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString _
As String, ByVal nSize As Integer, ByVal lpFileName As String) As Integer

Private Declare Function GetPrivateProfileStringNullKey Lib "kernel32" _


Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, _
ByVal lpKeyName As Integer, ByVal lpDefault As String, ByVal _
lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName _
As String) As Integer

When you wish to pass the value Null to the API, you use the GetPrivateProfileStringNullKey version. Doing it this way
means that the function upgrades to Visual Basic 2005.
The final area where you may need to make some changes is if you are using APIs that perform thread creation, derive from
Windows classes, perform message queue hooking, and so on. Some of these functions will cause a run-time error in Visual
Basic 2005. Many of these APIs have equivalents in Visual Basic 2005 or the .NET Framework. You will have to fix these on a
case-by-case basis.
See Also
Other Resources
Language Recommendations for Upgrading
Visual Basic Concepts

Visual Basic 6.0 Compatibility Library


If you have used previous versions of Visual Basic, you will notice that Visual Basic 2005 introduces several changes to the
Visual Basic language and that some familiar functions have seemingly disappeared. These changes were necessary in order to
make Visual Basic compliant with the .NET Framework and the Common Language Specification (CLS).
When a Visual Basic 6.0 application is upgraded to Visual Basic 2005, the conversion of some code is impossible, due to
syntactical or architectural differences. For this reason, functions in the Visual Basic 6.0 Compatibility library
(Microsoft.VisualBasic.Compatibility) are used to allow the code to run in Visual Basic 2005 without the need for extensive
modification. These functions mimic Visual Basic 6.0 behavior, while remaining compliant with the Common Language
Specification. Wherever possible, the upgrade tool attempts to move your code directly to functions in the
Microsoft.VisualBasic or System namespace.
Although the functions and objects in the Compatibility namespace were designed to support the upgrade tool, there is
nothing to prevent you from using them when creating a new application in Visual Basic 2005. In most cases, however, the
.NET Framework provides richer functionality.
See Also
Tasks
How to: Add Visual Basic 6.0 File System Controls to Your Application
Reference
VisualBasic.Compatibility Namespace Reference
Concepts
Working with Both Visual Basic 6.0 and the Current Version of Visual Basic
Other Resources
Language Changes for Visual Basic 6.0 Users
Upgrading from Visual Basic 6.0
Visual Basic Concepts

Visual Basic Upgrade Wizard


Visual Basic 2005 enables a fundamental shift from traditional Windows development to building next-generation Web and n-
tier applications. For this reason, your code will need to be upgraded to take advantage of Visual Basic 2005.
Process of Upgrading
The upgrade process happens automatically when you open a Visual Basic 6.0 project in Visual Basic 2005: the Upgrade
Wizard steps you through the upgrade process and creates a new Visual Basic 2005 project (your existing project is left
unchanged). This is a one-way process; the new Visual Basic 2005 project cannot be opened in Visual Basic 6.0.
When your project is upgraded, the language is modified for any syntax changes and your Visual Basic 6.0 forms are converted
to Windows Forms. In most cases, you will have to make some changes to your code after it is upgraded. This is required
because certain objects and language features either have no equivalent in Visual Basic 2005 or have an equivalent too
dissimilar for an automatic upgrade. After the upgrade, you may also want to change your application to take advantage of
some of the new features in Visual Basic 2005.
To help you make the changes, after your project is upgraded, Visual Basic 2005 adds an upgrade report to your project
itemizing any problems. It also inserts comments into your upgraded code alerting you to statements that will need to be
changed. Because these comments are displayed as 'TO DO' tasks in the new Task List window, you can easily see what
changes are required and navigate to the corresponding code statement simply by double-clicking the task. Each task and item
in the upgrade report is associated with a Help topic giving further guidance as to why the code needs to be changed, and what
you need to do.
See Also
Concepts
Completing the Upgrading Process
Why Upgrading Is Necessary
Preparing a Visual Basic 6.0 Application for Upgrading
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts

How to: Upgrade a Project with the Visual Basic Upgrade


Wizard
The Visual Basic Upgrade Wizard can be used to upgrade Visual Basic 6.0 projects for further development in Visual Basic
2005. The Upgrade Wizard does not modify your original Visual Basic 6.0 project, but rather creates a new Visual Basic 2005
project based on the original project.
Note
Although the wizard makes the upgrade process easier, you may be required to modify some code in the upgraded applicati
on. You should take some time to familiarize yourself with Visual Basic 2005 before attempting this process.

Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To upgrade a Visual Basic 6.0 project to Visual Basic 2005


1. Open your project in Visual Basic 6.0. On the File menu, choose Make <projectname>. Run the application and make
sure that there are no errors.
2. Start Visual Studio 2005. On the File menu, point to Open, and then click Project/Solution.
3. In the Open Project dialog box, browse to the location of the Visual Basic 6.0 project and select the project (.vbp) file.
This will open the Visual Basic Upgrade Wizard.
4. On the second page of the wizard, choose from the available upgrade options. The options will vary depending on the
type of project being upgraded.
Tip
For an explanation of available options, press F1 while in the wizard.

5. On the third page of the wizard, enter the location where the new project will be created.
Note
Each Visual Basic 2005 project must be in its own folder. If you specify a folder that contains files, you will be prompted
to choose a different folder.

6. On the fourth page of the wizard, click Next to begin the upgrade process. When the process is complete, the new
project will appear in Solution Explorer.
7. In Solution Explorer, double-click the _UpgradeReport.htm node to open the upgrade report.
8. Review the upgrade report. Any errors must be fixed before you can run the application. Any warnings should be
examined to make sure that they do not affect application behavior.
Tip
For an explanation of any error or warning, click on the description to display a Help topic.

9. On the Debug menu, choose Start. Run the application and make sure that there are no errors and that the behavior is
the same as it was in Visual Basic 6.0.
Note
The Upgrade Wizard cannot catch all possible incompatibilities; it is possible that you will encounter additional errors w
hen you run the application. For a list of known issues, see
Troubleshooting Applications Upgraded from Visual Basic 6.0.

See Also
Tasks
How to: View the Upgrade Report
Concepts
Preparing a Visual Basic 6.0 Application for Upgrading
WebClasses for Visual Basic 6.0 Users
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Reference

Upgrade Visual Basic 6 Code Dialog Box


Use the Upgrade Visual Basic 6 Code dialog box to upgrade Visual Basic 6.0 code to Visual Basic 2005 by typing code into
the Code window or pasting code from the Visual Basic 6.0 Code Editor. When you click the Upgrade button, the upgraded
code is inserted into the Visual Basic 2005 Code Editor at the cursor location.
In addition, COM references required by the Visual Basic 6.0 code can be added to the References tab; these are added to the
references in your Visual Basic 2005 project.
To access the Upgrade Visual Basic 6 Code dialog box, choose Upgrade Visual Basic 6 Code from the Tools menu.
Note
The Upgrade Visual Basic 6 Code command is only available when working in the Code Editor.

User Interface Element List


Code
Visual Basic 6.0 code can be typed into the code window or pasted from the Code Editor. Code is retained between uses so
that you can further modify it.
References
Displays COM references required by your Visual Basic 6.0 code.
Reference Name
Displays the friendly name of the COM component. Only references that are checked will be added to the Visual Basic 2005
project.
Version
Displays the version number (major and minor) of the COM component.
Path
Displays the file path and file name for the COM component.
Add Reference
Displays the Add Reference dialog box that contains a list of available COM components.
Upgrade
Upgrades any code entered into the code window and inserts it in the Visual Basic 2005 Code Editor; also adds any checked
references in the References list to the Visual Basic 2005 project.
Tips for Using the Upgrade Visual Basic 6 Code Dialog Box
The Upgrade Visual Basic 6 Code dialog box cannot successfully convert all code. To maximize your use of this tool:
See Things to Consider Before Upgrading.
Make your code easier to upgrade by following the recommendations in Language Recommendations for Upgrading.
How your Visual Basic 6.0 code is written can affect how it is upgraded.
Test the code in Visual Basic 6.0 before attempting the upgrade. If the code does not run in Visual Basic 6.0, it will not run
in Visual Basic 2005.
Event signatures in Visual Basic 2005 are different than their Visual Basic 6.0 counterparts. When entering code for form
or control event procedures, first add the procedure declaration in Visual Basic 2005 and then upgrade only the body of
the procedure.
The Upgrade Visual Basic 6 Code dialog box is designed to upgrade small sections of code. The code typed into the
dialog box determines the context for the upgrade.
For example, the statement L.Caption = "MyCaption" would not be translated because the tool cannot determine the
type for "L" to resolve the property Caption. Inserting a declaration for L (such as Dim L As Label) prior to the statement
results in a successful upgrade.
Check that the syntax is correct for your Visual Basic 6.0 code, as incorrect syntax can cause an Untranslated statement
in WrapperSub error.

For best performance, upgrade code in modules rather than in Form modules. If you need to upgrade a form, use the
Upgrade Wizard.
If you paste code that contains Unicode characters, a dialog will appear asking if you want to remove them. If you choose
OK, the code will be parsed and any Unicode characters will be removed.
See Also
Tasks
How to: Upgrade Visual Basic 6.0 Code with the Upgrade Visual Basic 6 Code Dialog Box
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts

How to: Upgrade Visual Basic 6.0 Code with the Upgrade Visual
Basic 6 Code Dialog Box
The Upgrade Visual Basic 6 Code dialog box is a tool that converts Visual Basic 6.0 code to equivalent Visual Basic 2005
code. Unlike the Visual Basic Upgrade Wizard, which upgrades an entire application, the Upgrade Visual Basic 6 Code dialog
box is available at design time to convert small amounts of code as you are developing your Visual Basic 2005 application.
The Upgrade Visual Basic 6 Code dialog box is useful in two ways:
You can make use of existing Visual Basic 6.0 code by pasting it into the tool.
You can type in code using Visual Basic 6.0 syntax in order to learn the Visual Basic 2005 equivalent.
After running the tool, Visual Basic 2005 code is inserted into the Code Editor at the current cursor location. If there are any
problems with the conversion, comments are inserted with clickable links to Help pages that explain the problem and any
possible workarounds.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To upgrade Visual Basic 6.0 code


1. In the Code Editor, move your mouse pointer where you want to insert code.
2. On the Tools menu, choose Upgrade Visual Basic 6 Code.
The Visual Basic 6.0 Code Upgrade dialog box is displayed.
3. In the Visual Basic 6.0 Code Upgrade dialog box, paste existing Visual Basic 6.0 code, or enter code using Visual Basic
6.0 syntax.
Note
If you paste code that contains Unicode characters, a dialog will appear asking if you want to remove them. If you choo
se OK, the code will be parsed and any Unicode characters will be stripped out.

4. If your code references a COM component, select the References tab and click Add Reference, then select the reference
in the Add Reference dialog box.
5. Click Upgrade to convert the code and insert it into the Code Editor.
Any COM references will be added to the References node for your project in Solution Explorer, and a project-level
Imports statement will be added for the Microsoft.VisualBasic.Compatibility namespace.
See Also
Reference
Upgrade Visual Basic 6 Code Dialog Box
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts

How to: Emulate a Visual Basic 6.0 Tri-state Control in an


Upgraded Application
In Visual Basic 6.0, the Picture, DownPicture, and DisabledPicture properties are used to display different pictures based on
the state of a CheckBox, CommandButton, or OptionButton control. For example, when a CheckBox control is checked, the
DownPicture image is displayed; if the control is disabled, the DisabledPicture image is displayed.
In Visual Basic 2005 you can achieve the same effect using an ImageList control as outlined in the following example.
Note
First, check your Visual Basic 6.0 application. If the DownPicture and DisabledPicture properties are not set at design time
or run time, the behavior should be the same in Visual Basic 2005.

Note
The dialog boxes and menu commands you see might differ from those described in Help, depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

Adding an ImageList Control


Take the following steps to modify the upgraded application if the DownPicture or DisabledPicture properties are set.
To emulate a tri-state control
1. Determine the file names and locations of the images that were assigned to the Picture, DownPicture, and
DisabledPicture properties and, if necessary, copy these to your development computer.
2. From the Toolbox, add an ImageList control to your form.
3. In the Properties window, select the Images property.
4. In the Image Collection editor, add three images to be used for the Picture, then the DownPicture, and then the
DisabledPicture.
5. If any of the properties were set at run time, remove the code. If any of the properties were set at design time, add the
following code to the Load event for the form:
VB
' Assign the first image (Picture) to the Image property.
CheckBox1.Image = ImageList1.Images(0)

6. To display the DownPicture image at run time, add the following code to the CheckedChanged event for the CheckBox
control.
VB
If CheckBox1.Checked = True Then
' Assign the second image (DownPicture) to the Image property.
CheckBox1.Image = ImageList1.Images(1)
Else
' Assign the first image (Picture) to the Image property.
CheckBox1.Image = ImageList1.Images(0)
End If

7. To display the DisabledPicture image at run time, add the following code to the EnabledChanged event for the
CheckBox control.
VB
If CheckBox1.Enabled = False Then
' Assign the third image (DisabledPicture) to the Image property.
CheckBox1.Image = ImageList1.Images(2)
ElseIf CheckBox1.Checked = True Then
' Assign the second image (DownPicture) to the Image property
CheckBox1.Image = ImageList1.Images(1)
Else
' Assign the first image (Picture)to the Image property
CheckBox1.Image = ImageList1.Images(0)
End If

The application should now behave exactly as it did in Visual Basic 6.0.
See Also
Concepts
Style Property for Visual Basic 6.0 Users
CheckBox Control for Visual Basic 6.0 Users
CommandButton Control for Visual Basic 6.0 Users
OptionButton Control for Visual Basic 6.0 Users
OptionButton Control for Visual Basic 6.0 Users
User Controls for Visual Basic 6.0 Users
Visual Basic Concepts

Upgrading WebClass Projects to Visual Basic 2005


Visual Basic 6.0 WebClass projects (also known as IIS Application projects) can be upgraded to ASP.NET Web Site projects
using the Upgrade wizard. The process for upgrading WebClass projects is essentially the same as for any other project type;
however, there are some issues that you will want to be aware of.
Upgrading WebClasses
When a WebClass project is upgraded, by default the project is created with a new project name of projectname.NET (where
projectname is the name of the Visual Basic 6.0 project).
When a Visual Basic 6.0 WebClass project is upgraded to ASP.NET, the .asp file for the project is upgraded to an .aspx file. Any
references to the .asp file within an HTML template file are not automatically changed to .aspx references. These are not
upgraded because a template file might contain references to other .asp files that were not part of the WebClass project.
In addition, when files are copied to the new project directory during upgrade, only HTML template files are copied. Any other
.html files or image files are not copied to the new directory.
When you add HTML files to an ASP.NET Web Site project, they are added as Content files by default. When a WebClass project
is upgraded, HTML files are added as Embedded Resources. If you add HTML Files to the project after upgrading, you must set
their Build Action property to Embedded Resource in order to make them visible to the application.
Tip
You can still reference an HTML file that is not embedded by providing a full path to the file.

If you have never created an ASP.NET Web Site Application before upgrading your first Visual Basic 6.0 WebClass project, you
will need to set the project's StartUp object. You do so by right-clicking the .aspx file and selecting Set As Start Page from the
shortcut menu before running the upgraded project.
See Also
Concepts
WebClasses for Visual Basic 6.0 Users
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts

Completing the Upgrading Process


After running the Upgrade Wizard, your upgraded project is opened in Visual Basic 2005. The project appears in Solution
Explorer; it includes upgraded copies of all project files plus an upgrade report.
In most cases, there is additional work that needs to be done to ensure that your project runs successfully in Visual Basic 2005.
There are three categories of work items that must be completed:
UPGRADE_ISSUE errors are items that prevent the application from compiling. You must correct these errors before
running the project. These are reported in the upgrade report and also appear as items in the Task List.
UPGRADE_TODO errors are items that do not keep the project from compiling but that cause run-time errors. You must
correct these errors before running the project. These are reported in the upgrade report, as items in the Task List, and
as comments in the upgraded code.
UPGRADE_WARNING errors are items that do not keep the project from compiling but that may cause run-time errors.
You should investigate these and correct them as necessary. These are reported in the upgrade report, as items in the
Task List, and as comments in the upgraded code.
UPGRADE_NOTE items are items that represent major changes to code or behavioral differences, which could have
potential side effects. You should read these notes and decide if you need to make changes. These are reported as
comments in the code.
To complete the upgrade process, you need to check the Task List for any errors or warnings and search your code for any
comments that begin with "UPGRADE_NOTE".
Tip
Every comment line inserted into your code during upgrade contains a hyperlink. Clicking the link (CTRL+click) takes you to
a Help page that explains the issue and what you need to do to address it. The link appears at the end of the comment line; y
ou may need to scroll in order to see it.

See Also
Concepts
Visual Basic Upgrade Wizard
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts

Visual Basic Upgrade Report


When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, an upgrade report is added to the project in Solution
Explorer. The upgrade report contains information about the upgrade process as well as a list of issues uncovered during the
upgrade that will need to be addressed before your project can be run.
Details of the Report
The upgrade report is in HTML format; you can view it within the Visual Basic 2005 development environment by double-
clicking the _UpgradeReport.htm file in Solution Explorer, or you can view it in an external browser by choosing View in
Browser from the context menu.
The first portion of the report contains general information about the upgrade, including the settings that were used during the
upgrade and the location of the new project files.
The remainder of the report contains a listing of global issues plus a listing for each file that was upgraded. By expanding the
section for each file, you can view a detailed list of issues that will need to be addressed. Each issue includes information about
the severity of the issue, the location of the code that must be fixed, and a description of the issue.
See Also
Concepts
Completing the Upgrading Process
Visual Basic Upgrade Wizard
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts

How to: View the Upgrade Report


When a Visual Basic 6.0 project is upgraded to Visual Basic 2005, an upgrade report is created and placed in the new project
folder. The upgrade report contains summary information about the upgrade process plus information on any errors or issues
encountered during upgrade.
Note
The upgrade report is only generated for projects upgraded using the Upgrade Wizard; no reported is generated for projects
upgraded from the command line.

The upgrade report can be viewed in the Visual Basic 2005 integrated development environment (IDE) or in any Web browser.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To view the upgrade report in Visual Studio 2005


In Solution Explorer, double-click the _UpgradeReport.htm node to open the upgrade report.
To view the upgrade report in a Web browser
1. In Solution Explorer, select the _UpgradeReport.htm node.
2. On the File menu, choose Browse With.
3. In the Browse With dialog box, select the Web browser.
See Also
Concepts
Preparing a Visual Basic 6.0 Application for Upgrading
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts

How to: Upgrade a Project from the Command Line


In addition to the Visual Basic Upgrade Wizard, Visual Basic 6.0 projects can be upgraded to Visual Basic 2005 using a
command-line tool, Vbupgrade.exe.
Note
Vbupgrade.exe is not on the path by default. You will need to either add it to the path or switch to the directory where it is ins
talled before running it from the command line. The default installation location is C:\Program Files\Microsoft Visual Studio
8\Vb\VBUpgrade.

Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To upgrade a project from the command line


1. Open your project in Visual Basic 6.0. On the File menu, choose Make <projectname>. Run the application and make
sure that there are no errors.
2. At a command prompt, type Vbupgrade <projectname> (where <projectname> is the full path for the Visual Basic 6.0
application) plus any additional command-line arguments.
Note
For information on Vbupgrade command-line syntax and options, see Vbupgrade Command-Line Syntax.

3. Open the resulting project in Visual Basic 2005. Review the code — notes are inserted into the code during upgrade to
alert you to any potential problems. Any errors must be fixed before you can run the application. Any warnings should be
examined to make sure that they do not affect application behavior.
Tip
For an explanation of any error or warning, click on the description to display Help.

4. On the Debug menu, choose Start. Run the application and make sure that there are no errors and that the behavior is
the same as it was in Visual Basic 6.0.
Note
The Vbupgrade tool cannot catch all possible incompatibilities; it is possible that you will encounter additional errors w
hen you run the application. For a list of known issues, see
Troubleshooting Applications Upgraded from Visual Basic 6.0.

See Also
Tasks
How to: View the Upgrade Report
Reference
Vbupgrade Command-Line Syntax
Concepts
Preparing a Visual Basic 6.0 Application for Upgrading
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Reference

Vbupgrade Command-Line Syntax


The Vbupgrade.exe command-line tool upgrades a Visual Basic 6.0 application to Visual Basic 2005.

vbupgrade[.exe] inputname [/out outputname] [/verbose [/nolog [/logfile logfilename]]]


vbupgrade[.exe] /?

Arguments
inputname
Required.
Specifies the path and file name of the Visual Basic 6.0 project to be upgraded.
/out outputname
Specifies the path for the folder where the Visual Basic 2005 project will be created. The default path is \OutDir.
/verbose
Displays all output to the Command Prompt window during upgrade.
/nolog
Does not create a log file during upgrade.
/logfile logfilename
Specifies the path and file name for the log file created during upgrade. If the path and file name are not specified, a log file is
created in the same folder as the Visual Basic 2005 project. The default file name is ProjectFileName.log, where
ProjectFileName is the name of the project file.
/?
Displays a list of command-line options.
Remarks
Paths or file names that contain spaces must be surrounded by quotation marks.
See Also
Tasks
How to: Upgrade a Project from the Command Line
Reference
Upgrade Wizard
Visual Basic Concepts

Troubleshooting Applications Upgraded from Visual Basic 6.0


Although the upgrading tools in Visual Basic 2005 are carefully designed to detect and report any issues with upgraded
applications, there are some cases that cannot possibly be detected. This page lists some known issues that are not detected by
the upgrading tools and explains how to address them.
Cannot Access Help Links After Upgrading Visual Studio
When working with an application upgraded with an earlier version of Visual Studio, the Help links inserted by the upgrade
tool may cause a "Page not found" error. This occurs because the links reference the Help collection for the earlier version, and
the format for the Help links have changed.
To fix this problem, you can copy the error string and use the Search function in Help to find the topic. Note that some error
strings include variables, so you may need to search on a partial string.
Behavioral Difference for Fixed-length Strings in User-defined Types
In Visual Basic 6.0, strings assigned to a fixed-length string in a user-defined type are automatically truncated if they are longer
than the fixed length. After upgrading to Visual Basic 2005, strings are no longer truncated, possibly resulting in incorrect
results.
Note
During upgrade, the VBFixedString attribute is added to fixed-length strings in user-defined types. This attribute allows the
file functions in the Visual Basic Compatibility library to treat them as fixed-length strings.

To fix this problem, find any code that assigns a string to the fixed-length string and add code to check the length of the string
and truncate it if necessary:
VB
' Before
MyString = "1234567"
MyStruct.FixedString5 = MyString

' After
MyString = "1234567"
If Len(MyString) > 5 Then
MyString = Microsoft.VisualBasic.Left(MyString, 5)
End If
MyStruct.FixedString5 = MyString

Closing a Form Calls Dispose


In Visual Basic 6.0, you can unload a form and later reload it by calling the Show method. In Visual Basic 2005, the Close
method for a form calls the Dispose method so that it is automatically garbage-collected. This can cause subtle behavioral
differences that may be hard to detect.
In Visual Basic 2005, if you call the Show method for a form that has been unloaded, you will get a new instance of the
form; any property settings from the base class will be lost.
For forms that are shown modally, Dispose is not called automatically. In some cases, you may want to call Dispose in
order to clean up resources.
Late-bound Calls to COM Objects May Cause Type Mismatch Errors
In Visual Basic 6.0, when a late-bound COM object is passed as a parameter to a late-bound call, the object is coerced to a
Variant of type Nothing. When upgraded to Visual Basic 2005, COM objects declared as type Object are treated the same as
Variants (which are always converted to type Object during upgrade); these objects are marshaled to the variant type Empty.
This causes a type mismatch error in Visual Basic 2005.
To fix this problem, make sure that all objects are early bound.
Values Returned by Err.Number May Be Different
In some cases, errors returned by Visual Basic 2005 may be different than those returned by Visual Basic 6.0. For error
handling code that relied on the values returned by Err.Number, this might cause different behavior in your application.
The following code shows an example of this:

' Visual Basic 6.0


On Local Error GoTo Result
Dim x() As Boolean
Dim y As Variant
y = x(10)

Result:
If Err.Number = 9 Then
' Do something.
Else
' Do something else.
End If

Before upgrading, Err.Number will always return 9 (Subscript out of range) and execute the first part of the If statement. After
upgrading, it will return 91 (Object variable or With block not set) and execute the Else clause. This is because in Visual Basic
2005, an array must be initialized before it can be referenced; in Visual Basic 6.0, arrays are initialized when declared.
If you depend on the return values from Err.Number in your code, you should carefully test the results and modify your code
as necessary.
See Also
Concepts
Working with Both Visual Basic 6.0 and the Current Version of Visual Basic
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts

Working with Both Visual Basic 6.0 and the Current Version of
Visual Basic
Both Visual Basic 2005 and Visual Basic 6.0, as well as applications created in either language, can be installed on the same
computer and run at the same time.
Components written in Visual Basic 2005 can interoperate with COM components written in earlier versions of Visual Basic
and other languages. For example, you can drag an ActiveX control written in Visual Basic 6.0 onto a Visual Basic 2005
Windows Form, use a Visual Basic 6.0 COM object from a Visual Basic 2005 class library, or add a reference to a Visual Basic
2005 library to a Visual Basic 6.0 executable.
Components compiled with Visual Basic 2005 have subtle run-time differences compared to components compiled with Visual
Basic 6.0. Because Visual Basic 2005 objects are released through garbage collection, when objects are explicitly destroyed,
there may be a lag before they are actually removed from memory. There are additional differences, such as data type and
other language changes. The combined result of these differences is that Visual Basic 2005 applications will have similar but
not identical run-time behavior to Visual Basic 6.0 applications.
In addition, Visual Basic 2005 makes binary compatibility between Visual Basic 2005 components and those in Visual Basic 6.0
unnecessary. Components now have a more robust versioning and deployment system, files can be deployed by simply
copying to a directory, and upgrading to a new version of a component is as simple as replacing the old file with a new file. All
you have to do is ensure classes and methods are compatible with the previous versions.
See Also
Concepts
Why Upgrading Is Necessary
Preparing a Visual Basic 6.0 Application for Upgrading
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Concepts

Walkthrough: Upgrading a Visual Basic 6.0 Application to the


Current Version of Visual Basic
In this walkthrough, you will upgrade a Visual Basic graphics sample application to Visual Basic 2005. In addition to illustrating
the upgrading process, this walkthrough highlights the differences in graphics architectures between Visual Basic 6.0 and
Visual Basic 2005. This should also serve as an introduction to dealing with architectural issues in your applications.
The sample application in this case is a simple form that contains two buttons, a picture box, a timer, and a hidden image
control. Although not typical of most applications that you will want to upgrade, it does present several challenging issues that
you may face when upgrading your own applications.
Note
This walkthrough requires Visual Basic 6.0 to be installed on your development computer.

To create the Visual Basic 6.0 application


1. Open Visual Basic 6.0. On the File menu, choose New Project.
2. In the New Project dialog box, choose Standard EXE, and click OK.
3. Add a PictureBox control to the form, and size it to fill most of the form, leaving space at the bottom.
4. Set the AutoRedraw property to True, the DrawStyle property to 0-Solid, and the FillStyle property to 0-Solid.
5. Add two CommandButton controls below the PictureBox control.
6. Select the first CommandButton, and set the Name property to ClearPictureBox and the Caption property to Clear.
7. Select the second CommandButton, and set the Name property to ShowImage and the Caption property to Show Image.

8. Add an Image control to the form, and set the Name property to sourceImage and the Visible property to False.
9. Set the Picture property of the Image control to any bitmap image. You can use one of the pictures in your My Pictures
folder.
10. Add a Timer control to the form. Set the Enabled property to False and the Interval property to 25.
11. Double-click the form to open the Code Editor, and enter the following code.

Option Explicit
Private LeftPos As Double

Private Sub ClearPictureBox_Click()


Picture1.Cls
End Sub

Private Sub ShowImage_Click()


LeftPos = 1
Me.Timer1.Enabled = True
End Sub

Private Sub Timer1_Timer()

If LeftPos <= 0 Then


Me.Timer1.Enabled = False
Picture1.Print "Visual Basic ROCKS!"
Else
LeftPos = LeftPos - 0.01
Picture1.Cls
Picture1.PaintPicture sourceImage, LeftPos * _
Picture1.Width, 0
End If
End Sub

12. Press F5 to run the application. Click the buttons to observe the behavior, and step through the code to see how it works.
13. On the File menu, choose Save Project As.
14. In the Save File As dialog box, save the form as PicForm.frm and save the project as Drawing.vbp.

To run the Upgrade wizard


1. Open Visual Basic 2005. On the File menu, choose Open Project.
2. In the Open Project dialog box, locate the Drawing.vbp file and open it.
This launches the Visual Basic Upgrade Wizard. The first page of the wizard contains an explanation of what the wizard
will do.
3. Click Next to go to the second page of the wizard. This page presents options for upgrading; in this case, there are no
applicable options available.
4. Click Next to go to the third page of the wizard. Click Next to accept the default location for the new project, or enter a
different location. The default location is a new folder immediately beneath the Visual Basic 6.0 project's folder.
If prompted to create a new folder, choose Yes.
5. On the fourth page of the Wizard, click Next to begin the upgrade.
When the upgrade is finished, the wizard closes, and the new project appears in Solution Explorer.

To view the upgrade results


1. In Solution Explorer, select _UpgradeReport.htm and double-click it to open the Upgrade Report.
Notice that the report shows no global issues that need to be addressed; for PicForm.vb it shows six errors and no
warnings.
Note
If there were warnings, they would also appear in the Task List window as UPGRADE_WARNING items. Warnings are f
or code that might cause subtle differences in the run-time behavior of your application. Double-clicking an UPGRADE_
WARNING in the Task List window takes you directly to the code that may need to be modified.

2. Expand the PicForm.vb section by clicking on the plus sign in the New Filename column. This displays a detailed list of
upgrade issues for the form.
Notice that the issues apply to three different locations: the ClearPictureBox_Click procedure, the Timer1_Timer
procedure, and the form layout. You can click on the Description link to display a Help topic explaining each issue. The
layout issues in this case do not require any action; checking the Help reveals that they are for two properties of the
Visual Basic 6.0 PictureBox control that do not map to equivalent Visual Basic 2005 properties.
To fix the ClearPictureBox_Click error
1. In Solution Explorer, select PicForm.vb. On the View menu, choose Code.
2. In the Code Editor, select the ClearPictureBox_Click procedure.
Tip
There is an UPGRADE_ISSUE comment added to the procedure. If you scroll to the end of the comment, you can click o
n the link that displays the associated Help topic. All issues (except for layout issues) are added as code comments duri
ng an upgrade, including UPGRADE_NOTE comments explaining what happened during the upgrade; these do not app
ear in the Upgrade Report.

3. Add the following code to the ClearPictureBox_Click procedure:


3. Add the following code to the ClearPictureBox_Click procedure:
VB
Dim g As Graphics = Picture1.CreateGraphics()
g.Clear(Picture1.BackColor)
g.Dispose()

The only error in the original procedure is the Picture1.Cls() method call. In Visual Basic 2005, the intrinsic controls do
not provide direct access to their drawing surfaces with methods (as in Visual Basic 6.0). All graphics operations are
handled with a special object of type Graphics. You can access a control's drawing surface by calling the
CreateGraphics() method to get an instance of a Graphics object.
4. Delete or comment out the original line, Picture1.Cls().

To fix the Timer1_Timer errors


1. In the Code Editor, select the Timer1_Tick procedure.
Note
The Timer event from the Visual Basic 6.0 Timer control is upgraded to the Tick event of the Visual Basic 2005 Timer
component. The Upgrade Report shows the old event name; the Code Editor uses the new event name.

2. At the start of the function, add the following code:


VB
Dim g As Graphics = Picture1.CreateGraphics()

As with the previous procedure, the errors here begin with the lack of a Graphics object.
3. Find the first UPGRADE_ISSUE, the Picture1.Print method. Add the following code:
VB
g.DrawString("VB .NET ROCKS!", Me.Font, New SolidBrush( _
Color.Yellow), 0, 0)

The DrawString method of the Graphics object replaces the Visual Basic 6.0 Print method. Where the Print method
took a single Text argument, DrawString also takes arguments specifying the Font, a Brush object that specifies a
Color object, and the starting coordinates for drawing the text.
4. Delete or comment out the original line, Picture1.Print("Visual Basic ROCKS!").

5. Find the next UPGRADE_ISSUE, Picture1.Cls(). Replace the code with the following:
VB
g.Clear(Picture1.BackColor)

6. Find the last UPGRADE_ISSUE, Picture1.PaintPicture. Add the following code:


VB
g.DrawImage(sourceImage.Image, CSng(LeftPos * Picture1.Size.Width), _
0)

In this case, the DrawImage method of the Graphics class replaces the PaintPicture method.
7. Delete or comment out the original line, Picture1.PaintPicture(sourceImage, LeftPos *
VB6.PixelsToTwipsX(Picture1.Width), 0).

8. At the end of the procedure, add the following code:


VB
g.Dispose()

The Dispose method is necessary to free up the memory resources associated with the Graphics object.

To test the application


1. On the Debug menu, choose Start.
Note
if you are prompted to save the Solution file, click Save to save the file and run the application.

2. Click the ShowImage button.


You will notice that the image flickers when drawing. This is due to the entire area being cleared before each updated
image is drawn on the screen.
Further Modifying the Application
The solution here is to draw only to the necessary parts of the screen, instead of the entire area represented by the Graphics
object. You will want to make sure that when the image is drawn on the screen, any pixels remaining on the screen from the
last call to DrawImage() are obscured with the background color. Since the image is moving from right to left, you only have
to obscure the additional pixels to the right of the picture.
To fix the screen flicker problem
1. In the Timer1_Tick procedure, replace the g.Clear(Picture1.BackColor) method with the following code:
VB
Dim imageWidth As Integer = sourceImage.Image.Width
Dim imageHeight As Integer = sourceImage.Image.Height
Dim left As Double = imageWidth + (Picture1.Size.Width * LeftPos)

g.FillRectangle(New SolidBrush(Me.BackColor), _
New Rectangle(left, 0, 6, imageHeight))

In place of the Clear method, use the FillRectangle method, using the background color to obscure any remaining
pixels to the right of the current image being drawn. To do this, you first need to calculate the left-most coordinate of the
rectangle, which is accomplished by the first three lines of code.
2. On the Debug menu, choose Start.
3. Click the ShowImage button.
You will notice that the image no longer flickers as it moves.
There is still one additional problem that should be fixed. You may have noticed that the message displayed in the PictureBox
control is in a smaller font than the original version. This is because the Font property of the PictureBox control in the Visual
Basic 6.0 application was set to Arial Bold 16 at design time. There is no Font property for the Visual Basic 2005 PictureBox
control; instead, the form's default font (Me.Font) is used. You can remedy this by declaring a new Font object.
To fix the font
1. In the Timer1_Tick procedure, add the following declaration:
VB
Dim f As System.Drawing.Font = New System.Drawing.Font("Arial", _
16, FontStyle.Bold)

2. In the call to g.DrawString, change the font parameter from Me.Font to f.


3. On the Debug menu, choose Start.
4. Click the ShowImage button.
The text is now displayed in the correct font.
Now that the application is back to parity with the original Visual Basic 6.0 application, you will add some code to enhance the
application. After all, there is no point in upgrading the application if you do not want to take advantage of Visual Basic 2005.
In the next step, you will add functionality to make the form fade out slowly when it is closed.
Note
The fade effect is not visible on 256-color displays; you will need to set your color depth to High Color or True Color to view t
he results. The Opacity property works only on Windows XP.

To enhance the application


1. In the Code Editor, select the Class Name drop-down list and choose (Form1 Events).
2. In the Method Name drop-down box, select the FormClosing event.
3. In the Form1_FormClosing procedure, add the following code:
VB
Dim i As Single
For i = 1 To 0 Step -0.1
Me.Opacity = i
Application.DoEvents()
System.Threading.Thread.Sleep(100)
Next

4. On the Debug menu, choose Start.


5. Close the form and notice how it fades away.
You can control how fast it fades by increasing the size of the step (or by reducing the Sleep delay).
See Also
Reference
Windows Forms Overview
Concepts
Graphics for Visual Basic 6.0 Users
Other Resources
Upgrading from Visual Basic 6.0
Visual Basic Reference

Visual Basic 6.0 Upgrading Reference


The topics in the following section of the Table of Contents are reference topics related to the Upgrade Wizard and the
VisualBasic.Compatibility namespace.
See Also
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Reference

Upgrade Wizard
Use the Upgrade Wizard to upgrade Visual Basic 6.0 projects to Visual Basic 2005. The wizard creates a new project, copies
each file from the original project into the new project and modifies it as necessary, and generates a report detailing what was
done and what you need to do to finish the upgrade.
To access the Upgrade Wizard, open any Visual Basic 6.0 project file (.vbp) in Visual Basic 2005.
User Interface Element List
The following options are available in the Upgrade Wizard.
What type of project would you like this to be upgraded to?
If the Visual Basic 6.0 project is an ActiveX EXE or ActiveX Document EXE project, you can upgrade it to either an .exe or a .dll
file. For all other project types, the correct option is already selected and cannot be changed.
Where do you want your new project created?
Specifies the location of the new project. By default, the project is placed in a directory directly beneath the Visual Basic 6.0
project. The new project is named ProjectName.NET, where ProjectName is the name of the project being upgraded.
See Also
Concepts
Visual Basic Upgrade Wizard
Other Resources
Upgrading Applications Created in Previous Versions of Visual Basic
Visual Basic Reference

VisualBasic.Compatibility Namespace Reference


Functions and objects in the VisualBasic.Compatibility namespace are provided for use by the Visual Basic 6.0 to Visual
Basic 2005 upgrade tools. In most cases, they duplicate functionality that can be achieved using other parts of the .NET
Framework; they are necessary only where the Visual Basic 6.0 code model differs significantly from the .NET implementation.
Functions and Objects in the Namespace
The following tables list functions and objects in the VisualBasic.Compatibility namespace. Additional functions and objects
related to the Microsoft.Compatibility.Data namespace are not listed; they are the equivalents of the ADO data binding in
Visual Basic 6.0.
VisualBasic.Compatibility Functions
Function Description
CopyArray Duplicates Visual Basic 6.0 functionality of assigning an array to a variant.

CursorToIPicture Used in format conversion.

Eqv Duplicates the Visual Basic 6.0 Eqv (equivalence) operator.

FontChangeBold Used in converting Visual Basic 6.0 fonts to Visual Basic 2005 Font objects.

FontChangeGdiCharSe Used in converting Visual Basic 6.0 fonts to Visual Basic 2005 Font objects.
t

FontChangeItalic Used in converting Visual Basic 6.0 fonts to Visual Basic 2005 Font objects.

FontChangeName Used in converting Visual Basic 6.0 fonts to Visual Basic 2005 Font objects.

FontChangeSize Used in converting Visual Basic 6.0 fonts to Visual Basic 2005 Font objects.

FontChangeStrikeout Used in converting Visual Basic 6.0 fonts to Visual Basic 2005 Font objects.

FontChangeUnderline Used in converting Visual Basic 6.0 fonts to Visual Basic 2005 Font objects.

FontToIFont Used in format conversion.

Format Duplicates the Visual Basic 6.0 Format function.

FromPixelsX Used for coordinate conversion.

FromPixelsY Used for coordinate conversion.

FromPixelsUserHeight Used for coordinate conversion.

FromPixelsUserWidth Used for coordinate conversion.

FromPixelsUserX Used for coordinate conversion.

FromPixelsUserY Used for coordinate conversion.

GetActiveControl Duplicates the Visual Basic 6.0 Screen.ActiveControl property.

GetCancel Duplicates the functionality of the Cancel property of a Visual Basic 6.0 CommandButton.
GetDefault Duplicates the functionality of the Default property of a Visual Basic 6.0 CommandButton.

GetEXEName Duplicates the Visual Basic 6.0 App.EXEName property.

GetHInstance Duplicates the Visual Basic 6.0 App.HInstance property.

GetItemData Duplicates the functionality of the ItemData property of a Visual Basic 6.0 ListBox or ComboBox.

GetItemString Duplicates the functionality of retrieving a value from a list in a Visual Basic 6.0 ListBox or ComboB
ox.

GetPath Duplicates the Visual Basic 6.0 App.Path property.

IconToIpicture Used in format conversion.

IFontToFont Used in format conversion.

ImageToIPicture Used in format conversion.

ImageToIPictureDisp Used in format conversion.

Imp Duplicates the Visual Basic 6.0 Imp (implication) operator.

IPictureDispToImage Used in format conversion.

IPictureToImage Used in format conversion.

LoadResData Duplicates the Visual Basic 6.0 LoadResData function.

LoadResPicture Duplicates the Visual Basic 6.0 LoadResPicture function.

LoadResString Duplicates the Visual Basic 6.0 LoadResString function.

PixelsToTwipsX Used for coordinate conversion.

PixelsToTwipsY Used for coordinate conversion.

SendKeys Duplicates the Visual Basic 6.0 SendKeys function.

SetCancel Duplicates the functionality of the Cancel property of a Visual Basic 6.0 CommandButton.

SetDefault Duplicates the functionality of the Default property of a Visual Basic 6.0 CommandButton.

SetItemData Duplicates the functionality of the ItemData property of a Visual Basic 6.0 ListBox or ComboBox.

SetItemString Duplicates the functionality of setting a value in a list in a Visual Basic 6.0 ListBox or ComboBox.

SetResourceBaseNam Used with LoadRes functions when a resource file uses a non-standard naming convention.
e

ShowForm Duplicates the functionality of the Show method of a Visual Basic 6.0 form.

TabLayout Used when converting Debug.Print statements that contain the Tab or Spc keywords.
ToPixelsX Used for coordinate conversion.

ToPixelsY Used for coordinate conversion.

ToPixelsUserHeight Used for coordinate conversion.

ToPixelsUserWidth Used for coordinate conversion.

ToPixelsUserX Used for coordinate conversion.

ToPixelsUserY Used for coordinate conversion.

TwipsPerPixelX Duplicates the Visual Basic Screen.TwipsPerPixelX property.

TwipsPerPixelY Duplicates the Visual Basic Screen.TwipsPerPixelY property.

TwipsToPixelsX Used for coordinate conversion.

TwipsToPixelsY Used for coordinate conversion.

ValidateControls Duplicates the functionality of the ValidateControls method of a Visual Basic 6.0 form.

WhatsThisMode Duplicates the functionality of the WhatsThisMode method of a Visual Basic 6.0 form.

Zorder Used for converting the z-order of controls.


VisualBasic.Compatibility Objects
Object Description
BaseControlArray Parent class for Visual Basic 6.0 control array emulation.

BaseOcxArray Parent class for emulated arrays of ActiveX controls.

ButtonArray Emulates a Visual Basic 6.0 control array of CommandButton controls.

CheckBoxArray Emulates a Visual Basic 6.0 control array of CheckBox controls.

CheckedListBoxArray Emulates a Visual Basic 6.0 control array of ListBox controls with the Style property set to Checked.

ComboBoxArray Emulates a Visual Basic 6.0 control array of ComboBox controls.

DirListBox Emulates a Visual Basic 6.0 DirListBox control.

DirListBoxArray Emulates a Visual Basic 6.0 control array of DirListBox controls.

DriveListBox Emulates a Visual Basic 6.0 DriveListBox control.

DriveListBoxArray Emulates a Visual Basic 6.0 control array of DriveListBox controls.

FileListBox Emulates a Visual Basic 6.0 FileListBox control.

FileListBoxArray Emulates a Visual Basic 6.0 control array of FileListBox controls.

FixedLengthString Emulates Visual Basic 6.0 fixed-length strings.


GroupBoxArray Emulates a Visual Basic 6.0 control array of Frame controls.

HScrollBarArray Emulates a Visual Basic 6.0 control array of HScrollBar controls.

LabelArray Emulates a Visual Basic 6.0 control array of Label controls.

ListBoxArray Emulates a Visual Basic 6.0 control array of ListBox controls.

ListBoxItem Emulates the ItemData property of a ListBox control.

MenuItemArray Emulates a Visual Basic 6.0 control array of Menu controls.

PanelArray Emulates a Visual Basic 6.0 control array of PictureBox controls that contain child controls.

PictureBoxArray Emulates a Visual Basic 6.0 control array of PictureBox controls.

RadioButtonArray Emulates a Visual Basic 6.0 control array of OptionButton controls.

TabControlArray Emulates a Visual Basic 6.0 control array of TabStrip controls.

TextBoxArray Emulates a Visual Basic 6.0 control array of TextBox controls.

TimerArray Emulates a Visual Basic 6.0 control array of Timer controls.

VscrollBarArray Emulates a Visual Basic 6.0 control array of VScrollBar controls.


See Also
Concepts
Visual Basic 6.0 Compatibility Library
Other Resources
Help for Visual Basic 6.0 Users
Visual Basic Language Concepts

Developing Applications with Visual Basic


This section covers conceptual documentation for the Visual Basic language.
In This Section
Using the Visual Basic Editor
Contains Help on features of the Visual Basic editor, such as Intellisense Code Snippets, Project Properties, and creating
XML documentation for Visual Basic.
Security and Visual Basic Development
Discusses the three common areas where you need to address security concerns.
Programming in Visual Basic
Covers a variety of programming subjects.
Development with My
Discusses a new feature called My, which provides access to information and default object instances that are related to an
application and its run-time environment.
Accessing Data in Visual Basic Applications
Contains Help on accessing data in Visual Basic.
Debugging Your Visual Basic Application
Provides pointers to documentation for the debugging features built into Visual Studio.
Exception and Error Handling in Visual Basic
Contains Help on both structured and unstructured exception handling, as well as configuring warnings, Smart Compile
Auto Correction, and types of errors.
Deploying Your Application
Gives an overview of deployment features in the .NET Framework and Visual Studio.
Creating and Using Components in Visual Basic
Defines the term component and discusses how and when to create components.
Going Further with Visual Basic
Provides overviews of various subject areas, such as forms, network operations, and Web services.
Customizing Projects and Extending My with Visual Basic
Describes how you can customize project templates to provide additional My objects.
Related Sections
Visual Basic Programming Guide
Walks through the essential elements of programming with Visual Basic.
Visual Basic Reference
Contains reference documentation for the Visual Basic language.
Visual Basic Language Concepts

Using the Visual Basic Editor


In addition to the core user interface features that Visual Studio provides, Visual Basic adds some to help with productivity and
ease of use.
In This Section
Visual Basic Settings
Describes how to optimize your experience working in the development environment.
Visual Basic IntelliSense Code Snippets
Introduces a library of code that you can access from within the development environment.
How to: Edit Code Attributes
Discusses how to use the Properties window to apply and edit attributes for your types and members.
Refactoring and Rename Dialog Box (Visual Basic)
Describes the mechanism for renaming identifiers in your code.
Visual Basic 6.0 Default Shortcut Keys
Has links to various pages that list shortcut keys.
Help for Event Handlers in Visual Basic Code
Demonstrates how to get F1 Help on an event handler.
How to: Compile and Run a Project in Visual Basic
Describes your options for compiling and running from within the development environment.
Reference
Edit and Continue (Visual Basic)
Discusses the debugging feature that enables you to make changes to your code while it is executing in Break mode.
Smart Compile Auto Correction
Describes how this feature suggests corrections when errors occur, allowing you to pick a solution to be applied to the code.
Configuring Warnings in Visual Basic
Describes how you can turn warnings off or have warnings treated as error messages.
Visual Basic Language Concepts

Visual Basic Settings


Visual Basic settings are designed to optimize the user experience and to maximize the productivity of Visual Basic developers.
It is part of the Visual Studio Settings feature, which enables you to customize and save your settings in the Visual Studio
Integrated Development Environment (IDE).
You can also port or reload your IDE settings on other computers. For more information, see
How to: Share Settings Between Computers.
Windows and Views
Feature Displayed by default? Notes
Class View No Hides Hidden Types and Members

Command Window No

Dynamic Help window No Does not appear when you press F1.

Immediate Window Yes, when debugging starts.

Object Browser No Displays, by default:


Namespaces
Public members
Inherited members

Output Window Yes, when build starts.

Properties Window Yes

Solution Explorer Yes

Server Explorer/Database Explorer No Displays data connections and available system servi
ces.

Start Page Yes Appears the first time you start the IDE. You can cust
omize it.

Task List (Visual Studio) Yes, when compile errors or warnings


exist.

Toolbox Yes Displays controls and components in alphabetical or


der.

In addition, the following elements have certain behaviors enabled when you select Visual Basic Development Settings.
Dialog Boxes
Feature Behavior
New Project Dialog Box When other platforms are installed on the computer, the IDE enables the combo box that all
ows you to specify the targeted platform.

Options Dialog Box (Visual Studio) Visual Basic enables simplified Options pages. Click the Show All Settings check box to se
e the full list of options.
Keyboard
Feature Behavior
Visual Basic 6.0 Default Shortcut Keys Supports typical Visual Basic 6 keyboard mapping.
Miscellaneous IDE Elements
Feature Behavior
Tool tips Appear for all menu items and toolbar buttons when the mouse hovers above th
em.

Visual Basic IntelliSense Code Snippets Includes a library of code snippets that are ready to be inserted in your application.

Visual Basic-Specific IntelliSense Provides all of the IntelliSense features with some productivity enhancements for
Visual Basic developers.
See Also
Tasks
How to: Customize Dynamic Help
How to: Change Select Settings
How to: Specify Settings for a Team
Reference
Import and Export Settings, Environment, Options Dialog Box
Other Resources
Import and Export Settings Wizard
Visual Basic: Samples

Visual Basic IntelliSense Code Snippets


Visual Basic includes a code library consisting of several hundred pieces of code, called IntelliSense code snippets, that are
ready to be inserted in your application. Each snippet performs a complete programming task such as creating a custom
exception, sending an e-mail message, or drawing a circle. You can insert a snippet into your source code with a few mouse
clicks. For more information, see How to: Insert Snippets Into Your Code (Visual Basic). You can also create your own snippets
that suit your business needs, add them to the library, and then use them when needed. For more information, see
Creating and Using IntelliSense Code Snippets.
A Productivity Tool for Visual Basic Users
These snippets increase your productivity by reducing the amount of time you spend looking for code samples, by reducing
the time required to learn to use an unfamiliar feature, and by supporting the reuse of code.
The code library supports the following features:
Insert one of the snippets into the Code Editor.
Create new tasks that you can reuse in your projects.
Create new tasks to share with your workgroup and colleagues.
Edit the tasks.
Download more tasks from third parties.
These code blocks are available throughout Visual Studio:
You can add them through the shortcut menu of the Code Editor.
You can drag the XML code files from Windows Explorer onto your source-code file.
See Also
Tasks
How to: Modify Existing Snippets
How to: Share Snippets with other Developers
How to: Delete a Snippet Added to Your Code
How to: Assign a Shortcut Name to a Snippet
Troubleshooting Snippets
How to: Manage Code Snippets
How to: Search for Code Snippets Online
Concepts
Best Practices for Using IntelliSense Code Snippets
Security Considerations in Using Snippets
Visual Basic: Samples

How to: Insert Snippets Into Your Code (Visual Basic)


You can insert IntelliSense code snippets using the navigation tools in the Code Editor or by dragging files from Windows
Explorer. When you know the name of the snippet you want to insert, you can do so by typing its shortcut followed by the TAB
key. When you need to browse for an appropriate snippet, you can use the snippet picker, which gives you categorized lists of
snippets to choose from.
After you insert the code snippet, you modify it to work in your application. For example, you may find that a particular snippet
inserts a new method in your application. If you inserted this new method inside an existing method, you would need to delete
some extra lines of code to fix the compiler errors. You might also want to change any messages to the user or file names
found in the snippet. For more information, see How to: Customize Snippet Code Once It Is Inserted into Your Code.
To insert a snippet by browsing in the Code Editor
1. Right-click the Code Editor where you want to insert the code.
2. Click Insert Snippet on the shortcut menu. The IntelliSense code snippet picker appears.
As an alternative to steps 1 and 2, type a question mark followed by the TAB key in the Code Editor to open the code
snippet picker.
3. Navigate to the task of your choice and click it. The snippet code is inserted into your code.
Once you have added the snippet to your code, there may be parts of it that need customization, such as replacing
variable names with more appropriate names. The editor helps you with this process. For more information, see
How to: Customize Snippet Code Once It Is Inserted into Your Code.
The snippets that appear in the picker are stored as files in subfolders of specific file locations. The file locations can be
examined and changed using the Code Snippets Manager. There is one file for each snippet, and the file-name extension
for the files is .snippet. Snippets that you have created or acquired from another source can be stored anywhere in the
file system, although they will not appear in the shortcut menu unless they reside in one of the specified folders. For
more information, see snippet manager.
To insert a snippet when you know its shortcut
Type the shortcut for the snippet in the Code Editor followed by the TAB key. The snippet will be inserted.
-or-
Type the first few characters of the shortcut name for the snippet in the Code Editor, followed by a question mark and
TAB. A picker will appear with the list of snippets whose shortcuts begin with the characters you typed. As you navigate
the list, the title of the selected shortcut will appear as a ToolTip.
There are two ways to find the shortcut name for a code snippet:
Use the Code Snippets Manager to view the shortcuts for all the snippets.
The shortcut is displayed as part of the description ToolTip in the code snippet picker.
To insert a snippet into your code using Windows Explorer
1. Open Windows Explorer.
2. Navigate in Windows Explorer to the folder that contains the file you want to insert. If you chose the default location for
the installation of Visual Studio 2005, the snippets are stored in C:\Program Files\Microsoft Visual Studio 8\Vb. If you
chose the default location for the installation of Visual Basic 2005 Express Edition, the snippets are stored in C:\Program
Files\Microsoft Visual Studio 8\Common7\IDE\VBExpress\Snippets\1033.
3. Drag the file from Windows Explorer to the place in your code where you want to insert it.
See Also
Tasks
How to: Search for Code Snippets Online
Reference
Creating and Using IntelliSense Code Snippets
Concepts
Visual Basic IntelliSense Code Snippets
Security Considerations in Using Snippets
Best Practices for Using IntelliSense Code Snippets
Visual Basic: Samples

How to: Customize Snippet Code Once It Is Inserted into Your


Code
When you add a snippet to your code, the inserted snippet code has one or more replacement points highlighted in the code.
You may or may not choose to change each replacement point. If you rest your mouse pointer over the replacement point, a
ToolTip appears that explains how you need to change the code. The Code Editor recognizes a snippet as a unit separate from
your surrounding code until you close the source-code file. As such, the replacement points remain highlighted until you have
closed the source file.
To customize the inserted code for your application
1. Use the TAB key to move from one replacement point to the next. Use SHIFT+TAB to move to a previous replacement
point.
2. Click CTRL+SPACE to invoke IntelliSense.
3. Select an item from the list, or type a replacement of your choice.
4. If you still have compiler errors in the code, then you may need to make other changes to your source code. For example,
if the task is searching for a node in a TreeView control named TreeView1, then you may need to add a TreeView control
named TreeView1 to your form.

See Also
Tasks
How to: Insert Snippets Into Your Code (Visual Basic)
Reference
Creating and Using IntelliSense Code Snippets
Concepts
Visual Basic IntelliSense Code Snippets
Security Considerations in Using Snippets
Best Practices for Using IntelliSense Code Snippets
Visual Basic: Samples

Security Considerations in Using Snippets


IntelliSense code snippets installed by Visual Studio are not in themselves a security hazard. Depending on where they are
used and how they are modified, they can create security risks in your application. Snippets downloaded from the Internet
should be treated like any other downloaded content.
Snippets from the Internet
When downloading snippet files from the Internet, be aware of the following:
A file extension of .snippet does not guarantee that the file contains plain-text XML. To be safe, download from sites you
trust, and use up-to-date virus software.
The Help URL that is part of the snippet file can potentially execute a malicious script file or display an offensive Web site.
The Help URL is not displayed in the Code Editor when you insert the snippet, but it is visible if you edit the snippet file
in the XML Editor or another editor such as Notepad.
The code itself could contain code that can damage your system if you execute it. Read the source carefully before
running it. Some of the code many be in collapsed #Region Directive sections. Expand these sections to read the code.
The snippet may contain references. These references are added silently to your project and may be loaded from
anywhere on your system. These references may have been downloaded to your computer from where you downloaded
the snippet. The snippet may then make a call to a method in the reference that executes malicious code. To protect
yourself against such an attack, read the snippet file carefully before inserting the snippet, and download from sites you
trust.
Security for All Snippets
How secure a snippet is depends on where it is used in the source code and how it is modified once it is in the code. The
following list contains a few of the areas that must be considered:
File and database access
Code access security
Protecting resources (such as event logs, registry)
Storing secrets
Verifying inputs
Passing data to scripting technologies
For more information, see Securing Applications.
See Also
Tasks
How to: Search for Code Snippets Online
Reference
Creating and Using IntelliSense Code Snippets
Concepts
Securing Applications
Visual Basic: Samples

Best Practices for Using IntelliSense Code Snippets


The code in each IntelliSense code snippet shows only a basic way to accomplish a task. For most applications, the code will
have to be modified to suit the application. This topic describes several common changes that should be made to the code.
Handling Exceptions
Typically, if the code contains a Try…Catch block, the code will catch and rethrow all exceptions. That may not be the right
choice for your project. For each exception, there are several ways to respond. Some possible actions:
Add code to each Catch block for the action you choose.
Do nothing, by removing the code that appears in the Catch block. This causes the application to ignore the error. It is
unlikely that your application will recover gracefully if you take this approach.
Get more input from the user to try to fix the condition.
During execution of the Try block, undo any changes that were made to application data before the exception was
thrown.
Throw the exception back to the calling method.
Throw an exception that you define for this application.
Delete the Catch statement for that exception and let the calling method handle it. This is especially appropriate if the
exception is not relevant to your task.
Add additional Catch blocks to the code to catch specific types of exceptions that you want to handle.
Add a Finally block to add code that you want to execute after the Try and Catch blocks.
Replacing Strings
If the code contains a string value, typically it is a specific string, such as "c:\filename.txt". This hard-coded string is useful for
demonstration purposes, but unlikely to be the correct string for your application. Potential sources of strings in your
application include:
A string variable.
A method or property that returns a string, such as the InputBox function.
A string from a Windows Forms control, such as a TextBox or ComboBox.
File Locations
Most file names in the code are shown as either being in My Documents or in c:\. When replacing the file locations, there are
several considerations, including:
Finding an accessible location. Users may not have access to the \Program Files folder of the computer, so storing files
with the application files may not work.
Finding a secure location. Storing files in the root folder (c:\) is not secure. For application data, we recommend the
\Application Data folder. For individual user data, the application can create a file for each user in the \My Documents
folder.
Using a valid file name. You can use the OpenFileDialog Component (Windows Forms) and
SaveFileDialog Component (Windows Forms) to reduce the likelihood of invalid file names. Be aware that between the
time the user selects a file and the time your code manipulates the file, the file may be deleted. In addition, the user may
not have permissions to write to the file.
Controls and Components
Control and component names referenced in the code usually have a default designer name, such as Button1 or TreeView1.
This emphasizes the type of control being shown, but it may not be a name you use in your application.
Missing Code
Some snippets only show an empty language structure, such as a Try…Catch block. Another common scenario is a validation
variable, such as IsValid, that is set to True by default. The code provided will compile and run, but will not have any
functionality. In these examples, you will need to add the code for your task.
Security
How secure a snippet is depends on where it is used in the source code and how it is modified once it is in the code. The
following list contains a few of the areas that must be considered.
File and database access
Code access security
Protecting resources (such as event logs, registry)
Storing secrets
Verifying inputs
Passing data to scripting technologies
For more information, see Security Considerations in Using Snippets and Securing Applications.
See Also
Tasks
How to: Insert Snippets Into Your Code (Visual Basic)
Reference
Creating and Using IntelliSense Code Snippets
Concepts
Visual Basic IntelliSense Code Snippets
Security Considerations in Using Snippets
Securing Applications
Visual Basic: Samples

Troubleshooting Snippets
Problems with IntelliSense code snippets are typically caused by two problems: a corrupt snippet file or bad content in the
snippet file.
Common Problems
The Snippet Cannot Be Dragged from Windows Explorer to a Visual Studio Source File
The XML in the snippet file may be corrupt. The XML Editor in Visual Studio can locate problems in the XML structure.
The snippet file may not conform to the snippet schema. The XML Editor in Visual Studio can locate problems in the
XML structure.
The Code Has Compiler Errors That Are Not Highlighted
You may be missing a project reference. Examine the documentation about the snippet. If the reference is not found on
the computer, you will need to install it. Inserting a snippet should add to the project any references needed. If the
snippet is missing the reference information, that can be reported to the snippet creator as an error.
A variable may be undefined. Undefined variables in a snippet should be highlighted. If not, that can be reported to the
snippet creator as an error.
See Also
Reference
Creating and Using IntelliSense Code Snippets
Visual Basic Language Concepts

How to: Edit Code Attributes


When you are in the Visual Basic Code Editor, you can use the Properties window to apply and edit attributes for your types
and members. Attributes that are listed in the Properties window can be applied by setting the attribute to True or by setting
the attribute's Apply property to True. After attributes are applied, you can edit them by editing the properties displayed in the
Properties window. For more information, see Attributes in Visual Basic.
To apply a new attribute
1. Locate the desired attribute in the Properties window.
2. If the desired attribute is not listed, you must apply the attribute manually in code. For more information, see
Application of Attributes.
3. Do one of the following:
If the attribute has properties, set the Apply property to True.
-or-
If the attribute does not have properties, set the attribute to True.
See Also
Reference
Properties Window
Concepts
Attributes Overview in Visual Basic
Common Uses for Attributes
Attributes Used in Visual Basic
Application of Attributes
Visual Basic Language Concepts

Refactoring and Rename Dialog Box (Visual Basic)


Use Visual Basic's built-in Rename dialog box to rename identifiers in your code for symbols such as fields, local variables,
methods, namespaces, properties, and types. You can open the Rename dialog box by right-clicking the element declaration.
New Name
Specifies the new name for the code element.
Location
Identifies the namespace to search when performing the rename operation.
Rename Operations
The Rename dialog box performs slightly different rename operations, depending on the type of the element renamed.
Element ty Rename Operation
pe
Class Changes all declarations and all usages of the class to the new name. For partial classes, the rename operation pr
opagates to all parts.

Field Changes the declaration and usages of the field to the new name.

Local variab Changes the declaration and usages of the variable to the new name.
le

Method Changes the name of the method and all references to that method to the new name.

Namespace Changes the name of the namespace to the new name, in the declaration, all Imports statements, and all fully qu
alified names.

Property Changes the declaration and usages of the property to the new name.

Refactoring
To provide a more complete refactoring experience, Visual Basic has partnered with Developer Express Inc. to get the developer
refactoring support. See Refactor! (http://msdn.microsoft.com/vbasic/downloads/2005/tools/refactor/) on the MSDN Visual
Basic Developer Center for additional details and instructions on how to download this tool. Refactor! supports more than 15
individual refactoring features, including operations like Reorder Parameters, Extract Method, Encapsulate Field, and Create
Overload.
See Also
Tasks
How to: Rename an Identifier
Other Resources
Using the Visual Basic Editor
Visual Basic Language Concepts

How to: Rename an Identifier


The Visual Studio Integrated Development Environment (IDE) can analyze your code and use scoping information to assist in
renaming identifiers. This provides a more controlled renaming experience than using find and replace.
For example, consider a class that defines two subroutines named Test1 and Test2, each subroutine defining a variable named
Value. If you rename the Value variable in Test1 to Counter, all code in Test1 that referenced Value will be updated to
reference Counter.However, the code in Test2 will not be changed.
To rename from any instance of the identifier
1. Right-click the identifier.
2. Choose Rename from the shortcut menu to open the Rename dialog box.
3. Change the name in the New Name box to the new name for the identifier.
4. Click OK to rename all references to the identifier.
To rename from the identifier declaration
1. Select the identifier name where it declared.
2. Change the name of the identifier.
When you change the name, a symbol appears under the right side of the name.
3. Rest your mouse pointer over the symbol to activate the smart tag.
4. Click the smart tag glyph to open the panel.
5. Choose the Rename panel item to rename the other references to the identifier.
See Also
Reference
Refactoring and Rename Dialog Box (Visual Basic)
Other Resources
Using the Visual Basic Editor
Visual Basic Language Concepts

Visual Basic 6.0 Default Shortcut Keys


The Help pages listed below show the default key combinations available for the Visual Basic 6.0 keyboard scheme. For
information on changing default combinations, see How to: Work with Shortcut Key Combinations.
In This Section
Global Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Lists common shortcut key combinations as well as key combinations that can be used in a variety of places within the IDE.
Integrated Help Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Lists the shortcut key combinations available when displaying and browsing Help topics.
Project Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Lists the shortcut key combinations that can be used to add new items to a project, build a project, or open files or projects.
HTML Designer Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Lists the shortcut key combinations available when working in Design view and HTML view of the HTML designer.
Image Editor Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Lists the shortcut key combinations available when working in the Image editor.
Debug Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Lists the shortcut key combinations available when using the Debugger.
Search and Replace Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Lists the shortcut key combinations available when using the Find, Replace, Find in Files, and Replace in Files dialog
boxes.
Visual Database Tools Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Lists the shortcut key combinations available when using the Query designer or Database designer.
Object Browser Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Lists the shortcut key combinations available when working in the Object Browser.
Control Manipulation Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Lists the shortcut key combinations available for moving and resizing controls on a design surface.
Text Navigation Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Lists the shortcut key combinations available when moving within code in an open document.
Text Selection Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Lists the shortcut key combinations available when selecting text in an open document.
Text Manipulation Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Lists the shortcut key combinations available when moving, deleting, or formatting text in an open document.
Window Management Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Lists the shortcut key combinations available for moving, closing, or navigating in tool and document windows.
Macro Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Lists the shortcut key combinations that can be used when working with macros.
Tool Window Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Lists the shortcut key combinations that display the various tool windows.
Related Sections
How to: Work with Shortcut Key Combinations
Describes how to determine the current keyboard mapping scheme, how to determine the shortcut key combination for a
Describes how to determine the current keyboard mapping scheme, how to determine the shortcut key combination for a
specific command, how to create custom mapping scheme, and how to create new shortcut key combination.
Shortcut Keys
Lists the predefined keyboard binding schemes available in the Visual Studio development environment.
Visual Basic Language Concepts

Global Shortcut Keys, Visual Basic 6.0 Default Shortcut Option


The following shortcut key combinations can be used in various places within the integrated development environment (IDE).
Command Shortcut K Description
eys
Edit.Copy CTRL + C Places a duplicate of the currently selected item on the system Clipboard.
CTRL + INS
ERT

Edit.Cut CTRL + X Removes the currently selected item to the system Clipboard.
SHIFT + DE
LETE

Edit.CycleCli CTRL + SHI Pastes an item from the Clipboard Ring tab of the Toolbox at the insertion point in the file and aut
pboardRing FT + V omatically selects the pasted item. You can review each item on the Clipboard by repeatedly pressing
the shortcut keys.
CTRL + SHI
FT + INSER
T

Edit.Delete DELETE Deletes one character to the right.

Edit.DeleteB BACKSPACE Deletes one character to the left.


ackwards
SHIFT + BA
CKSPACE

Edit.GotoNe F12 Moves the cursor to the next item, such as a task in the Task List window or a search match in the Fi
xtLocation nd Results window. Each time you press F12, you move to the next item in the list.

Edit.GotoPr SHIFT + F12 Moves the cursor to the previous item in the Task List window or Find Results window.
eviousLocat
ion

Edit.ListMe CTRL + J Lists members of the current class for statement completion when editing code.
mbers

Edit.Parame CTRL + SHI Displays a ToolTip that contains information for the current parameter based on the current languag
terInfo FT + I e.

Edit.Paste CTRL + V Inserts the Clipboard contents at the insertion point.


SHIFT + INS
ERT

Edit.QuickIn CTRL + I Displays the complete declaration for the identifier nearest the insertion point in a ToolTip.
fo

Edit.Redo CTRL + SHI Restores the previously undone action.


FT + Z
SHIFT + ALT
+ BACKSPA
CE
Edit.Selectio ESC Closes a menu or dialog box, cancels an operation in progress, or places focus in the current docume
nCancel nt window.

Edit.Undo ALT + BACK Reverses the last editing action.


SPACE
CTRL + Z

File.AddExis CTRL + D Displays the Add Existing Item dialog box, which allows you to add an existing file to the current pr
tingItem oject.

File.AddNe CTRL + SHI Displays the Add New Item dialog box, which allows you to add a new file to the current project.
wItem FT + A

File.Exit ALT + Q Exits the integrated development environment.

File.Print CTRL + P Displays the Print dialog box where you can choose printer settings.

File.SaveAll CTRL + SHI Saves all documents in the current solution and any files in the external files project.
FT + S

File.SaveSel CTRL + S Saves the selected items in the current project.


ectedItems

Tools.GoTo CTRL + / Places the caret in the Find/Command box on the Standard toolbar.
CommandLi
ne

View.Navig CTRL + SHI Goes back to the previous document or window in the navigation history.
ateBackwar FT + F2
d

View.Navig CTRL + SHI Moves forward to the next document or window in the navigation history.
ateForward FT + -

View.WebN ALT + LEFT Displays the previous page in the viewing history. Available only in the integrated Web browser.
avigateBack ARROW

View.WebN ALT + RIGH Displays the next page in the viewing history. Available only in the integrated Web browser.
avigateForw T ARROW
ard
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Project Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Integrated Help Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts

Integrated Help Shortcut Keys, Visual Basic 6.0 Default


Shortcut Option
The following shortcut key combinations can be used to view and move among topics in Help.
Command Shortcut Keys Description
Name
Help.Content CTRL + ALT + F Displays the Contents window for the documentation contained in MSDN.
s 1

Help.Dynami CTRL + F1 Displays the Dynamic Help window, which displays different topics depending on what items
cHelp currently have focus in the product.

Help.F1Help F1 Displays a topic from Help that corresponds to the current user interface selected.

Help.Index CTRL + ALT + F Displays the Index window for the documentation contained in MSDN.
2

Help.Nexttop ALT + DOWN A Displays the next topic in the table of contents. Available only in the Help (Web) browser windo
ic RROW w.

Help.Previou ALT + UP ARRO Displays the previous topic in the table of contents. Available only in the Help (Web) browser w
stopic W indow.

Help.Search CTRL + ALT + F Displays the Search window, which allows you to search for words or phrases in the document
3 ation contained in MSDN.

Help.Window SHIFT + F1 Displays a topic from Help that corresponds to the current user interface selected.
Help
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Window Management Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts

Project Shortcut Keys, Visual Basic 6.0 Default Shortcut Option


The following shortcut key combinations can be used to add new items to a project, build a project, or open files or projects.
Command N Shortcut Ke Description
ame ys
Build.BuildSol CTRL + SHIF Builds all of the projects in the solution using the current solution configuration.
ution T+B

Build.Compile CTRL + F7 Creates an object file containing machine code, linker directives, sections, external references, and
function/data names for the selected file.

File.NewFile CTRL + SHIF Displays the New File dialog box where you can select a new file to add to the current project.
T+N

File.NewProje CTRL + N Displays the New Project dialog box where you can create projects and add them to the current s
ct olution.

File.OpenFile CTRL + SHIF Displays the Open File dialog box where you can select an existing file to open.
T+O

File.OpenProj CTRL + O Displays the Open Project dialog box where you can add existing projects to your solution.
ect

File.AddExistin CTRL + D Displays the Add Existing Item dialog box, which allows you to add an existing file to the current
gItem project.

File.AddNewIt CTRL + SHIF Displays the Add New Item dialog box, which allows you to add a new file to the current project.
em T+A

Project.RunSe CTRL + Q Runs the current selection.


lection
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Global Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Integrated Help Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Window Management Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Concepts
Introduction to Solutions, Projects, and Items
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts

HTML Designer Shortcut Keys, Visual Basic 6.0 Default Shortcut


Option
The following shortcut key combinations can only be used while editing in the HTML Designer. Certain key combinations are
only available in a specific view of that designer.
Comman Shortcut Description
d Keys
Edit.CharTr CTRL + T Swaps the characters on either side of the insertion point. For example, AC|BD becomes AB|CD. Only av
anspose ailable in HTML view of the HTML Designer.

Edit.ClearA CTRL + K, Removes all unnamed bookmarks in the current document. Only available in HTML view of the HTML
llBookmar CTRL + L Designer.
ks

Edit.Compl CTRL + SP Displays Word Completion based on the current language. Only available in HTML view of the HTML
eteWord ACEBAR Designer.

Edit.MakeL CTRL + U Changes the selected text to lowercase characters. Available only in HTML view of the HTML Designe
owercase r.

Edit.MakeU CTRL + SH Changes the selected text to uppercase characters. Available only in HTML view of the HTML Designer
ppercase IFT + U .

Edit.NextB CTRL + K, Moves to the next bookmark in the document. Available only in HTML view of the HTML Designer.
ookmark CTRL + N

Edit.Word CTRL + DE Deletes the word to the right of the insertion point. Available only in HTML view of the HTML Designe
DeleteToEn LETE r.
d
CTRL + SH
IFT + BAC
KSPACE

Edit.Word CTRL + BA Deletes the word to the left of the insertion point. Available only in HTML view of the HTML Designer.
DeleteToSt CKSPACE
art

Format.Bol CTRL + B Toggles the selected text between bold and normal. Available only in Design view of the HTML Desig
d ner.

Format.De CTRL + SH Decreases the selected paragraph by one indent unit. Available only in Design view of the HTML Desi
creaseInde IFT + T gner.
nt

Format.Inc CTRL + T Indents the selected paragraph by one indent unit. Available only in Design view of the HTML Design
reaseInden er.
t

Format.Itali CTRL + I Toggles the selected text between italic and normal. Available only in Design view of the HTML Desig
c ner.

Format.Loc CTRL + SH Prevents an absolutely positioned element from being inadvertently moved. Available only in Design v
kElement IFT + K iew of the HTML Designer.
Format.Sh CTRL + G Toggles snap to grid. Available only in Design view of the HTML Designer.
owGrid

Format.Sn CTRL + SH Specifies that elements be aligned using an invisible grid. You can set grid spacing on the Display pan
aptoGrid IFT G e of HTML Designer options in the Options dialog box, and the grid will be changed the next time you o
pen a document. Available only in Design view of the HTML Designer.

Format.Un CTRL + U Toggles the selected text between underlined and normal. Available only in Design view of the HTML
derline Designer.

Format.Ins CTRL + SH Displays the Bookmark dialog box, which allows you to create a target for jumps within the current doc
ertBookma IFT + L ument. Available in Design view and HTML view of the HTML Designer.
rk

Format.Co CTRL + L When text is selected, displays the Hyperlink dialog box. Available in Design view and HTML view of th
nverttoHyp e HTML Designer.
erlink

Table.Inser CTRL + AL Adds one row above the current row in the table. Available only in Design view of the HTML Designer
tRowAbov T + UP AR .
e ROW

Table.Inser CTRL + AL Adds one row below the current row in the table. Available only in Design view of the HTML Designer
tRowBelow T + DOW .
N ARROW

Table.Inser CTRL + AL Adds one column to the left of the current column in the table. Available only in Design view of the HT
tColumnst T + LEFT A ML Designer.
otheLeft RROW

Table.Inser CTRL + AL Adds one column to the right of the current column in the table. Available only in Design view of the H
tColumnst T + RIGHT TML Designer.
otheRight ARROW

View.Detail CTRL + SH Displays signal icons for HTML elements that do not have a visual representation, such as comments, s
s IFT + Q cripts, and anchors for absolutely positioned elements. Available only in Design view of the HTML Des
igner.

View.Next CTRL + PA Switches from Design view to HTML view and vice versa. Available only in Design view of the HTML
View GE DOWN Designer.

View.Visibl CTRL + Q Displays a 1-pixel border around HTML elements that support a BORDER attribute such as tables, table
eBorders cells, and divisions, and has it set to zero. Available only in Design view of the HTML Designer.
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
HTML Designer
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts

Image Editor Shortcut Keys, Visual Basic 6.0 Default Shortcut


Option
The following shortcut key combinations can be used in the Image editor.
Command Shortcut K Description
eys
Image.DrawOpa CTRL + J Makes the current selection either opaque or transparent. Available only in the Image editor.
que

Image.FlipHoriz CTRL + H Flips the image from right to left on the horizontal axis. Available only in the Image editor.
ontal

Image.FlipVertic SHIFT + ALT Flips the image from top to bottom on the vertical axis. Available only in the Image editor.
al +H

Image.NewImag INSERT Displays the New Icon Image Type dialog box, which allows you to select a new image type to
eType create. Available only in the Image editor.

Image.Rotate90 CTRL + SHI Rotates the image 90 degrees clockwise. Available only in the Image editor.
Degrees FT + H
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Image Editor
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts

Debug Shortcut Keys, Visual Basic 6.0 Default Shortcut Option


The following shortcut key combinations can be used while debugging code.
Command Shortc Description
ut Key
s
Debug.Appl ALT + Applies the changes made to code without stopping the debugger.
yCodeChan F10
ges

Debug.Auto CTRL Displays the Auto window to view the values of variables currently in the scope of the current line of exec
s + ALT ution within the current procedure.
+ V, A

Debug.Brea CTRL Temporarily stops execution of all processes in a debugging session. Available only in Run mode.
kAll + BRE
AK

Debug.Brea CTRL Displays the Breakpoints dialog box where you can add and modify breakpoints.
kpoints + ALT
+B

Debug.Call CTRL Displays the Call Stack window to display a list of all active procedures or stack frames for the current thr
Stack + L ead of execution. Available only in Run mode.

Debug.Clea CTRL Clears all of the breakpoints in the project.


rAllBreakpo + SHIF
ints T + F9

Debug.Disa CTRL Displays the Disassembly dialog box.


ssembly + ALT
+D

Debug.Exce CTRL Displays the Exceptions dialog box.


ptions + ALT
+E

Debug.Imm CTRL Displays the Immediate window where you can evaluate expressions and execute individual commands.
ediate +G

Debug.Loca CTRL Displays the Locals window to view the variables and their values for each procedure in the current stack f
ls + ALT rame.
+ V, L

Debug.Me CTRL Displays the Memory 1 window, which allows you to view large buffers, strings, and other data that do no
mory1 + ALT t display well in the Watch or Variables window.
+ M, 1

Debug.Me CTRL Displays the Memory 2 window, which allows you to view large buffers, strings, and other data that do no
mory2 + ALT t display well in the Watch or Variables window.
+ M, 2
Debug.Me CTRL Displays the Memory 3 window, which allows you to view large buffers, strings, and other data that do no
mory3 + ALT t display well in the Watch or Variables window.
+ M, 3

Debug.Me CTRL Displays the Memory 4 window, which allows you to view large buffers, strings, and other data that do not
mory4 + ALT display well in the Watch or Variables window.
+ M, 4
Debug.Mod CTRL Displays the Modules window which allows you to view the .dll or .exe files used by the program.
ules + ALT
+U

Debug.New CTRL Inserts or clears a breakpoint in the current line of code.


Breakpoint + B

Debug.Quic SHIFT Displays the Quick Watch dialog box with the current value of the selected expression. Available only in B
kWatch + F9 reak mode. Use this command to check the current value of a variable, property, or other expression for w
hich you have not defined a watch expression.

Debug.Regi CTRL Displays the Registers window, which displays content for debugging native code applications.
sters +ALT
+G

Debug.Rest SHIFT Terminates a debugging session, rebuilds, and then starts running the application from the beginning. Ava
art + F5 ilable in Break and Run modes.

Debug.Run CTRL Displays the Running Documents window that shows the set of documents that you are in the process o
ningDocum + ALT f debugging. Available in Run mode.
ents +N

Debug.Run CTRL In Break mode, resumes execution of your code from the current statement to the selected statement. The
ToCursor + F8 Current Line of Execution margin indicator appears in the Margin Indicator bar. In Design mode, starts
the debugger and executes your code to the cursor location.

Debug.Set CTRL Sets the execution point to the line of code you choose.
NextStatem + F9
ent

Debug.Sho ALT + Highlights the next statement to be executed.


wNextState NUM*
ment

Debug.Start F5 Automatically attaches the debugger and runs the application from the startup form specified in the <Proj
ect> Properties dialog box. Changes to Continue if in Break mode.

Debug.Start CTRL Runs the code without invoking the debugger.


WithoutDe + F5
bugging

Debug.Step F8 Executes code one statement at a time, following execution into function calls.
Into

Debug.Step CTRL Executes the remaining lines of a function in which the current execution point lies.
Out + SHIF
T + F8
Debug.Step SHIFT Executes the next line of code, but does not follow execution through any function calls.
Over + F8

Debug.This CTRL Displays the This window, which allows you to view the data members of the object associated with the cu
+ ALT rrent method.
+ V, T

Debug.Thre CTRL Displays the Threads window to view all of the threads for the current process and information about the
ads + ALT m.
+H

Debug.Tog F9 Sets or removes a breakpoint at the current line.


gleBreakpoi
nt

Debug.Tog CTRL Displays the disassembly information for the current source file. Available only in Break mode.
gleDisasse + F11
mbly

Tools.Debu CTRL Displays the Processes dialog box, which allows you to debug multiple programs at the same time in a sin
gProcesses + ALT gle solution.
+P
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Tool Window Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts

Search and Replace Shortcut Keys, Visual Basic 6.0 Default


Shortcut Option
The following shortcut key combinations can be used with the Find, Replace, Find in Files, and Replace in Files dialog boxes.
Command Shortcut K Description
eys
Edit.Find CTRL + F Displays the Find dialog box.

Edit.FindNext F3 Finds the next occurrence of the previous search text.

Edit.FindNextSel CTRL + F3 Finds the next occurrence of the currently selected text in the document.
ected

Edit.FindPreviou SHIFT + F3 Finds the previous occurrence of the search text.


s

Edit.FindPreviou CTRL + SHI Finds the previous occurrence of the currently selected text, or the word at the caret.
sSelected FT + F3

Edit.GoToFindC CTRL + SHI Places the caret in the Find/Command line on the Standard toolbar.
ombo FT + F

Edit.HiddenText ALT + F3, H Selects or clears the Search Hidden Text option for the Find dialog box.

Edit.Incremental CTRL + ALT Starts Incremental search. If Incremental search is started but you have not typed any characters,
Search +I recalls the previous pattern. If text has been found, searches for the next occurrence.

Edit.MatchCase ALT + F3, + Selects or clears the Match Case option for Find and Replace operations.
C

Edit.RegularExp ALT + F3, + Selects or clears the Regular expression option so that special characters can be used in Find a
ression R nd Replace operations.

Edit.Replace CTRL + H Displays the Replace dialog box.

Edit.ReplaceinFil CTRL + SHI Displays the Replace in Files dialog box.


es FT + H

Edit.ReverseIncr CTRL + SHI Changes the direction of Incremental search to begin at the bottom of the file and progress towa
ementalSearch FT + ALT + I rds the top.

Edit.StopSearch ALT + F3, + Halts the current Find in Files operation.


S

Edit.Up ALT + F3, + Selects or clears the Search Up option for Find and Replace operations.
B

Edit.WholeWor ALT + F3, + Selects or clears the Match whole word option for Find and Replace operations.
d W

Edit.Wildcard ALT + F3, P Selects or clears the Wildcard option for Find and Replace operations.
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Text Navigation Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Text Selection Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Text Manipulation Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts

Visual Database Tools Shortcut Keys, Visual Basic 6.0 Default


Shortcut Option
The following shortcut key combinations can be used in the Database Designer or Query Designer.
Command Shortcut Key Description
s
Database.Run CTRL + R Runs the currently selected database object.

Database.StepInt CTRL + E Steps into debug mode for the currently active database object.
o

Query.Run CTRL + R Executes the query. Available only in Visual Database Tools.

View.Diagram CTRL + 1 Displays the Diagram pane of the Query designer. Available only in the Query and View desig
ners.

View.Grid CTRL + 2 Displays the Grid pane of the Query designer. Available only in the Query and View designers.

View.Results CTRL + 4 Displays the Results pane of the Query designer. Available only in the Query and View design
ers.

View.SQL CTRL + 3 Displays the SQL pane of the Query designer. Available only in the Query and View designers.
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Global Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts

Object Browser Shortcut Keys, Visual Basic 6.0 Default Shortcut


Option
The following shortcut key combinations can be used while in the Object Browser window.
Command Shortcut Keys Description
Edit.FindSymbol CTRL + SHIFT + Y Displays the Find Symbol dialog box.
CTRL + SHIFT+ ALT +
F12

View.FindSymbolResult CTRL + ALT + Y Displays the Find Symbol Results window.


s

View.ObjectBrowserBac ALT + - Moves back to the previously selected object in the selection history of the Obj
k ect Browser.

View.ObjectBrowserFor SHIFT + ALT + - Moves forward to the next object in the selection history of the Object Brows
ward er.
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Tool Window Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Window Management Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts

Control Manipulation Shortcut Keys, Visual Basic 6.0 Default


Shortcut Option
The following shortcut key combinations can be used to move, select, and change the size of controls on design surfaces.
Command Shortcut Keys Description
Edit.MoveControlDown CTRL + DOWN ARROW Moves the selected control down in increments of 1 on the design sur
face.

Edit.MoveControlDownG DOWN ARROW Moves the selected control down in increments of 8 on the design sur
rid face.

Edit.MoveControlLeft CTRL + LEFT ARROW Moves the control left in increments of 1 on the design surface.

Edit.MoveControlLeftGri LEFT ARROW Moves the control left in increments of 8 on the design surface.
d

Edit.MoveControlRight CTRL + RIGHT ARROW Moves the control to the right in increments of 1 on the design surfac
e.

Edit.MoveControlRightGr RIGHT ARROW Moves the control right in increments of 8 on the design surface.
id

Edit.MoveControlUp CTRL + UP ARROW Moves the control up in increments of 1 on the design surface.

Edit.MoveControlUpGrid UP ARROW Moves the control up in increments of 8 on the design surface.

Edit.SelectNextControl TAB Selects the next control on the design surface.

Edit.SelectPreviousContr SHIFT + TAB Selects the previously selected control on the design surface.
ol

Edit.SizeControlDown CTRL + SHIFT + DOWN ARR Increases the height of the control in increments of 1 on the design su
OW rface.

Edit.SizeControlDownGri SHIFT + DOWN ARROW Increases the height of the control in increments of 8 on the design su
d rface.

Edit.SizeControlLeft CTRL + SHIFT + LEFT ARROW Reduces the width of the control in increments of 1 on the design surf
ace.

Edit.SizeControlLeftGrid SHIFT + LEFT ARROW Reduces the width of the control in increments of 8 on the design surf
ace.

Edit.SizeControlRight CTRL + SHIFT +RIGHT ARRO Increases the width of the control in increments of 1 on the design sur
W face.

Edit.SizeControlRightGri SHIFT + RIGHT ARROW Increases the width of the control in increments of 8 on the design sur
d face.

Edit.SizeControlUp CTRL + SHIFT + UP ARROW Decreases the height of the control in increments of 1 on the design s
urface.
Edit.SizeControlUpGrid SHIFT + UP ARROW Decreases the height of the control in increments of 8 on the design s
urface.

Format.BringToFront CTRL + J Moves the selected control to the top of the Z-order.
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Global Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts

Text Navigation Shortcut Keys, Visual Basic 6.0 Default


Shortcut Option
The following shortcut key combinations can be used in text editors to move within an open document.
Command Shortcut Keys Description
Edit.CharLeft LEFT ARROW Moves the cursor left one character.

Edit.CharRight RIGHT ARROW Moves the cursor right one character.

Edit.DocumentEnd CTRL + END Moves the insertion point to the last line of the document.

Edit.DocumentStart CTRL + HOME Moves the insertion point to the first line of the document.

Edit.GotoBrace CTRL + ] Moves the insertion point to the next brace in the document.

Edit.GoToDeclaration CTRL + ALT + F12 Displays the definition of the selected symbol in the code.

Edit.GoToDefinition SHIFT + F2 Displays the declaration for the selected symbol in code.

Edit.LineDown DOWN ARROW Moves the insertion point down one line.

Edit.LineEnd END Moves the insertion point to the end of the line.

Edit.LineStart HOME Moves the insertion point to the beginning of the line.

Edit.LineUp UP ARROW Moves the insertion point up one line.

Edit.PageDown PAGE DOWN Scrolls the document down one page.

Edit.PageUp PAGE UP Scrolls the document up one page.

Edit.PreviousBookmark CTRL + K, CTRL + P Moves to the previous bookmark.

Edit.ScrollLineDown CTRL + DOWN ARROW Scrolls text down one line.

Edit.ScrollLineUp CTRL + UP ARROW Scrolls text up one line.

Edit.ToggleWordWrap CTRL + R, CTRL + R Enables or disables word wrap in an editor.

Edit.ViewBottom CTRL + PAGE DOWN Moves to the bottom of the current document.

Edit.ViewTop CTRL + PAGE UP Moves to the top of the current window or document.

Edit.WordNext CTRL + RIGHT ARROW Moves the insertion point right one word.

Edit.WordPrevious CTRL + LEFT ARROW Moves the insertion point left one word.

View.ViewCode F7 Displays the selected item in Code view of the Editor.

View.ViewDesigner SHIFT + F7 Displays the selected item in Design view of the Editor.
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Text Selection Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Text Manipulation Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts

Text Selection Shortcut Keys, Visual Basic 6.0 Default Shortcut


Option
The following shortcut key combinations can be used in text editors to select text within an open document.
Command Shortcut Keys Description
Edit.CharLeftExtend SHIFT + LEFT ARROW Moves the cursor left one character, extending the selection.

Edit.CharLeftExtendColu SHIFT + ALT + LEFT ARROW Moves the cursor left one character, extending the column selection.
mn

Edit.CharRightExtend SHIFT + RIGHT ARROW Moves the cursor right one character, extending the selection.

Edit.CharRightExtendCol SHIFT + ALT + RIGHT ARRO Moves the cursor right one character, extending the column selection.
umn W

Edit.DocumentEndExtend CTRL + SHIFT + END Selects the text from the insertion point to the last line of the document
.

Edit.DocumentStartExten CTRL + SHIFT + HOME Selects the text from the insertion point to the first line of the documen
d t.

Edit.GotoBraceExtend CTRL + SHIFT + ] Moves the insertion point to the next brace, extending the selection.

Edit.LineDownExtend SHIFT + DOWN ARROW Extends text selection down one line, starting at the location of the inse
rtion point.

Edit.LineDownExtendCol SHIFT + ALT + DOWN ARRO Moves the cursor down one line, extending the column selection.
umn W

Edit.LineEndExtend SHIFT + END Selects text from the insertion point to the end of the current line.

Edit.LineEndExtendColu SHIFT + ALT + END Moves the insertion point to the end of the line, extending the column
mn selection.

Edit.LineStartExtend SHIFT + HOME Selects text from the insertion point to the start of the line.

Edit.LineUpExtend SHIFT + UP ARROW Selects text up line by line starting from the location of the insertion po
int.

Edit.LineUpExtendColum SHIFT + ALT + UP ARROW Moves the cursor up one line, extending the column selection.
n

Edit.PageDownExtend SHIFT + PAGE DOWN Extends selection down one page.

Edit.PageUpExtend SHIFT + PAGE UP Extends selection up one page.

Edit.SelectAll CTRL + A Selects everything in the current document.

Edit.SelectCurrentWord CTRL + W Selects the word containing the insertion point or the word to the right
of the insertion point.
Edit.SelectToLastGoBack CTRL + = Selects from the current location in the Editor back to the previous loca
tion in the Editor.

Edit.ViewBottomExtend CTRL + SHIFT +PAGE DOW Moves the cursor to the last line in view, extending the selection.
N

Edit.ViewTopExtend CTRL + SHIFT +PAGE UP Extends the selection to the top of the current window or document.

Edit.WordNextExtend CTRL + SHIFT + RIGHT ARR Extends the selection one word to the right.
OW

Edit.WordNextExtendCol CTRL + SHIFT + ALT + RIGH Moves the cursor right one word, extending the column selection.
umn T ARROW

Edit.WordPreviousExtend CTRL + SHIFT + LEFT ARRO Extends the selection one word to the left.
W

Edit.WordPreviousExtend CTRL + SHIFT + ALT + LEFT Moves the cursor left one word, extending the column selection.
Column ARROW
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Text Navigation Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Text Manipulation Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts

Text Manipulation Shortcut Keys, Visual Basic 6.0 Default


Shortcut Option
The following shortcut key combinations can be used in text editors to delete, move, or format text within an open document.
Command Shortcut Ke Description
ys
Edit.BreakLine ENTER SHIF Inserts a new line.
T + ENTER

Edit.CollapsetoDef CTRL + M, C Automatically determines logical boundaries for creating regions in code such as procedures,
inition TRL + O and then hides them.

Edit.CommentSele CTRL + K, CT Marks the current line of code as a comment, using the correct comment syntax for the progr
ction RL + C amming language.

Edit.DeleteHorizon CTRL + K, CT Collapses white space in the selection, or deletes white space adjacent to the cursor if there is
talWhiteSpace RL + \ no selection.

Edit.FormatDocu CTRL + K, CT Applies the indenting and space formatting for the language as specified on the Formatting p
ment RL + D ane of that language in the Text Editor section of the Options dialog box.

Edit.FormatSelecti CTRL + K, CT Correctly indents the selected lines of code based on the surrounding lines of code.
on RL + F

Edit.HideSelection CTRL + M, C Hides the selected text. A signal icon marks the location of the hidden text in the file.
TRL + H

Edit.InsertTab TAB Indents the line of text a specified number of spaces, such as five. Available only in the .NET Fr
amework Designer.

Edit.LineCut CTRL + Y Cuts all selected lines, or the current line if there is no selection, to the Clipboard.

Edit.LineDelete CTRL + SHIF Deletes all selected lines, or the current line if there is no selection.
T+Y

Edit.LineOpenAbo CTRL + ENT Inserts a blank line above the insertion point.
ve ER

Edit.LineOpenBelo CTRL + SHIF Inserts a blank line below the insertion point.
w T + ENTER

Edit.LineTranspos SHIFT + ALT Moves the line containing the insertion point below the next line.
e +T

Edit.OvertypeMod INSERT Types over any characters already in the document instead of inserting the characters. Availab
e le only in Text editors.

Edit.StopHidingCu CTRL + M, C Removes the outlining information for the currently selected region.
rrent TRL + U

Edit.StopOutlining CTRL + M, C Removes all outlining information from the entire document.
TRL + P
Edit.SwapAnchor CTRL + R, C Swaps the anchor and end points of the current selection.
TRL + P

Edit.TabLeft SHIFT + TAB Moves selected lines left one tab stop. Available only in the .NET Framework Designer.

Edit.ToggleAllOutli CTRL + M, C Toggles all previously marked hidden text sections between hidden and display states.
ning TRL + L

Edit.ToggleBookm CTRL + K, CT Sets or removes a bookmark at the current line.


ark RL + K

Edit.ToggleOutlini CTRL + M, C Toggles the currently selected hidden text section between the hidden and display state.
ngExpansion TRL + M

Edit.ToggleTaskLis CTRL + K, CT Sets or removes a shortcut at the current line.


tShortcut RL + H

Edit.UncommentS CTRL + K, CT Removes the comment syntax from the current line of code.
election RL + U

Edit.ViewWhiteSp CTRL + R, C Shows or hides spaces and tab marks.


ace TRL + W

Edit.WordTranspo CTRL + SHIF Transposes the words on either side of the insertion point.
se T+T

View.ShowRefere ALT + F12 Performs a case-sensitive, whole word symbol search and displays the results in the Find Sym
nces bol Results window.
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Text Navigation Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Text Selection Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts

Window Management Shortcut Keys, Visual Basic 6.0 Default


Shortcut Option
The following shortcut key combinations can be used to move, close, or navigate within tool and document windows.
Command Shortcut Keys Description
View.FullScreen SHIFT + ALT + Toggles Full Screen mode on and off.
ENTER

Window.ActivateDocumen ESC Closes a menu or dialog box, cancels an operation in progress, or places focus in t
tWindow he current document window.

Window.CloseDocument CTRL + F4 Closes the current MDI child window.


Window

Window.CloseToolWindo SHIFT + ESC Closes the current tool window.


w

Window.MoveToDropDow CTRL + F2 Moves the cursor to the drop-down bar while the Editor is in Code view.
nBar

Window.NextDocumentWi CTRL + F6 Cycles through the MDI child windows one window at a time.
ndow
CTRL + TAB

Window.NextPane CTRL + F12 Moves to the next tool window.

Window.NextSplitPane F6 Moves to the next pane of a split pane view of a single document.

Window.NextTab CTRL + PAGE D Moves to the next tab in the document or window.
OWN

Window.PreviousDocume CTRL + SHIFT + Moves to the previous document in the Editor or Designer.
ntWindow F6
CTRL + SHIFT +
TAB

Window.PreviousPane CTRL + SHIFT + Moves to the previously selected window.


F12

Window.PreviousSplitPan SHIFT + F6 Moves to the previous pane of a document in split pane view.
e

Window.PreviousTab CTRL + PAGE U Moves to the previous tab in the document or window.
P
See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Tool Window Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Global Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts

Macro Shortcut Keys, Visual Basic 6.0 Default Shortcut Option


The following shortcut key combinations can be used when working with macros.
Command Shortcut Keys Description
Tools.MacrosIDE ALT + F11 Launches the Macros IDE, Microsoft Visual Studio Macros.

Tools.RecordTemporaryMacro CTRL + SHIFT + R Places the environment in Macro record mode.

Tools.RunTemporaryMacro CTRL + SHIFT + P Plays back a recorded macro.


See Also
Tasks
How to: Work with Shortcut Key Combinations
Reference
Text Manipulation Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Window Management Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Tool Window Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Project Shortcut Keys, Visual Basic 6.0 Default Shortcut Option
Other Resources
Visual Studio Macros
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Concepts

Tool Window Shortcut Keys, Visual Basic 6.0 Default Shortcut


Option
The following shortcut key combinations allow you to display specific tool windows.
Command Shortcut Description
Keys
Tools.CommandWi CTRL + S Places the Command window in a mode allowing for the selection of text within the window.
ndowMarkMode HIFT + M

Tools.AddRemoveT CTRL + T Displays the Customize Toolbox dialog box, which allows you to add and remove items on the
oolboxItems Toolbox.

View.MacroExplore ALT + F8 Displays the Macro Explorer window which lists all available macros in the current solution.
r

View.ClassView CTRL + S Displays the Class View window.


HIFT + C

View.CommandWi CTRL + A Displays the Command window, which allows you to type commands that manipulate the IDE.
ndow LT + A

View.DocumentOut CTRL + A Displays the Document Outline window to view the flat or hierarchical outline of the current d
line LT + T ocument.

View.Favorites CTRL + A Displays the Favorites window, which lists shortcuts to Web pages.
LT + F

View.ObjectBrowse F2 Displays the Object Browser to view the classes, properties, methods, events, and constants av
r ailable for packages, and the object libraries and procedures in your project.

View.Output CTRL + A Displays the Output window to view status messages at run time.
LT + O

View.PropertiesWi F4 Displays the Properties window, which lists the design-time properties and events for the curre
ndow ntly selected item.

View.PropertyPage SHIFT + F Displays the property pages for the item currently selected.
s 4

View.ResourceView CTRL + S Displays the Resource View window.


HIFT + E

View.ServerExplore CTRL + A Displays Server Explorer, which allows you to view and manipulate database servers, event log
r LT + S s, message queues, Web services, and many other operating system services.

View.SolutionExplo CTRL + R Displays Solution Explorer, which lists the projects and files in the current solution.
rer

View.TaskList CTRL + A Displays the Task List window where you customize, categorize, and manage tasks, comments,
LT + K shortcuts, warnings and error messages.
View.Toolbox CTRL + A Displays the Toolbox, which contains controls and other items that can be included or used wit
LT + X h your code.
See Also
Tasks
How to: Work with Shortcut Key Combinations
Other Resources
Visual Basic 6.0 Default Shortcut Keys
Visual Basic Language Reference

Help for Event Handlers in Visual Basic Code


To get Help on a particular event handler while in the code editor, put your cursor on the Handles clause at the back end of the
event procedure, then press F1. For example, in the Form1_Load statement below, the correct place to put the cursor is in the
bold term after Handles:

Private Sub Form1_Load(ByVal sender As System.Object, _


ByVal e As System.EventArgs) _
Handles MyBase.Load

End Sub

See Also
Concepts
Event Handlers Overview (Windows Forms)
Other Resources
Handling and Raising Events
Visual Basic Language Concepts

How to: Compile and Run a Project in Visual Basic


The Visual Studio Integrated Development Environment (IDE) makes it easy to compile a project and run the resulting
application.
You can use the debugger built into the IDE to debug your project as it runs. For more information about debugging, see
Debugging Your Visual Basic Application and Edit and Continue (Visual Basic).
Note
The dialog boxes and menu commands you see might differ from those described in Help, depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To compile and run the current project


Press F5 while you are in the Visual Studio Integrated Development Environment (IDE).
The IDE compiles the project and runs the application within the Visual Studio debugger.
To compile and run the current project from the menu
From the Debug menu of the Visual Studio IDE, choose Start Debugging.
The IDE compiles the project and runs the application within the Visual Studio debugger.
To compile and run the current project without debugging
Press CTRL+F5 in the Visual Studio IDE.
The IDE compiles the project and runs the application.
For information about compiling and running Visual Basic code using the command-line compiler, see
Building from the Command Line (Visual Basic).
See Also
Tasks
How to: Start Execution
Concepts
Debugging Your Visual Basic Application
Other Resources
Building from the Command Line (Visual Basic)
Edit and Continue (Visual Basic)
Visual Basic Language Concepts

Security and Visual Basic Development


Visual Basic developers need to address key security issues as they begin working with the .NET Framework. This overview
discusses both Windows and Web applications, and the implementation, debugging, and deployment phases of development.
Overview
Visual Studio provides you with control over the security of running applications. While you have control with the .NET
Framework, that control requires that you think about your programming with an eye on security. There are security issues
that you need to address to create friendly and usable applications for your users.
There are three common situations where you will need to address security concerns:
Permissions: The user running your application may deny privileges to your application. Such a situation can happen
because your application is running from a location that the user has specified not to be allowed access to some system
resources. For example, the user can configure the common language runtime to deny file privileges to any application
that is stored on a network drive. You need to be aware of this in your work, and you should write code that responds
gracefully to denials. For more information, see Security Policy.
Web Applications: Users accessing your Web applications from your Web servers need to be prevented from running
malicious code or corrupting data on your servers. For more information, see
Basic Security Practices for Web Applications (Visual Studio).
Setup of Visual Studio: The way you set up Visual Studio can leave your server more or less at risk from attacks by
malicious code. For more information, see User Permissions and Visual Studio.
Securing resources is a process that spans several technologies and the entire development cycle. Through careful design,
implementation, testing, and deployment of applications, you can create very secure applications. Security technologies,
provided by ASP.NET, the operating system, and Web browsers are available to secure your applications.
For more information, see Security In Visual Studio.
See Also
Other Resources
Secure Coding Guidelines
Windows Forms Security
ASP.NET Web Site Security (Visual Studio)
Security in Device Projects
Visual Basic Security Samples
Visual Basic Language Concepts

.Net Framework Security Basics


Code access security is the part of the .NET Framework that controls access to resources by controlling the execution of code.
This security feature is separate from, and in addition to, the security provided by the operating system.
How it Works
When a user runs your application, it is assigned to a zone by the .NET Framework common language runtime. The five zones
are:
Zone Description
My Computer The application code resides on on the user's computer.

Local Intranet The application code runs from a file share on the user's intranet.

Internet The application code runs from the Internet.

Trusted Sites These are applications from sites defined as "Trusted" through Internet Explorer.

Untrusted Sites These are applications from sites defined as "Restricted" through Internet Explorer.

The assignment of the first three zones, My Computer, Local Intranet, and Internet, is based on where the code is located.
You can override the assignment by assigning specific sites to the Trusted Sites or Untrusted Sites groups in the Internet
Explorer.
Each of these zones has specific access permissions set by a system administrator. The security level for a zone may be set to
full trust, medium trust, low trust, or no trust. The trust levels define the resources that are accessible to the application. The
zone, together with other security evidence, such as the publisher, strong name, Web site, and URL of the code, determines the
permissions that are granted to the code at run time. (For more information about security evidence, see Evidence.) You have
no control over the security settings on the user's computer, yet your application must work within the settings it encounters
as it runs. This may mean that your application will be denied access to particular resources. For example, your application may
need to write data to a file, yet the user's system will deny write access at run time by raising an exception.
Your job is to develop your application to handle this situation. This does not necessarily mean that you will make your
application find another way to write the data. It does mean that your application needs to anticipate that it may not be able to
write the data and then respond to such a possibility. You may want to use more exception handling
(How to: Test Code with a Try…Catch Block in Visual Basic) or some of the objects in the System.Security.Permissions
namespace to make your code more robust. A brief description of these methods is included in a later section of this article,
"Developing for Partial-Trust Environments."
The security levels for zones are set using the Administration Tools installed when the .NET Framework is installed. To learn
more about the setting security levels for zones on a computer, see Administration Tools.
Full Trust
Developers often work in a full-trust environment. They keep their source code on their hard drives, and they test their
applications from their development computers. In this full-trust environment, any code the developer compiles is allowed to
run on the local computer. Security exceptions do not surface, because the local computer is defined to be a full-trust
environment by default.
Partial Trust
Partial trust describes any zone that is not a full trust zone. When an application is deployed, it may move into a new zone,
perhaps one that does not grant full trust to the application. The two most common scenarios that run code in partial trust are:
Running code that is downloaded from the Internet.
Running code that resides on a network share (intranet).
Some examples of resources that might be denied in a partial-trust zone are:
File I/O operations, including reading, writing, creating, deleting, or printing files.
System components, such as registry values and environment variables.
Server components, including directory services, registry, event logs, performance counters, and message queues.
What is not allowed in partial trust? That is not easy to determine. Each class and each method of each class in the .NET
Framework has a security attribute that defines the level of trust needed to run that method, and that attribute may not be
accessible at run time because of just these security features. The zone level is not a simple mapping of trust level to attributes,
but is a collection of particular permissions given to particular classes and methods. Your application will not be able to simply
query for the trust level and then be able to predict which resources are not available. You can determine whether or not your
application is running in full trust. One method of doing so is described in the next section, "Developing for Partial Trust
Environments."
Developing for Partial-Trust Environments
This section presents a very brief look into how security concerns might affect the code you write. There is no single solution to
developing for the partial-trust environment. Your solution will depend on the application you are writing. Additionally,
because the trust level may change during execution of your application, you cannot simply test for the existing trust level and
then proceed.
Security Exception Code
The first step in developing for partial-trust zones is to write code that recognizes that security exceptions will surface. Consider
the following code:

Public Sub MakeABitmap()


Dim b As Bitmap = New Bitmap(100, 100)
' Some code here to draw a nice picture in the bitmap
b.Save("c:\PrettyPicture.bmp")
End Sub

This method runs without throwing an exception if the project and the project assembly are stored on the hard disk of your
computer, and if you are a member of the Administrators group on your computer. If you deploy this application to your
intranet, SecurityException may be thrown when the application attempts to save the bitmap object. If you do not have a
Try...Catch...Finally Statement (Visual Basic) block around this code, your application terminates with the exception. This is
probably not a satisfactory user experience. If you add exception-handling code, then your application can:
Warn the user that the application cannot complete all the tasks it needs to.
Clean up any existing objects, so that code that runs after the catch block does not fail.
You could modify the bitmap-saving code as shown below. The added code warns the user that that file was not saved because
of a security denial, and it separates security failures from other file I/O failures, such as incorrect file names. This method does
not create any security holes. The user will either modify security to trust your application, or the application will not run.

Public Sub MakeABitmap()


Dim b As Bitmap = Nothing
Try
b = New Bitmap(100, 100)
b.Save("c:\PrettyPicture.bmp")
Catch ex As System.Security.SecurityException
' Let the user know the save won't work.
MessageBox.Show("Permission to save the file was denied, " & _
"and the bitmap was not saved.")
Catch ex As System.Exception
' React to other exceptions here.
MessageBox.Show("Unable to create and save the bitmap.")
End Try
End Sub

Classes, attributes, and enumerations from the System.Security.Permissions namespace support even more control over the
security tasks in your application. If you are writing libraries that may be called from other applications, you will want your
library to verify the permissions of the calling code. For example, you could simply add the following assembly-level attribute
at the top of your code file, or to the AssemblyInfo.vb or AssemblyInfo.cs file. For more information, see
Setting Assembly Attributes.
<Assembly: System.Security.Permissions.FileIOPermissionAttribute( _
System.Security.Permissions.SecurityAction.RequestMinimum, _
Write:="c:\PrettyPicture.bmp")>

The runtime verifies the permission when the assembly loads. If the runtime denies the permission requested, the assembly
fails to load and a security exception is thrown. If you add this attribute to a stand-alone application, the application might not
run. If this attribute appears in a class library, then the library may not load at run time. You would need to add a try/catch
block to the code that calls the class library.
You can also specifically ask for permissions from the runtime, shown below using the Demand method. The runtime may then
grant or deny the demand. The demand is denied by raising a security exception. You might rewrite the code like this to
explicitly demand permission to write the bitmap file:

Public Sub MakeABitmap()


Dim b As Bitmap = Nothing
Dim filename As String = "c:\PrettyPicture.bmp"
Dim permission As New System.Security.Permissions.FileIOPermission( _
System.Security.Permissions.FileIOPermissionAccess.Write, _
filename)

Try
permission.Demand()
Catch ex As System.Security.SecurityException
' Let the user know the save won't work.
MessageBox.Show("Permission to save the file was denied, " & _
"and the bitmap was not saved.")
Catch ex As System.Exception
' React to other exceptions here.
MessageBox.Show("Other error.")
End Try

Try
b = New Bitmap(100, 100)
b.Save(filename)
Catch ex As System.Exception
MessageBox.Show("Unable to create and save the bitmap.")
End Try
End Sub

Testing
The second step in developing for partial-trust zones is testing in multiple environments, especially from your intranet and the
Internet. This will force the security exceptions to be thrown. One important test is to create a user account on your local
computer that does not have Administrator rights and try running your application with that account.
See Also
Concepts
Introduction to Code Access Security
Other Resources
Code Access Security
Security Namespaces in Visual Studio
Secure Coding Guidelines
Visual Basic Language Concepts

Coding Aids for Creating Secure Applications


In thinking about security, you need to protect your development computers from attacks of malicious code and data
corruption, as well as protect your servers. There are several mechanisms in the development environment you can take
advantage of to help secure your development servers:
Visual Studio Tools
Users account groups are added when you install Visual Studio. The Users group has the necessary file, share, and Internet
Information Services (IIS) permissions to create and develop Web applications on a server. The Users group also has the ability
to debug processes on a particular computer, either locally or remotely. As a member of the Users group you have access to
most resources. For more information, see User Permissions and Visual Studio.
Debugging
It is recommended that you debug on a test computer, rather than the deployment computer. If you must debug on a
deployment server, install only the Remote Debugging Component and uninstall the component when you are done
debugging. Take the server offline when you are debugging. For more information, How to: Set Up Remote Debugging. For
general information on debugging, see Debugger Security.
Deployment
For most applications, it is sufficient if the .NET Framework alone is installed on the server. If Visual Studio or the Visual Studio
Server Components are installed on the deployment computer, then the Users group is on the deployment computer. In
addition, you may also want to disable dynamic discovery.
Note
It is strongly recommended that you not install Visual Studio 2005 on your deployment server. The Visual Studio setup adds
both files and users to your system that can be exploited. You can secure a system that has Visual Studio 2005 installed, but i
f you do not need Visual Studio 2005 on the deployment server, it is recommended that you not install it there.

The Copy Project feature of Visual Studio includes the option to deploy an application with a configuration file (Web.config)
that is different from the configuration file used in development. It is likely that the development file has debugging enabled,
which if deployed, would allow users to examine the call stack when an exception is thrown. It is recommended that you deploy
with a separate configuration file that does not allow debugging.
For more information, see ClickOnce Deployment and Security and How to: Debug a Partial Trust Application.
See Also
Reference
The proxy settings on this computer are not configured correctly for Web discovery.
Concepts
Security and Visual Basic Development
Basic Security Practices for Web Applications (Visual Studio)
Security in Windows Forms Overview
Visual Basic Language Concepts

Programming in Visual Basic


This section discusses programming tasks that you may want to learn more about as you create your Visual Basic application.
In This Section
Accessing a Running Application in Visual Basic
Contains documentation on how to control the application's run-time behavior and get run-time information about the
application.
Accessing Application Forms
Contains documentation on accessing an application's forms by using the My.Forms and My.Application objects.
Accessing Application Resources
Contains documentation on accessing an application's resources using the My.Resouces object.
Accessing Application Settings
Contains documentation on accessing an application's settings using the My.Settings object.
Accessing Application Web Services
Contains documentation on how to access the Web services referenced by the application using the My.WebServices
object.
Accessing Computer Resources
Contains documentation on how to use the My.Computer object to access information about the computer on which an
application runs and how to control the computer.
Accessing User Data
Contains documentation on tasks that you can accomplish using the My.User object.
Logging Information from the Application
Contains documentation on how to log information from your application using the My.Application.Log and My.Log
objects, and how to extend the application's logging capabilities.
Processing Drives, Directories, and Files
Contains documentation on how to access the file system using the My.Computer.FileSystem object.
Updating an Application
Contains documentation on how to update ClickOnce applications using the My.Application.Deployment property
See Also
Other Resources
Developing Applications with Visual Basic
Visual Basic Language Concepts

Accessing Computer Resources


The My.Computer object is one of the three central objects in My, providing access to information and commonly used
functionality. My.Computer provides methods, properties, and events for accessing the computer on which the application is
running. Its objects include:
My.Computer.Audio Object
My.Computer.Clipboard Object
My.Computer.Clock Object
My.Computer.FileSystem Object
My.Computer.Info Object
My.Computer.Keyboard Object
My.Computer.Mouse Object
My.Computer.Network Object
My.Computer.Ports Object
My.Computer.Registry Object
In This Section
Playing Sounds
Lists tasks associated with My.Computer.Audio, such as playing a sound in the background.
Storing Data to and Reading From the Clipboard
Lists tasks associated with My.Computer.Clipboard, such as reading data from or writing data to the Clipboard.
Accessing the Computer's Clock
Lists tasks associated with My.Computer.Clock, such as determining the local system time.
Getting Information about the Computer
Lists tasks associated with My.Computer.Info, such as determining a computer's full name or IP addresses.
Accessing the Keyboard
Lists tasks associated with My.Computer.Keyboard, such as determining whether CAPS LOCK is on.
Accessing the Mouse
Lists tasks associated with My.Computer.Mouse, such as determining whether a mouse is present.
Performing Network Operations
Lists tasks associated with My.Computer.Network, such as uploading or downloading files.
Accessing the Computer's Ports
Lists tasks associated with My.Computer.Ports, such as showing available serial ports or sending strings to serial ports.
Reading from and Writing to the Registry
Lists tasks associated with My.Computer.Registry, such as reading data from or writing data to registry keys.
Visual Basic Language Concepts

Playing Sounds
The My.Computer.Audio object provides methods for playing sounds.
In This Section
How to: Play Sounds and Wait For Completion in Visual Basic
Demonstrates how to play sounds from a sound file or application resource and wait for them to complete.
How to: Play Sounds in Visual Basic
Demonstrates how to play a sound from a sound file or application resource in the background.
How to: Play Looping Sounds in Visual Basic
Demonstrates how to play a sound from a sound file or application resource as a continuous loop.
How to: Stop Playing Sounds in the Background in Visual Basic
Demonstrates how to stop a sound playing in the background.
How to: Play System Sounds in Visual Basic
Demonstrates how to play a system sound.
Reference
My.Computer.Audio Object
Describes the My.Computer.Audio object.
My.Computer.Audio.Play Method
Describes the Play method.
My.Computer.Audio.PlaySystemSound Method
Describes the PlaySystemSound method.
My.Computer.Audio.Stop Method
Describes the Stop method, which is used to stop a sound that is currently playing.
Visual Basic Language Concepts

How to: Play Sounds and Wait For Completion in Visual Basic
This example plays sounds from a sound file and an application resource using the My.Computer.Audio.Play method, and
waits for them to complete.
Background playing lets the application execute other code while the sound plays. The My.Computer.Audio.Play method
allows the application to play only one background sound at a time; when the application plays a new background sound, it
stops playing the previous background sound.
The My.Computer.Audio class provides methods and properties that can be used to play audio files.
Example
The My.Computer.Audio.Play method plays the specified sound and waits for it to complete.
Check that the file name references a .wav sound file on your system.
VB
Sub PlaySoundFile()
My.Computer.Audio.Play("C:\Waterfall.wav", _
AudioPlayMode.WaitToComplete)
End Sub

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows Forms
Applications > Sound. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
The My.Computer.Audio.Play method plays the specified sound and waits for it to complete.
Check that the application resources include a .wav sound file named Waterfall.
VB
Sub PlaySoundResource()
My.Computer.Audio.Play(My.Resources.Waterfall, _
AudioPlayMode.WaitToComplete)
End Sub

Compiling the Code


These code examples can run only within a Windows Forms or console application. For more information, see
My.Computer.Audio.Play Method.
Robust Programming
The file name should reference a .wav sound file on your system.
To simplify the management of your sound files, consider storing the files as application resources. They can then be accessed
through the My.Resources Object.
See Also
Tasks
How to: Play System Sounds in Visual Basic
How to: Play Sounds in Visual Basic
Reference
My.Computer.Audio.Play Method
AudioPlayMode Enumeration
My.Computer.Audio Object
Visual Basic Language Concepts

How to: Play Sounds in Visual Basic


This example plays a sound in the background.
Background playing lets the application execute other code while the sound plays. The My.Computer.Audio.Play method
allows the application to play only one background sound at a time; when the application plays a new background sound, it
stops playing the previous background sound. If you want to play a sound and wait for it to complete, see
How to: Play Sounds and Wait For Completion in Visual Basic.
In general, when an application plays a looping sound, it should eventually stop the sound. For more information, see
How to: Stop Playing Sounds in the Background in Visual Basic.
Example
The My.Computer.Audio.Play method plays a sound in the background when PlayMode.Background is specified.
Check that the file name references a .wav sound file on your system.
VB
Sub PlayBackgroundSoundFile()
My.Computer.Audio.Play("C:\Waterfall.wav", _
AudioPlayMode.Background)
End Sub

The My.Computer.Audio.Play method plays the specified sound in the background when PlayMode.Background is
specified.
Check that the application resources include a .wav sound file named Waterfall.
VB
Sub PlayBackgroundSoundResource()
My.Computer.Audio.Play(My.Resources.Waterfall, _
AudioPlayMode.Background)
End Sub

Compiling the Code


These code examples can run only within a Windows Forms or console application. For more information, see
My.Computer.Audio.Play Method.
Robust Programming
The file name should reference a .wav sound file on your system.
To simplify the management of your sound files, consider storing the files as application resources. They can then be accessed
through the My.Resources Object.
See Also
Tasks
How to: Play System Sounds in Visual Basic
How to: Stop Playing Sounds in the Background in Visual Basic
How to: Play Looping Sounds in Visual Basic
Reference
My.Computer.Audio.Play Method
AudioPlayMode Enumeration
Visual Basic Language Concepts

How to: Play Looping Sounds in Visual Basic


This example plays a looping sound in the background.
Background playing lets the application execute other code while the sound plays. This is particularly useful when the playing
sound should not block the application execution. The My.Computer.Audio.Play method allows the application to play only
one background sound at a time; when the application plays a new background sound, it stops playing the previous
background.
In general, when an application plays a looping sound, it should eventually stop the sound. For more information, see
How to: Stop Playing Sounds in the Background in Visual Basic.
Example
The My.Computer.Audio.Play method plays the specified sound in the background when PlayMode.BackgroundLoop is
specified.
Check that the file name references a .wav sound file on your system.
VB
Sub PlayLoopingBackgroundSoundFile()
My.Computer.Audio.Play("C:\Waterfall.wav", _
AudioPlayMode.BackgroundLoop)
End Sub

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows Forms
Applications > Sound. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
The My.Computer.Audio.Play method plays the specified sound in the background when PlayMode.BackgroundLoop is
specified.
Check that the application resources include a .wav sound file named Waterfall.
VB
Sub PlayLoopingBackgroundSoundResource()
My.Computer.Audio.Play(My.Resources.Waterfall, _
AudioPlayMode.BackgroundLoop)
End Sub

Compiling the Code


These code examples can run only within a Windows Forms or console application. For more information, see
My.Computer.Audio.Play Method.
Robust Programming
The file name should reference a .wav sound file on your system.
To simplify the management of your sound files, consider storing the files as application resources. They can then be accessed
through the My.Resources Object.
See Also
Tasks
How to: Play System Sounds in Visual Basic
How to: Stop Playing Sounds in the Background in Visual Basic
How to: Play Sounds in Visual Basic
Reference
My.Computer.Audio.Play Method
AudioPlayMode Enumeration
Visual Basic Language Concepts

How to: Stop Playing Sounds in the Background in Visual Basic


This example stops a sound playing in the background.
Background playing lets the application execute other code while the sound plays. For more information, see
How to: Play Looping Sounds in Visual Basic and How to: Play Sounds in Visual Basic.
In general, when an application plays a looping sound, it should stop the sound at some point.
Example
Use the My.Computer.Audio.Stop method to stop the application's currently playing background or looping sound.
VB
Sub StopBackgroundSound()
My.Computer.Audio.Stop()
End Sub

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows Forms
Applications > Sound. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This code example can run only within a Windows Forms or console application. For more information, see
My.Computer.Audio.Stop Method.
See Also
Tasks
How to: Play Sounds in Visual Basic
How to: Determine if a File Exists in Visual Basic
Reference
My.Computer.Audio.Stop Method
Other Resources
Playing Sounds
Visual Basic Language Concepts

How to: Play System Sounds in Visual Basic


This example uses the My.Computer.Audio.PlaySystemSound method to play a system sound.
The My.Computer.Audio.PlaySystemSound method takes as a parameter one of the shared members from the
SystemSound class.
Example
Use the My.Computer.Audio.PlaySystemSound method to play the specified system sound.
The system sound Asterisk generally denotes errors. For more information, see SystemSound.
VB
Sub PlaySystemSound()
My.Computer.Audio.PlaySystemSound( _
System.Media.SystemSounds.Asterisk)
End Sub

Compiling the Code


This code example can run only within a Windows Forms or console application. For more information, see
My.Computer.Audio.PlaySystemSound Method.
See Also
Tasks
How to: Play Sounds in Visual Basic
How to: Play Looping Sounds in Visual Basic
How to: Determine if a File Exists in Visual Basic
Reference
My.Computer.Audio.Stop Method
System.Media.SystemSound
Visual Basic Language Concepts

Storing Data to and Reading From the Clipboard


The My.Computer.Clipboard object provides methods and properties that can be used to interact with the Clipboard,
allowing the user to write data to or get data from the Clipboard, as well as to check whether data of a specified format exists
on the Clipboard. The Clipboard is a set of functions and messages that enable applications to transfer data. Because all
applications have access to the Clipboard, data can be transferred easily between them.
In This Section
How to: Clear the Clipboard in Visual Basic
Demonstrates how to clear the Clipboard.
How to: Read from the Clipboard in Visual Basic
Demonstrates how to read data from the Clipboard.
How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
Demonstrates how to determine what type of data is stored on the Clipboard.
How to: Write to the Clipboard in Visual Basic
Demonstrates how to write data to the Clipboard.
How to: Retrieve an Image from the Clipboard in Visual Basic
Demonstrates how to retrieve an image from the Clipboard.
How to: Save an Audio Stream to the Clipboard in Visual Basic
Demonstrates how to save audio data to the Clipboard.
Reference
My.Computer.Clipboard Object
Describes the My.Computer.Clipboard object and its methods and properties.
Related Sections
Serialization
Describes serialization. A class must be serializable for it to be put on the Clipboard.
Visual Basic Language Reference

How to: Clear the Clipboard in Visual Basic


The My.Computer.Clipboard.Clear Method clears the Clipboard. Because the Clipboard is shared by other processes, clearing it
may have an impact on those processes.
To clear the Clipboard
Use the Clear method, as follows.
VB
My.Computer.Clipboard.Clear()

See Also
Tasks
How to: Read from the Clipboard in Visual Basic
How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
How to: Save an Audio Stream to the Clipboard in Visual Basic
How to: Write to the Clipboard in Visual Basic
Reference
My.Computer.Clipboard.Clear Method
Visual Basic Language Concepts

How to: Read from the Clipboard in Visual Basic


The Clipboard can be used to store data, such as text and images. Because the Clipboard is shared by all active processes, it can
be used to transfer data between them. The My.Computer.Clipboard object allows you to easily access the Clipboard and to
read and write to it. The GetText, GetImage, GetData, GetAudioStream, and GetFileDropDownList methods allow you to
specify what type of data you would like to read from the Clipboard.
If data cannot be retrieved from the Clipboard, an ExternalException is thrown.
To read text from the Clipboard and display it
Use the My.Computer.Clipboard.GetText method to read the text. The following code reads the text and displays it in a
message box. There must be text stored on the Clipboard for the example to run correctly.
VB
MsgBox(My.Computer.Clipboard.GetText())

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows
Forms Applications > Clipboard. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
To read an image from the Clipboard
Use the My.Computer.Clipboard.GetImage method to read an image from the Clipboard. The following code reads an
image from the Clipboard and assigns it to the Image property of Button1. There must be an image stored on the
Clipboard and a Button named Button1 for the example to run correctly.
VB
Button1.Image = My.Computer.Clipboard.GetImage()

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows
Forms Applications > Clipboard. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
See Also
Tasks
How to: Write to the Clipboard in Visual Basic
How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object Members
My.Computer.Clipboard Object
Visual Basic Language Concepts

How to: Determine What Type of File is Stored on the


Clipboard in Visual Basic
The Clipboard can be used to store data, such as text and images. Because the Clipboard is available across processes, it can be
used to transfer data between them. The My.Computer.Clipboard object allows you to easily access the Clipboard and to
read and write to it.
Data on the Clipboard may take a number of different forms, such as text, an audio file, or an image. In order to determine
what sort of file is on the Clipboard, you can use methods such as ContainsAudio, ContainsFileDropList, ContainsImage,
and ContainsText. The ContainsData method can be used if you have a custom format that you want to check.
To determine whether the Clipboard holds an image
Use the ContainsImage function to determine whether the data contained on the Clipboard is an image. The following
code checks to see whether the data is an image and reports accordingly.
VB
If My.Computer.Clipboard.ContainsImage() = True Then
MsgBox("Clipboard contains an image.")
Else
MsgBox("Clipboard does not contain an image.")
End If

See Also
Tasks
How to: Read from the Clipboard in Visual Basic
How to: Write to the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsAudio Method
My.Computer.Clipboard.ContainsFileDropList Method
My.Computer.Clipboard.ContainsImage Method
My.Computer.Clipboard.ContainsText Method
My.Computer.Clipboard.ContainsData Method
Visual Basic Language Concepts

How to: Write to the Clipboard in Visual Basic


The Clipboard can be used to store data, such as text and images. Because the Clipboard is shared by all processes, it can be
used to transfer data between them. The My.Computer.Clipboard object allows you to easily access the Clipboard and to
read and write to it. The SetAudio, SetData, SetFileDropDownList, SetImage, and SetText methods allow you to place data
on the Clipboard.
Security Note
Because the Clipboard can be accessed by other users, do not use it to store sensitive information, such as passwords or conf
idential data.

To write text to the Clipboard


Use the My.Computer.Clipboard.SetText method to write text to the Clipboard. The following code writes the string
"This is a test string" to the Clipboard.
VB
My.Computer.Clipboard.SetText("This is a test string.")

To write text to the Clipboard in a specific format


Use the My.Computer.Clipboard.SetText method to write text to the Clipboard, including the type of TextDataFormat.
The following code writes the string "This is a test string" to the Clipboard as RTF text.
VB
My.Computer.Clipboard.SetText("This is a test string.", _
System.Windows.Forms.TextDataFormat.Rtf)

To write data to the Clipboard


Use the My.Computer.Clipboard.SetData method to write data to the Clipboard. This example writes the DataObject
dataChunk to the Clipboard in the custom format specialFormat.

VB
My.Computer.Clipboard.SetData("specialFormat", dataChunk)

See Also
Tasks
How to: Read from the Clipboard in Visual Basic
How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.SetText Method
My.Computer.Clipboard.SetData Method
My.Computer.Clipboard.SetDataObject Method
TextDataFormat
Visual Basic Language Concepts

How to: Retrieve an Image from the Clipboard in Visual Basic


The My.Computer.Clipboard.GetImage method allows you to retrieve an image from the Clipboard.
Items placed on the Clipboard will persist even after the application is shut down.
To retrieve an image from the Clipboard
Use the My.Computer.Clipboard.GetImage method to retrieve an image from the Clipboard. This example checks to
see if there is an image on the Clipboard before retrieving it and assigning it to PictureBox1.
VB
If My.Computer.Clipboard.ContainsImage() Then
Dim grabpicture As System.Drawing.Image
grabpicture = My.Computer.Clipboard.GetImage()
picturebox1.Image = grabpicture
End If

See Also
Tasks
How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard Object Members
My.Computer.Clipboard.ContainsImage Method
My.Computer.Clipboard.GetImage Method
Visual Basic Language Concepts

How to: Save an Audio Stream to the Clipboard in Visual Basic


The My.Computer.Clipboard.SetAudio method can be used to save audio data to the Clipboard.
To save audio data to the Clipboard
Use the My.Computer.Clipboard.SetAudio method to write audio data to the Clipboard. This example creates the byte
array musicReader, reads the file cool.wav into it, and then writes it to the Clipboard.
VB
Dim musicReader As Byte()
musicReader = My.Computer.FileSystem.ReadAllBytes("cool.wav")
My.Computer.Clipboard.SetAudio(musicReader)

See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.SetAudio Method
My.Computer.Clipboard.GetAudioStream Method
My.Computer.Clipboard.ContainsAudio Method
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Concepts

Accessing the Computer's Clock


The My.Computer.Clock object provides properties for accessing the current local time and Universal Coordinated Time
(equivalent to Greenwich Mean Time) from the system clock.
Remarks
This table lists common tasks involving the My.Computer.Clock object and points to topics demonstrating each.
To See
Determine the GMT Time My.Computer.Clock.GmtTime Property

Determine the local system time My.Computer.Clock.LocalTime Property

Determine the number of ticks that have occurred since the computer was started My.Computer.Clock.TickCount Property

See Also
Reference
My.Computer.Clock Object
My.Computer.Clock Object Members
System.DateTime
Concepts
Formatting Date and Time for a Specific Culture
Visual Basic Language Concepts

Getting Information about the Computer


The My.Computer.Info object provides properties for getting information about the computer's memory, loaded assemblies,
name, and operating system.
Remarks
This table lists tasks commonly accomplished through the My.Computer.Info object and points to topics demonstrating how
to perform each.
To See
Determine how much virtual address space is available for the computer on w My.Computer.Info.TotalVirtualMemory Property
hich the application is installed

Determine the platform type of the computer on which the application is runn My.Computer.Info.OSPlatform Property
ing

Determine the operating system of the computer on which the application is r My.Computer.Info.OSFullName Property
unning

Determine what service packs have been installed on the computer on which t My.Computer.Info.OSVersion Property
he application is running

Determine the installed UICulture on the computer on which the application i My.Computer.Info.InstalledUICulture Property
s running.

See Also
Reference
My.Computer.Info Object
My.Computer.Info Object Members
Visual Basic Language Concepts

Accessing the Keyboard


The My.Computer.Keyboard object provides properties for accessing the current state of the keyboard, such as what keys are
currently pressed, and provides a method to send keystrokes to the active window.
Tasks
This table lists tasks associated with the My.Computer.Keyboard object and points to topics demonstrating how to perform
each task.
To See
Determine whether CAPS LOCK is on How to: Determine If CapsLock is On in Visual Basic

Determine whether the SHIFT key is down My.Computer.Keyboard.ShiftKeyDown Property

Determine whether the ALT key is down My.Computer.Keyboard.AltKeyDown Property

Determine whether the CTRL key is down My.Computer.Keyboard.CtrlKeyDown Property

Determine whether NUM LOCK is on My.Computer.Keyboard.NumLock Property

Determine whether SCROLL LOCK is on My.Computer.Keyboard.ScrollLock Property

Start an application and send it keystrokes How to: Start an Application and Send it Keystrokes (Visual Basic)

See Also
Reference
My.Computer.Keyboard Object
System.Windows.Forms.Keys
Visual Basic Language Concepts

How to: Determine If CapsLock is On in Visual Basic


The My.Computer.Keyboard object can be used to determine the current state of the keyboard, including such things as
whether NUM LOCK or CAPS LOCK is on.
To determine if CAPS LOCK is on
To determine whether or not CAPS LOCK is on, use the My.Computer.Keyboard.CapsLock property. The following
code displays a message about the state of the CAPS LOCK.
VB
If My.Computer.Keyboard.CapsLock Then
MsgBox("CAPS LOCK is on")
Else
MsgBox("CAPS LOCK is off")
End If

See Also
Reference
My.Computer.Keyboard Object
Concepts
Accessing the Keyboard
Visual Basic Language Concepts

How to: Start an Application and Send it Keystrokes (Visual


Basic)
This example uses the Shell function to start the calculator application and then multiplies two numbers by sending keystrokes
using the My.Computer.Keyboard.SendKeys method.
Example
VB
Dim ProcID As Integer
' Start the Calculator application, and store the process id.
ProcID = Shell("CALC.EXE", AppWinStyle.NormalFocus)
' Activate the Calculator application.
AppActivate(ProcID)
' Send the keystrokes to the Calculator application.
My.Computer.Keyboard.SendKeys("22", True)
My.Computer.Keyboard.SendKeys("*", True)
My.Computer.Keyboard.SendKeys("44", True)
My.Computer.Keyboard.SendKeys("=", True)
' The result is 22 * 44 = 968.

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows Forms
Applications > Forms. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Robust Programming
A ArgumentException exception is raised if an application with the requested process identifier cannot be found.
Security
The call to the Shell function requires full trust (SecurityException class).
See Also
Reference
My.Computer.Keyboard.SendKeys Method
Shell Function
AppActivate Function
Visual Basic Language Concepts

Accessing the Mouse


The My.Computer.Mouse object provides a way to find information about the computer's mouse, such as if a mouse exists,
the number of mouse buttons, and details about the mouse wheel.
Remarks
This table lists tasks associated with the My.Computer.Mouse object and points to topics demonstrating how to accomplish
each.
To See
Determine whether the mouse has a scroll wheel. My.Computer.Mouse.WheelExists Property

Determine whether the left and right mouse buttons have been swapped My.Computer.Mouse.ButtonsSwapped Property

Set how much to scroll when the mouse wheel is rotated one notch. My.Computer.Mouse.WheelScrollLines Property

See Also
Reference
My.Computer.Mouse Object
My.Computer.Mouse Object Members
Visual Basic Language Concepts

Performing Network Operations


The following tables list tasks associated with the My.Computer.Network object.
In This Section
How to: Upload a File in Visual Basic
Demonstrates how to upload a file and store it to a remote location using My.Computer.Network.
How to: Download a File in Visual Basic
Demonstrates how to download a file from a remote location using My.Computer.Network.
How to: Check Connection Status in Visual Basic
Shows how to determine whether the computer has a working network connection.
How to: Determine if a Remote Computer is Available in Visual Basic
Shows how to use the Ping method to determine whether a remote computer or host is available.
Reference
My.Computer.Network Object
Lists methods, properties, and events for working with the network.
My.Computer.Network.DownloadFile Method
Describes the DownloadFile method.
My.Computer.Network.Ping Method
Describes the Ping method.
My.Computer.Network.UploadFile Method
Describes the UploadFile method.
My.Computer.Network.IsAvailable Property
Describes the IsAvailable property.
Custom
Describes the NetworkAvailable event.
Visual Basic Language Concepts

How to: Upload a File in Visual Basic


The My.Computer.Network.UploadFile Method can be used to upload a file and store it to a remote location. If the ShowUI
parameter is set to True, a dialog box is displayed that shows the progress of the download and allows users to cancel the
operation.
To upload a file
Use the UploadFile method to upload a file, specifying the source file's location and the target directory location as a
string or URI (Uniform Resource Identifier).This example uploads the file Order.txt to
http://www.cohowinery.com/uploads.aspx.

VB
My.Computer.Network.UploadFile( _
"C:\My Documents\Order.txt", _
"http://www.cohowinery.com/upload.aspx")

To upload a file and show the progress of the operation


Use the UploadFile method to upload a file, specifying the source file's location and the target directory location as a
string or URI. This example uploads the file Order.txt to http://www.cohowinery.com/uploads.aspx without supplying
a user name or password, shows the progress of the upload, and has a time-out interval of 500 milliseconds.
VB
My.Computer.Network.UploadFile( _
"C:\My Documents\Order.txt", _
"http://www.cohowinery.com/upload.aspx", "", "", True, 500)

To upload a file, supplying a user name and password


Use the UploadFile method to upload a file, specifying the source file's location and the target directory location as a
string or URI, and specifying the user name and the password. This example uploads the file Order.txt to
http://www.cohowinery.com/uploads.aspx, supplying the user name anonymous and a blank password.

VB
My.Computer.Network.UploadFile( _
"C:\My Documents\Order.txt", _
"http://www.cohowinery.com/upload.aspx", "anonymous", "")

Robust Programming
The following conditions may throw an exception:
The local file path is not valid (ArgumentException).
Authentication failed (SecurityException).
The connection timed out (TimeoutException).
See Also
Tasks
How to: Download a File in Visual Basic
How to: Determine if a Remote Computer is Available in Visual Basic
How to: Parse File Paths in Visual Basic
Reference
My.Computer.Network Object
My.Computer.Network Object Members
My.Computer.Network.UploadFile Method
Visual Basic Language Concepts

How to: Download a File in Visual Basic


The My.Computer.Network.DownloadFile Method can be used to download a remote file and store it to a specific location. If
the ShowUI parameter is set to True, a dialog box is displayed showing the progress of the download and allowing users to
cancel the operation. By default, existing files having the same name are not overwritten; if you want to overwrite existing files,
set the overwrite parameter to True.
The following conditions may cause an exception:
Drive name is not valid (ArgumentException).
Necessary authentication has not been supplied (UnauthorizedAccessException or SecurityException).
The server does not respond within the specified connectionTimeout (TimeoutException).
The request is denied by the Web site (WebException).
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help, depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

Security Note
Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be
a Visual Basic source file. Verify all inputs before using the data in your application. The contents of the file may not be what i
s expected, and methods to read from the file may fail.

To download a file
Use the DownloadFile method to download the file, specifying the target file's location as a string or URI and specifying
the location at which to store the file. This example downloads the file WineList.txt from
http://www.cohowinery.com/downloads and saves it to C:\Documents and Settings\All Users\Documents:

VB
My.Computer.Network.DownloadFile _
("http://www.cohowinery.com/downloads/WineList.txt", _
"C:\Documents and Settings\All Users\Documents\WineList.txt")

To download a file, specifying a time-out interval


Use the DownloadFile method to download the file, specifying the target file's location as a string or URI, specifying the
location at which to store the file, and specifying the time-out interval in milliseconds (the default is 1000). This example
downloads the file WineList.txt from http://www.cohowinery.com/downloads and saves it to C:\Documents and
Settings\All Users\Documents, specifying a time-out interval of 500 milliseconds:

VB
My.Computer.Network.DownloadFile _
("http://www.cohowinery.com/downloads/WineList.txt", _
"C:\Documents and Settings\All Users\Documents\WineList.txt", False, 500)

To download a file, supplying a user name and password


Use the DownLoadFile method to download the file, specifying the target file's location as a string or URI and specifying
the location at which to store the file, the user name, and the password. This example downloads the file WineList.txt
from http://www.cohowinery.com/downloads and saves it to C:\Documents and Settings\All Users\Documents, with
the user name anonymous and a blank password.
VB
My.Computer.Network.DownloadFile _
("http://www.cohowinery.com/downloads/WineList.txt", _
"C:\Documents and Settings\All Users\Documents\WineList.txt", "anonymous", "")

Security Note
The FTP protocol used by the DownLoadFile method sends information, including passwords, in plain text and should
not be used for transmitting sensitive information.

See Also
Tasks
How to: Upload a File in Visual Basic
How to: Parse File Paths in Visual Basic
Reference
My.Computer.Network Object
My.Computer.Network Object Members
My.Computer.Network.DownloadFile Method
Visual Basic Language Concepts

How to: Check Connection Status in Visual Basic


The My.Computer.Network.IsAvailable Property can be used to determine whether the computer has a working network or
Internet connection.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help, depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To check whether a computer has a working connection


Determine whether the IsAvailable property is True or False. The following code checks the property's status and
reports it:
VB
If My.Computer.Network.IsAvailable = True Then
MsgBox("Computer is connected.")
Else
MsgBox("Computer is not connected.")
End If

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in
Connectivity and Networking. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
See Also
Tasks
How to: Determine if a Remote Computer is Available in Visual Basic
Reference
My.Computer.Network Object
My.Computer.Network.IsAvailable Property
Visual Basic Language Concepts

How to: Determine if a Remote Computer is Available in Visual


Basic
You can use the My.Computer.Network.Ping Method to determine whether a remote computer or host is available. The server
can be specified by URL, computer name, or IP address. Do not include http:// when specifying a URL.
The Ping method is not a fail-safe method for determining the availability of a remote computer: the ping port on the target
machine may be turned off, or the ping request may be blocked by a firewall or router.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help, depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To ping a server
Determine whether the Ping method returns True. This example reports whether or not the server can be pinged, by
determining whether the Ping method returned True. Replace 198.01.01.01 with the IP address, URL, or computer
name of the server to ping
VB
If My.Computer.Network.Ping("198.01.01.01") Then
MsgBox("Server pinged successfully.")
Else
MsgBox("Ping request timed out.")
End If

To ping a server and specify a time-out


Determine whether the Ping method returns True, specifying the time-out interval in milliseconds. If no time-out is
specified, 500 is used as the default. This example reports whether or not the server can be pinged, by determining
whether the Ping method returned True, and it specifies a time-out interval of 1000 milliseconds. Replace
www.cohowinery.com with the IP address, URL, or computer name of the server to ping.

VB
If My.Computer.Network.Ping("www.cohowinery.com", 1000) Then
MsgBox("Server pinged successfully.")
Else
MsgBox("Ping request timed out.")
End If

See Also
Tasks
How to: Check Connection Status in Visual Basic
Reference
My.Computer.Network Object
My.Computer.Network Object Members
My.Computer.Network.Ping Method
Visual Basic Language Concepts

Accessing the Computer's Ports


The My.Computer.Ports object provides a property and a method for accessing the computer's serial ports.
In This Section
How to: Show Available Serial Ports in Visual Basic
Demonstrates how to show available serial ports.
How to: Dial Modems Attached to Serial Ports in Visual Basic
Demonstrates how to dial a modem attached to the serial port of a computer.
How to: Send Strings to Serial Ports in Visual Basic
Demonstrates how to send a string to a computer's serial port.
How to: Receive Strings From Serial Ports in Visual Basic
Demonstrates how to receive a string from a computer's serial port.
Reference
My.Computer.Ports Object
Describes the My.Computer.Ports object and its members.
My.Computer.Ports.SerialPortNames Property
Describes the SerialPortNames property, which gets a collection of the names of the serial ports on the computer.
My.Computer.Ports.OpenSerialPort Method
Describes the OpenSerialPort method, which creates and opens a System.IO.Ports.SerialPort object.
Related Sections
SerialPort
Describes the .NET Framework SerialPort class.
Visual Basic Language Concepts

How to: Show Available Serial Ports in Visual Basic


This topic describes how to use My.Computer.Ports to show the available serial ports of the computer in Visual Basic.
To allow a user to select which port to use, the names of the serial ports are placed in a ListBox control.
Example
This example loops over all the strings that the My.Computer.Ports.SerialPortNames property returns. These strings are the
names of the available serial ports on the computer.
Typically, a user selects which serial port the application should use from the list of available ports. In this example, the serial
port names are stored in a ListBox control. For more information, see ListBox Control (Windows Forms).
VB
Sub GetSerialPortNames()
' Show all available COM ports.
For Each sp As String In My.Computer.Ports.SerialPortNames
ListBox1.Items.Add(sp)
Next
End Sub

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Connectivity and
Networking. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
A project reference to System.Windows.Forms.dll.
Access to the members of the System.Windows.Forms namespace. Add an Imports statement if you are not fully
qualifying member names in your code. For more information, see Imports Statement.
That your form have a ListBox control named ListBox1.

Robust Programming
You do not have to use the ListBox control to display the available serial port names. Instead, you can use a ComboBox or
other control. If the application does not need a response from the user, you can use a TextBox control to display the
information.
Note
The port names returned by My.Computer.Ports.SerialPortNames may be incorrect when run on Windows 98. To prevent
application errors, use exception handling, such as the Try...Catch...Finally statement or the Using statement, when using th
e port names to open ports.

See Also
Tasks
How to: Dial Modems Attached to Serial Ports in Visual Basic
How to: Send Strings to Serial Ports in Visual Basic
How to: Receive Strings From Serial Ports in Visual Basic
Reference
My.Computer.Ports Object
Visual Basic Language Concepts

How to: Dial Modems Attached to Serial Ports in Visual Basic


This topic describes how to use My.Computer.Ports to dial a modem in Visual Basic.
Typically, the modem is connected to one of the serial ports on the computer. For your application to communicate with the
modem, it must send commands to the appropriate serial port.
To dial a modem
1. Determine which serial port the modem is connected to. This example assumes the modem is on COM1.
2. Use the My.Computer.Ports.OpenSerialPort method to obtain a reference to the port. For more information, see
My.Computer.Ports.OpenSerialPort Method.
The Using block allows the application to close the serial port even if it generates an exception. All code that manipulates
the serial port should appear within this block, or within a Try...Catch...Finally block.
VB
Using com1 As IO.Ports.SerialPort = _
My.Computer.Ports.OpenSerialPort("COM1", 9600)
End Using

3. Set the DtrEnable property to indicate that the computer is ready to accept an incoming transmission from the modem.
VB
com1.DtrEnable = True

4. Send the dial command and the phone number to the modem through the serial port by means of the Write method.
VB
com1.Write("ATDT 555-0100" & vbCrLf)

Example
VB
Sub DialModem()
' Dial a number via an attached modem on COM1.
Using com1 As IO.Ports.SerialPort = _
My.Computer.Ports.OpenSerialPort("COM1", 9600)
com1.DtrEnable = True
com1.Write("ATDT 555-0100" & vbCrLf)
' Insert code to transfer data to and from the modem.
End Using
End Sub

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Connectivity and
Networking. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires a reference to the System namespace.
Robust Programming
This example assumes the modem is connected to COM1. We recommend that your code allow the user to select the desired
serial port from a list of available ports. For more information, see How to: Show Available Serial Ports in Visual Basic.
This example uses a Using block to make sure that the application closes the port even if it throws an exception. For more
information, see Using Statement (Visual Basic).
In this example, the application disconnects the serial port after it dials the modem. Realistically, you will want to transfer data
to and from the modem. For more information, see How to: Receive Strings From Serial Ports in Visual Basic.
See Also
Tasks
How to: Send Strings to Serial Ports in Visual Basic
How to: Receive Strings From Serial Ports in Visual Basic
How to: Show Available Serial Ports in Visual Basic
Reference
My.Computer.Ports Object
System.IO.Ports.SerialPort
Visual Basic Language Concepts

How to: Send Strings to Serial Ports in Visual Basic


This topic describes how to use My.Computer.Ports to send strings to the computer's serial ports in Visual Basic.
Example
This example sends a string to the COM1 serial port. You may need to use a different serial port on your computer.
Use the My.Computer.Ports.OpenSerialPort method to obtain a reference to the port. For more information, see
My.Computer.Ports.OpenSerialPort Method.
The Using block allows the application to close the serial port even if it generates an exception. All code that manipulates the
serial port should appear within this block or within a Try...Catch...Finally block.
The WriteLine method sends the data to the serial port.
VB
Sub SendSerialData(ByVal data As String)
' Send strings to a serial port.
Using com1 As IO.Ports.SerialPort = _
My.Computer.Ports.OpenSerialPort("COM1")
com1.WriteLine(data)
End Using
End Sub

Compiling the Code


This example assumes the computer is using COM1.

Robust Programming
This example assumes the computer is using COM1; for more flexibility, the code should allow the user to select the desired
serial port from a list of available ports. For more information, see How to: Show Available Serial Ports in Visual Basic.
This example uses a Using block to make sure that the application closes the port even if it throws an exception. For more
information, see Using Statement (Visual Basic).
See Also
Tasks
How to: Dial Modems Attached to Serial Ports in Visual Basic
How to: Show Available Serial Ports in Visual Basic
Reference
My.Computer.Ports Object
System.IO.Ports.SerialPort
Visual Basic Language Concepts

How to: Receive Strings From Serial Ports in Visual Basic


This topic describes how to use My.Computer.Ports to receive strings from the computer's serial ports in Visual Basic.
To receive strings from the serial port
1. Initialize the return string.
VB
Dim returnStr As String = ""

2. Determine which serial port should provide the strings. This example assumes it is COM1.
3. Use the My.Computer.Ports.OpenSerialPort method to obtain a reference to the port. For more information, see
My.Computer.Ports.OpenSerialPort Method.
The Using block allows the application to close the serial port even if it generates an exception. All code that manipulates
the serial port should appear within this block, or within a Try...Catch...Finally block.
VB
Using com1 As IO.Ports.SerialPort = _
My.Computer.Ports.OpenSerialPort("COM1")
End Using

4. Create a Do loop for reading lines of text until no more lines are available.
VB
Do
Loop

5. Use the ReadLine method to read the next available line of text from the serial port.
VB
Dim Incoming As String = com1.ReadLine()

6. Use an If statement to determine if the ReadLine method returns Nothing (which means no more text is available). If it
does return Nothing, exit the Do loop.
VB
If Incoming Is Nothing Then
Exit Do
End If

7. Add an Else block to the If statement to handle the case if the string is actually read. The block appends the string from
the serial port to the return string.
VB
Else
returnStr &= Incoming & vbCrLf
8. Return the string.
VB
Return returnStr

Example
VB
Function ReceiveSerialData() As String
' Receive strings from a serial port.
Dim returnStr As String = ""
Using com1 As IO.Ports.SerialPort = _
My.Computer.Ports.OpenSerialPort("COM1")
Do
Dim Incoming As String = com1.ReadLine()
If Incoming Is Nothing Then
Exit Do
Else
returnStr &= Incoming & vbCrLf
End If
Loop
End Using

Return returnStr
End Function

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Connectivity and
Networking. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example assumes the computer is using COM1.
Robust Programming
This example assumes the computer is using COM1. For more flexibility, the code should allow the user to select the desired
serial port from a list of available ports. For more information, see How to: Show Available Serial Ports in Visual Basic.
This example uses a Using block to make sure that the application closes the port even if it throws an exception. For more
information, see Using Statement (Visual Basic).
See Also
Tasks
How to: Dial Modems Attached to Serial Ports in Visual Basic
How to: Send Strings to Serial Ports in Visual Basic
How to: Show Available Serial Ports in Visual Basic
Reference
My.Computer.Ports Object
System.IO.Ports.SerialPort
Visual Basic Language Concepts

Reading from and Writing to the Registry


Lists task and conceptual topics associated with the registry.
When programming in Visual Basic 2005, you can choose to access the registry by means of either the functions provided by
Visual Basic 2005 or the registry classes of the .NET Framework. The registry hosts information from the operating system as
well as information from applications hosted on the machine. Working with the registry may compromise security by allowing
inappropriate access to system resources or protected information.
In This Section
Common Registry Tasks
Lists tasks associated with the registry, such as determining or setting the value of a registry key.
Reading from and Writing to the Registry Using My
Explains how to use the My.Computer.Registry object to access the registry.
Reading from and Writing to the Registry Using the Microsoft.Win32 Namespace
Explains how to use the Visual Basic 2005 functions, DeleteSetting, GetSetting, GetAllSettings, and SaveSetting, to
access the registry.
Walkthrough: Creating a Registry Key and Changing Its Values
Demonstrates how to create a registry key and its subkeys, change their settings, and delete keys.
Security and the Registry
Discusses security issues involving the registry.
Troubleshooting: Manipulating the Registry
Lists common issues encountered when accessing the registry and how to address them.
Related Sections
My.Computer.Registry Object
Lists and explains members of the My.Computer.Registry object.
Registry Class
Presents an overview of the Registry class, along with links to individual keys and members.
Visual Basic Language Concepts

Common Registry Tasks


The My.Computer.Registry object provides properties and methods for accessing the registry.
Tasks
The following table lists examples involving the registry.
To See
Create a registry key and set its values How to: Create a Registry Key and Set Its Values in Visual Basic

Determine whether a value exists in a specific registry key How to: Determine if a Value Exists in a Registry Key in Visual Basic

Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic

Set a value in a registry key How to: Set Values in Registry Keys in Visual Basic

Delete a registry key How to: Delete a Registry Key in Visual Basic

See Also
Tasks
Walkthrough: Creating a Registry Key and Changing Its Values
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
Concepts
Reading from and Writing to the Registry Using My
Security and the Registry
Visual Basic Language Concepts

How to: Create a Registry Key and Set Its Values in Visual Basic
The CreateSubKey method of the My.Computer.Registry object can be used to create a registry key.
Procedure
To create a registry key
Use the CreateSubKey method, specifying which hive to place the key under as well as the name of the key. The
parameter Subkey is not case-sensitive. This example creates the registry key MyTestKey under HKEY_CURRENT_USER.
VB
My.Computer.Registry.CurrentUser.CreateSubKey("MyTestKey")

To create a registry key and set a value in it


1. Use the CreateSubkey method, specifying which hive to place the key under as well as the name of the key. This
example creates the registry key MyTestKey under HKEY_CURRENT_USER.
VB
My.Computer.Registry.CurrentUser.CreateSubKey("MyTestKey")

2. Set the value with the SetValue method. This example sets the string value. "MyTestKeyValue" to "This is a test value".
VB
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\MyTestKey", _
"MyTestKeyValue", "This is a test value.")

Example
This example creates the registry key MyTestKey under HKEY_CURRENT_USER and then sets the string value MyTestKeyValue
to This is a test value.
VB
My.Computer.Registry.CurrentUser.CreateSubKey("MyTestKey")
' Change MyTestKeyValue to This is a test value.
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\MyTestKey", _
"MyTestKeyValue", "This is a test value.")

Robust Programming
Examine the registry structure to find a suitable location for your key. For example, you may want to open the
HKEY_CURRENT_USER\Software key of the current user, and create a key with your company's name. Then add the registry
values to your company's key.
When reading the registry from a Web application, the current user depends on the authentication and impersonation
implemented in the Web application.
It is more secure to write data to the user folder (CurrentUser) rather than to the local computer (LocalMachine).
When you create a registry value, you need to decide what to do if that value already exists. Another process, perhaps a
malicious one, may have already created the value and have access to it. When you put data in the registry value, the data is
available to the other process. To prevent this, use the GetValue method. It returns Nothing if the key does not already exist.
It is not secure to store secrets, such as passwords, in the registry as plain text, even if the registry key is protected by ACLs
(Access Control Lists).
The following conditions may cause an exception:
The name of the key is Nothing (ArgumentNullException).
The user does not have permissions to create registry keys (SecurityException).
The key name exceeds the 255-character limit (ArgumentException).
The key is closed (IOException).
The registry key is read-only (UnauthorizedAccessException).
Security
To run this process, your assembly requires a privilege level granted by the RegistryPermission class. If you are running in a
partial-trust context, the process might throw an exception due to insufficient privileges. Similarly, the user must have the
correct ACLs for creating or writing to settings. For example, a local application that has the code access security permission
might not have operating system permission. For more information, see Code Access Security Basics.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Walkthrough: Creating a Registry Key and Changing Its Values
Reference
My.Computer.Registry Object
My.Computer.Registry.CurrentUser Property
CreateSubKey
Concepts
Common Registry Tasks
Code Access Security Basics
Visual Basic Language Concepts

How to: Determine if a Value Exists in a Registry Key in Visual


Basic
The GetValue method of the My.Computer.Registry object can be used to determine whether a given value exists in a
specific registry key.
When reading the registry from a Web application, the current user depends on the authentication and impersonation
implemented in the Web application.
To determine whether a value exists in a registry key
Use the GetValue method to retrieve the value. The following code checks the value and returns a message if it does not
exist.
VB
If My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\TestApp", _
"TestValue", Nothing) Is Nothing Then
MsgBox("Value does not exist.")
End If

Robust Programming
The following conditions may cause an exception:
The name of the key is Nothing (ArgumentNullException).
The user does not have permissions to create registry keys (SecurityException).
The key name exceeds the 255-character limit (ArgumentException).
The key is closed (IOException).
The registry key is read-only (UnauthorizedAccessException).
Security
To run this process, your assembly requires a privilege level granted by the RegistryPermission class. If you are running in a
partial-trust context, the process might throw an exception due to insufficient privileges. Similarly, the user must have the
correct access control lists for creating or writing to settings. For example, a local application that has the code access security
permission might not have operating system permission. For more information, see Code Access Security Basics.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Walkthrough: Creating a Registry Key and Changing Its Values
Reference
My.Computer.Registry Object
My.Computer.Registry.CurrentUser Property
Concepts
Code Access Security Basics
Common Registry Tasks
Visual Basic Language Concepts

How to: Read a Value from a Registry Key in Visual Basic


The GetValue method of the My.Computer.Registry object can be used to read values in the Windows registry. If the key, in
this case "Software\MyApp", does not exist, an exception is thrown. If the ValueName, in this case "Name", does not exist,
Nothing is returned.
To read a value from a registry key
Use the GetValue method, specifying the path and name) to read a value from registry key. The following example reads
the value Name from HKEY_CURRENT_USER\Software\MyApp and displays it in a message box.
VB
Dim readValue As String
readValue = My.Computer.Registry.GetValue _
("HKEY_CURRENT_USER\Software\MyApp", "Name", Nothing)
MsgBox("The value is " & readValue)

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows
Operating System > Registry. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Robust Programming
The registry holds top-level, or root, keys that are used to store data. For instance, the HKEY_LOCAL_MACHINE root key is used
for storing machine-level settings used by all users, while HKEY_CURRENT_USER is used for storing data specific to an
individual user.
The following conditions may cause an exception:
The name of the key is Nothing (ArgumentNullException).
The user does not have permissions to read from registry keys (SecurityException).
The key name exceeds the 255-character limit (ArgumentException).
Security
To run this process, your assembly requires a privilege level granted by the RegistryPermission class. If you are running in a
partial-trust context, the process might throw an exception due to insufficient privileges. Similarly, the user must have the
correct ACLs for creating or writing to settings. For example, a local application that has the code access security permission
might not have operating system permission. For more information, see Code Access Security Basics.
See Also
Tasks
Walkthrough: Creating a Registry Key and Changing Its Values
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
RegistryHive
Concepts
Common Registry Tasks
Visual Basic Language Concepts

How to: Set Values in Registry Keys in Visual Basic


The SetValue method of the My.Computer.Registry object can be used to write values in the Windows registry. The registry
holds top-level, or root, keys that are used to store data. For instance, the HKEY_LOCAL_MACHINE root key is used for storing
machine-level settings used by all users, while HKEY_CURRENT_USER is used for storing data specific to an individual user.
The value, including the complete key path, is created if it does not exist.
Procedure
To write a value to a registry key
Use the SetValue method, specifying the key and value. This example sets the value Name to "Author's Name" in the key
HKEY_CURRENT_USER\Software\TestApp.
VB
My.Computer.Registry.SetValue _
("HKEY_CURRENT_USER\Software\TestApp", "Name", "Author's Name")

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows
Operating System > Registry. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Robust Programming
User preference data should be written to the Microsoft.Win32.Registry.CurrentUser hive.
It is not secure to store secrets, such as passwords, in the registry as plain text, even if the registry key is protected by access
control lists (ACLs).
The following conditions may cause an exception:
The name of the key is Nothing (ArgumentNullException).
The key name exceeds the 255-character limit (ArgumentException).
The specified hive is not valid (ArgumentException).
The key is closed (IOException).
The path is not valid (IOException).
The registry key is read-only (UnauthorizedAccessException).
Security
To run this process, your assembly requires a privilege level granted by the RegistryPermission class. If you are running in a
partial-trust context, the process might throw an exception due to insufficient privileges. Similarly, the user must have the
correct ACLs for creating or writing to settings. For example, a local application that has the code access security permission
might not have operating system permission. For more information, see Code Access Security Basics.
See Also
Tasks
How to: Read a Value from a Registry Key in Visual Basic
Walkthrough: Creating a Registry Key and Changing Its Values
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object Members
My.Computer.Registry.SetValue Method
Concepts
Common Registry Tasks
Visual Basic Language Concepts

How to: Delete a Registry Key in Visual Basic


The DeleteSubKey and DeleteSubKey methods can be used to delete registry keys.
Procedure
To delete a registry key
Use the DeleteSubKey method to delete a registry key. This example deletes the key Software/TestApp in the CurrentUser
hive. You can change this in the code to the appropriate string, or have it rely on user-supplied information.
VB
My.Computer.Registry.CurrentUser.DeleteSubKey(text)

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows
Operating System > Registry. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Robust Programming
The DeleteSubKey method returns an empty string if the key/value pair does not exist.
The following conditions may cause an exception:
The name of the key is Nothing (ArgumentNullException).
The user does not have permissions to delete registry keys (SecurityException).
The key name exceeds the 255-character limit (ArgumentException).
The registry key is read-only (UnauthorizedAccessException).
Security
Registry calls fail if either sufficient run-time permissions are not granted (RegistryPermission) or if the user does not have the
correct access (as determined by the ACLs) for creating or writing to settings. For example, a local application that has the code
access security permission might not have operating system permission.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Walkthrough: Creating a Registry Key and Changing Its Values
Reference
DeleteSubKey
DeleteSubKey
RegistryKey
Concepts
Security and the Registry
Common Registry Tasks
Visual Basic Language Concepts

Reading from and Writing to the Registry Using My


The My.Computer.Registry object offers methods and properties for working with registry keys.
The Windows registry hosts information from the operating system as well as information from applications hosted on the
computer. Although My.Settings is recommended for storing such information, legacy applications may make use of the
registry.
For a complete list of the My.Computer.Registry members, see My.Computer.Registry Object Members.
Tasks
The following table lists examples of tasks for registry keys involving the My.Computer.Registry object.
To See
Create a registry key How to: Create a Registry Key and Set Its Values in Visual Basic

Delete a registry key How to: Delete a Registry Key in Visual Basic

Determine whether a value exists How to: Determine if a Value Exists in a Registry Key in Visual Basic

Read a value How to: Read a Value from a Registry Key in Visual Basic

Security and the Registry


Working with the registry may compromise security by allowing inappropriate access to system resources or protected
information. To use these properties, you must have read and write permissions from the RegistryPermissionAccess
enumeration, which controls access to registry variables. Any code running with full trust (under the default security policy, this
is any code installed on the user's local hard disk) has the necessary permissions to access the registry. For more information,
see RegistryPermission class.
Registry variables should not be stored in memory locations where code without RegistryPermission can access them.
Similarly, when granting permissions, grant the minimum privileges necessary to get the job done.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Walkthrough: Creating a Registry Key and Changing Its Values
Reference
My.Settings Object
Concepts
Security and the Registry
Visual Basic Language Concepts

Reading from and Writing to the Registry Using the


Microsoft.Win32 Namespace
Although My.Computer.Registry should cover your basic needs when programming against the registry, you can also use
the Registry and RegistryKey classes in the Microsoft.Win32 namespace of the .NET Framework.
Keys in the Registry Class
The Registry class supplies the base registry keys that can be used to access subkeys and their values. The base keys
themselves are read-only. The following table lists and describes the seven keys exposed by the Registry class.
Key Description
ClassesRoot Defines the types of documents and the properties associated with those types.

CurrentConfig Contains hardware configuration information that is not user-specific.

CurrentUser Contains information about the current user preferences, such as environmental variables.

DynData Contains dynamic registry data, such as that used by Virtual Device Drivers.

LocalMachine Contains five subkeys (Hardware, SAM, Security, Software, and System) that hold the configuration data for t
he local computer.

PerformanceData Contains performance information for software components.

Users Contains information about the default user preferences.


Security Note
It is more secure to write data to the current user (CurrentUser) than to the local computer (LocalMachine). A condition that's
typically referred to as "squatting" occurs when the key you are creating was previously created by another, possibly malicio
us, process. To prevent this from occurring, use a method, such as GetValue, that returns Nothing if the key does not already
exist.

Reading a Value from the Registry


The following code shows how to read a string from HKEY_CURRENT_USER.
VB
Dim regVersion As Microsoft.Win32.RegistryKey
Dim keyValue As String
keyValue = "Software\\Microsoft\\TestApp\\1.0"
regVersion = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(keyValue, False)
Dim intVersion As Integer = 0
If (Not regVersion Is Nothing) Then
intVersion = regVersion.GetValue("Version", 0)
regVersion.Close()
End If

The following code reads, increments, and then writes a string to HKEY_CURRENT_USER.
VB
Dim regVersion As Microsoft.Win32.RegistryKey
regVersion = Microsoft.Win32.Registry.CurrentUser.OpenSubKey( _
"SOFTWARE\\Microsoft\\TestApp\\1.0", True)
If regVersion Is Nothing Then
' Key doesn't exist; create it.
regVersion = Microsoft.Win32.Registry.CurrentUser.CreateSubKey( _
"SOFTWARE\\Microsoft\\TestApp\\1.0")
End If
Dim intVersion As Integer = 0
If (Not regVersion Is Nothing) Then
intVersion = regVersion.GetValue("Version", 0)
intVersion = intVersion + 1
regVersion.SetValue("Version", intVersion)
regVersion.Close()
End If

See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
SystemException Class
ApplicationException Class
My.Computer.Registry Object
Concepts
Structured Exception Handling Overview for Visual Basic
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Visual Basic Language Concepts

Walkthrough: Creating a Registry Key and Changing Its Values


This walkthrough demonstrates how to create an application that will browse to registry keys on the computer so users can
create and delete keys, as well as how to read, get, set, and delete values.
To create the main form
1. Select New Project in the File menu and click Windows Application.
2. Add a TextBox named Value to the form. In the Properties window in the lower-right corner, in the (Name) field, type
Value.
3. Add a ListBox named History to the form. In the Properties window in the lower-right corner, in the (Name) field, type
History.
4. Create the additional variable and add it immediately after the class declaration.
VB
Dim tempKey As Microsoft.Win32.RegistryKey

To browse registry keys in a ComboBox


1. Add to your form a ComboBox named selectHive, which will display the registry hives and allow you to select one.
Populate it by adding the following code to the form's load event.
VB
selectHive.Items.Add("ClassesRoot")
selectHive.Items.Add("CurentConfig")
selectHive.Items.Add("CurrentUser")
selectHive.Items.Add("DynData")
selectHive.Items.Add("LocalMachine")
selectHive.Items.Add("PerformanceData")
selectHive.Items.Add("Users")

2. Attach the following code after your class declaration.


VB
Dim registryObject As Microsoft.Win32.RegistryKey = Nothing

3. Add the following code to the selectHive SelectedIndexChanged event.


VB
Select Case selectHive.Text
Case "ClassesRoot"
registryObject = My.Computer.Registry.ClassesRoot
Case "CurrentConfig"
registryObject = My.Computer.Registry.CurrentConfig
Case "CurrentUser"
registryObject = My.Computer.Registry.CurrentUser
Case "DynData"
registryObject = My.Computer.Registry.DynData
Case "LocalMachine"
registryObject = My.Computer.Registry.LocalMachine
Case "PerformanceData"
registryObject = My.Computer.Registry.PerformanceData
Case "Users"
registryObject = My.Computer.Registry.Users
End Select

To read a value in a registry key


1. Add to the form a Button named ReadValueButton with the text "Read Value".
2. Add to the form a TextBox named showSubKey with the text "Enter Subkey".
3. Add the following code to the ReadValueButton Click event.
VB
tempKey = registryObject
If tempKey Is Nothing Then
MsgBox("Please select a registry hive.")
Return
End If
Value.Text = CStr(tempKey.GetValue(ShowSubKey.Text))
History.Items.Add("Read Value " & selectHive.Text & _
"\" & ShowSubKey.Text)

4. Test your application by entering the name of an existing subkey into the showSubKey textbox. When the
ReadValueButton is clicked, the Value text box displays the value.

To set a value in a registry key


1. Add to the form a button named SetValueButton with the text "Set Value".
2. Add the following code to its Click event.
VB
tempKey = registryObject
If tempKey Is Nothing Then
MsgBox("Please select a registry hive.")
Return
End If
If Value.Text Is Nothing Then
MsgBox("Please enter a value.")
Return
End If
tempKey.SetValue(showSubKey.Text, Value.Text)
tempKey.Close()
History.Items.Add("Set Value " & selectHive.Text & _
"\" & showSubKey.Text)

3. Test your application by entering a new value for a subkey in the Value text box and then confirming that the value has
been changed with the button named ReadValueButton.

To create a registry key


1. Add to the form a button named CreateButton with the text "Create Key".
2. Add the following code to its Click event.
VB
registryObject.CreateSubKey(showSubKey.Text)
History.Items.Add("Create Key " & selectHive.Text & _
"\" & showSubKey.Text)

3. Test your application by entering a new key name in the showSubKey text box and using the Registry Editor to confirm
that your key has been created.

To delete a registry key


1. Add a button to the form named DeleteButton with the text "Delete Key".
2. Add the following code to its Click event.
VB
tempKey = registryObject
If tempKey Is Nothing Then
MsgBox("Please select a registry hive.")
Return
End If
If showSubKey.Text Is Nothing Then
MsgBox("Please enter a subkey.")
Return
End If
registryObject.DeleteSubKey(showSubKey.Text)
History.Items.Add("Delete Key " & selectHive.Text & _
"\" & showSubKey.Text)

3. Test your code by deleting a subkey and using the Registry Editor to confirm that the key was deleted.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Reading from and Writing to the Registry Using the Microsoft.Win32 Namespace
Visual Basic Language Concepts

Security and the Registry


This page discusses the security implications of storing data in the registry.
Permissions
It is not secure to store secrets, such as passwords, in the registry as plain text, even if the registry key is protected by ACLs
(access control lists).
Working with the registry may compromise security by allowing inappropriate access to system resources or protected
information. To use these properties, you must have read and write permissions from the RegistryPermissionAccess
enumeration, which controls access to registry variables. Any code running with full trust (under the default security policy, this
is any code installed on the user's local hard disk) has the necessary permissions to access the registry. For more information,
see RegistryPermission class.
Registry variables should not be stored in memory locations where code without RegistryPermission can access them.
Similarly, when granting permissions, grant the minimum privileges necessary to get the job done.
Registry permission access values are defined by the RegistryPermissionAccess enumeration. The following table details its
members.
Value Access to Registry Variables
AllAccess Create, read, and write

Create Create

NoAccess No access

Read Read

Write Write

Checking Values in Registry Keys


When you create a registry value, you need to decide what to do if that value already exists. Another process, perhaps a
malicious one, may have already created the value and have access to it. When you put data in the registry value, the data is
available to the other process. To prevent this, use the GetValue method. It returns Nothing if the key does not already exist.
Security Note
When reading the registry from a Web application, the identity of current user depends on the authentication and impersona
tion implemented in the Web application.

See Also
Tasks
Walkthrough: Creating a Registry Key and Changing Its Values
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
My.Computer.Registry Object Members
Concepts
Common Registry Tasks
Reading from and Writing to the Registry Using My
Visual Basic Language Concepts

Troubleshooting: Manipulating the Registry


In working with the registry, you may encounter specific exceptions. This topic lists the most common exceptions and provides
suggestions on how to address each of them.
Exceptions
The following table lists exceptions that may occur while working with the registry and provides tips on how to address them.
Exception Suggestion
ArgumentException Make sure the key you are performing an operation on exists, and that the path you have suppli
ed is both correct and not over 255 characters.

SecurityException Make sure you have read and write permissions from RegistryPermissionAccess.

UnauthorizedAccessException Make sure the key was opened for writing if attempting to write to it.
See Also
Tasks
Walkthrough: Creating a Registry Key and Changing Its Values
Reference
My.Computer.Registry Object
Concepts
Common Registry Tasks
Reading from and Writing to the Registry Using My
Reading from and Writing to the Registry Using the Microsoft.Win32 Namespace
Security and the Registry
Visual Basic Language Concepts

Accessing Other Processes


This page lists topics that explain how to access other processes using the Process class.
In This Section
How to: Stop an Application (Visual Basic)
How to stop a running application.
How to: List Processes (Visual Basic)
How to get a list of running application processes.
Related Sections
How to: Start an Application and Send it Keystrokes (Visual Basic)
How to start an application.
Shell Function
Runs an executable program, and returns an integer containing the program's process ID if the program is still running.
Visual Basic Language Concepts

How to: Stop an Application (Visual Basic)


This example stops a running application.
Example
VB
Dim pList() As System.Diagnostics.Process = _
System.Diagnostics.Process.GetProcessesByName("notepad")
For Each proc As System.Diagnostics.Process In pList
Dim resp As MsgBoxResult
resp = MsgBox("Terminate " & proc.ProcessName & "?", _
MsgBoxStyle.YesNo, "Terminate?")
If resp = MsgBoxResult.Yes Then
proc.Kill()
End If
Next

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows
Operating System > Processes. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
An Imports statement specifying the System.Diagnostics namespace. For more information, see Imports Statement.
A running instance of the Notepad (Notepad.exe) application.
Security
Because this example abruptly terminates processes, data loss could occur if it is used with some applications.
The Kill method requires full trust (SecurityException class).
See Also
Reference
Process
Other Resources
Accessing Other Processes
Visual Basic Language Concepts

How to: List Processes (Visual Basic)


This example produces a list of running application processes. This information can be used when calling the AppActivate
function.
Example
VB
Dim pList() As System.Diagnostics.Process = _
System.Diagnostics.Process.GetProcesses
For Each proc As System.Diagnostics.Process In pList
MsgBox(proc.ProcessName)
Next

Compiling the Code


This example requires:
An Imports statement specifying the System.Diagnostics namespace. For more information, see Imports Statement.
See Also
Reference
AppActivate Function
Process
Other Resources
Visual Basic Windows Forms Samples
Visual Basic Language Concepts

Updating an Application
The My.Application.Deployment property can be used to check for available updates to the application. If the application
was deployed as a ClickOnce application, the example displays appropriate user interface text.
In This Section
This table shows tasks associated with the My.Application.Deployment property and points to topics showing how to
accomplish each task.
To See
Check for application updates How to: Check for ClickOnce Application Updates

Download application updates How to: Download ClickOnce Application Updates

See Also
Reference
My.Application.Deployment Property
My.Application Object
Visual Basic Language Concepts

How to: Check for ClickOnce Application Updates


This example uses the My.Application.Deployment object to check for available updates to the application. If the application
was deployed as a ClickOnce application, the example displays appropriate user interface (UI) text.
For more information on ClickOnce applications and how to deploy them, see ClickOnce Deployment and
Setting ClickOnce Publishing Properties.
Example
This example uses the My.Application.IsNetworkDeployed Property to make sure that the application is deployed from a
network using ClickOnce. Then it uses the CheckForUpdate method of the My.Application.Deployment object to check if a
ClickOnce update is available for the application.
VB
Sub CheckUpdateAvailability()
If My.Application.IsNetworkDeployed() Then
If My.Application.Deployment.CheckForUpdate() Then
MsgBox("Update is available for download")
Else
MsgBox("No updates are available for download")
End If
Else
MsgBox("Application is not ClickOnce deployed")
End If
End Sub

Only applications that are deployed using ClickOnce can be updated using the My.Application.Deployment object. For more
information on deploying a ClickOnce application, see How to: Publish a ClickOnce Application.
See Also
Tasks
How to: Download ClickOnce Application Updates
Reference
My.Application.Deployment Property
Visual Basic Language Concepts

How to: Download ClickOnce Application Updates


This example uses the My.Application.Deployment object to download and install the latest version of an application. The
example does not update the application unless it is out of date and was deployed as a ClickOnce application.
For more information on ClickOnce applications and how to deploy them, see ClickOnce Deployment and
Setting ClickOnce Publishing Properties.
Example
This example downloads and installs the update after using the My.Application.IsNetworkDeployed Property to make sure that
the application is deployed using ClickOnce. The Update method does not update the application unless it is out of date. The
application has to restart to use the update.
VB
Sub UpdateApplication()
If My.Application.IsNetworkDeployed Then
My.Application.Deployment.Update()
End If
End Sub

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Application—
Compiling, Resources, and Settings. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Only applications that are deployed using ClickOnce can be updated using the My.Application.Deployment object. For more
information on deploying a ClickOnce application, see How to: Publish a ClickOnce Application.
See Also
Tasks
How to: Check for ClickOnce Application Updates
Reference
My.Application.Deployment Property
Visual Basic Language Concepts

Logging Information from the Application


This section contains topics that cover how to log information from your application using the My.Application.Log or
My.Log object, and how to extend the application's logging capabilities.
The Log object provides methods for writing information to the application's log listeners, and the Log object's advanced
TraceSource property provides detailed configuration information. The Log object is configured by the application's
configuration file.
The My.Log object is available only for ASP.NET applications. For client applications, use My.Application.Log. For more
information, see My.Application.Log Object and My.Log Object.
Tasks
To See
Write event information to the application's logs. How to: Write Log Messages

Write exception information to the application's logs How to: Log Exceptions in Visual Basic
.

Write trace information to the application's logs whe How to: Log Messages When the Application Starts or Shuts Down
n the application starts and shuts down.

Configure My.Application.Log to write informatio How to: Write Event Information to a Text File
n to a text file.

Configure My.Application.Log to write informatio How to: Write to an Application Event Log
n to an event log.

Change where My.Application.Log writes informat Walkthrough: Changing Where My.Application.Log Writes Information
ion.

Determine where My.Application.Log writes infor Walkthrough: Determining Where My.Application.Log Writes Information
mation.

Create a custom log listener for My.Application.Lo Walkthrough: Creating Custom Log Listeners
g.

Filter the output of the My.Application.Log logs. Walkthrough: Filtering My.Application.Log Output

See Also
Tasks
Troubleshooting: Log Listeners
Reference
My.Application.Log Object
My.Log Object
Concepts
Working with Application Logs in Visual Basic
Logging and Tracing in the .NET Framework with Visual Basic
Visual Basic Language Concepts

How to: Write Log Messages


You can use the My.Application.Log and My.Log objects to log information about your application. This example shows how
to use the My.Application.Log.WriteEntry method to log tracing information.
For logging exception information, use the My.Application.Log.WriteException method; see
How to: Log Exceptions in Visual Basic.
Example
This example uses the My.Application.Log.WriteEntry method to write out the trace information.
VB
Public Sub TracingTest(ByVal fileName As String)
My.Application.Log.WriteEntry( _
"Entering TracingTest with argument " & _
fileName & ".")
' Code to trace goes here.
My.Application.Log.WriteEntry( _
"Exiting TracingTest with argument " & _
fileName & ".")
End Sub

Security
Make sure the data you write to the log does not include sensitive information such as user passwords. For more information,
see Working with Application Logs in Visual Basic.
See Also
Tasks
How to: Log Exceptions in Visual Basic
Walkthrough: Determining Where My.Application.Log Writes Information
Walkthrough: Changing Where My.Application.Log Writes Information
Walkthrough: Filtering My.Application.Log Output
Reference
My.Application.Log Object
My.Log Object
WriteEntry Method (My.Application.Log and My.Log)
WriteException Method (My.Application.Log and My.Log)
Concepts
Working with Application Logs in Visual Basic
Visual Basic Language Concepts

How to: Log Exceptions in Visual Basic


You can use the My.Application.Log and My.Log objects to log information about exceptions that occur in your application.
These examples show how to use the My.Application.Log.WriteException method to log exceptions that you catch explicitly
and exceptions that are unhandled.
For logging tracing information, use the My.Application.Log.WriteEntry method. For more information, see
WriteEntry Method (My.Application.Log and My.Log).
To log a handled exception
1. Create the method that will generate the exception information.
VB
Public Sub ExceptionLogTest(ByVal fileName As String)
End Sub

2. Use a Try...Catch block to catch the exception.


VB
Try
Catch ex As Exception
End Try

3. Put the code that could generate an exception in the Try block.
Uncomment the Dim and MsgBox lines to cause a NullReferenceException exception.
VB
' Code that might generate an exception goes here.
' For example:
' Dim x As Object
' MsgBox(x.ToString)

4. In the Catch block, use the My.Application.Log.WriteException method to write the exception information.
VB
My.Application.Log.WriteException(ex, _
TraceEventType.Error, _
"Exception in ExceptionLogTest " & _
"with argument " & fileName & ".")

To log an unhandled exception


1. Have a project selected in Solution Explorer. On the Project menu, choose Properties.
2. Click the Application tab.
3. Click the View Application Events button to open the Code Editor.
This opens the ApplicationEvents.vb file.
4. Have the ApplicationEvents.vb file open in the Code Editor. On the General menu, choose MyApplication Events.
5. On the Declarations menu, choose UnhandledException.
The application raises the UnhandledException event before the main application runs.
6. Add the My.Application.Log.WriteException method to the UnhandledException event handler.
VB
My.Application.Log.WriteException(e.Exception, _
TraceEventType.Critical, _
"Application shut down at " & _
My.Computer.Clock.GmtTime.ToString)

Example
This example shows the complete code for logging a handled exception.
VB
Public Sub ExceptionLogTest(ByVal fileName As String)
Try
' Code that might generate an exception goes here.
' For example:
' Dim x As Object
' MsgBox(x.ToString)
Catch ex As Exception
My.Application.Log.WriteException(ex, _
TraceEventType.Error, _
"Exception in ExceptionLogTest " & _
"with argument " & fileName & ".")
End Try
End Sub

The next example shows the complete code for logging an unhandled exception. You can use the Project Designer to access
the application events in the Code Editor. For more information, see How to: Handle Application Events (Visual Basic).
VB
Private Sub MyApplication_UnhandledException( _
ByVal sender As Object, _
ByVal e As ApplicationServices.UnhandledExceptionEventArgs _
) Handles Me.UnhandledException
My.Application.Log.WriteException(e.Exception, _
TraceEventType.Critical, _
"Application shut down at " & _
My.Computer.Clock.GmtTime.ToString)
End Sub

See Also
Tasks
How to: Write Log Messages
Walkthrough: Determining Where My.Application.Log Writes Information
Walkthrough: Changing Where My.Application.Log Writes Information
Reference
My.Application.Log Object
My.Log Object
WriteEntry Method (My.Application.Log and My.Log)
WriteException Method (My.Application.Log and My.Log)
Concepts
Working with Application Logs in Visual Basic
Visual Basic Language Concepts

How to: Log Messages When the Application Starts or Shuts


Down
You can use the My.Application.Log and My.Log objects to log information about events that occur in your application. This
example shows how to use the My.Application.Log.WriteEntry method with the Startup and Shutdown events to write
tracing information.
To access the application's event-handler code
1. Have a project selected in Solution Explorer. On the Project menu, choose Properties.
2. Click the Application tab.
3. Click the View Application Events button to open the Code Editor.
This opens the ApplicationEvents.vb file.
To log messages when the application starts
1. Have the ApplicationEvents.vb file open in the Code Editor. On the General menu, choose MyApplication Events.
2. On the Declarations menu, choose Startup.
The application raises the Startup event before the main application runs.
3. Add the My.Application.Log.WriteEntry method to the Startup event handler.
VB
My.Application.Log.WriteEntry("Application started at " & _
My.Computer.Clock.GmtTime.ToString)

To log messages when the application shuts down


1. Have the ApplicationEvents.vb file open in the Code Editor. On the General menu, choose MyApplication Events.
2. On the Declarations menu, choose Shutdown.
The application raises the Shutdown event after the main application runs, but before it shuts down.
3. Add the My.Application.Log.WriteEntry method to the Shutdown event handler.
VB
My.Application.Log.WriteEntry("Application shut down at " & _
My.Computer.Clock.GmtTime.ToString)

Example
You can use the Project Designer to access the application events in the Code Editor. For more information, see
How to: Handle Application Events (Visual Basic).
VB
Private Sub MyApplication_Startup( _
ByVal sender As Object, _
ByVal e As ApplicationServices.StartupEventArgs _
) Handles Me.Startup
My.Application.Log.WriteEntry("Application started at " & _
My.Computer.Clock.GmtTime.ToString)
End Sub
Private Sub MyApplication_Shutdown( _
ByVal sender As Object, _
ByVal e As System.EventArgs _
) Handles Me.Shutdown
My.Application.Log.WriteEntry("Application shut down at " & _
My.Computer.Clock.GmtTime.ToString)
End Sub

See Also
Tasks
How to: Handle Application Events (Visual Basic)
Reference
My.Log Object
My.Application.Log Object
WriteEntry Method (My.Application.Log and My.Log)
WriteException Method (My.Application.Log and My.Log)
Concepts
Working with Application Logs in Visual Basic
Visual Basic Language Concepts

How to: Write to an Application Event Log


You can use the My.Application.Log and My.Log objects to write information about events that occur in your application.
This example shows how to configure an event log listener so My.Application.Log writes tracing information to the
Application event log.
You cannot write to the Security log. In order to write to the System log, you must be a member of the LocalSystem or
Administrator account.
To view an event log, you can use Server Explorer or Windows Event Viewer. For more information, see
How to: Work with Event Logs in Server Explorer or How to: Launch Event Viewer.
Note
Event logs are not supported on Windows 95, Windows 98, or Windows Millennium Edition.

To add and configure the event log listener


1. Right-click app.config in Solution Explorer and choose Open.
- or -
If there is no app.config file,
a. On the Project menu, choose Add New Item.
b. From the Add New Item dialog box, choose Application Configuration File.
c. Click Add.
2. Locate the <listeners> section in the application configuration file.
You will find the <listeners> section in the <source> section with the name attribute "DefaultSource", which is nested
under the <system.diagnostics> section, which is nested under the top-level <configuration> section.
3. Add this element to that <listeners> section:

<add name="EventLog"/>

4. Locate the <sharedListeners> section, in the <system.diagnostics> section, in the top-level <configuration> section.
5. Add this element to that <sharedListeners> section:

<add name="EventLog"
type="System.Diagnostics.EventLogTraceListener, System, Version=2.0.0.0, Culture=n
eutral, PublicKeyToken=b77a5c561934e089"
initializeData="APPLICATION_NAME"/>

Replace APPLICATION_NAME with the name of your application.


Note
Typically, an application writes only errors to the event log. For information on filtering log output, see
Walkthrough: Filtering My.Application.Log Output.

To write event information to the event log


Use the My.Application.Log.WriteEntry or My.Application.Log.WriteException method to write information to the
event log. For more information, see How to: Write Log Messages and How to: Log Exceptions in Visual Basic.
After you configure the event log listener for an assembly, it receives all messages that My.Applcation.Log writes from
that assembly.
See Also
Tasks
How to: Log Exceptions in Visual Basic
Walkthrough: Determining Where My.Application.Log Writes Information
Reference
My.Application.Log Object
My.Log Object
WriteEntry Method (My.Application.Log and My.Log)
WriteException Method (My.Application.Log and My.Log)
Concepts
Working with Application Logs in Visual Basic
Visual Basic Language Concepts

How to: Write Event Information to a Text File


You can use the My.Application.Log and My.Log objects to log information about events that occur in your application. This
example shows how to use the My.Application.Log.WriteEntry method to log tracing information to a log file.
To add and configure the file log listener
1. Right-click app.config in Solution Explorer and choose Open.
- or -
If there is no app.config file:
a. On the Project menu, choose Add New Item.
b. From the Add New Item dialog box, choose Application Configuration File.
c. Click Add.
2. Locate the <listeners> section in the application configuration file.
You will find the <listeners> section in the <source> section with the name attribute "DefaultSource", which is nested
under the <system.diagnostics> section, which is nested under the top-level <configuration> section.
3. Add this element to that <listeners> section:

<add name="FileLogListener" />

4. Locate the <sharedListeners> section in the <system.diagnostics> section, nested under the top-level
<configuration> section.

5. Add this element to that <sharedListeners> section:

<add name="FileLogListener"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
initializeData="FileLogListenerWriter"
location="Custom"
customlocation="c:\temp\" />

Change the value of the customlocation attribute to the log directory.


Note
To set the value of a listener property, use an attribute that has the same name as the property, with all letters in the na
me lowercase. For example, the location and customlocation attributes set the values of the Location and
CustomLocation properties.

To write event information to the file log


Use the My.Application.Log.WriteEntry or My.Application.Log.WriteException method to write information to the
file log. For more information, see How to: Write Log Messages and How to: Log Exceptions in Visual Basic.
After you configure the file log listener for an assembly, it receives all messages that My.Application.Log writes from
that assembly.
See Also
Tasks
How to: Log Exceptions in Visual Basic
Reference
My.Application.Log Object
My.Log Object
WriteEntry Method (My.Application.Log and My.Log)
WriteException Method (My.Application.Log and My.Log)
Concepts
Working with Application Logs in Visual Basic
Visual Basic Language Concepts

Working with Application Logs in Visual Basic


The My.Applicaton.Log and My.Log objects make it easy to write logging and tracing information to logs.
How Messages are Logged
First, the severity of the message is checked with the Switch property of the log's TraceSource property. By default, only
messages of severity "Information" and higher are passed on to the trace listeners, specified in the log's TraceListener
collection. Then, each listener compares the severity of the message to the listener's Switch property. If the message's severity
is high enough, the listener writes out the message.
The following diagram shows how a message written to the WriteEntry method gets passed to the WriteLine methods of the
log's trace listeners:

You can change the behavior of the log and the trace listeners by changing the application's configuration file. The following
diagram shows the correspondence between the parts of the log and the configuration file.

Where Messages are Logged


If the assembly has no configuration file, the My.Application.Log and My.Log objects write to the application's debug output
(through the DefaultTraceListener class). In addition, the My.Application.Log object writes to the assembly's log file (through
the FileLogTraceListener class), while the My.Log object writes to the ASP.NET Web page's output (through the
WebPageTraceListener class).
The debug output can be viewed in the Visual Studio Output window when running your application in debug mode. To open
the Output window, click the Debug menu item, point to Windows, and then click Output. In the Output window, select
Debug from the Show output from box.
By default, My.Application.Log writes the log file in the path for the user's application data. You can get the path from the
FullLogFileName property of the DefaultFileLogWriter Property (My.Application.Log and My.Log). The format of that path is as
follows:
BasePath\CompanyName\ProductName\ProductVersion
A typical value for BasePath is as follows.
C:\Documents and Settings\username\Application Data
The values of CompanyName, ProductName, and ProductVersion come from the application's assembly information. The form
of the log file name is AssemblyName.log, where AssemblyName is the file name of the assembly without the extension. If
more than one log file is needed, such as when the original log is unavailable when the application attempts to write to the log,
the form for the log file name is AssemblyName-iteration.log, where iteration is a positive Integer.
You can override the default behavior by adding or changing the computer's and the application's configuration files. For more
information, see Walkthrough: Changing Where My.Application.Log Writes Information.
Configuring Log Settings
The Log object has a default implementation that works without an application configuration file, app.config. To change the
defaults, you must add a configuration file with the new settings. For more information, see
Walkthrough: Filtering My.Application.Log Output.
The log configuration sections are located in the <system.diagnostics> node in the main <configuration> node of the
app.config file. Log information is defined in several nodes:
The listeners for the Log object are defined in the <sources> node named DefaultSource.
The severity filter for the Log object is defined in the <switches> node named DefaultSwitch.
The log listeners are defined in the <sharedListeners> node.
Examples of <sources>, <switches>, and <sharedListeners> nodes are shown in the following code:

<configuration>
<system.diagnostics>
<sources>
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
initializeData="FileLogWriter"
/>
</sharedListeners>
</system.diagnostics>
</configuration>

Changing Log Settings after Deployment


When you develop an application, its configuration settings are stored in the app.config file, as shown in the examples above.
After you deploy your application, you can still configure the log by editing the configuration file. In a Windows-based
application, this file's name is applicationName.exe.config, and it must reside in the same folder as the executable file. For a
Web application, this is the Web.config file associated with the project.
When your application executes the code that creates an instance of a class for the first time, it checks the configuration file for
information about the object. For the Log object, this happens the first time the Log object is accessed. The system examines
the configuration file only once for any particular object—the first time your application creates the object. Therefore, you may
need to restart the application for the changes to take effect.
In a deployed application, you enable trace code by reconfiguring switch objects before your application starts. Typically, this
involves turning the switch objects on and off or by changing the tracing levels, and then restarting your application.
Security Considerations
Consider the following when writing data to the log:
Avoid leaking user information. Ensure that your application writes only approved information to the log. For
example, it may be acceptable for the application log to contain user names, but not user passwords.
Make log locations secure. Any log that contains potentially sensitive information should be stored in a secure
location.
Avoid misleading information. In general, your application should validate all data entered by a user before using that
data. This includes writing data to the application log.
Avoid denial of service. If your application writes too much information to the log, it could fill the log or make finding
important information difficult.
See Also
Reference
My.Application.Log Object
My.Log Object
Concepts
Logging Information from the Application
Visual Basic Language Concepts

Walkthrough: Determining Where My.Application.Log Writes


Information
The My.Application.Log object can write information to several log listeners. The log listeners are configured by the
computer's configuration file and can be overridden by an application's configuration file. This topic describes the default
settings and how to determine the settings for your application.
For more information about the default output locations, see Working with Application Logs in Visual Basic.
To determine the listeners for My.Application.Log
1. Locate the assembly's configuration file. If you are developing the assembly, you can access the app.config in Visual
Studio from the Solution Explorer. Otherwise, the configuration file name is the assembly's name appended with
".config", and it is located in the same directory as the assembly.
Note
Not every assembly has a configuration file.

The configuration file is an XML file.


2. Locate the <listeners> section, in the <source> section with the name attribute "DefaultSource", located in the <sources>
section. The <sources> section is located in the <system.diagnostics> section, in the top-level <configuration> section.
If these sections do not exist, then the computer's configuration file may configure the My.Application.Log log listeners.
The following steps describe how to determine what the computer configuration file defines:
a. Locate the computer's machine.config file. Typically, it is located in the
SystemRoot\Microsoft.NET\Framework\frameworkVersion\CONFIG directory, where SystemRoot is the operating
system directory, and frameworkVersion is the version of the .NET Framework.
The settings in machine.config can be overridden by an application's configuration file.
If the optional elements listed below do not exist, you can create them.
b. Locate the <listeners> section, in the <source> section with the name attribute "DefaultSource", in the <sources>
section, in the <system.diagnostics> section, in the top-level <configuration> section.
If these sections do not exist, then the My.Application.Log has only the default log listeners.
3. Locate the <add> elements in the <listeners> section.
These elements add the named log listeners to My.Application.Log source.
4. Locate the <add> elements with the names of the log listeners in the <sharedListeners> section, in the
<system.diagnostics> section, in the top-level <configuration> section.

5. For many types of shared listeners, the listener's initialization data includes a description of where the listener directs the
data:
A Microsoft.VisualBasic.Logging.FileLogTraceListener listener writes to a file log, as described in the introduction.
A System.Diagnostics.EventLogTraceListener listener writes information to the computer event log specified by the
initializeData parameter. To view an event log, you can use Server Explorer or Windows Event Viewer. For
more information, see How to: Work with Event Logs in Server Explorer or How to: Launch Event Viewer.
The System.Diagnostics.DelimitedListTraceListener and System.Diagnostics.XmlWriterTraceListener listeners write
to the file specified in the initializeData parameter.
A System.Diagnostics.ConsoleTraceListener listener writes to the command-line console.
For information about where other types of log listeners write information, consult that type's documentation.
See Also
Tasks
How to: Log Exceptions in Visual Basic
How to: Write Log Messages
Walkthrough: Changing Where My.Application.Log Writes Information
How to: Work with Event Logs in Server Explorer
How to: Launch Event Viewer
Troubleshooting: Log Listeners
Reference
My.Application.Log Object
My.Log Object
DefaultTraceListener
EventLogTraceListener
DelimitedListTraceListener
XmlWriterTraceListener
ConsoleTraceListener
System.Diagnostics
Concepts
Working with Application Logs in Visual Basic
Visual Basic Language Concepts

Walkthrough: Changing Where My.Application.Log Writes


Information
You can use the My.Application.Log and My.Log objects to log information about events that occur in your application. This
walkthrough shows how to override the default settings and cause the Log object to write to other log listeners.
Prerequisites
The Log object can write information to several log listeners. You need to determine the current configuration of the log
listeners before changing the configurations. For more information, see
Walkthrough: Determining Where My.Application.Log Writes Information.
You may want to review How to: Write Event Information to a Text File or How to: Write to an Application Event Log.
To add listeners
1. Right-click app.config in Solution Explorer and choose Open.
- or -
If there is no app.config file:
a. On the Project menu, choose Add New Item.
b. From the Add New Item dialog box, select Application Configuration File.
c. Click Add.
2. Locate the <listeners> section, under the <source> section with the name attribute "DefaultSource", in the <sources>
section. The <sources> section is in the <system.diagnostics> section, in the top-level <configuration> section.
3. Add these elements to that <listeners> section.

<!-- Uncomment to connect the application file log. -->


<!-- <add name="FileLog" /> -->
<!-- Uncomment to connect the event log. -->
<!-- <add name="EventLog" /> -->
<!-- Uncomment to connect the event log. -->
<!-- <add name="Delimited" /> -->
<!-- Uncomment to connect the XML log. -->
<!-- <add name="XmlWriter" /> -->
<!-- Uncomment to connect the console log. -->
<!-- <add name="Console" /> -->

4. Uncomment the log listeners that you want to receive Log messages.
5. Locate the <sharedListeners> section, in the <system.diagnostics> section, in the top-level <configuration> section.
6. Add these elements to that <sharedListeners> section.

<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
Microsoft.VisualBasic, Version=8.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
initializeData="FileLogWriter" />
<add name="EventLog"
type="System.Diagnostics.EventLogTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="sample application"/>
<add name="Delimited"
type="System.Diagnostics.DelimitedListTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="c:\temp\sampleDelimitedFile.txt"
delimiter=";;;"
traceOutputOptions="DateTime" />
<add name="XmlWriter"
type="System.Diagnostics.XmlWriterTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="c:\temp\sampleLogFile.xml" />
<add name="Console"
type="System.Diagnostics.ConsoleTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="true" />

7. The content of the app.config file should be similar to the following XML:

<?xml version="1.0" encoding="utf-8" ?>


<configuration>
<system.diagnostics>
<sources>
<!-- This section configures My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment to connect the application file log. -->
<!-- <add name="FileLog" /> -->
<!-- Uncomment to connect the event log. -->
<!-- <add name="EventLog" /> -->
<!-- Uncomment to connect the event log. -->
<!-- <add name="Delimited" /> -->
<!-- Uncomment to connect the XML log. -->
<!-- <add name="XmlWriter" /> -->
<!-- Uncomment to connect the console log. -->
<!-- <add name="Console" /> -->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
Microsoft.VisualBasic, Version=8.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
initializeData="FileLogWriter" />
<add name="EventLog"
type="System.Diagnostics.EventLogTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="sample application"/>
<add name="Delimited"
type="System.Diagnostics.DelimitedListTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="c:\temp\sampleDelimitedFile.txt"
delimiter=";;;"
traceOutputOptions="DateTime" />
<add name="XmlWriter"
type="System.Diagnostics.XmlWriterTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="c:\temp\sampleLogFile.xml" />
<add name="Console"
type="System.Diagnostics.ConsoleTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="true" />
</sharedListeners>
</system.diagnostics>
</configuration>

To reconfigure a listener
1. Locate the listener's <add> element from the <sharedListeners> section.
2. The type attribute gives the name of the listener type. This type must inherit from the TraceListener class. Use the
strongly named type name to ensure that the right type is used. For more information, see the "To reference a strongly
named type" section below.
Some types that you can use are:
A Microsoft.VisualBasic.Logging.FileLogTraceListener listener, which writes to a file log.
A System.Diagnostics.EventLogTraceListener listener, which writes information to the computer event log specified
by the initializeData parameter.
The System.Diagnostics.DelimitedListTraceListener and System.Diagnostics.XmlWriterTraceListener listeners, which
write to the file specified in the initializeData parameter.
A System.Diagnostics.ConsoleTraceListener listener, which writes to the command-line console.
For information about where other types of log listeners write information, consult that type's documentation.
3. When the application creates the log-listener object, it passes the initializeData attribute as the constructor parameter.
The meaning of the initializeData attribute depends on the trace listener.
4. After creating the log listener, the application sets the listener's properties. These properties are defined by the other
attributes in the <add> element. For more information on the properties for a particular listener, see the documentation
for that listener's type.

To reference a strongly named type


1. To ensure that the right type is used for your log listener, make sure to use the fully qualified type name and the strongly
named assembly name. The syntax of a strongly named type is as follows:
<type name>, <assembly name>, <version number>, <culture>, <strong name>
2. This code example shows how to determine the strongly named type name for a fully qualified type
—"System.Diagnostics.FileLogTraceListener" in this case.
VB
Public Sub DisplayStrongName()
Dim t As Type = GetType(Logging.FileLogTraceListener)
MsgBox(t.FullName & ", " & t.Assembly.FullName)
End Sub
This is the output, and it can be used to uniquely reference a strongly named type, as in the "To add listeners" procedure
above.
Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a

See Also
Tasks
How to: Write Event Information to a Text File
How to: Write to an Application Event Log
Reference
My.Application.Log Object
My.Log Object
TraceListener
Microsoft.VisualBasic.Logging.FileLogTraceListener
System.Diagnostics.EventLogTraceListener
Visual Basic Language Concepts

Walkthrough: Filtering My.Application.Log Output


This walkthrough demonstrates how to change the default log filtering for the My.Application.Log object, to control what
information is passed from the Log object to the listeners and what information is written by the listeners. You can change the
logging behavior even after building the application, because the configuration information is stored in the application's
configuration file.
Getting Started
Each message that My.Application.Log writes has an associated severity level, which filtering mechanisms use to control the
log output. This sample application uses My.Application.Log methods to write several log messages with different severity
levels.
To build the sample application
1. Open a new Visual Basic Windows Application project.
2. Add a button named Button1 to Form1.
3. In the Click event handler for Button1, add the following code:
VB
' Activity tracing information
My.Application.Log.WriteEntry("Entering Button1_Click", TraceEventType.Start)

' Tracing information


My.Application.Log.WriteEntry("In Button1_Click", TraceEventType.Information)

' Create an exception to log.


Dim ex As New ApplicationException
' Exception information
My.Application.Log.WriteException(ex)

' Activity tracing information


My.Application.Log.WriteEntry("Leaving Button1_Click", TraceEventType.Stop)

4. Run the application in the debugger.


5. Press Button1.
The application writes the following information to the application's debug output and log file.
DefaultSource Information: 0 : In Button1_Click

DefaultSource Error: 2 : Error in the application.

6. Close the application.


For information on how to view the application's debug output window, see Output Window. For information on the location
of the application's log file, see Walkthrough: Determining Where My.Application.Log Writes Information.
Note
By default, the application flushes the log-file output when the application closes.

In the example above, the second call to the WriteEntry Method (My.Application.Log and My.Log) and the call to the
WriteException Method (My.Application.Log and My.Log) produces log output, while the first and last calls to the WriteEntry
method do not. This is because the severity levels of WriteEntry and WriteException are "Information" and "Error", both of
which are allowed by the My.Application.Log object's default log filtering. However, events with "Start" and "Stop" severity
levels are prevented from producing log output.
Filtering for All My.Application.Log Listeners
The My.Application.Log object uses a SourceSwitch named DefaultSwitch to control which messages it passes from the
WriteEntry and WriteException methods to the log listeners. You can configure DefaultSwitch in the application's
configuration file by setting its value to one of the SourceLevels enumeration values. By default, its value is "Information".
This table shows the severity level required for Log to write a message to the listeners, given a particular DefaultSwitch
setting.
DefaultSwitch Value Message severity required for output
Critical Critical

Error Critical or Error

Warning Critical, Error, or Warning

Information Critical, Error, Warning, or Information

Verbose Critical, Error, Warning, Information, or Verbose

ActivityTracing Start, Stop, Suspend, Resume, or Transfer

All All messages are allowed.

Off All messages are blocked.


Note
The WriteEntry and WriteException methods each have an overload that does not specify a severity level. The implicit seve
rity level for the WriteEntry overload is "Information", and the implicit severity level for the WriteException overload is "Er
ror".

This table explains the log output shown in the previous example: with the default DefaultSwitch setting of "Information", only
the second call to the WriteEntry method and the call to the WriteException method produce log output.
To log only activity tracing events
1. Right-click app.config in the Solution Explorer and select Open.
-or-
If there is no app.config file:
a. On the Project menu, choose Add New Item.
b. From the Add New Item dialog box, choose Application Configuration File.
c. Click Add.
2. Locate the <switches> section, which is in the <system.diagnostics> section, which is in the top-level <configuration>
section.
3. Find the element that adds DefaultSwitch to the collection of switches. It should look similar to this element:
<add name="DefaultSwitch" value="Information" />

4. Change the value of the value attribute to "ActivityTracing".


5. The content of the app.config file should be similar to the following XML:

<?xml version="1.0" encoding="utf-8" ?>


<configuration>
<system.diagnostics>
<sources>
<!-- This section configures My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="ActivityTracing" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
Microsoft.VisualBasic, Version=8.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a,
processorArchitecture=MSIL"
initializeData="FileLogWriter"/>
</sharedListeners>
</system.diagnostics>
</configuration>

6. Run the application in the debugger.


7. Press Button1.
The application writes the following information to the application's debug output and log file:
DefaultSource Start: 4 : Entering Button1_Click

DefaultSource Stop: 5 : Leaving Button1_Click

8. Close the application.


9. Change the value of the value attribute back to "Information".
Note
The DefaultSwitch switch setting controls only My.Application.Log. It does not change how the .NET
Framework System.Diagnostics.Trace and System.Diagnostics.Debug classes behave.

Individual Filtering For My.Application.Log Listeners


The previous example shows how to change the filtering for all My.Application.Log output. This example demonstrates how
to filter an individual log listener. By default, an application has two listeners that write to the application's debug output and
the log file.
The configuration file controls the behavior of the log listeners by allowing each one to have a filter, which is similar to a switch
for My.Application.Log. A log listener will output a message only if the message's severity is allowed by both the log's
DefaultSwitch and the log listener's filter.

This example demonstrates how to configure filtering for a new debug listener and add it to the Log object. The default debug
listener should be removed from the Log object, so it is clear that the debug messages come from the new debug listener.
To log only activity-tracing events
1. Right-click app.config in the Solution Explorer and choose Open.
-or-
If there is no app.config file:
a. On the Project menu, choose Add New Item.
b. From the Add New Item dialog box, choose Application Configuration File.
c. Click Add.
2. Right-click app.config in Solution Explorer. Choose Open.
3. Locate the <listeners> section, in the <source> section with the name attribute "DefaultSource", which is under the
<sources> section. The <sources> section is under the <system.diagnostics> section, in the top-level <configuration>
section.
4. Add this element to the <listeners> section:

<!-- Remove the default debug listener. -->


<remove name="Default"/>
<!-- Add a filterable debug listener. -->
<add name="NewDefault"/>

5. Locate the <sharedListeners> section, in the <system.diagnostics> section, in the top-level <configuration> section.
6. Add this element to that <sharedListeners> section:

<add name="NewDefault"
type="System.Diagnostics.DefaultTraceListener,
System, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089,
processorArchitecture=MSIL">
<filter type="System.Diagnostics.EventTypeFilter"
initializeData="Error" />
</add>

The EventTypeFilter filter takes one of the SourceLevels enumeration values as its initializeData attribute.
7. The content of the app.config file should be similar to the following XML:

<?xml version="1.0" encoding="utf-8" ?>


<configuration>
<system.diagnostics>
<sources>
<!-- This section configures My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Remove the default debug listener. -->
<remove name="Default"/>
<!-- Add a filterable debug listener. -->
<add name="NewDefault"/>
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
Microsoft.VisualBasic, Version=8.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a,
processorArchitecture=MSIL"
initializeData="FileLogWriter"/>
<add name="NewDefault"
type="System.Diagnostics.DefaultTraceListener,
System, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089,
processorArchitecture=MSIL">
<filter type="System.Diagnostics.EventTypeFilter"
initializeData="Error" />
</add>
</sharedListeners>
</system.diagnostics>
</configuration>

8. Run the application in the debugger.


9. Press Button1.
The application writes the following information to the application's log file:
Default Information: 0 : In Button1_Click

Default Error: 2 : Error in the application.

The application writes less information to the application's debug output because of the more restrictive filtering.
Default Error 2 Error

10. Close the application.


For more information about changing log settings after deployment, see Working with Application Logs in Visual Basic.
See Also
Tasks
Walkthrough: Determining Where My.Application.Log Writes Information
Walkthrough: Changing Where My.Application.Log Writes Information
Walkthrough: Creating Custom Log Listeners
How to: Write Log Messages
Concepts
Trace Switches
Logging Information from the Application
Visual Basic Language Concepts

Walkthrough: Turning Off My.Application.Log Output


This walkthrough demonstrates how to turn off the default log filtering for the My.Application.Log object. You can change
the logging behavior even after building the application, because the configuration information is stored in the application's
configuration file.
Getting Started
The My.Application.Log object passes each message it gets to its log listeners. This sample application uses the
My.Application.Log.WriteEntry methods to write a message to the listeners.
To build the sample application
1. Open a new Visual Basic Windows Application project.
2. Add a button named Button1 to Form1.
3. In the Click event handler for Button1, add the following code:
VB
My.Application.Log.WriteEntry("Log entry")

4. Run the application in the debugger.


5. Press Button1.
The application writes the following information to the application's debug output and log file.
DefaultSource Information: 0 : Log entry

6. Close the application.


For information on how to view the application's debug output window, see Output Window. For information on the location
of the application's log file, see Walkthrough: Determining Where My.Application.Log Writes Information.
Removing Listeners from My.Application.Log
By default, an application has two listeners that write to the application's debug output and the log file. This example
demonstrates how to remove those listeners.
To remove log listeners from the Log object
1. Right-click app.config in Solution Explorer and choose Open.
-or-
If there is no app.config file:
a. On the Project menu, click Add New Item.
b. In the Add New Item box, choose Application Configuration File.
c. Click Add.
2. Locate the <listeners> section in the <source> section with the name attribute "DefaultSource".
These log configuration sections are located in the <system.diagnostics> node in the main <configuration> node of
the configuration file. The XML for the DefaultSource is in the <sources> node.
3. Remove the <add> element with the "FileLog" name attribute. It should look like this element:
<add name="FileLog"/>

4. Add this element to the <listeners> section.


<!-- Remove the default debug listener. -->
<remove name="Default"/>

5. The content of the app.config file should be similar to the following XML:

<?xml version="1.0" encoding="utf-8" ?>


<configuration>
<system.diagnostics>
<sources>
<!-- This section configures My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<!-- Remove the default debug listener. -->
<remove name="Default"/>
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
</system.diagnostics>
</configuration>

6. Run the application in the debugger.


7. Press Button1.
The application writes no information to the application's log file or debug output.
For more information about changing log settings after deployment, see Working with Application Logs in Visual Basic.
See Also
Tasks
Walkthrough: Determining Where My.Application.Log Writes Information
Walkthrough: Changing Where My.Application.Log Writes Information
Walkthrough: Filtering My.Application.Log Output
Walkthrough: Creating Custom Log Listeners
How to: Write Log Messages
Concepts
Logging Information from the Application
Visual Basic Language Concepts

Walkthrough: Creating Custom Log Listeners


This walkthrough demonstrates how to create a custom log listener and configure it to listen to the output of the
My.Application.Log object.
Getting Started
Log listeners must inherit from the TraceListener class.
To create the listener
In your application, create a class named SimpleListener that inherits from TraceListener.
VB
Public Class SimpleListener
Inherits System.Diagnostics.TraceListener

<Security.Permissions.HostProtection(Synchronization:=True)> _
Public Overloads Overrides Sub Write(ByVal message As String)
MsgBox("Write: " & message)
End Sub

<Security.Permissions.HostProtection(Synchronization:=True)> _
Public Overloads Overrides Sub WriteLine(ByVal message As String)
MsgBox("WriteLine: " & message)
End Sub
End Class

The Write and WriteLine methods, required by the base class, call MsgBox to display their input.
The HostProtectionAttribute attribute is applied to the Write and WriteLine methods so that their attributes match the
base class methods. The HostProtectionAttribute attribute allows the host that runs the code to determine that the
code exposes host-protection synchronization.
Note
The HostProtectionAttribute attribute is effective only on unmanaged applications that host the common language r
untime and that implement host protection, such as SQL Server.

To ensure that My.Application.Log uses your log listener, you should strongly name the assembly that contains your log
listener.
The next procedure provides some simple steps for creating a strongly named log-listener assembly. For more information,
see Creating and Using Strong-Named Assemblies.
To strongly name the log-listener assembly
1. Have a project selected in Solution Explorer. On the Project menu, choose Properties. For more information, see
Introduction to the Project Designer.
2. Click the Signing tab.
3. Select the Sign the assembly box.
4. Select <New> from the Choose a strong name key file drop-down list.
The Create Strong Name Key dialog box opens.
5. Provide a name for the key file in the Key file name box.
6. Enter a password in the Enter password and Confirm password boxes.
7. Click OK.
8. Rebuild the application.
Adding the Listener
Now that the assembly has a strong name, you need to determine the strong name of the listener so that My.Application.Log
uses your log listener.
The format of a strongly named type is as follows.
<type name>, <assembly name>, <version number>, <culture>, <strong name>
To determine the strong name of the listener
The following code shows how to determine the strongly named type name for SimpleListener.
VB
Public Sub DisplaySimpleListenerStrongName()
Dim t As Type = GetType(SimpleListener)
MsgBox(t.FullName & ", " & t.Assembly.FullName)
End Sub

The strong name of the type depends on your project.


With the strong name, you can add the listener to the My.Application.Log log-listener collection.
To add the listener to My.Application.Log
1. Right-click on app.config in the Solution Explorer and choose Open.
-or-
If there is an app.config file:
a. On the Project menu, choose Add New Item.
b. From the Add New Item dialog box, choose Application Configuration File.
c. Click Add.
2. Locate the <listeners> section, in the <source> section with the name attribute "DefaultSource", located in the <sources>
section. The <sources> section is located in the <system.diagnostics> section, in the top-level <configuration> section.
3. Add this element to the <listeners> section:

<add name="SimpleLog" />

4. Locate the <sharedListeners> section, in the <system.diagnostics> section, in the top-level <configuration> section.
5. Add this element to that <sharedListeners> section:

<add name="SimpleLog" type="SimpleLogStrongName" />

Change the value of SimpleLogStrongName to be the strong name of the listener.


See Also
Tasks
How to: Log Exceptions in Visual Basic
How to: Write Log Messages
Walkthrough: Changing Where My.Application.Log Writes Information
Reference
My.Application.Log Object
My.Log Object
Concepts
Working with Application Logs in Visual Basic
Visual Basic Language Reference

Troubleshooting: Log Listeners


You can use the My.Application.Log and My.Log objects to log information about events that occur in your application.
To determine which log listeners receive those messages, see
Walkthrough: Determining Where My.Application.Log Writes Information.
The Log object can use log filtering to limit the amount of information that it logs. If the filters are misconfigured, the logs
might contain the wrong information. For more information about filtering, see
Walkthrough: Filtering My.Application.Log Output.
However, if a log is configured incorrectly, you may need more information about its current configuration. You can get to this
information through the log's advanced TraceSource property.
To determine the log listeners for the Log object in code
1. Import the System.Diagnostics namespace at the beginning of the code file. For more information, see
Imports Statement.
VB
Imports System.Diagnostics

2. Create a function that returns a string consisting of information for each of the log's listeners.
VB
Function GetListeners(ByVal listeners As TraceListenerCollection) As String
Dim ret As String = ""
For Each listener As TraceListener In listeners
ret &= listener.Name
Dim listenerType As Type = listener.GetType
If listenerType Is GetType(DefaultTraceListener) Then
Dim tmp As DefaultTraceListener = _
DirectCast(listener, DefaultTraceListener)
ret &= ": Writes to the debug output."
ElseIf listenerType Is GetType(Logging.FileLogTraceListener) Then
Dim tmp As Logging.FileLogTraceListener = _
DirectCast(listener, Logging.FileLogTraceListener)
ret &= ": Log filename: " & tmp.FullLogFileName
ElseIf listenerType Is GetType(EventLogTraceListener) Then
Dim tmp As EventLogTraceListener = _
DirectCast(listener, EventLogTraceListener)
ret &= ": Event log name: " & tmp.EventLog.Log
ElseIf listenerType Is GetType(XmlWriterTraceListener) Then
Dim tmp As Diagnostics.XmlWriterTraceListener = _
DirectCast(listener, XmlWriterTraceListener)
ret &= ": XML log"
ElseIf listenerType Is GetType(ConsoleTraceListener) Then
Dim tmp As ConsoleTraceListener = _
DirectCast(listener, ConsoleTraceListener)
ret &= ": Console log"
ElseIf listenerType Is GetType(DelimitedListTraceListener) Then
Dim tmp As DelimitedListTraceListener = _
DirectCast(listener, DelimitedListTraceListener)
ret &= ": Delimited log"
Else
ret &= ": Unhandeled log type: " & _
listenerType.ToString
End If
ret &= vbCrLf
Next

Return ret
End Function

3. Pass the collection of the log's trace listeners to the GetListeners function, and display the return value.
VB
Dim ListenerCollection As TraceListenerCollection
ListenerCollection = My.Application.Log.TraceSource.Listeners
Dim ListenersText As String = GetListeners(ListenerCollection)
MsgBox(ListenersText)

For more information, see TraceSource Property (My.Application.Log and My.Log).


See Also
Tasks
Walkthrough: Determining Where My.Application.Log Writes Information
Reference
My.Application.Log Object
My.Log Object
Concepts
Working with Application Logs in Visual Basic
Visual Basic Language Concepts

Accessing a Running Application in Visual Basic


This section contains topics that cover how to use the Visual Basic Application model to control the application's run-time
behavior, and topics that cover how to get run-time information about the application.
The My.Application object provides properties, methods, and events related to the current application. It allows you to get
information about the application, such as the current culture, how the application was deployed, and the environment
variables. The Visual Basic Application model exposed by the My.Application object allows an application to run code when
the application starts up and shuts down. Similarly, the My.Application.Deployment property provides the current
application's ClickOnce deployment object.
Tasks
To See
Allow your application to handle other events that might be rais My.Application.DoEvents Method
ed while your code runs

Determine the application's command-line arguments How to: Access Command-Line Arguments (Visual Basic)

Check if the application started with the string "/batch" as an arg How to: Enable a Batch Mode for Window Forms Applications
ument

Handle any uncaught exception in your application My.Application.UnhandledException Event

Use the events provided by the Visual Basic Application model t How to: Run Code When the Application Starts or Ends
o run code when the application starts or ends

Check the command-line arguments of subsequent attempts to My.Application.StartupNextInstance Event


start a single-instance application

Download and install the latest version of a ClickOnce applicatio How to: Download ClickOnce Application Updates
n

See Also
Tasks
How to: Specify Assembly Information
Reference
My.Application Object
My.Application.Log Object
My.Application.Info Object
Concepts
Overview of the Visual Basic Application Model
Logging Information from the Application
Visual Basic Language Concepts

How to: Run Code When the Application Starts or Ends


You use the events provided by the Visual Basic Application model to run code when the application starts or ends. The
Project Designer provides access to the application's event-handler code.
Note
The Visual Basic Application model is available only for Windows Forms applications. For more information, see
Overview of the Visual Basic Application Model.

Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is de
scribed in Help, depending on your active settings or edition. This Help page was written with General Development Settin
gs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To access the application's event-handler code


1. Have a project selected in Solution Explorer. From the Project menu, click Properties.
2. Click the Application tab.
3. Click the View Application Events button to open the Code Editor.
This opens the ApplicationEvents.vb file.
To run code when the application starts
1. Have the ApplicationEvents.vb file open in the Code Editor. From the General menu, choose MyApplication Events.
2. From the Declarations menu, choose Startup.
The application raises the Startup event before the main application runs.
3. If your application is a single-instance application, you may want to handle subsequent starts of the application. To do
this, from the General menu, choose MyApplication Events.
4. From the Declarations menu, choose StartupNextInstance.
A single-instance application raises the StartupNextInstance event in the first instance of the application when a
subsequent instance of the application starts. The subsequent instance then closes without raising any of its own events.
To run code when the application ends
1. Have the ApplicationEvents.vb file open in the Code Editor. From the General menu, choose MyApplication Events.
2. From the Declarations menu, choose Shutdown.
The application raises the Shutdown event after the main application runs, but before it shuts down.
3. From the General menu, choose MyApplication Events.
4. From the Declarations menu, choose UnhandledException.
The application raises the UnhandledException event if it encounters an unhandled exception. Because the application
does not raise the Shutdown event after the UnhandledException event, you may want the UnhandledException
handler to call the same shut-down code that the Shutdown handler calls.
See Also
Tasks
How to: Handle Application Events (Visual Basic)
Concepts
Overview of the Visual Basic Application Model
Visual Basic Language Concepts

How to: Enable a Batch Mode for Window Forms Applications


This example uses the My.Application.Startup event to check if the application started with the string /batch as an
argument.
To enable a batch mode for a Window Forms Application
1. Have a project selected in Solution Explorer. On the Project menu, click Properties.
2. On the Application tab, click View Application Events to open the Code Editor.
3. Create the method that handles the My.Application.Startup Event. For more information, see
How to: Handle Application Events (Visual Basic).
VB
Private Sub MyApplication_Startup( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs _
) Handles Me.Startup

VB
End Sub

4. Iterate through the application's command-line arguments, and set the Cancel property of the e object to True if one of
the arguments is /batch.
When the Cancel property is set to True, the startup form does not start.
VB
For Each s As String In My.Application.CommandLineArgs
If s.ToLower = "/batch" Then
' Stop the start form from loading.
e.Cancel = True
End If
Next

5. If the Cancel property of the e object is set to True, call the main routine for windowless operation.
VB
If e.Cancel Then
' Call the main routine for windowless operation.
Dim c As New BatchApplication
c.Main()
End If

Example
VB
Private Sub MyApplication_Startup( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs _
) Handles Me.Startup
For Each s As String In My.Application.CommandLineArgs
If s.ToLower = "/batch" Then
' Stop the start form from loading.
e.Cancel = True
End If
Next
If e.Cancel Then
' Call the main routine for windowless operation.
Dim c As New BatchApplication
c.Main()
End If
End Sub
Class BatchApplication
Sub Main()
' Insert code to run without a graphical user interface.
End Sub
End Class

See Also
Tasks
How to: Access Command-Line Arguments (Visual Basic)
Reference
My.Application Object
My.Application.CommandLineArgs Property
Concepts
Overview of the Visual Basic Application Model
Visual Basic Language Concepts

How to: Access Command-Line Arguments (Visual Basic)


The following code example loops over the application's command-line arguments.
Example
VB
For Each argument As String In My.Application.CommandLineArgs
' Add code here to use the argument.
Next

See Also
Tasks
How to: Enable a Batch Mode for Window Forms Applications
Reference
My.Application.CommandLineArgs Property
Structure of a Visual Basic Program
Visual Basic Language Concepts

Accessing User Data


This section contains topics dealing with the My.User object and tasks that you can accomplish with it.
The My.User object provides access to information about the logged-on user by returning an object that implements the
IPrincipal interface.
Tasks
To See
Get the user's login name How to: Determine a User's Login Name

Get the user's domain name, if the application uses Wi How to: Determine the User's Domain
ndows authentication

Determine the user's role How to: Determine if a User is in a Group

Implement custom authentication Walkthrough: Implementing Custom Authentication and Authorization

See Also
Reference
My.User Object
Other Resources
Authentication and Authorization in the .NET Framework with Visual Basic
Visual Basic Language Concepts

How to: Determine a User's Login Name


You can use the My.User object to get information about the current user. This example shows how to use the My.User.Name
property to get the user's login name.
An application uses Windows authentication by default, so the My.User returns the Windows information about the user who
started the application.
Example
This example checks if the application uses Windows or custom authentication, and then uses that information to parse the
My.User.Name property.
VB
Function GetUserName() As String
If TypeOf My.User.CurrentPrincipal Is _
Security.Principal.WindowsPrincipal Then
' The application is using Windows authentication.
' The name format is DOMAIN\USERNAME.
Dim parts() As String = Split(My.User.Name, "\")
Dim username As String = parts(1)
Return username
Else
' The application is using custom authentication.
Return My.User.Name
End If
End Function

See Also
Tasks
How to: Determine the User's Domain
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User.Name Property
Concepts
Accessing User Data
Visual Basic Language Concepts

How to: Determine if a User is in a Group


You can use the My.User object to get information about the current user. This example shows how to use the
My.User.IsInRole method to determine if the user is a member of a particular group.
Example
This example uses the My.User.IsInRole method to determine if the user is an administrator before accessing a resource.
VB
If My.User.IsInRole( _
ApplicationServices.BuiltInRole.Administrator) Then
' Insert code to access a resource here.
End If

See Also
Tasks
How to: Determine the User's Domain
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User.IsInRole Method
Concepts
Accessing User Data
Visual Basic Language Concepts

How to: Determine the User's Domain


You can use the My.User object to get information about the current user. This example shows how to use the My.User.Name
property to get the user's domain name if the application uses Windows authentication.
Because the application uses Windows authentication by default, My.User returns the Windows information about the user
who started the application.
Example
This example checks if the application uses Windows authentication before parsing the My.User.Name property to determine
the domain name.
This example returns an empty string if the application uses custom authentication, because an implementation of custom
authentication does not necessarily provide domain information.
VB
Function GetUserDomain() As String
If TypeOf My.User.CurrentPrincipal Is _
Security.Principal.WindowsPrincipal Then
' My.User is using Windows authentication.
' The name format is DOMAIN\USERNAME.
Dim parts() As String = Split(My.User.Name, "\")
Dim domain As String = parts(0)
Return domain
Else
' My.User is using custom authentication.
Return ""
End If
End Function

See Also
Tasks
How to: Determine a User's Login Name
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User.Name Property
Concepts
Accessing User Data
Visual Basic Language Concepts

Accessing Application Forms


The My.Forms object provides an easy way to access an instance of each Windows Form declared in the application's project.
You can also use properties of the My.Application object to access the application's splash screen and main form, and get a
list of the application's open forms.
Tasks
The following table lists examples showing how to access an application's forms.
To See
Access one form from another form in an application. How to: Communicate Between Forms in an Application

Display the titles of all the application's open forms. How to: Access All Open Forms of an Application

Update the splash screen with status information as the application st My.Application.SplashScreen Property
arts.

See Also
Reference
My.Forms Object
My.Application.OpenForms Property
My.Application.SplashScreen Property
Visual Basic Language Concepts

How to: Communicate Between Forms in an Application


This example shows how to use the My.Forms object to access one form from another form.
The My.Forms object provides access to an instance of each form in a Windows application that is declared in the application's
project. This allows code in one form to communicate with another form.
To create code in one form that can communicate with another form
1. Create a new Windows Application.
The default name of the main form is Form1.
For more information, see How to: Create a Windows Application Project.
2. Add another form named Form2.
For more information, see How to: Add Windows Forms to a Project.
3. Add a button named Button1 to Form1 in Application Designer.
4. Double-click Button1.
5. In the event handler for the Click event of Button1, add the following code:
VB
My.Forms.Form2.Text = Now.ToString
My.Forms.Form2.Show()

6. Run the application.


7. Click Button1.
Form2 opens, and its title shows the current time.
8. Wait a few seconds and click Button1 again.
Form2 remains open and its title updates to the current time.

See Also
Tasks
How to: Access All Open Forms of an Application
Reference
My.Forms Object
Concepts
Accessing Application Forms
Visual Basic Language Concepts

How to: Access All Open Forms of an Application


This example uses the My.Application.OpenForms property to display the titles of all the application's open forms.
The My.Application.OpenForms property returns all currently open forms, regardless of which thread opened them. This
means that you should check the InvokeRequired property of each form before accessing it; otherwise it might throw an
InvalidOperationException exception.
This example declares a function that obtains each form's title in a thread-safe manner. First, it checks the form's
InvokeRequired property and, if necessary, uses the BeginInvoke method to execute the function on the form's thread. Then
the function returns the form's title.
Example
This example loops over the application's open forms and displays their titles in a ListBox control. For simpler code that
displays only the forms directly accessible from the current thread, see My.Application.OpenForms Property.
VB
Private Sub GetOpenFormTitles()
Dim formTitles As New Collection

Try
For Each f As Form In My.Application.OpenForms
' Use a thread-safe method to get all form titles.
formTitles.Add(GetFormTitle(f))
Next
Catch ex As Exception
formTitles.Add("Error: " & ex.Message)
End Try

Form1.ListBox1.DataSource = formTitles
End Sub

Private Delegate Function GetFormTitleDelegate(ByVal f As Form) As String


Private Function GetFormTitle(ByVal f As Form) As String
' Check if the form can be accessed from the current thread.
If Not f.InvokeRequired Then
' Access the form directly.
Return f.Text
Else
' Marshal to the thread that owns the form.
Dim del As GetFormTitleDelegate = AddressOf GetFormTitle
Dim param As Object() = {f}
Dim result As System.IAsyncResult = f.BeginInvoke(del, param)
' Give the form's thread a chance process function.
System.Threading.Thread.Sleep(10)
' Check the result.
If result.IsCompleted Then
' Get the function's return value.
Return "Different thread: " & f.EndInvoke(result).ToString
Else
Return "Unresponsive thread"
End If
End If
End Function

See Also
Tasks
How to: Make Thread-Safe Calls to Windows Forms Controls
Reference
My.Application.OpenForms Property
Visual Basic Language Concepts

Accessing Application Web Services


The My.WebServices object provides an instance of each Web service referenced by the current project. Each instance is
instantiated on demand. You can access these Web services through the properties of the My.WebServices object. The name
of the property is the same as the name of the Web service that the property accesses. Any class that inherits from
SoapHttpClientProtocol is a Web service. For information about adding Web services to a project, see
How to: Access an XML Web Service in Managed Code.
Tasks
The following table lists possible ways to access Web services referenced by an application.
To See
Call a Web service My.WebServices Object

Call a Web service asynchronously and handle an event when it completes How to: Call a Web Service Asynchronously

See Also
Reference
My.WebServices Object
Visual Basic Language Concepts

How to: Call a Web Service Asynchronously


This example attaches a handler to an XML Web service's asynchronous handler event, so that it can retrieve the result of an
asynchronous method call. This example used the DemoTemperatureService Web service at http://www.xmethods.net.
When you reference a Web service in your project in the Visual Studio Integrated Development Environment (IDE), it is added
to the My.WebServices object, and the IDE generates a client proxy class to access a specified Web service
The proxy class allows you to call the Web service methods synchronously, where your application waits for the function to
complete. In addition, the proxy creates additional members to help call the method asynchronously. For each Web service
function, NameOfWebServiceFunction, the proxy creates a NameOfWebServiceFunctionAsync subroutine, a
NameOfWebServiceFunctionCompleted event, and a NameOfWebServiceFunctionCompletedEventArgs class. This example
demonstrates how to use the asynchronous members to access the getTemp function of the DemoTemperatureService Web
service.
Note
This code does not work in Web applications, because ASP.NET does not support the My.WebServices object.

To call a Web service asynchronously


1. Reference the DemoTemperatureService Web service at http://www.xmethods.net. The address is

http://www.xmethods.net/sd/2001/DemoTemperatureService.wsdl

For more information, see How to: Access an XML Web Service in Managed Code.
2. Add an event handler for the getTempCompleted event:

Private Sub getTempCompletedHandler(ByVal sender As Object, _


ByVal e As net.xmethods.www.getTempCompletedEventArgs)

MsgBox("Temperature: " & e.Result)


End Sub

Note
You cannot use the Handles statement to associate an event handler with the My.WebServices object's events.

3. Add a field to track if the event handler has been added to the getTempCompleted event:

Private handlerAttached As Boolean = False

4. Add a method to add the event handler to the getTempCompleted event, if necessary, and to call the getTempAsynch
method:

Sub CallGetTempAsync(ByVal zipCode As Integer)


If Not handlerAttached Then
AddHandler _
My.WebServices.TemperatureService.getTempCompleted, _
AddressOf Me.TS_getTempCompleted
handlerAttached = True
End If
My.WebServices.TemperatureService.getTempAsync(zipCode)
End Sub
To call the getTemp Web method asynchronously, call the CallGetTempAsync method. When the Web method finishes, its
return value is passed to the getTempCompletedHandler event handler.

See Also
Tasks
How to: Access an XML Web Service in Managed Code
Reference
My.WebServices Object
Concepts
Accessing Application Web Services
Visual Basic Language Concepts

Accessing Application Resources


This section contains Help pages dealing with the My.Resources object and tasks that you can accomplish using the
My.Resources object.
The properties of the My.Resources object provide read-only access to your application's resources.
Tasks
The following table lists examples showing how to access an application's resources.
To See
Retrieve an audio resource How to: Retrieve Audio Resources in Visual Basic

Retrieve an icon resource How to: Retrieve Icon Resources in Visual Basic

Retrieve an image resource How to: Retrieve Image Resources in Visual Basic

Retrieve a string resource How to: Retrieve String Resources in Visual Basic

Retrieve a localized resource How to: Retrieve Localized Resources in Visual Basic

See Also
Reference
My.Resources Object
Other Resources
Managing Application Resources
Visual Basic Language Concepts

How to: Retrieve Audio Resources in Visual Basic


You can retrieve the audio resources of an application by accessing the resource's property on the My.Resources object.
The My.Resources object exposes each resource as a read-only property. The property name is the same as the resource
name, and the property type is determined by the resource classification. For more information, see My.Resources Object.
Example
This example uses the My.Computer.Audio.Play method to play the sound stored as an audio resource named
Form1Greeting in the application's resource file.

VB
Sub PlayFormGreeting()
My.Computer.Audio.Play(My.Resources.Form1Greeting, _
AudioPlayMode.Background)
End Sub

For this example to work, your application must have an audio resource named Form1Greeting in the application's resource
file. For more information, see How to: Add or Remove Resources.
The My.Computer.Audio.Play method is available only for Windows Forms applications. For more information, see
My.Computer.Audio.Play Method.
See Also
Tasks
How to: Retrieve String Resources in Visual Basic
How to: Retrieve Image Resources in Visual Basic
How to: Retrieve Icon Resources in Visual Basic
How to: Retrieve Localized Resources in Visual Basic
Reference
My.Resources Object
My.Computer.Audio.Play Method
Other Resources
Managing Application Resources
Visual Basic Language Concepts

How to: Retrieve Icon Resources in Visual Basic


You can retrieve the icon resources of an application by accessing the resource's property on the My.Resources object.
The My.Resources object exposes each resource as a read-only property. The property name is the same as the resource
name, and the property type is determined by the resource classification. For more information, see My.Resources Object.
Example
This example sets the form's icon to the icon named Form1Icon in the stored application's resource file.
VB
Sub SetFormIcon()
Me.Icon = My.Resources.Form1Icon
End Sub

For this example to work, your application must have an icon named Form1Icon in the application's resource file. For more
information, see How to: Add or Remove Resources.
See Also
Tasks
How to: Retrieve String Resources in Visual Basic
How to: Retrieve Image Resources in Visual Basic
How to: Retrieve Audio Resources in Visual Basic
How to: Retrieve Localized Resources in Visual Basic
Reference
My.Resources Object
Other Resources
Managing Application Resources
Visual Basic Language Concepts

How to: Retrieve Image Resources in Visual Basic


You can retrieve the image resources of an application by accessing the resource's property on the My.Resources object.
The My.Resources object exposes each resource as a read-only property. The property name is the same as the resource
name, and the property type is determined by the resource classification. For more information, see My.Resources Object.
Example
This example sets the background image of the form to the image resource named Form1Background, which is in the
application resource file.
VB
Sub SetFormBackgroundImage()
Me.BackgroundImage = My.Resources.Form1Background
End Sub

For this example to work, your application must have an image resource named Form1Background in the application's resource
file. For more information, see How to: Add or Remove Resources.
See Also
Tasks
How to: Retrieve String Resources in Visual Basic
How to: Retrieve Icon Resources in Visual Basic
How to: Retrieve Audio Resources in Visual Basic
How to: Retrieve Localized Resources in Visual Basic
Reference
My.Resources Object
Other Resources
Managing Application Resources
Visual Basic Language Concepts

How to: Retrieve String Resources in Visual Basic


You can retrieve the string resources of an application by accessing the resource's property on the My.Resources object.
The My.Resources object exposes each resource as a read-only property. The property name is the same as the resource
name, and the property type is determined by the resource classification. For more information, see My.Resources Object.
Example
This example sets the title of the form to the string resource named Form1Title from the application resource file.
VB
Sub SetFormTitle()
Me.Text = My.Resources.Form1Title
End Sub

For this example to work, your application must have a string named Form1Title in the application's resource file. For more
information, see How to: Add or Remove Resources.
See Also
Tasks
How to: Retrieve Image Resources in Visual Basic
How to: Retrieve Icon Resources in Visual Basic
How to: Retrieve Audio Resources in Visual Basic
How to: Retrieve Localized Resources in Visual Basic
Reference
My.Resources Object
Other Resources
Managing Application Resources
Visual Basic Language Concepts

How to: Retrieve Localized Resources in Visual Basic


The My.Resources object provides the localized application resources (if available) based on the culture settings of the
computer on which the application runs. You can override the computer's culture settings by setting the
My.Application.UICulture Property.
The runtime identifies a localized resource by its culture signature, or name. The project's default resource file, Resources.resx,
determines the properties that the My.Resources object displays. To provide localized resources, you need to:
Copy and rename the resource file to Resources.CultureSignature.resx
Localize the strings and any files referenced by the resource file
Add the localized resource file to your project
The My.Resources object exposes each resource as a read-only property. The property name is the same as the resource
name, and the property type is determined by the resource classification. For more information, see My.Resources Object and
Resources in Applications.
Each culture has a unique name, which is a combination of a two-letter lowercase culture name associated with a language
and, if required, a two-letter uppercase subculture name associated with a country or region. The subculture name follows the
culture name, separated by a dash (-). Examples include ja-JP for Japanese in Japan, en-US for US English, or de-DE for German
in Germany (as opposed to an alternate, such as de-AT for German in Austria). For more information about culture names, see
CultureInfo.
Example
This example retrieves the French-culture version of the application's string resource named Message.
To change the culture that the My.Resources object uses, this example uses the My.Application.ChangeUICulture Method.
VB
Sub ShowLocalizedMessage()
Dim culture As String = My.Application.UICulture.Name
My.Application.ChangeUICulture("fr-FR")
MsgBox(My.Resources.Message)
My.Application.ChangeUICulture(culture)
End Sub

For this example to work, your application must have a string named Message in the application's resource file, and the
application should have the French-culture version of that resource file, Resources.fr-FR.resx. For more information, see
How to: Add or Remove Resources.
If the application does not have the French-culture version of that resource file, the My.Resource object retrieves the resource
from the default-culture resource file.
See Also
Tasks
How to: Retrieve String Resources in Visual Basic
Reference
My.Resources Object
Other Resources
Managing Application Resources
Visual Basic Language Concepts

Accessing Application Settings


This section contains topics describing the My.Settings object and the tasks it enables you to accomplish.
My.Settings
The properties of the My.Settings object provide access to your application's settings. To add or remove settings, use the
Project Designer. For more information, see How to: Add or Remove Application Settings.
The methods of the My.Settings object allow you to save the current user settings or revert the user settings to the last saved
values.
Tasks
The following table lists examples showing how to access an application's forms.
To See
Update the value of a user setting How to: Change User Settings in Visual Basic

Display application and user settings in a property grid How to: Create Property Grids for User Settings in Visual Basic

Save updated user setting values How to: Persist User Settings in Visual Basic

Determine the values of user settings How to: Read Application Settings in Visual Basic

See Also
Reference
My.Settings Object
Other Resources
Managing Application Settings
Visual Basic Language Concepts

How to: Create Property Grids for User Settings in Visual Basic
You can create a property grid for user settings by populating a PropertyGrid control with the user setting properties of the
My.Settings object.
Note
In order for this example to work, your application must have its user settings configured. For information on adding user set
tings, see How to: Add or Remove Application Settings.

The My.Settings object exposes each setting as a property. The property name is the same as the setting name, and the
property type is the same as the setting type. The setting's Scope determines if the property is read-only; the property for an
Application-scope setting is read-only, while the property for a User-scope setting is read-write. For more information, see
My.Settings Object.
Note
You cannot change or save the values of application-scope settings at run time. Application-scope settings can be changed o
nly when creating the application (through the Project Designer) or by editing the application's configuration file. For more
information, see Managing Application Settings.

This example uses a PropertyGrid control to access the user-setting properties of the My.Settings object. By default, the
PropertyGrid shows all the properties of the My.Settings object. However, the user-setting properties have the
UserScopedSettingAttribute attribute. This example sets the BrowsableAttributes property of the PropertyGrid to
UserScopedSettingAttribute to display only the user-setting properties.
To add a user setting property grid
1. Add the PropertyGrid control from the Toolbox to the design surface for your application, assumed here to be Form1.

The default name of the property-grid control is PropertyGrid1.


2. Double-click the design surface for Form1 to open the code for the form-load event handler.
3. Set the My.Settings object as the selected object for the property grid.
VB
PropertyGrid1.SelectedObject = My.Settings

4. Configure the property grid to show only the user settings.


VB
' Attribute for the user-scope settings.
Dim userAttr As New System.Configuration.UserScopedSettingAttribute
Dim attrs As New System.ComponentModel.AttributeCollection(userAttr)
PropertyGrid1.BrowsableAttributes = attrs

Note
To show only the application-scope settings, use the ApplicationScopedSettingAttribute attribute instead of UserScope
dSettingAttribute.

Robust Programming
The application saves the user settings when the application shuts down. To save the settings immediately, call the
My.Settings.Save method. For more information, see How to: Persist User Settings in Visual Basic.
See Also
Tasks
How to: Read Application Settings in Visual Basic
How to: Change User Settings in Visual Basic
How to: Persist User Settings in Visual Basic
How to: Add or Remove Application Settings
Reference
My.Settings Object
Other Resources
Managing Application Settings
Visual Basic Language Concepts

How to: Persist User Settings in Visual Basic


You can use the My.Settings.Save method to persist changes to the user settings.
Typically, applications are designed to persist the changes to the user settings when the application shuts down. This is because
saving the settings can take, depending on several factors, several seconds.
For more information, see My.Settings Object.
Note
Although you can change and save the values of user-scope settings at run time, application-scope settings are read-only an
d cannot be changed programmatically. You can change application-scope settings when creating the application, through th
e Project Designer, or by editing the application's configuration file. For more information, see
Managing Application Settings.

Example
This example changes the value of the LastChanged user setting and saves that change by calling the My.Settings.Save
method.
VB
Sub ChangeAndPersistSettings()
My.Settings.LastChanged = Today
My.Settings.Save()
End Sub

For this example to work, your application must have a LastChanged user setting, of type Date. For more information, see
How to: Add or Remove Application Settings.
See Also
Tasks
How to: Read Application Settings in Visual Basic
How to: Change User Settings in Visual Basic
How to: Create Property Grids for User Settings in Visual Basic
How to: Add or Remove Application Settings
Reference
My.Settings Object
Other Resources
Managing Application Settings
Visual Basic Language Concepts

How to: Change User Settings in Visual Basic


You can change a user setting by assigning a new value to the setting's property on the My.Settings object.
The My.Settings object exposes each setting as a property. The property name is the same as the setting name, and the
property type is the same as the setting type. The setting's Scope determines if the property is read-only: The property for an
Application-scope setting is read-only, while the property for a User-scope setting is read-write. For more information, see
My.Settings Object.
Note
Although you can change and save the values of user-scope settings at run time, application-scope settings are read-only an
d cannot be changed programmatically. You can change application-scope settings when creating the application, through th
e Project Designer, or by editing the application's configuration file. For more information, see
Managing Application Settings.

Example
This example changes the value of the Nickname user setting.
VB
Sub ChangeNickname(ByVal newNickname As String)
My.Settings.Nickname = newNickname
End Sub

For this example to work, your application must have a Nickname user setting, of type String. For more information, see
How to: Add or Remove Application Settings.
The application saves the user settings when the application shuts down. To save the settings immediately, call the
My.Settings.Save method. For more information, see How to: Persist User Settings in Visual Basic.
See Also
Tasks
How to: Read Application Settings in Visual Basic
How to: Persist User Settings in Visual Basic
How to: Create Property Grids for User Settings in Visual Basic
How to: Add or Remove Application Settings
Reference
My.Settings Object
Other Resources
Managing Application Settings
Visual Basic Language Concepts

How to: Read Application Settings in Visual Basic


You can read a user setting by accessing the setting's property on the My.Settings object.
The My.Settings object exposes each setting as a property. The property name is the same as the setting name, and the
property type is the same as the setting type. The setting's Scope indicates if the property is read-only; the property for an
Application scope setting is read-only, while the property for a User scope setting is read-write. For more information, see
My.Settings Object.
Example
This example displays the value of the Nickname setting.
VB
Sub ShowNickname()
MsgBox("Nickname is " & My.Settings.Nickname)
End Sub

For this example to work, your application must have a Nickname setting, of type String. For more information, see
How to: Add or Remove Application Settings.
See Also
Tasks
How to: Change User Settings in Visual Basic
How to: Persist User Settings in Visual Basic
How to: Create Property Grids for User Settings in Visual Basic
How to: Add or Remove Application Settings
Reference
My.Settings Object
Other Resources
Managing Application Settings
Visual Basic Language Concepts

Processing Drives, Directories, and Files


You can use Visual Basic to process drives, folders, and files with the My.Computer.FileSystem object, which provides better
performance and is easier to use than traditional methods such as the FileOpen and Write functions (although they are still
available). The following sections discuss these methods in detail.
In This Section
File Access with Visual Basic
Discusses how to use the My.Computer.FileSystem object to work with files, drives, and folders.
Walkthrough: Manipulating Files Using .NET Framework Methods
Demonstrates how to use the .NET Framework to manipulate files and folders.
Walkthrough: Manipulating Files and Directories in Visual Basic
Demonstrates how to use the My.Computer.FileSystem object to manipulate files and folders.
Related Sections
Program Structure and Code Conventions
Provides guidelines for the physical structure and appearance of programs.
My.Computer.FileSystem Object
Reference documentation for the My.Computer.FileSystem object and its members.
File I/O in the .NET Framework with Visual Basic
Provides an overview of file I/O with the .NET Framework.
Visual Basic Language Concepts

File Access with Visual Basic


The My.Computer.FileSystem object provides tools for working with files and folders. Its properties, methods, and events
allow you to create, copy, move, investigate, and delete files and folders. My.Computer.FileSystem provides better
performance than the legacy functions (FileOpen, FileClose, Input, InputString, LineInput, etc.) that are provided by Visual
Basic for backward compatibility.
In This Section
Reading from Files in Visual Basic
Lists topics dealing with using the My.Computer.FileSystem object to read from files
Writing to Files in Visual Basic
Lists topics dealing with using the My.Computer.FileSystem object to write to files
Creating, Deleting, and Moving Files and Directories in Visual Basic
Lists topics dealing with using the My.Computer.FileSystem object to creating, copying, deleting and moving files and
folders.
File, Directory, and Drive Properties in Visual Basic
Lists topics dealing with using the My.Computer.FileSystem object to determine file, folder, and drive properties.
Parsing Text Files with the TextFieldParser Object
Discusses how to use the TextFieldReader to parse text files such as logs.
File Encodings
Describes file encodings and their use.
Walkthrough: Manipulating Files and Directories in Visual Basic
Demonstrates how to create a utility that reports information about files and folders.
Troubleshooting: Reading from and Writing to Text Files
Lists common problems encountered when reading and writing to text files, and suggests remedies for each.
Visual Basic Language Concepts

Reading from Files in Visual Basic


This section lists tasks associated with reading from files.
In This Section
How to: Read From Text Files in Visual Basic
Demonstrates how to read from a text file.
How to: Read From Comma-Delimited Text Files in Visual Basic
Demonstrates how to read from a delimited text file.
How to: Read From Fixed-width Text Files in Visual Basic
Demonstrates how to read from a fixed-width text file.
How to: Read From Text Files with Multiple Formats in Visual Basic
Demonstrates how to read from a text file with multiple formats.
How to: Read From Binary Files in Visual Basic
Demonstrates how to read from a binary file.
How to: Read From Existing Text Files in My Documents (Visual Basic)
Demonstrates how to read from a text file in the My Documents directory.
How to: Read Text from Files with a StreamReader (Visual Basic)
Demonstrates how to use a StreamReader to read from a file.
Reference
My.Computer.FileSystem Object
Describes the My.Computer.FileSystem object and its members.
My.Computer.FileSystem.ReadAllText Method
Describes the ReadAllText method.
My.Computer.FileSystem.ReadAllBytes Method
Describes the ReadAllBytes method.
My.Computer.FileSystem.OpenTextFieldParser Method
Describes the OpenTextFieldParser method.
My.Computer.FileSystem.OpenTextFileReader Method
Describes the OpenTextFileReader method.
Related Sections
How to: Read from the Clipboard in Visual Basic
Demonstrates how to read data from the Clipboard.
Parsing Text Files with the TextFieldParser Object
Provides an overview of reading text files with the TextFieldParser object.
Walkthrough: Manipulating Files and Directories in Visual Basic
Demonstrates how to use the My feature with files and directories.
Walkthrough: Manipulating Files Using .NET Framework Methods
Demonstrates how to use .NET Framework methods with files and directories.
Visual Basic Language Concepts

How to: Read From Text Files in Visual Basic


The ReadAllText method of the My.Computer.FileSystem object allows you to read from a text file. The file encoding can be
specified if the contents of the file use an encoding such as ASCII or UTF-8.
If you are reading from a file with extended characters, you will need to specify the file encoding.
To read from a text file
Use the ReadAllText method of the My.Computer.FileSystem object to read the contents of a text file into a string,
supplying the path. The following example reads the contents of test.txt into a string and then displays it in a message
box.
VB
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt")
MsgBox(fileReader)

To read from a text file that is encoded


Use the ReadAllText method of the My.Computer.FileSytem object to read the contents of a text file into a string,
supplying the path and file encoding type. The following example reads the contents of the UTF32 file test.txt into a string
and then displays it in a message box.
VB
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt", _
System.Text.Encoding.UTF32)
MsgBox(fileReader)

Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The file does not exist (FileNotFoundException).
The file is in use by another process or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
There is not enough memory to write the string to buffer (OutOfMemoryException).
The user lacks necessary permissions to view the path (SecurityException).
Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a
Visual Basic source file.
Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to
read from the file may fail.
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.ReadAllText Method
Concepts
File Encodings
Other Resources
Reading from Files in Visual Basic
Visual Basic Language Concepts

How to: Read From Comma-Delimited Text Files in Visual Basic


The TextFieldParser object provides a way to easily and efficiently parse structured text files, such as logs. The TextFieldType
property defines whether it is a delimited file or one with fixed-width fields of text.
To parse a comma delimited text file
1. Create a new TextFieldParser. The following code creates the TextFieldParser named MyReader and opens the file
test.txt.

VB
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser _
("C:\TestFolder\test.txt")

2. Define the TextField type and delimiter. The following code defines the TextFieldType property as Delimited and the
delimiter as ",".
VB
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")

3. Loop through the fields in the file. If any lines are corrupt, report an error and continue parsing. The following code loops
through the file, displaying each field in turn and reporting any fields that are formatted incorrectly.
VB

Dim currentRow As String()


While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As _
Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try

4. Close the While and Using blocks with End While and End Using.
VB
End While
End Using

Example
This example reads from the file test.txt.
VB
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
End Using

Robust Programming
The following conditions may cause an exception:
A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line
causing the exception, while the TextFieldParser.ErrorLine Property is assigned the text contained in the line.
The specified file does not exist (FileNotFoundException).
A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).
The path is too long (PathTooLongException).
The user does not have sufficient permissions to access the file (UnauthorizedAccessException).
See Also
Tasks
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Walkthrough: Manipulating Files and Directories in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
TextFieldParser Object
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Concepts

How to: Read From Fixed-width Text Files in Visual Basic


The TextFieldParser object provides a way to easily and efficiently parse structured text files, such as logs.
The TextFieldType property defines whether it is a delimited file or one with fixed-width fields of text. To specify a field of
variable width in a fixed-width file, define the field width as -1.
To parse a fixed-width text file
1. Create a new TextFieldParser. The following code creates the TextFieldParser named Reader and opens the file
test.log.

VB
Using Reader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser _
("C:\TestFolder\test.log")

2. Define the TextFieldType property as FixedWidth, defining the width and format. The following code defines the
columns of text; the first is 5 characters wide, the second 10, the third 11, and the fourth is of variable width.
VB
Reader.TextFieldType = _
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(5, 10, 11, -1)

3. Loop through the fields in the file. If any lines are corrupted, report an error and continue parsing.
VB
Dim currentRow As String()
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As _
Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try

4. Close the While and Using blocks with End While and End Using.
VB
End While
End Using

Example
This example reads from the file test.log.
VB
Using Reader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\TestFolder\test.log")
Reader.TextFieldType = _
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(5, 10, 11, -1)
Dim currentRow As String()
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
End Using

Robust Programming
The following conditions may cause an exception:
A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line
causing the exception, while the TextFieldParser.ErrorLine Property is assigned to the text contained in the line.
The specified file does not exist (FileNotFoundException).
A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).
The path is too long (PathTooLongException).
The user does not have sufficient permissions to access the file (UnauthorizedAccessException).

See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Walkthrough: Manipulating Files and Directories in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
TextFieldParser Object
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Concepts

How to: Read From Text Files with Multiple Formats in Visual
Basic
The TextFieldParser object provides a way to easily and efficiently parse structured text files, such as logs. You can process a
file with multiple formats by using the PeekChars method to determine the format of each line as you parse through the file.
To parse a text file with multiple formats
1. Define the expected format and the format used when an error is reported.
VB
Dim StdFormat As Integer()= {5,10,11,-1}
Dim ErrorFormat As Integer() = {5,5,-1}

2. Create a new TextFieldParser object, defining the width and format.


VB
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
MyReader.TextFieldType = FileIO.FieldType.FixedWidth

3. Loop through the rows, testing for format before reading.


VB
Dim CurrentRow As String()
While Not MyReader.EndOfData
Try
Dim RowType As String = MyReader.PeekChars(3)
If String.Compare(RowType, "Err") = 0 Then
' If this line describes an error, the format of
' the row will be different.
MyReader.SetFieldWidths(ErrorFormat)
CurrentRow = MyReader.ReadFields
MyReader.SetFieldWidths(StdFormat)
Else
'Otherwise parse the fields normally
CurrentRow = MyReader.ReadFields
For Each newString As String In CurrentRow
My.Computer.FileSystem.WriteAllText _
("newFile.txt", newString, True)
Next
End If

4. Write errors to the console.


VB
Catch ex As _
Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid.")
End Try
End While
End Using
Example
This example reads from the file testfile.txt.
VB
Dim StdFormat As Integer() = {5, 10, 11, -1}
Dim ErrorFormat As Integer() = {5, 5, -1}
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
MyReader.TextFieldType = FileIO.FieldType.FixedWidth
MyReader.FieldWidths = StdFormat
Dim CurrentRow As String()
While Not MyReader.EndOfData
Try
Dim RowType As String = MyReader.PeekChars(3)
If String.Compare(RowType, "Err") = 0 Then
' If this line describes an error, the format of the row will be different.
MyReader.SetFieldWidths(ErrorFormat)
CurrentRow = MyReader.ReadFields
MyReader.SetFieldWidths(StdFormat)
Else
' Otherwise parse the fields normally
CurrentRow = MyReader.ReadFields
For Each newString As String In CurrentRow
My.Computer.FileSystem.WriteAllText("newFile.txt", newString, True)
Next
End If
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using

Robust Programming
The following conditions may cause an exception:
A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line
causing the exception, while the TextFieldParser.ErrorLine Property is assigned to the text contained in the line.
The specified file does not exist (FileNotFoundException).
A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).
The path is too long (PathTooLongException).
The user does not have sufficient permissions to access the file (UnauthorizedAccessException).
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
Reference
TextFieldParser Object
TextFieldParser.PeekChars Method
My.Computer.FileSystem.WriteAllText Method
TextFieldParser.EndOfData Property
TextFieldParser.TextFieldType Property
MalformedLineException
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Concepts

How to: Read From Binary Files in Visual Basic


The My.Computer.FileSystem object provides the ReadAllBytes method for reading from binary files.
To read from a binary file
Use the ReadAllBytes method, which returns the contents of a file as a byte array. This example reads from the file
C:/Documents and Settings/selfportrait.jpg.

VB
My.Computer.FileSystem.ReadAllBytes _
("C:/Documents and Settings/selfportrait.jpg")

Robust Programming
The following conditions may cause an exception to be thrown:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The file does not exist (FileNotFoundException).
The file is in use by another process, or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
There is not enough memory to write the string to buffer (OutOfMemoryException).
The user lacks necessary permissions to view the path (SecurityException).
Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a
Visual Basic source file.
Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to
read from the file may fail.
See Also
Tasks
How to: Read From Text Files with Multiple Formats in Visual Basic
Reference
My.Computer.FileSystem.ReadAllBytes Method
My.Computer.FileSystem.WriteAllBytes Method
Other Resources
Reading from Files in Visual Basic
Storing Data to and Reading From the Clipboard
Visual Basic Language Concepts

How to: Read From Existing Text Files in My Documents (Visual


Basic)
The following code example reads the contents of the text files in the My Documents folder into a single file.
Example
VB
Dim filePaths As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
Dim allText As String
Try
filePaths = My.Computer.FileSystem.GetFiles _
(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
For Each file As String In filePaths
allText = My.Computer.FileSystem.ReadAllText(file)
My.Computer.FileSystem.WriteAllText("bigfile.txt", allText, True)
Next
Catch fileException As Exception
Throw fileException
End Try

Compiling the Code


Replace "bigfile.txt" with the name of the file you want to write to.
Robust Programming
The files that are read must be text files.
You can use the OpenFileDialog Component (Windows Forms) and the SaveFileDialog Component (Windows Forms) to
reduce the likelihood of permissions-related run-time errors.
Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a
Visual Basic source file.
Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to
read from the file may fail.
Security
To read from a file, your assembly requires a privilege level granted by the FileIOPermission class. If you are running in a
partial-trust context, the code might throw an exception due to insufficient privileges. For more information, see
Code Access Security Basics. The user also needs access to the file. For more information, see Access Control Lists (ACLs).
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
My.Computer.FileSystem.ReadAllText Method
My.Computer.FileSystem.WriteAllText Method
OpenFileDialog
SaveFileDialog
Visual Basic Language Concepts

How to: Read Text from Files with a StreamReader (Visual


Basic)
The My.Computer.FileSystem object provides methods to open a TextReader and a TextWriter. These methods,
OpenTextFileWriter and OpenTextFileReader, are advanced methods that do not appear in IntelliSense unless you select
the All tab.
To read a line from a file with a text reader
Use the OpenTextFileReader method to open the TextReader, specifying the file. This example opens the file named
testfile.txt, reads a line from it, and displays the line in a message box.

VB
Dim fileReader As System.IO.StreamReader
fileReader = _
My.Computer.FileSystem.OpenTextFileReader("C:\\testfile.txt")
Dim stringReader As String
stringReader = fileReader.ReadLine()
MsgBox("The first line of the file is " & stringReader)

Robust Programming
The file that is read must be a text file.
Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a
Visual Basic source file.
Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to
read from the file may fail.
Security
To read from a file, your assembly requires a privilege level granted by the FileIOPermission class. If you are running in a
partial-trust context, the code might throw an exception due to insufficient privileges. For more information, see
Code Access Security Basics. The user also needs access to the file. For more information, see Access Control Lists (ACLs).
See Also
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.OpenTextFileWriter Method
My.Computer.FileSystem.OpenTextFileReader Method
OpenFileDialog
Other Resources
SaveFileDialog Component (Windows Forms)
Reading from Files in Visual Basic
Visual Basic Language Concepts

Writing to Files in Visual Basic


This section lists tasks involving writing to files.
In This Section
How to: Write Text to Files in Visual Basic
Demonstrates how to write to text files.
How to: Append to Text Files in Visual Basic
Demonstrates how to append text to a text file.
How to: Write to Binary Files in Visual Basic
Demonstrates how to write to a binary file.
How to: Write Text to Files in the My Documents Directory in Visual Basic
Demonstrates how to create and write to a new text file in the My Documents directory.
How to: Write Text to Files with a StreamWriter in Visual Basic
Demonstrates how to write to a file with a System.IO.StreamWriter object.
Reference
My.Computer.FileSystem Object
Describes the My.Computer.FileSystem object and its methods and properties.
My.Computer.FileSystem.OpenTextFileWriter Method
Describes the OpenTextFileWriter method.
My.Computer.FileSystem.WriteAllBytes Method
Describes the WriteAllBytes method.
My.Computer.FileSystem.WriteAllText Method
Describes the WriteAllText method.
Related Sections
Reading from Files in Visual Basic
Lists tasks involving reading from files.
Creating, Deleting, and Moving Files and Directories in Visual Basic
Lists tasks involving creating, deleting, moving, and renaming files and directories.
File, Directory, and Drive Properties in Visual Basic
Lists tasks involving determining file, directory, and drive properties.
How to: Write to the Clipboard in Visual Basic
Demonstrates how to write data to the Clipboard.
File Encodings
Provides an overview of file encodings.
Visual Basic Language Concepts

How to: Write Text to Files in Visual Basic


The My.Computer.FileSystem.WriteAllText Method can be used to write text to files. If the specified file does not exist, it is
created.
Procedure
To write text to a file
Use the WriteAllText method to write text to a file, specifying the file and text to be written. This example writes the line
"This is new text." to the file named test.txt, appending the text to any existing text in the file.

VB
My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt", _
"This is new text to be added.",True)

To write a series of strings to a file


Loop through the string collection. Use the WriteAllText method to write text to a file, specifying the target file and
string to be added and setting append to True.
This example writes the names of the files in the Documents and Settings directory to FileList.txt, inserting a carriage
return between each for better readability.
VB
For Each foundFile As String In _
My.Computer.FileSystem.GetFiles("C:\Documents and Settings")
foundFile = foundFile & vbCrLf
My.Computer.FileSystem.WriteAllText _
("C:\Documents and Settings\FileList.txt", foundFile, True)
Next

Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
File points to a path that does not exist (FileNotFoundException or DirectoryNotFoundException).
The file is in use by another process, or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The disk is full, and the call to WriteAllText fails (IOException).
If you are running in a partial-trust context, the code might throw an exception due to insufficient privileges. For more
information, see Code Access Security Basics.
See Also
Tasks
How to: Read From Text Files in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.WriteAllText Method
Visual Basic Language Concepts

How to: Append to Text Files in Visual Basic


The My.Computer.FileSystem.WriteAllText Method can be used to append to a text file by specifying that the append parameter
is set to True.
To append to a text file
Use the WriteAllText method, specifying the target file and string to be appended and setting the append parameter to
True.
This example writes the string "This is a test string." to the file named Testfile.txt.

VB
Dim inputString As String = "This is a test string."
My.Computer.FileSystem.WriteAllText _
("C://testfile.txt", inputString, True)

Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
File points to a path that does not exist (FileNotFoundException or DirectoryNotFoundException).
The file is in use by another process, or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
See Also
Reference
My.Computer.FileSystem.WriteAllText Method
My.Computer.FileSystem Object
Other Resources
Writing to Files in Visual Basic
Visual Basic Language Concepts

How to: Write to Binary Files in Visual Basic


The My.Computer.FileSystem.WriteAllBytes Method writes data to a binary file. If the append parameter is True, it will append
the data to the file; otherwise data in the file is overwritten.
If the specified path excluding the file name is not valid, a DirectoryNotFoundException exception will be thrown. If the path is
valid but the file does not exist, the file will be created.
To write to a binary file
Use the WriteAllBytes method, supplying the file path and name and the bytes to be written. This example appends the
data array CustomerData to the file named CollectedData.dat.
VB
My.Computer.FileSystem.WriteAllBytes _
("C:\MyDocuments\CustomerData", CustomerData, True)

Robust Programming
The following conditions may create an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; or it contains
invalid characters. (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
File points to a path that does not exist (FileNotFoundException or DirectoryNotFoundException).
The file is in use by another process, or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
See Also
Tasks
How to: Write Text to Files in Visual Basic
Reference
My.Computer.FileSystem.WriteAllBytes Method
Visual Basic Language Concepts

How to: Write Text to Files in the My Documents Directory in


Visual Basic
The My.Computer.FileSystem.SpecialDirectories object allows you to access special directories, such as the
MyDocuments directory.
Procedure
To write new text files in the My Documents directory
1. Use the My.Computer.FileSystem.SpecialDirectories.MyDocuments property to supply the path.
VB
Dim filePath As String
filePath = System.IO.Path.Combine( _
My.Computer.FileSystem.SpecialDirectories.MyDocuments, "test.txt")

2. Use the WriteAllText method to write text to the specified file.


VB
My.Computer.FileSystem.WriteAllText(filePath, "some text", True)

Example
VB
Try
Dim filePath As String
filePath = System.IO.Path.Combine( _
My.Computer.FileSystem.SpecialDirectories.MyDocuments, "test.txt")
My.Computer.FileSystem.WriteAllText(filePath, "some text", False)
Catch fileException As Exception
Throw fileException
End Try

Compiling the Code


Replace test.txt with the name of the file you want to write to.
Robust Programming
This code rethrows all the exceptions that may occur when writing text to the file. You can reduce the likelihood of exceptions
by using Windows Forms controls such as the OpenFileDialog and the SaveFileDialog components that limit the user choices
to valid file names. Using these controls is not foolproof, however. The file system can change between the time the user
selects a file and the time that the code executes. Exception handling is therefore nearly always necessary when with working
with files.
Security
If you are running in a partial-trust context, the code might throw an exception due to insufficient privileges. For more
information, see Code Access Security Basics.
This example creates a new file. If an application needs to create a file, that application needs Create permission for the folder.
Permissions are set using access control lists. If the file already exists, the application needs only Write permission, a lesser
privilege. Where possible, it is more secure to create the file during deployment, and only grant Read privileges to a single file,
rather than to grant Create privileges for a folder. Also, it is more secure to write data to user folders than to the root folder or
the Program Files folder. For more information, see Access Control Lists (ACLs).
See Also
Reference
My.Computer Object
My.Computer.FileSystem Object
My.Computer.FileSystem.WriteAllText Method
My.Computer.FileSystem.SpecialDirectories Object
System.IO.Path.Combine(System.String,System.String)
Visual Basic Language Concepts

How to: Write Text to Files with a StreamWriter in Visual Basic


This example opens a StreamWriter object with the My.Computer.FileSystem.OpenTextFileWriter method and uses it to
write a string to a text file with the WriteLine method of the StreamWriter class.
Example
VB
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", True)
file.WriteLine("Here is the first string.")
file.Close()

Robust Programming
The following conditions may cause an exception:
The file exists and is read-only (IOException).
The disk is full (IOException).
The pathname is too long (PathTooLongException).
Security
This example creates a new file, if the file does not already exist. If an application needs to create a file, that application needs
Create access for the folder. If the file already exists, the application needs only Write access, a lesser privilege. Where
possible, it is more secure to create the file during deployment, and only grant Read access to a single file, rather than Create
access for a folder.
See Also
Tasks
How to: Read From Text Files in Visual Basic
Reference
My.Computer.FileSystem.OpenTextFileWriter Method
StreamWriter
Other Resources
Writing to Files in Visual Basic
Visual Basic Language Concepts

Creating, Deleting, and Moving Files and Directories in Visual


Basic
This section lists tasks associated with creating, deleting, moving, and renaming files and directories in Visual Basic.
In This Section
How to: Copy Files with a Specific Pattern to a Directory in Visual Basic
Demonstrates how to copy files with a specific file name pattern, such as only .txt files, to a directory.
How to: Create a Copy of a File in the Same Directory in Visual Basic
Demonstrates how to create a copy of a file in the same directory.
How to: Create a Copy of a File in a Different Directory in Visual Basic
Demonstrates how to copy a file to another directory.
How to: Create a File in Visual Basic
Demonstrates how to create a file.
How to: Delete a File in Visual Basic
Demonstrates how to delete a file.
How to: Delete All Files in a Directory in Visual Basic
Demonstrates how to delete all the files in a specific directory.
How to: Find Files with a Specific Pattern in Visual Basic
Demonstrates how to list only files with a specific file name pattern in a directory.
How to: Move a File in Visual Basic
Demonstrates how to move a file to a different directory.
How to: Move a Collection of Files in Visual Basic
Demonstrates how to move multiple files to a different directory.
How to: Rename a File in Visual Basic
Demonstrates how to rename a file.
How to: Rename a Directory in Visual Basic
Demonstrates how to rename a directory.
How to: Copy a Directory to Another Directory in Visual Basic
Demonstrates how to copy a directory to another location.
How to: Create a Directory in Visual Basic
Demonstrates how to create a directory.
How to: Delete a Directory in Visual Basic
Demonstrates how to delete a directory.
How to: Find Subdirectories with a Specific Pattern in Visual Basic
Demonstrates how to list directories with a specific pattern in their name.
How to: Get the Collection of Files in a Directory in Visual Basic
Demonstrates how to list the files in a directory.
How to: Determine How Many Files Are in a Directory in Visual Basic
Demonstrates how to determine how many files are in a directory.
How to: Move a Directory in Visual Basic
Demonstrates how to move a directory.
How to: Move the Contents of a Directory in Visual Basic
Demonstrates how to move the contents of a directory.
How to: Retrieve the Contents of the My Documents Directory in Visual Basic
Demonstrates how to read from special directories.
How to: Parse File Paths in Visual Basic
Demonstrates how to use My methods to combine file paths.
Reference
My.Computer.FileSystem Object
Describes the My.Computer.FileSystem object and its members.
My.Computer.FileSystem.CombinePath Method
Describes the CombinePath method.
My.Computer.FileSystem.CopyDirectory Method
Describes the CopyDirectory method.
My.Computer.FileSystem.CopyFile Method
Describes the CopyFile method.
My.Computer.FileSystem.CreateDirectory Method
Describes the CreateDirectory method.
My.Computer.FileSystem.DeleteDirectory Method
Describes the DeleteDirectory method.
My.Computer.FileSystem.DeleteFile Method
Describes the DeleteFile method.
My.Computer.FileSystem.GetParentPath Method
Describes the GetParentPath method.
My.Computer.FileSystem.MoveDirectory Method
Describes the MoveDirectory method.
My.Computer.FileSystem.MoveFile Method
Describes the MoveFile method.
My.Computer.FileSystem.RenameDirectory Method
Describes the RenameDirectory method.
My.Computer.FileSystem.RenameFile Method
Describes the RenameFile method.
My.Computer.FileSystem.SpecialDirectories Object
Describes the SpecialDirectories object.
Related Sections
Reading from Files in Visual Basic
Lists tasks associated with reading from files.
Writing to Files in Visual Basic
Lists tasks involving writing to files.
File, Directory, and Drive Properties in Visual Basic
Lists tasks associated with getting and setting file, directory, and drive properties.
Visual Basic Language Concepts

How to: Copy Files with a Specific Pattern to a Directory in


Visual Basic
The My.Computer.FileSystem.GetFiles Method returns a read-only collection of strings representing the path names for the
files. You can use the wildCards parameter to specify a specific pattern.
An empty collection is returned if no matching files are found.
You can use the My.Computer.FileSystem.CopyFile Method to copy the files to a directory.
To copy files with a specific pattern to a directory
1. Use the GetFiles method to return the list of files. This example returns all .rtf files in the specified directory.
VB
For Each foundFile As String In My.Computer.FileSystem.GetFiles( _
My.Computer.FileSystem.SpecialDirectories.MyDocuments, _
FileIO.SearchOption.SearchTopLevelOnly, "*.rtf")

2. Use the CopyFile method to copy the files. This example copies the files to the directory named testdirectory.
VB
My.Computer.FileSystem.CopyFile(foundFile, "C:\testdirectory\" & foundFile)

3. Close the For statement with a Next statement.


VB
Next

Example
The following example, which presents the above snippets in complete form, copies all .rtf files in the specified directory to the
directory named testdirectory.
VB
For Each foundFile As String In My.Computer.FileSystem.GetFiles( _
My.Computer.FileSystem.SpecialDirectories.MyDocuments, _
FileIO.SearchOption.SearchTopLevelOnly, "*.rtf")

My.Computer.FileSystem.CopyFile(foundFile, "C:\testdirectory\" & foundFile)


Next

Security
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The directory does not exist (DirectoryNotFoundException).
The directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException). The user lacks necessary permissions
(UnauthorizedAccessException).
See Also
Tasks
How to: Find Subdirectories with a Specific Pattern in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
How to: Get the Collection of Files in a Directory in Visual Basic
Reference
My.Computer.FileSystem.CopyFile Method
My.Computer.FileSystem.GetFiles Method
Visual Basic Language Concepts

How to: Create a Copy of a File in the Same Directory in Visual


Basic
Use the My.Computer.FileSystem.CopyFile method to copy files. The parameters allow you to overwrite existing files,
rename the file, show the progress of the operation, and allow the user to cancel the operation.
To create a copy of a file in the same folder
Use the CopyFile method, supplying the target file and the location. The following example creates a copy of test.txt
called test2.txt.
VB
My.Computer.FileSystem.CopyFile("C:\TestFolder\test.txt", _
"C:\TestFolder\test2.txt", Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Fil
eIO.UICancelOption.DoNothing)

To create a copy of a file in the same folder, overwriting existing files


Use the CopyFile method, supplying the target file and location, and setting overwrite to True. The following example
creates a copy of test.txt called test2.txt and overwrites any existing files by that name.
VB
My.Computer.FileSystem.CopyFile("C:\TestFolder\test.txt", _
"C:\TestFolder\test2.txt", True)

Robust Programming
The following conditions may cause an exception to be thrown:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The system could not retrieve the absolute path (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The source file is not valid or does not exist (FileNotFoundException).
The combined path points to an existing directory (IOException).
The destination file exists and overwrite is set to False (IOException).
The user does not have sufficient permissions to access the file (IOException).
A file in the target folder with the same name is in use (IOException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
ShowUI is set to True, onUserCancel is set to ThrowException, and the user has cancelled the operation
(OperationCanceledException).
ShowUI is set to True, onUserCancel is set to ThrowException, and an unspecified I/O error occurs
(OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
The user does not have required permission (UnauthorizedAccessException).
The user lacks necessary permissions to view the path (SecurityException).
See Also
Tasks
How to: Copy Files with a Specific Pattern to a Directory in Visual Basic
How to: Create a Copy of a File in a Different Directory in Visual Basic
How to: Copy a Directory to Another Directory in Visual Basic
How to: Rename a File in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.CopyFile Method
UICancelOption Enumeration
Visual Basic Language Concepts

How to: Create a Copy of a File in a Different Directory in


Visual Basic
The My.Computer.FileSystem.CopyFile method allows you to copy files. Its parameters provide the ability to overwrite
existing files, rename the file, show the progress of the operation, and allow the user to cancel the operation.
To copy a text file to another folder
Use the CopyFile method to copy a file, specifying a source file and the target directory. The overwrite parameter allows
you to specify whether or not to overwrite existing files. The following code examples demonstrate how to use CopyFile.
VB
' Copy the file to a new location without overwriting existing file.
My.Computer.FileSystem.CopyFile( _
"C:\UserFiles\TestFiles\testFile.txt", _
"C:\UserFiles\TestFiles2\testFile.txt")

' Copy the file to a new folder, overwriting existing file.


My.Computer.FileSystem.CopyFile( _
"C:\UserFiles\TestFiles\testFile.txt", _
"C:\UserFiles\TestFiles2\testFile.txt", _
FileIO.UIOption.AllDialogs, _
FileIO.UICancelOption.DoNothing)

' Copy the file to a new folder and rename it.


My.Computer.FileSystem.CopyFile( _
"C:\UserFiles\TestFiles\testFile.txt", _
"C:\UserFiles\TestFiles2\NewFile.txt", _
FileIO.UIOption.AllDialogs, _
FileIO.UICancelOption.DoNothing)

Robust Programming
The following conditions may cause an exception to be thrown:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The system could not retrieve the absolute path (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The source file is not valid or does not exist (FileNotFoundException).
The combined path points to an existing directory (IOException).
The destination file exists and overwrite is set to False (IOException).
The user does not have sufficient permissions to access the file (IOException).
A file in the target folder with the same name is in use (IOException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
ShowUI is set to True, onUserCancel is set to ThrowException, and the user has cancelled the operation
(OperationCanceledException).
ShowUI is set to True, onUserCancel is set to ThrowException, and an unspecified I/O error occurs
(OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
The user does not have required permission (UnauthorizedAccessException).
The user lacks necessary permissions to view the path (SecurityException).
See Also
Tasks
How to: Copy Files with a Specific Pattern to a Directory in Visual Basic
How to: Create a Copy of a File in the Same Directory in Visual Basic
How to: Copy a Directory to Another Directory in Visual Basic
How to: Rename a File in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.CopyFile Method
UICancelOption Enumeration
Visual Basic Language Concepts

How to: Create a File in Visual Basic


This example creates an empty text file at the specified path using the Create method in the File class.
Example
VB
Dim file As System.IO.FileStream
file = System.IO.File.Create("c:\test.txt")

Compiling the Code


Use the file variable to write to the file.
Robust Programming
If the file already exists, it is replaced.
The following conditions may cause an exception:
The path name is malformed. For example, it contains illegal characters or is only white space (ArgumentException).
The path is read-only (IOException).
The path name is Nothing (ArgumentNullException).
The path name is too long (PathTooLongException).
The path is invalid (DirectoryNotFoundException).
The path is only a colon ":" (NotSupportedException).
Security
A SecurityException may be thrown in partial-trust environments.
The call to the Create method requires FileIOPermission.
An UnauthorizedAccessException is thrown if the user does not have permission to create the file.
See Also
Reference
System.IO
Create
Concepts
Using Libraries from Partially Trusted Code
Code Access Security Basics
Visual Basic Language Concepts

How to: Delete a File in Visual Basic


The DeleteFile method of the My.Computer.FileSystem object allows you to delete a file. Among the options it offers are:
whether to send the deleted file to the Recycle Bin, whether to ask the user to confirm that the file should be deleted, and
what to do when the user cancels the operation.
To delete a text file
Use the DeleteFile method to delete the file. The following code demonstrates how to delete the file named test.txt.
VB
My.Computer.FileSystem.DeleteFile("C:\test.txt")

To delete a text file and ask the user to confirm that the file should be deleted
Use the DeleteFile method to delete the file, setting showUI to AllDialogs. The following code demonstrates how to
delete the file named test.txt and allow the user to confirm that the file should be deleted.
VB
My.Computer.FileSystem.DeleteFile("C:\test.txt", _
FileIO.UIOption.AllDialogs, FileIO.RecycleOption.DeletePermanently, FileIO.UIC
ancelOption.DoNothing)

To delete a text file and send it to the Recycle Bin


Use the DeleteFile method to delete the file, specifying SendToRecycleBin for the recycle parameter. The following
code demonstrates how to delete the file named test.txt and send it to the Recycle Bin.
VB
My.Computer.FileSystem.DeleteFile("C:\test.txt", _
FileIO.UIOption.AllDialogs, FileIO.RecycleOption.SendToRecycleBin)

Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The file is in use (IOException).
The user lacks necessary permissions to view the path (SecurityException).
The file does not exist (FileNotFoundException).
The user does not have permission to delete the file, or the file is read-only (UnauthorizedAccessException).
A partial-trust situation exists in which the user does not have sufficient permissions (SecurityException).
The user cancelled the operation and onUserCancel is set to Microsoft.VisualBasic.FileIO.UICancelOption.ThrowException
(OperationCanceledException).
See Also
Tasks
How to: Get the Collection of Files in a Directory in Visual Basic
How to: Delete a Directory in Visual Basic
Reference
UICancelOption Enumeration
My.Computer.FileSystem Object
UIOption Enumeration
RecycleOption Enumeration
Visual Basic Language Concepts

How to: Delete All Files in a Directory in Visual Basic


The DeleteFile method of the My.Computer.FileSystem object allows you to delete a file. Among the options it offers are:
whether to send the deleted file to the Recycle Bin, whether to ask the user to confirm that the file should be deleted, and
what to do when the user cancels the operation.
To delete all of the files in a folder
1. Use the My.Computer.FileSystem.GetFiles method to return the collection of strings representing the files in the
directory.
2. Use a For…Each loop with the DeleteFile method to delete each file in turn.
The following example deletes all files in the My Documents folder.
VB
For Each foundFile As String In My.Computer.FileSystem.GetFiles( _
My.Computer.FileSystem.SpecialDirectories.MyDocuments, _
FileIO.SearchOption.SearchAllSubDirectories, "*.*")

My.Computer.FileSystem.DeleteFile(foundFile, _
FileIO.UIOption.AllDialogs, _
FileIO.RecycleOption.DeletePermanently)
Next

Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The file is in use (IOException).
The user lacks necessary permissions to view the path (SecurityException).
The file does not exist (FileNotFoundException).
The user does not have permission to delete the file, or the file is read-only (UnauthorizedAccessException).
A partial-trust situation exists in which the user does not have sufficient permissions (SecurityException).
The user cancelled the operation and onUserCancel is set to Microsoft.VisualBasic.FileIO.UICancelOption.ThrowException
(OperationCanceledException).
See Also
Tasks
How to: Delete a File in Visual Basic
How to: Delete a Directory in Visual Basic
How to: Rename a File in Visual Basic
How to: Determine the Absolute Path of a File in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.DeleteFile Method
RecycleOption Enumeration
UICancelOption Enumeration
Visual Basic Language Concepts

How to: Find Files with a Specific Pattern in Visual Basic


The My.Computer.FileSystem.GetFiles Method returns a read-only collection of strings representing the path names for the
files. You can use the wildCards parameter to specify a specific pattern. If you would like to include subdirectories in the search,
set the searchType parameter to SearchOption.SearchAllSubDirectories.
An empty collection is returned if no files matching the specified pattern are found.
To find files with a specified pattern
Use the GetFiles method, supplying the name and path of the directory you want to search and specifying the pattern.
The following example returns all files with the extension .dll in the directory and adds them to ListBox1.
VB
For Each foundFile As String In My.Computer.FileSystem.GetFiles( _
My.Computer.FileSystem.SpecialDirectories.MyDocuments, _
FileIO.SearchOption.SearchAllSubDirectories, "*.dll")

Listbox1.Items.Add(foundFile)
Next

Security
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
directory does not exist (DirectoryNotFoundException).
directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user lacks necessary permissions (UnauthorizedAccessException).
See Also
Tasks
How to: Find Subdirectories with a Specific Pattern in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
How to: Get the Collection of Files in a Directory in Visual Basic
Reference
My.Computer.FileSystem.GetFiles Method
Visual Basic Language Concepts

How to: Move a File in Visual Basic


The My.Computer.FileSystem.MoveFile method can be used to move a file to another folder. If the target structure does not
exist, it will be created.
To move a file
Use the MoveFile method to move the file, specifying the file name and location for both the source file and the target
file. This example moves the file named test.txt from TestDir1 to TestDir2. Note that the target file name is specified
even though it is the same as the source file name.
VB
My.Computer.FileSystem.MoveFile("C:\TestDir1\test.txt", _
"C:\TestDir2\test.txt")

To move a file and rename it


Use the MoveFile method to move the file, specifying the source file name and location, the target location, and the new
name at the target location. This example moves the file named test.txt from TestDir1 to TestDir2 and renames it
nexttest.txt.

VB
My.Computer.FileSystem.MoveFile("C:\TestDir1\test.txt", _
"C:\TestDir2\nexttest.txt", _
FileIO.UIOption.AllDialogs, _
FileIO.UICancelOption.ThrowException)

Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
destinationFileName is Nothing or an empty string (ArgumentNullException).
The source file is not valid or does not exist (FileNotFoundException).
The combined path points to an existing directory, the destination file exists and overwrite is set to False, a file in the
target directory with the same name is in use, or the user does not have sufficient permissions to access the file
(IOException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
showUI is set to True, onUserCancel is set to ThrowException, and either the user has cancelled the operation or an
unspecified I/O error occurs (OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
The user lacks necessary permissions to view the path (SecurityException).
The user does not have required permission (UnauthorizedAccessException).
See Also
Tasks
How to: Rename a File in Visual Basic
How to: Move a Collection of Files in Visual Basic
How to: Create a Copy of a File in a Different Directory in Visual Basic
How to: Parse File Paths in Visual Basic
How to: Move a Directory in Visual Basic
Reference
My.Computer.FileSystem.MoveFile Method
Visual Basic Language Concepts

How to: Move a Collection of Files in Visual Basic


The My.Computer.FileSystem.MoveFile method allows you to move files between directories.
If the target structure does not exist, it will be created.
To move a collection of files from one directory to another
Define the collection of files and call the MoveFile method. This example moves all files in the directory MyDocuments to
the folder StorageDir.
VB
For Each foundFile As String In My.Computer.FileSystem.GetFiles( _
My.Computer.FileSystem.SpecialDirectories.MyDocuments, _
FileIO.SearchOption.SearchAllSubDirectories, "*.*")

Dim foundFileInfo As New System.IO.FileInfo(foundFile)


My.Computer.FileSystem.MoveFile(foundFile, "C:\StorageDir\" & foundFileInfo.Name)
Next

Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The source file is not valid or does not exist (FileNotFoundException).
The combined path points to an existing directory, the destination file exists and overwrite is set to False, a file in the
target directory with the same name is in use, or the user does not have sufficient permissions to access the file
(IOException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
showUI is set to True, onUserCancelOption is set to ThrowException, and either the user has cancelled the operation or
an unspecified I/O error occurs (OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
The user lacks necessary permissions to view the path (SecurityException).
The user does not have required permission (UnauthorizedAccessException).
See Also
Tasks
How to: Rename a File in Visual Basic
How to: Move a File in Visual Basic
How to: Create a Copy of a File in a Different Directory in Visual Basic
How to: Parse File Paths in Visual Basic
How to: Move a Directory in Visual Basic
How to: Move the Contents of a Directory in Visual Basic
Reference
My.Computer.FileSystem.MoveFile Method
My.Computer.FileSystem.GetFiles Method
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Concepts

How to: Rename a File in Visual Basic


Use the RenameFile method of the My.Computer.FileSystem object to rename a file by supplying the current location, file
name, and the new file name. This method cannot be used to move a file; use the MoveFile method to move and rename the
file.
To rename a file
Use the My.Computer.FileSystem.RenameFile method to rename a file. This example renames the file named
Test.txt to SecondTest.txt.

VB
' Change "c:\test.txt" to the path and filename for the file that
' you want to rename.
My.Computer.FileSystem.RenameFile("C:\Test.txt", "SecondTest.txt")

This code example is also available as an IntelliSense code snippet. In the code snippet picker, the snippet is located in File
system - Processing Drives, Folders, and Files. For more information, see
How to: Insert Snippets Into Your Code (Visual Basic).
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
newName contains path information (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
newName is Nothing or an empty string (ArgumentNullException).
The source file is not valid or does not exist (FileNotFoundException).
There is an existing file or directory with the name specified in newName (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user does not have the required permission (UnauthorizedAccessException).
See Also
Tasks
How to: Move a File in Visual Basic
How to: Move a Collection of Files in Visual Basic
How to: Create a Copy of a File in the Same Directory in Visual Basic
How to: Create a Copy of a File in a Different Directory in Visual Basic
Reference
My.Computer.FileSystem.RenameFile Method
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Concepts

How to: Rename a Directory in Visual Basic


The RenameDirectory method of the My.Computer.FileSystem object can be used to rename a directory by supplying the
current location and name of the directory, along with the new name for the directory. This method cannot be used to move a
directory; use the MoveDirectory method to move and rename the directory.
To rename a directory
Use the My.Computer.FileSystem.RenameDirectory method to rename a directory. The following code renames the
Test directory to SecondTest.

VB
My.Computer.FileSystem.RenameDirectory("C:MyDocuments\Test", _
"SecondTest")

This code example is also available as an IntelliSense code snippet. In the code snippet picker, the example is located in File
system - Processing Drives, Folders, and Files. For more information, see
How to: Insert Snippets Into Your Code (Visual Basic).
Robust Programming
The following conditions can cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
newName contains path information (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
newName is Nothing or an empty string (ArgumentNullException).
The source directory is not valid or does not exist (DirectoryNotFoundException).
There is an existing file or folder with the name specified in newName (IOException).
The folder is a root folder (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user does not have required permission (UnauthorizedAccessException).
See Also
Tasks
How to: Copy a Directory to Another Directory in Visual Basic
How to: Parse File Paths in Visual Basic
How to: Move a Directory in Visual Basic
How to: Move the Contents of a Directory in Visual Basic
Reference
My.Computer.FileSystem.RenameDirectory Method
Visual Basic Language Concepts

How to: Copy a Directory to Another Directory in Visual Basic


Use the My.Computer.FileSystem.CopyDirectory Method method to copy a directory to another directory. This method copies
the contents of the directory as well as the directory itself. If the target directory does not exist, it will be created. If a directory
with the same name exists in the target location and overwrite is set to False, the contents of the two directories will be
merged. You can specify a new name for the directory during the operation.
When copying files within a directory, exceptions may be thrown that are caused by specific file, such as a file existing during a
merge while overwrite is set to False. When such exceptions are thrown, they are consolidated into a single exception, whose
Data property holds entries in which the file or directory path is the key and the specific exception message is contained in the
corresponding value.
To copy a directory to another directory
Use the CopyDirectory method, specifying source and destination directory names. The following example copies the
directory named TestDirectory1 into TestDirectory2, overwriting existing files.
VB
My.Computer.FileSystem.CopyDirectory("C:\TestDirectory1", "C:\TestDirectory2", True)

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in File system
- Processing Drives, Folders, and Files. For more information, see
How to: Insert Snippets Into Your Code (Visual Basic).
Robust Programming
The following conditions may cause an exception:
The new name specified for the directory contains a colon (:) or slash (\ or /) (ArgumentException).
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
destinationDirectoryName is Nothing or an empty string (ArgumentNullException)
The source directory does not exist (DirectoryNotFoundException).
The source directory is a root directory (IOException).
The combined path points to an existing file (IOException).
The source path and target path are the same (IOException).
ShowUI is set to UIOption.AllDialogs and the user cancels the operation, or one or more files in the directory cannot be
copied (OperationCanceledException).
The operation is cyclic (InvalidOperationException).
The path contains a colon (:) (NotSupportedException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
A destination file exists but cannot be accessed (UnauthorizedAccessException).
See Also
Tasks
How to: Find Subdirectories with a Specific Pattern in Visual Basic
How to: Get the Collection of Files in a Directory in Visual Basic
How to: Move a Directory in Visual Basic
How to: Move the Contents of a Directory in Visual Basic
Reference
My.Computer.FileSystem.CopyDirectory Method
Visual Basic Language Concepts

How to: Create a Directory in Visual Basic


Use the CreateDirectory method of the My.Computer.FileSystem object to create directories.
If the directory already exists, no exception is thrown.
To create a directory
Use the CreateDirectory method by specifying the full path of the location where the directory should be created. This
example creates the directory NewDirectory in C:\Documents and Settings\All Users\Documents.
VB
My.Computer.FileSystem.CreateDirectory _
("C:\Documents and Settings\All Users\Documents\NewDirectory")

Robust Programming
The following conditions may cause an exception:
The directory name is malformed. For example, it contains illegal characters or is only white space (ArgumentException).
The parent directory of the directory to be created is read-only (IOException).
The directory name is Nothing (ArgumentNullException).
The directory name is too long (PathTooLongException).
The directory name is a colon ":" (NotSupportedException).
The user does not have permission to create the directory (UnauthorizedAccessException).
The user lacks permissions in a partial-trust situation (SecurityException).
See Also
Tasks
How to: Determine if a Directory Exists in Visual Basic
Reference
My.Computer.FileSystem.CreateDirectory Method
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Concepts

How to: Delete a Directory in Visual Basic


Use the DeleteDirectory method of the My.Computer.FileSystem object to delete a directory. Among the options are:
whether or not to delete the directory's contents, whether or not to send the deleted directory to the Recycle Bin, and whether
or not to show the progress of the deletion.
To delete a directory only if it is empty
Use the DeleteDirectory method to delete the directory, specifying False for onDirectoryNotEmpty. This example
deletes the directory named OldDirectory only if it is empty.
VB
My.Computer.FileSystem.DeleteDirectory("C:\OldDirectory", _
FileIO.DeleteDirectoryOption.ThrowIfDirectoryNonEmpty)

To delete a directory and send it to the Recycle Bin


Use the DeleteDirectory method to delete the directory, specifying RecycleOption.SendToRecycleBin for recycle.
This example deletes the directory named OldDirectory and all of its contents, sending them to the Recycle Bin and
showing the operation progress.
VB
My.Computer.FileSystem.DeleteDirectory("C:\OldDirectory", FileIO.UIOption.AllDialogs,
FileIO.RecycleOption.SendToRecycleBin)

Robust Programming
The following conditions may cause an exception:
The path is a zero-length string, is malformed, contains only white space, or contains invalid characters (including
wildcard characters) (ArgumentException).
The path is a device path (starts with \\.\) (ArgumentException).
The path is Nothing (ArgumentNullException).
The directory does not exist or is a file (DirectoryNotFoundException).
The user does not have permission to delete the directory or subdirectory (IOException).
A file in the directory or subdirectory is in use (IOException).
A file or directory name contains a colon (:) (NotSupportedException).
OnUserCancel is set to ThrowException and the user cancels the operation (OperationCanceledException).
OnUserCancel is set to ThrowException and the directory cannot be deleted (OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
showUI is set to AllDialogs and the user does not have required permissions (UnauthorizedAccessException).
See Also
Tasks
How to: Delete a File in Visual Basic
Reference
UICancelOption Enumeration
My.Computer.FileSystem.DeleteDirectory Method
RecycleOption Enumeration
UIOption Enumeration
DeleteDirectoryOption Enumeration
Visual Basic Language Concepts

How to: Find Subdirectories with a Specific Pattern in Visual


Basic
The My.Computer.FileSystem.GetDirectories Method returns a read-only collection of strings representing the path names for
the subdirectories in a directory. You can use the wildCards parameter to specify a specific pattern. If you would like to include
the contents of subdirectories in the search, set the searchType parameter to SearchOption.SearchAllSubDirectories.
An empty collection is returned if no directories matching the specified pattern are found.
To find subdirectories with a specific pattern
Use the GetDirectories method, supplying the name and path of the directory you want to search. The following
example returns all the directories in the directory structure that contain the word "Logs" in their name, and adds them to
ListBox1.

VB
For Each foundDirectory As String In _
My.Computer.FileSystem.GetDirectories( _
My.Computer.FileSystem.SpecialDirectories.MyDocuments, True, _
"*Logs*")

ListBox1.Items.Add(foundDirectory)
Next

Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
One or more of the specified wildcard characters is Nothing, an empty string, or contains only spaces
(ArgumentNullException).
directory does not exist (DirectoryNotFoundException).
directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user lacks necessary permissions (UnauthorizedAccessException).
See Also
Tasks
How to: Find Files with a Specific Pattern in Visual Basic
Reference
My.Computer.FileSystem.GetDirectories Method
Visual Basic Language Concepts

How to: Get the Collection of Files in a Directory in Visual Basic


The My.Computer.FileSystem.GetFiles Method returns a read-only collection of strings representing the name of the files
within a directory. You can use the wildCards parameter to specify a specific pattern. To include subdirectories in the search, set
the searchType parameter to SearchOption.SearchAllSubDirectories.
An empty collection is returned if no files matching the specified pattern are found.
To list files in a directory
Use the GetFiles method, supplying the name and path of the directory to search. The following example returns all files
in the directory and adds them to ListBox1.
VB
For Each foundFile As String In My.Computer.FileSystem.GetFiles _
(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
listBox1.Items.Add(foundFile)
Next

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in File system
- Processing Drives, Folders, and Files. For more information, see
How to: Insert Snippets Into Your Code (Visual Basic).
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
directory does not exist (DirectoryNotFoundException).
directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user lacks necessary permissions (UnauthorizedAccessException).
See Also
Tasks
How to: Find Files with a Specific Pattern in Visual Basic
How to: Find Subdirectories with a Specific Pattern in Visual Basic
Reference
My.Computer.FileSystem.GetFiles Method
Visual Basic Language Concepts

How to: Determine How Many Files Are in a Directory in Visual


Basic
You can use the My.Computer.FileSystem.GetFiles Method to return a read-only collection of strings representing the names of
files within the specified directory. Then you can use the Count property to determine the number of files.
To determine the number of files in a directory
1. Use the GetFiles method to return the collection of files in the specified directory. This example returns the files in the
directory named TestDir.
VB
Dim counter As _
System.Collections.ObjectModel.ReadOnlyCollection(Of String)
counter = My.Computer.FileSystem.GetFiles("C:\TestDir")

2. Use the Count property to determine the number of files in the collection. This example displays the result in a message
box.
VB
MsgBox("number of files is " & CStr(counter.Count))

Example
This example, which presents the above snippet in complete form, counts the number of files in TestDir and reports it in a
message box.
VB
Dim counter As _
System.Collections.ObjectModel.ReadOnlyCollection(Of String)
counter = My.Computer.FileSystem.GetFiles("C:\TestDir")
MsgBox("number of files is " & CStr(counter.Count))

Compiling the Code


This example requires:
Access to the members of the System.Collections namespace. Add an Imports statement if you are not fully qualifying
member names in your code. For more information, see Imports Statement.
A directory named TestDir at the specified location. Replace the path with the path of the directory you wish to examine.

Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The directory does not exist or is a file (DirectoryNotFoundException).
directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user lacks necessary permissions (UnauthorizedAccessException).
See Also
Tasks
How to: Get the Collection of Files in a Directory in Visual Basic
How to: Find Files with a Specific Pattern in Visual Basic
Reference
My.Computer.FileSystem.GetFiles Method
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts

How to: Move a Directory in Visual Basic


The My.Computer.FileSystem.MoveDirectory Method can be used to move directories.
If an attempt is made to move a directory inside a directory that does not exist, the target directory will be created.
If overwrite is True and the destination directory already exists, the new files will be added to the already existing files in the
directory. Files in the destination directory will be overwritten if the source directory contains files with the same name.
To move a directory
Use the MoveDirectory method to move a directory, specifying the source and target directories. The following example
moves Dir1 inside Dir2.
VB
My.Computer.FileSystem.MoveDirectory("C:\Dir1", "C:\Dir2")

To move a directory and overwrite existing directories


Use the MoveDirectory method to move a directory, specifying the source and target directories. The following example
moves Dir1 inside Dir2, adding its files to the existing files if the destination directory already exists.
VB
My.Computer.FileSystem.MoveDirectory("C:\Dir1", "C:\Dir2", True)

Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is Nothing (ArgumentNullException).
The source is invalid (DirectoryNotFoundException).
The source is a root directory (IOException).
The combined path points to an existing file (IOException).
The source path and the target path are the same (IOException).
The file already exists and overwrite is set to False (IOException).
A subdirectory of file cannot be copied (IOException).
The operation is cyclic (InvalidOperationException).
A file or directory name in the path contains a colon (:) (NotSupportedException).
onUserCancel is set to UICancelOption.ThrowException, and the user cancels the operation
(OperationCanceledException).
onUserCancel is set to UICancelOption.ThrowException, and the operation cannot be completed
(OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
onUserCancel is set to UICancelOption.ThrowException, and the user lacks necessary permissions (SecurityException).
The user does not have permission to modify the file (UnauthorizedAccessException).
See Also
Tasks
How to: Move the Contents of a Directory in Visual Basic
How to: Copy a Directory to Another Directory in Visual Basic
How to: Rename a Directory in Visual Basic
How to: Parse File Paths in Visual Basic
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Concepts

How to: Move the Contents of a Directory in Visual Basic


Use the My.Computer.FileSystem.GetFiles Method to get the list of files in a folder, and use the
My.Computer.FileSystem.MoveFile Method to move files between directories.
If the target structure does not exist when MoveFile is called, it will be created.
To move the contents of a directory
Use the GetFiles method to get the list of files in the directory, followed by the MoveFile method, supplying the source
file and the directory to which to move it. This example moves all the files in the My Documents directory to the
directory named StorageDir.
VB
For Each foundFile As String In My.Computer.FileSystem.GetFiles( _
My.Computer.FileSystem.SpecialDirectories.MyDocuments, _
FileIO.SearchOption.SearchAllSubDirectories, "*.*")

My.Computer.FileSystem.MoveFile(foundFile, "C:\StorageDir")
Next

Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains
invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
directory does not exist (DirectoryNotFoundException).
directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user lacks necessary permissions (UnauthorizedAccessException).
See Also
Tasks
How to: Rename a File in Visual Basic
How to: Move a File in Visual Basic
How to: Create a Copy of a File in a Different Directory in Visual Basic
How to: Parse File Paths in Visual Basic
How to: Move a Directory in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
How to: Move a Collection of Files in Visual Basic
Reference
My.Computer.FileSystem.MoveFile Method
My.Computer.FileSystem.GetFiles Method
Visual Basic Language Concepts

How to: Retrieve the Contents of the My Documents Directory


in Visual Basic
The My.Computer.FileSystem.SpecialDirectories Object can be used to read from many of the All Users directories, such as My
Documents or Desktop.
To read from the My Documents folder
Use the ReadAllText method to read the text from each file in a specific directory. The following code specifies a
directory and file and then uses ReadAllText to read them into the string named patients.
VB
Dim path As String
Dim patients As String
path = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\" & "Patients.txt"
patients = My.Computer.FileSystem.ReadAllText(path)

See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
My.Computer.FileSystem.SpecialDirectories Object Members
My.Computer.FileSystem.ReadAllText Method
Visual Basic Language Concepts

How to: Parse File Paths in Visual Basic


The My.Computer.FileSystem Object offers a number of useful methods when parsing file paths.
The My.Computer.FileSystem.CombinePath Method takes two paths and returns a properly formatted combined path.
The My.Computer.FileSystem.GetParentPath Method returns the absolute path of the parent of the provided path.
The My.Computer.FileSystem.GetFileInfo Method returns a FileInfo object that can be queried to determine the file's
properties, such as its name and path.
Do not make decisions about the contents of the file based on the file name extension. For example, the file Form1.vb may not
be a Visual Basic source file.
To determine a file's name and path
Use the DirectoryName and Name properties of the FileInfo object to determine a file's name and path. This example
determines the name and path and displays them.
VB
Dim testFile As System.IO.FileInfo
testFile = My.Computer.FileSystem.GetFileInfo("C:\TestFolder1\test1.txt")
Dim folderPath As String = testFile.DirectoryName
MsgBox(folderPath)
Dim fileName As String = testFile.Name
MsgBox(fileName)

To combine a file's name and directory to create the full path


Use the CombinePath method, supplying the directory and name. This example takes the strings folderPath and
fileName created in the previous example, combines them, and displays the result.

VB
Dim fullPath As String
fullPath = My.Computer.FileSystem.CombinePath(folderPath, fileName)
MsgBox(fullPath)

See Also
Tasks
How to: Get the Collection of Files in a Directory in Visual Basic
How to: Determine the Absolute Path of a File in Visual Basic
How to: Get Information About a File in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.CombinePath Method
My.Computer.FileSystem.GetFileInfo Method
FileInfo
Visual Basic Language Concepts

File, Directory, and Drive Properties in Visual Basic


This section contains topics about getting and setting file, directory, and drive properties.
In This Section
How to: Get Information About a File in Visual Basic
Demonstrates how to get information, such as last access time, about a file.
How to: Determine the Absolute Path of a File in Visual Basic
Demonstrates how to determine the absolute path of a file.
How to: Determine a File's Extension in Visual Basic
Demonstrates how to determine the extension of a file.
How to: Determine a File's Last Accessed Time in Visual Basic
Demonstrates how to determine the last time a file was accessed.
How to: Determine a File's Last Modified Time in Visual Basic
Demonstrates how to determine the last time a file was modified.
How to: Determine a File's Size in Visual Basic
Demonstrates how to determine a file's size in bytes.
How to: Determine a File's Creation Time in Visual Basic
Demonstrates how to determine when a file was created.
How to: Determine if a File is Hidden in Visual Basic
Demonstrates how to determine if a file is hidden.
How to: Determine if a File is Read-only in Visual Basic
Demonstrates how to determine if a file is read-only.
How to: Determine a File's Attributes in Visual Basic
Demonstrates how to determine a file's attributes.
How to: Determine a Directory's Creation Time in Visual Basic
Demonstrates how to determine when a directory was created.
How to: Determine if a Directory is Read-Only in Visual Basic
Demonstrates how to determine whether a directory is read-only.
How to: Determine a Directory's Attributes in Visual Basic
Demonstrates how to determine a directory's attributes.
How to: Determine if a File Exists in Visual Basic
Demonstrates how to determine whether a file exists.
How to: Determine if a Directory Exists in Visual Basic
Demonstrates how to determine whether a directory exists.
How to: Determine a Drive's Volume Label in Visual Basic
Demonstrates how to determine a drive's volume label.
How to: Determine a Drive's Format in Visual Basic
Demonstrates how to determine a drive's file-system type.
How to: Determine a Drive's Type in Visual Basic
Demonstrates how to determine a drive's type.
Demonstrates how to determine a drive's type.
How to: Determine a Drive's Total Space in Visual Basic
Demonstrates how to determine a drive's total space.
How to: Determine a Drive's Physical Free Space in Visual Basic
Demonstrates how to determine a drive's physical free space.
How to: Determine a Drive's Root Directory in Visual Basic
Demonstrates how to determine a drive's root directory.
How to: Determine the Windows System Directory in Visual Basic
Demonstrates how to determine the location of the Windows System directory.
Reference
My.Computer.FileSystem Object
Describes the My.Computer.FileSystem object and its methods and properties.
My.Computer.FileSystem.DirectoryExists Method
Describes the DirectoryExists method.
My.Computer.FileSystem.FileExists Method
Describes the FileExists method.
My.Computer.FileSystem.GetDirectoryInfo Method
Describes the GetDirectoryInfo method.
My.Computer.FileSystem.GetFileInfo Method
Describes the GetFileInfo method.
My.Computer.FileSystem.GetParentPath Method
Describes the GetParentPath method.
Related Sections
FileInfo
Describes the FileInfo object.
DirectoryInfo
Describes the DirectoryInfo object.
FileAttributes
Describes the FileAttributes enumeration.
Writing to Files in Visual Basic
Lists tasks involving writing to files.
Reading from Files in Visual Basic
Lists tasks involving reading from files.
Creating, Deleting, and Moving Files and Directories in Visual Basic
Lists tasks involving creating, deleting, and moving directories and files.
Visual Basic Language Concepts

How to: Get Information About a File in Visual Basic


The My.Computer.FileSystem.GetFileInfo Method can be used to easily determine information about a file's properties.
Properties of the FileInfo object include attributes, creation time, directory, directory name, whether it exists, extension, full
name, last access time, last write time, length, and name.
An exception is not thrown if the file does not exist; rather, it is thrown the first time the object's properties are accessed.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help, depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

Procedure
To get information about a file
1. Use the GetFileInfo method to retrieve a FileInfo object that can be examined to determine its properties. The following
example retrieves a FileInfo object for the file MyLogFile.log.
VB
Dim information As System.IO.FileInfo
information = My.Computer.FileSystem.GetFileInfo("C:\MyLogFile.log")

2. Examine the FileInfo object to extract the information you need. The following lines of code report the file's full name,
last access time, and length.
VB
MsgBox("The file's full name is " & information.FullName & ".")
MsgBox("Last access time is " & information.LastAccessTime & ".")
MsgBox("The length is " & information.Length & ".")

Robust Programming
The following conditions may cause an exception:
The path name is malformed. For example, it contains invalid characters or is only white space (ArgumentException).
The file does not exist or is Nothing (ArgumentNullException).
The path contains a colon in the middle of the string (NotSupportedException).
The path is too long (PathTooLongException).
The user lacks necessary permissions (SecurityException).
The user lacks ACL (access control list) access to the file (UnauthorizedAccessException).
See Also
Tasks
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
FileInfo
Other Resources
File Access with Visual Basic
Visual Basic Language Concepts

How to: Determine the Absolute Path of a File in Visual Basic


The My.Computer.FileSystem.GetFileInfo Method returns a FileInfo object that can be used to determine information about a
file, including its location, which is contained in the FullName property.
If a file does not exist, GetFileInfo does not throw an exception, but one is thrown the first time a property on the
System.IO.FileInfo object is accessed.
Procedure
To determine the absolute path of a file
Use the GetFileInfo method to return a FileInfo object for the file you wish to examine. The FullName property
contains the absolute path. The following example determines the absolute path of Test.txt and displays it in a message
box.
VB
Dim getInfo As System.IO.FileInfo
getInfo = My.Computer.FileSystem.GetFileInfo("C:\TestFolder1\test.txt")
MsgBox(getInfo.FullName)

Robust Programming
The following conditions may cause an exception:
The path name is malformed. For example, it contains invalid characters or is only white space (ArgumentException).
The file does not exist or is Nothing (ArgumentNullException).
The path contains a colon in the middle of the string (NotSupportedException).
The path is too long (PathTooLongException).
The user lacks necessary permissions (SecurityException).
The user lacks ACL (access control list) access to the file (UnauthorizedAccessException).
See Also
Tasks
How to: Parse File Paths in Visual Basic
Reference
My.Computer.FileSystem.GetFileInfo Method
FileInfo
Visual Basic Language Concepts

How to: Determine a File's Extension in Visual Basic


The My.Computer.FileSystem.GetFiles Method returns the names of files as a read-only collection of strings, which can be
parsed with the Split Function (Visual Basic).
To determine a file's extension
Retrieve the file path or name of the file and the Split function to determine the extension by supplying the delimiter.
This example uses the GetFiles method to return the collection of file names in the directory testDirectory and reports
each file's extension.
VB
For Each foundFile As String In _
My.Computer.FileSystem.GetFiles("C:\TestDir")
Dim check As String = _
System.IO.Path.GetExtension(foundFile)
MsgBox("The file extension is " & check)
Next

See Also
Tasks
How to: Search for a String in an Array of Strings (Visual Basic)
How to: Parse File Paths in Visual Basic
Reference
My.Computer.FileSystem.GetFiles Method
Path
Visual Basic Language Concepts

How to: Determine a File's Last Accessed Time in Visual Basic


The My.Computer.FileSystem.GetFileInfo Method can be used to get a FileInfo object, which contains information about the
specified file.
You can use the LastAccessTime or the LastAccessTimeUtc property to get or set the last access time. LastAccessTimeUtc
displays the time in Coordinated Universal Time (UTC). For more information, see Date and Time Format Strings.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is de
scribed in Help, depending on your active settings or edition. This Help page was written with General Development Settin
gs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To determine a file's last accessed time


Use the GetFileInfo method to return a FileInfo object for the file, which can be queried for information. This example
gets a FileInfo object for Testfile.txt and uses the LastAccessTime property to display the last access time.
VB
Dim infoReader As System.IO.FileInfo
infoReader = My.Computer.FileSystem.GetFileInfo("C:\testfile.txt")
MsgBox("File was last accessed on " & infoReader.LastAccessTime)

See Also
Tasks
How to: Determine a File's Attributes in Visual Basic
How to: Determine a File's Creation Time in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.GetFileInfo Method
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts

How to: Determine a File's Last Modified Time in Visual Basic


The My.Computer.FileSystem.GetFileInfo Method can be used to get a FileInfo object, which contains information about the
specified file.
You can use the LastWriteTime or the LastWriteTimeUtc property to get or set the last time the file was modified.
LastWriteTimeUtc displays the time in Coordinated Universal Time (UTC). For more information, see
Date and Time Format Strings.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help, depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To determine a file's last modified time


Use the GetFileInfo method to return a FileInfo object for the file, which can be queried for information. This example
gets a FileInfo object for Testfile.txt and uses the LastWriteTime property to display the last access time.
VB
Dim infoReader As System.IO.FileInfo
infoReader = My.Computer.FileSystem.GetFileInfo("C:\testfile.txt")
MsgBox("File was last modified on " & infoReader.LastWriteTime)

See Also
Tasks
How to: Determine a File's Attributes in Visual Basic
How to: Determine a File's Creation Time in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.GetFileInfo Method
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts

How to: Determine a File's Size in Visual Basic


The My.Computer.FileSystem.GetFileInfo Method can be used to get a FileInfo object, which contains information about the
specified file.
You can use the Length property to determine the size of the file in bytes.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is de
scribed in Help, depending on your active settings or edition. This Help page was written with General Development Settin
gs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To determine a file's size


Use the GetFileInfo method to return a FileInfo object for the file, which can be queried for information. This example
gets a FileInfo object for Testfile.txt and uses the Length property to display the size of the file in bytes.
VB
Dim infoReader As System.IO.FileInfo
infoReader = My.Computer.FileSystem.GetFileInfo("C:\testfile.txt")
MsgBox("File is " & infoReader.Length & " bytes.")

See Also
Tasks
How to: Determine a File's Attributes in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.GetFileInfo Method
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts

How to: Determine a File's Creation Time in Visual Basic


The My.Computer.FileSystem.GetFileInfo Method can be used to get a FileInfo object, which contains information about the
specified file.
You can use the CreationTime or the CreationTimeUtc property to get or set the last access time. CreationTimeUtc
displays the time in Coordinated Universal Time (UTC). For more information, see Date and Time Format Strings.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help, depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To determine a file's creation time


Use the GetFileInfo method to return a FileInfo object for the file, which can be queried for information. This example
gets a FileInfo object for Testfile.txt and uses the CreationTime property to display the creation time.
VB
Dim infoReader As System.IO.FileInfo
infoReader = My.Computer.FileSystem.GetFileInfo("C:\testfile.txt")
MsgBox("File was created on " & infoReader.CreationTime)

See Also
Tasks
How to: Determine a File's Attributes in Visual Basic
How to: Determine a File's Last Accessed Time in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.GetFileInfo Method
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts

How to: Determine if a File is Hidden in Visual Basic


The My.Computer.FileSystem.GetFileInfo Method can be used to get a FileInfo object, which contains information about the
specified file, including a FileAttributes enumeration.
To determine if a file is hidden
1. Get a FileInfo object for the file you wish to examine. This example gets a FileInfo object for the file Testfile.txt.
VB
Dim infoReader As System.IO.FileInfo
infoReader = My.Computer.FileSystem.GetFileInfo("C:\testfile.txt")

2. Get a FileAttributes object from the FileInfo object. This example gets FileAttributes from the FileInfo object.
VB
Dim attributeReader As System.IO.FileAttributes
attributeReader = infoReader.Attributes

3. Query FileAttributes to determine if the file is hidden. This example determines if the file is hidden and displays a result
accordingly.
VB
If (attributeReader And System.IO.FileAttributes.Hidden) > 0 Then
MsgBox("File is hidden!")
Else
MsgBox("File is not hidden!")
End If

See Also
Tasks
How to: Determine a File's Attributes in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem Object Members
My.Computer.FileSystem.GetFileInfo Method
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts

How to: Determine if a File is Read-only in Visual Basic


The My.Computer.FileSystem.GetFileInfo Method can be used to get a FileInfo object, which contains information about the
specified file.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help, depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To determine if a file is read-only


Use the GetFileInfo method to return a FileInfo object for the file, which can be queried for information. This example
gets a FileInfo object for Testfile.txt and displays the appropriate message if the IsReadOnly property is set to True.
VB
Dim infoReader As System.IO.FileInfo
infoReader = My.Computer.FileSystem.GetFileInfo("C:\testfile.txt")
If infoReader.IsReadOnly = True Then
MsgBox("File is readonly!")
End If

See Also
Tasks
How to: Determine if a Directory is Read-Only in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.GetFileInfo Method
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts

How to: Determine a File's Attributes in Visual Basic


The My.Computer.FileSystem.GetFileInfo Method can be used to get a FileInfo object, which contains information about the
specified file, including a FileAttributes enumeration.
This table shows the members of FileAttributes.
Member Description
Archive The file's archive status. Applications use this attribute to mark files for backup or removal.

Compressed The file is compressed.

Device This member is not used at this time.

Directory The file is a directory.

Encrypted All of the data in the file is encrypted.

Hidden The file is hidden and will not be displayed in an ordinary directory listing.

Normal The file has no other attributes set.

NotContentIndexed The file will not be indexed by the operating system's content indexing service.

Offline The file is offline. The data in the file is not immediately available.

ReadOnly The file is read-only.

ReparsePoint The file contains a reparse point, which is a block of user-defined data.

SparseFile The file is a sparse file. Sparse files are usually large files containing data that is mostly zeroes.

System The file is a system file. The file is part of the operating system or is used exclusively by the operating syste
m.

Temporary The file is temporary. File systems attempt to keep all of the data in memory for quicker access, rather tha
n flushing the data back to mass storage. A temporary file should be deleted by the application as soon as
it is no longer needed.

To determine if a file is encrypted


1. Get a FileInfo object for the file you wish to examine. This example gets a FileInfo object for the file Testfile.txt.
VB
Dim infoReader As System.IO.FileInfo
infoReader = My.Computer.FileSystem.GetFileInfo("C:\testfile.txt")

2. Get a FileAttributes object from the FileInfo object. This example gets FileAttributes from the FileInfo object.
VB
Dim attributeReader As System.IO.FileAttributes
attributeReader = infoReader.Attributes
3. Query FileAttributes. This example determines if the file is encrypted and displays a result accordingly.
VB
If (attributeReader And System.IO.FileAttributes.Encrypted) > 0 Then
MsgBox("File is encrypted!")
Else
MsgBox("File is not encrypted!")
End If

See Also
Tasks
How to: Determine if a File is Hidden in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.GetFileInfo Method
FileAttributes
FileInfo
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts

How to: Determine a Directory's Creation Time in Visual Basic


The My.Computer.FileSystem.GetDirectoryInfo Method returns a DirectoryInfo object that can be queried for information about
the directory.
If the directory does not exist, an exception is not thrown until the first time a property on the DirectoryInfo object is accessed.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help, depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To determine a directory's creation time


Use the GetDirectoryInfo method to retrieve a DirectoryInfo object for the directory, and query the CreationTime
property. This example displays CreationTime for C:\Documents and Settings.
VB
Dim getInfo As System.IO.DirectoryInfo
getInfo = My.Computer.FileSystem.GetDirectoryInfo _
("C:\Documents and Settings")
MsgBox("The directory was created at " & getInfo.CreationTime)

Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks the necessary permissions to view the path (SecurityException).
See Also
Tasks
How to: Determine if a Directory Exists in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
Reference
My.Computer.FileSystem.GetDirectoryInfo Method
DirectoryInfo
CreationTime
Visual Basic Language Concepts

How to: Determine if a Directory is Read-Only in Visual Basic


The My.Computer.FileSystem.GetDirectoryInfo Method method returns a DirectoryInfo object with a Attributes property that
can be queried to determine information about the directory, including whether it is read-only.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help, depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To determine if a directory is read-only


1. Use the GetDirectoryInfo method to return a DirectoryInfo object for the specified directory. This example returns a
DirectoryInfo object for the directory TestDirectory.
VB
Dim reader As System.IO.DirectoryInfo
reader = My.Computer.FileSystem.GetDirectoryInfo("C:\testDirectory")

2. Query the Attributes property of the object to determine whether it is read-only.


VB
If (reader.Attributes And System.IO.FileAttributes.ReadOnly) > 0 Then
MsgBox("Directory is readonly!")
End If

Example
The following example, which presents the above snippet in complete form, determines whether the directory testDirectory
is read-only and reports the result in a message box.
VB
Dim reader As System.IO.DirectoryInfo
reader = My.Computer.FileSystem.GetDirectoryInfo("C:\testDirectory")
If (reader.Attributes And System.IO.FileAttributes.ReadOnly) > 0 Then
MsgBox("File is readonly!")
End If

Compiling the Code


If the directory does not exist, an exception is not thrown until the first time a property on the DirectoryInfo object is accessed.
Robust Programming
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
See Also
Tasks
How to: Determine a Directory's Attributes in Visual Basic
Reference
My.Computer.FileSystem.GetDirectoryInfo Method
Visual Basic Language Concepts

How to: Determine a Directory's Attributes in Visual Basic


The My.Computer.FileSystem.GetDirectoryInfo Method method returns a DirectoryInfo object whose Attributes property can
be queried to determine information about the directory.
The following table lists the members of the FileAttributes enumeration used by the Attributes property.
Member Numeri Description
c Value
ReadOnly 1 The file is read-only.

Hidden 2 The file is hidden and therefore not included in an ordinary directory listing.

System 4 The file is a system file. The file is part of the operating system or used exclusively by the operatin
g system.

Directory 16 The file is a directory.

Archive 32 The file's archive status. Applications use this attribute to mark files for backup or removal.

Device 64 Not used.

Normal 128 The file is normal and no other attributes are set. This attribute is valid only if used alone.

Temporary 256 The file is temporary. File systems attempt to keep all of the data in memory for quicker access. A
temporary file should be deleted when it is no longer needed.

SparseFile 512 The file is a sparse file. Sparse files are typically large files containing data that is mostly zeroes.

ReparsePoint 1024 The file contains a reparse point, which is a block of user-defined data associated with a file or dir
ectory.

Compressed 2048 The file is compressed.

Offline 4096 The file is offline and the data is not immediately available.

NotContentIndexed 8192 The file will not be indexed by the operating system's content indexing service.

Encrypted 16384 The file or directory is encrypted. For files, this means that all data in the file is encrypted. For dire
ctories, this means that encryption is the default for newly created files and directories.

To determine if a directory is hidden


Use the GetDirectoryInfo method to return a DirectoryInfo object. This example returns DirectoryInfo for the
directory TestDir, gets a FileAttributes object from the DirectoryInfo object and checks it to determine whether or not
it is hidden. You can test for other attributes in a similar manner.
VB
Dim checkFile As System.IO.DirectoryInfo
checkFile = My.Computer.FileSystem.GetDirectoryInfo("C:\TestDir")
Dim attributeReader As System.IO.FileAttributes
attributeReader = checkFile.Attributes

If (attributeReader And System.IO.FileAttributes.Hidden) > 0 Then


MsgBox("Directory is hidden")
End If

See Also
Tasks
How to: Determine a File's Attributes in Visual Basic
Reference
My.Computer.FileSystem.GetDirectoryInfo Method
DirectoryInfo
FileAttributes
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts

How to: Determine if a File Exists in Visual Basic


You can use the My.Computer.FileSystem.FileExists Method to determine whether or not a specified file exists.
If the application does not have sufficient permissions to read the specified file, the FileExists method returns False regardless
of the existence of path; the method does not throw an exception.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help, depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

Procedure
To determine if a file exists
Use the My.Computer.FileSystem.FileExists method, supplying the path, to determine whether or not the specified file
exists. The following example checks to see whether or not the file Check.txt exists and supplies the information in a
message box.
VB
If My.Computer.FileSystem.FileExists("c://Check.txt") Then
MsgBox("File found.")
Else
MsgBox("File not found.")
End If

See Also
Tasks
How to: Determine if a Directory Exists in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
My.Computer.FileSystem.FileExists Method
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Concepts

How to: Determine if a Directory Exists in Visual Basic


You can use the My.Computer.FileSystem.DirectoryExists Method to determine whether or not a specified directory exists.
The call to DirectoryExists requires FileIOPermission.
This method throws no exceptions.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help, depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

Procedure
To determine if a directory exists
Use the My.Computer.FileSystem.DirectoryExists method, supplying the path, to determine whether or not the
specified directory exists. The following example checks to determine whether or not the directory C:\backup\logs exists
and checks its properties.
VB
Dim logDirectoryProperties As System.IO.DirectoryInfo
If My.Computer.FileSystem.DirectoryExists("C:\backup\logs") Then
logDirectoryProperties = My.Computer.FileSystem.GetDirectoryInfo("C:\backup\logs")
End If

See Also
Tasks
How to: Determine if a File Exists in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
My.Computer.FileSystem.DirectoryExists Method
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Concepts

How to: Determine a Drive's Volume Label in Visual Basic


The My.Computer.FileSystem.GetDriveInfo Method provides a DriveInfo object that can be queried for information about a
drive on a computer. You can use the VolumeLabel property to determine the drive label. Attempting to access the property
without sufficient permission throws a SecurityException exception.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help, depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To determine a drive's volume label


Use the VolumeLabel property to determine the drive label, as illustrated in the following code.
VB
Dim cdrive As System.IO.DriveInfo
cdrive = My.Computer.FileSystem.GetDriveInfo("C:\")
MsgBox(cdrive.VolumeLabel)

See Also
Tasks
How to: Determine a Drive's Total Space in Visual Basic
How to: Determine a Drive's Format in Visual Basic
How to: Determine a Drive's Type in Visual Basic
Reference
My.Computer.FileSystem.GetDriveInfo Method
Visual Basic Language Concepts

How to: Determine a Drive's Format in Visual Basic


The My.Computer.FileSystem.GetDriveInfo Method provides a DriveInfo object that can be queried for information about a
drive on a computer. You can use the DriveFormat property to determine the drive format. Attempting to access the property
without sufficient permission throws a SecurityException exception.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help, depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To determine a drive's format


Use the DriveFormat property to determine the drive format, as illustrated in the following code.
VB
Dim cdrive As System.IO.DriveInfo
cdrive = My.Computer.FileSystem.GetDriveInfo("C:\")
MsgBox(cdrive.DriveFormat)

See Also
Tasks
How to: Determine a Drive's Total Space in Visual Basic
How to: Determine a Drive's Volume Label in Visual Basic
How to: Determine a Drive's Type in Visual Basic
Reference
My.Computer.FileSystem.GetDriveInfo Method
Visual Basic Language Concepts

How to: Determine a Drive's Type in Visual Basic


The My.Computer.FileSystem.GetDriveInfo Method provides a DriveInfo object that can be queried for information about a
drive on a computer. You can use the DriveType property to determine the drive's type. Attempting to access the property
without sufficient permission throws a SecurityException exception.
The following table shows the members of the DriveType enumeration.
Member Valu Description
e
Unknown 0 Drive type cannot be determined.

CDRom 1 Drive is a CD-ROM. No distinction is made between read-only and read/write CD-ROM drives.

DVDRom 2 Drive is a DVD-ROM.

Fixed 3 Drive has fixed (nonremovable) media. This value includes all hard drives, even hard drives that are remova
ble.

RamDisk 4 Drive is a block of Random Access Memory (RAM) on the local computer that behaves like a disk drive.

Remote 5 Network drives. This includes drives shared anywhere on a network.

Removabl 6 Drive has removable media. This includes all floppy drives.
e

To determine the type of a drive


Use the DriveType property to determine the type, as illustrated in the following code.
VB
Dim cdrive As System.IO.DriveInfo
cdrive = My.Computer.FileSystem.GetDriveInfo("C:\")
MsgBox(cdrive.DriveType.ToString)

See Also
Tasks
How to: Determine a Drive's Total Space in Visual Basic
How to: Determine a Drive's Volume Label in Visual Basic
Reference
My.Computer.FileSystem.GetDriveInfo Method
DriveInfo
Visual Basic Language Concepts

How to: Determine a Drive's Total Space in Visual Basic


The My.Computer.FileSystem.GetDriveInfo Method provides a DriveInfo object that can be queried for information about a
drive on a computer. You can use the TotalSize property to determine the amount of space on a drive. Attempting to access
the property without sufficient permission will throw a SecurityException exception.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help, depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To determine the total amount of disk space on a drive


Use the TotalSize property to determine the total amount of space on the drive, as illustrated in the following code:
VB
Dim cdrive As System.IO.DriveInfo
cdrive = My.Computer.FileSystem.GetDriveInfo("C:\")
MsgBox(cdrive.TotalSize)

See Also
Tasks
How to: Determine a Drive's Physical Free Space in Visual Basic
How to: Determine a Drive's Volume Label in Visual Basic
How to: Determine a Drive's Type in Visual Basic
Reference
My.Computer.FileSystem.GetDriveInfo Method
DriveInfo
Visual Basic Language Concepts

How to: Determine a Drive's Physical Free Space in Visual Basic


The My.Computer.FileSystem.GetDriveInfo Method provides a DriveInfo object that can be queried for information about a
drive on a computer. You can use the TotalFreeSpace property to determine the amount of space on a drive. Attempting to
access the property without sufficient permission throws a SecurityException exception.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help, depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To determine the amount of free space on a drive


Use the TotalFreeSpace property to determine the amount of free space, as illustrated in the following code:
VB
Dim cdrive As System.IO.DriveInfo
cdrive = My.Computer.FileSystem.GetDriveInfo("C:\")
MsgBox("Total free space: " & CStr(cdrive.TotalFreeSpace))

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in File system
- Processing Drives, Folders, and Files. For more information, see
How to: Insert Snippets Into Your Code (Visual Basic).
See Also
Tasks
How to: Determine a Drive's Total Space in Visual Basic
How to: Determine a Drive's Format in Visual Basic
How to: Determine a Drive's Type in Visual Basic
Reference
My.Computer.FileSystem.GetDriveInfo Method
DriveInfo
Visual Basic Language Concepts

How to: Determine a Drive's Root Directory in Visual Basic


The My.Computer.FileSystem.GetDriveInfo Method provides a DriveInfo object that can be queried for information about a
drive on a computer. You can use the RootDirectory property to determine the root directory. Attempting to access the
property without sufficient permission throws a SecurityException exception.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help, depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To determine a drive's root directory


Use the RootDirectory property to determine the root directory, as illustrated in the following code.
VB
Dim cdrive As System.IO.DriveInfo
cdrive = My.Computer.FileSystem.GetDriveInfo("C:\")
MsgBox(cdrive.RootDirectory)

See Also
Tasks
How to: Determine a Drive's Total Space in Visual Basic
How to: Determine a Drive's Type in Visual Basic
Reference
My.Computer.FileSystem.GetDriveInfo Method
DriveInfo
Visual Basic Language Concepts

How to: Determine the Windows System Directory in Visual


Basic
This example sets a string containing the path of the Windows System directory.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help, depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

Example
VB
Dim systemDirectory As String
systemDirectory = System.Environment.SystemDirectory

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows
Operating System > System Information. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
The property returns a value such as "c:\WINNT\System32".
Security
This code requires FileIOPermission Class.
See Also
Tasks
How to: Determine a Directory's Attributes in Visual Basic
Reference
Environment.GetFolderPath Method
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Concepts

Parsing Text Files with the TextFieldParser Object


The TextFieldParser object allows you to parse and process very large file that are structured as delimited-width columns of
text, such as log files or legacy database information. Parsing a text file with TextFieldParser is similar to iterating over a text
file, while the parse method to extract fields of text is similar to string manipulation methods used to tokenize delimited strings.
Parsing Different Types of Text Files
Text files may have fields of various width, delimited by a character such as a comma or a tab space. Define TextFieldType
and the delimiter, as in the following example, which uses the SetDelimiters method to define a tab-delimited text file:
VB
testReader.SetDelimiters(vbTab)

Other text files may have field widths that are fixed. In such cases, you need to define the TextFieldType as FixedWidth and
define the widths of each field, as in the following example. This example uses the SetFieldWidths method to define the
columns of text: the first column is 5 characters wide, the second is 10, the third is 11, and the fourth is of variable width.
VB
testReader.SetFieldWidths(5, 10, 11, -1)

Once the format is defined, you can loop through the file, using the ReadFields method to process each line in turn.
If a field does not match the specified format, a MalformedLineException exception is thrown. When such exceptions are
thrown, the ErrorLine and ErrorLineNumber properties hold the text causing the exception and the line number of that text..
Parsing Files with Multiple Formats
The PeekChars method of the TextFieldParser object can be used to check each field before reading it, allowing you to define
multiple formats for the fields and react accordingly. For more information, see
How to: Read From Text Files with Multiple Formats in Visual Basic.
See Also
Tasks
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
My.Computer.FileSystem.OpenTextFieldParser Method
TextFieldParser Object
TextFieldParser.PeekChars Method
TextFieldParser.ReadFields Method
TextFieldParser.CommentTokens Property
TextFieldParser.Delimiters Property
TextFieldParser.ErrorLine Property
TextFieldParser.ErrorLineNumber Property
TextFieldParser.FieldWidths Property
TextFieldParser.HasFieldsEnclosedInQuotes Property
TextFieldParser.LineNumber Property
TextFieldParser.TextFieldType Property
TextFieldParser.TrimWhiteSpace Property
TextFieldParser.SetDelimiters Method
TextFieldParser.SetFieldWidths Method
Visual Basic Language Concepts

File Encodings
File encodings, also known as character encodings, specify how to represent characters when text processing. One encoding
may be preferable over another in terms of which language characters it can or cannot handle, although Unicode is usually
preferred.
When reading from or writing to files, improperly matching file encodings may result in exceptions or incorrect results.
Types of Encodings
Unicode is the preferred encoding when working with files. Unicode is a worldwide character-encoding standard that uses 16-
bit code values to represent all the characters used in modern computing, including technical symbols and special characters
used in publishing.
Previous character-encoding standards consisted of traditional character sets, such as the Windows ANSI character set that
uses 8-bit code values, or combinations of 8-bit values, to represent the characters used in a specific language or geographical
region.
Encoding Class
The Encoding class represents a character encoding. This table lists the type of encodings available and describes each.
Name Description
ASCIIEncoding Represents an ASCII character encoding of Unicode characters.

UnicodeEncoding Represents a UTF-16 encoding of Unicode characters.

UTF32Encoding Represents a UTF-32 encoding of Unicode characters.

UTF7Encoding Represents a UTF-7 encoding of Unicode characters.

UTF8Encoding Represents a UTF-8 encoding of Unicode characters.

See Also
Other Resources
Reading from Files in Visual Basic
Writing to Files in Visual Basic
Visual Basic Language Concepts

Troubleshooting: Reading from and Writing to Text Files


This topic discusses common problems encountered when working with text files and suggests an approach to each.
Common Problems
The most common issues encountered when working with text files include security exceptions, file encodings, or invalid paths.
Security Exceptions
A SecurityException is thrown when a security error occurs. This is often a result of the user lacking necessary permissions,
which may be solved by adding permissions or working with files in isolated storage. For more information, see
Troubleshooting Exceptions: System.Security.SecurityException and Isolated Storage.
File Encodings
File encodings, also known as character encodings, specify how to represent characters when text processing. Unexpected
characters in a text file may result from incorrect encoding. For most files, one encoding may be preferable over another in
terms of which language characters it can or cannot handle, although Unicode is usually preferred. For more information, see
File Encodings and Encoding.
Incorrect Paths
When parsing file paths, particularly relative paths, it is easy to supply the wrong data. Many problems can be corrected by
making sure you are supplying the correct path. For more information, see How to: Parse File Paths in Visual Basic.
See Also
Reference
My.Computer.FileSystem Object
Concepts
Parsing Text Files with the TextFieldParser Object
Other Resources
Reading from Files in Visual Basic
Writing to Files in Visual Basic
Visual Basic Language Concepts

Walkthrough: Manipulating Files Using .NET Framework


Methods
This walkthrough demonstrates how to open and read a file using the StreamReader class, check to see if a file is being
accessed, search for a string within a file read with an instance of the StreamReader class, and write to a file using the
StreamWriter class.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

Creating the Application


Start Visual Studio and begin the project by creating a form that the user can use to write to the designated file.
To create the project
1. On the File menu, select New Project.
2. In the New Project pane, click Windows Application.
3. In the Name box type MyDiary and click OK.
Visual Studio adds the project to Solution Explorer, and the Windows Forms Designer opens.
4. Add the controls in the following table to the form and set the corresponding values for their properties.
Object Properties Value
Button Name Submit
Text Submit Entry

Button Name Clear


Text Clear Entry

TextBox Name Entry


Text Please enter something.
Multiline False

Writing to the File


To add the ability to write to a file via the application, use the StreamWriter class. StreamWriter is designed for character
output in a particular encoding, whereas the Stream class is designed for byte input and output. Use StreamWriter for writing
lines of information to a standard text file. For more information on the StreamWriter class, see StreamWriter Class.
To add writing functionality
1. From the View menu, choose Code to open the Code Editor.
2. Because the application references the System.IO namespace, add the following statements at the very beginning of your
code, before the class declaration for the form, which begins Public Class Form1.
VB
Imports System
Imports System.IO
Before writing to the file, you must create an instance of a StreamWriter class.
3. From the View menu, choose Designer to return to the Windows Forms Designer. Double-click the Submit button to
create a Click event handler for the button, and then add the following code.
VB
Dim fw As StreamWriter

Note
The Visual Studio Integrated Development Environment (IDE) will return to the Code Editor and position the insertion point
within the event handler where you should add the code.

1. To write to the file, use the Write method of the StreamWriter class. Add the following code directly after Dim fw As
StreamWriter. You do not need to worry that an exception will be thrown if the file is not found, because it will be created
if it does not already exist.
VB
Dim ReadString As String
Try
'Pass the file path and name to the StreamWriter constructor.
'Indicate that Append is True, so file will not be overwritten.
fw = New StreamWriter("C:\MyDiary.txt", True)
ReadString = Entry.Text
fw.WriteLine(ReadString)
Finally
'Close the file.
fw.Close()
End Try

2. Make sure that the user cannot submit a blank entry by adding the following code directly after Dim ReadString As
String.

VB
If (Entry.Text = "" Or Entry.Text = "Please enter something.") Then
Entry.Text = "Please enter something."
Return
End If

3. Because this is a diary, the user will want to assign a date to each entry. Insert the following code after fw = New
StreamWriter("C:\MyDiary.txt", True) to set the variable Today to the current date.

VB
Dim Today As DateTime
Today = Now
fw.Write(CStr(Today))
fw.Write(ControlChars.CrLf)

4. Finally, attach code to clear the TextBox. Add the following code to the Clear button's Click event.
VB
Entry.Text = ""

Adding Display Features to the Diary


In this section, you add a feature that displays the latest entry in the DisplayEntry TextBox. You can also add a ComboBox
that displays various entries and from which a user can select an entry to display in the DisplayEntry TextBox. An instance of
the StreamReader class reads from MyDiary.txt. Like the StreamWriter class, StreamReader is intended for use with text
files.
For this section of the walkthrough, add the controls in the following table to the form and set the corresponding values for
their properties.
Control Properties Values
TextBox Name DisplayEntry
Visible False
Size 120,60
Multiline True

Button Name Display


Text Display

Button Name GetEntries


Text Get Entries

ComboBox Name PickEntries


Text Select an Entry
Enabled False

To populate the combo box


1. The PickEntries ComboBox is used to display the dates on which a user submits each entry, so the user can select an
entry from a specific date. Create a Click event handler to the GetEntries button and add the following code.
VB
Dim fr As StreamReader
Dim FileString As String
FileString = ""
Try
fr = New System.IO.StreamReader("C:\MyDiary.txt")
PickEntries.Items.Clear()
PickEntries.Enabled = True
Do
FileString = fr.ReadLine
If IsDate(FileString) Then
PickEntries.Items.Add(FileString)
End If
Loop Until (FileString Is Nothing)
Finally
If fr IsNot Nothing Then
fr.Close()
End If
End Try
PickEntries.Enabled = True
2. To test your code, press F5 to compile the application, and then click Get Entries. Click the drop-down arrow in the
ComboBox to display the entry dates.

To choose and display individual entries


1. Create a Click event handler for the Display button and add the following code.
VB
Dim fr As StreamReader
Dim ReadString As String
'Make sure ReadString begins empty.
ReadString = ""
Dim FileString As String
fr = New StreamReader("C:\MyDiary.txt")
'If no entry has been selected, show the whole file.
If PickEntries.Enabled = False Or PickEntries.SelectedText Is Nothing Then
Do
'Read a line from the file into FileString.
FileString = fr.ReadLine
'add it to ReadString
ReadString = ReadString & ControlChars.CrLf & FileString
Loop Until (FileString = Nothing)
Else
'An entry has been selected, find the line that matches.
Do

FileString = fr.ReadLine
Loop Until FileString = CStr(PickEntries.SelectedItem)
FileString = CStr(PickEntries.SelectedItem) & ControlChars.CrLf
ReadString = FileString & fr.ReadLine

'Read from the file until EOF or another Date is found.


Do Until ((fr.Peek < 0) Or (IsDate(fr.ReadLine)))
ReadString = ReadString & fr.ReadLine
Loop
End If
fr.Close()
DisplayEntry.Visible = True
DisplayEntry.Text = ReadString

2. To test your code, press F5 to compile the application, and then submit an entry. Click Get Entries, select an entry from
the ComboBox, and then click Display. The contents of the selected entry appear in the DisplayEntry TextBox.
Enabling Users to Delete or Modify Entries
Finally, you can include additional functionality enables users to delete or modify an entry by using DeleteEntry and
EditEntry buttons. Both buttons remain disabled unless an entry is displayed.

Add the controls in the following table to the form and set the corresponding values for their properties.
Control Properties Values
Button Name DeleteEntry
Text Delete Entry
Enabled False
Button Name EditEntry
Text Edit Entry
Enabled False

Button Name SubmitEdit


Text Submit Edit
Enabled False

To enable deletion and modification of entries


1. Add the following code to the Display button's Click event, after DisplayEntry.Text = ReadString.

VB
DeleteEntry.enabled = True

2. Create a Click event handler for the DeleteEntry button and add the following code.
VB
Dim fr As StreamReader
Dim ReadString As String
Dim WriteString As String
Dim ConfirmDelete As MsgBoxResult
fr = New StreamReader("C:\MyDiary.txt")
ReadString = fr.ReadLine
' Read through the textfile
Do Until (fr.Peek < 0)
ReadString = ReadString & vbCrLf & fr.ReadLine
Loop
WriteString = Replace(ReadString, DisplayEntry.Text, "")
fr.Close()
' Check to make sure the user wishes to delete the entry
ConfirmDelete = MsgBox("Do you really wish to delete this entry?", _
MsgBoxStyle.OKCancel)
If ConfirmDelete = MsgBoxResult.OK Then
File.Delete("C:\MyDiary.txt")
Dim fw As StreamWriter = File.CreateText("C:\MyDiary.txt")
fw.WriteLine(WriteString)
fw.Close()
' Reset controls on the form
DisplayEntry.Text = ""
PickEntries.Text = ""
PickEntries.Items.Clear()
PickEntries.Enabled = False
DeleteEntry.Enabled = False
End If

3. When a user displays an entry, the EditEntry button becomes enabled. Add the following code to the Click event of the
Display button after DisplayEntry.Text = ReadString.

VB
EditEntry.Enabled = True
4. Create a Click event handler for the EditEntry button and add the following code.
VB
Entry.Text = DisplayEntry.Text
SubmitEdit.Enabled = True

5. Create a Click event handler for the SubmitEdit button and add the following code
VB
Dim fr As StreamReader
Dim ReadString As String
Dim WriteString As String
If Entry.Text = "" Then
MsgBox("Use Delete to Delete an Entry")
Return
End If
fr = New StreamReader("C:\MyDiary.txt")
ReadString = fr.ReadLine
Do Until (fr.Peek < 0)
ReadString = ReadString & vbCrLf & fr.ReadLine
Loop
WriteString = Replace(ReadString, DisplayEntry.Text, Entry.Text)
fr.Close()
File.Delete("C:\MyDiary.txt")
Dim fw As StreamWriter = File.CreateText("C:\MyDiary.txt")
fw.WriteLine(WriteString)
fw.Close()
DisplayEntry.Text = Entry.Text
Entry.Text = ""
EditEntry.Enabled = False
SubmitEdit.Enabled = False

To test your code, press F5 to compile the application. Click Get Entries, select an entry, and then click Display. The entry
appears in the DisplayEntry TextBox. Click Edit Entry. The entry appears in the Entry TextBox. Edit the entry in the Entry
TextBox and click Submit Edit. Open the MyDiary.txt file to confirm your correction. Now select an entry and click Delete
Entry. When the MessageBox requests confirmation, click OK. Close the application and open MyDiary.txt to confirm the
deletion.
See Also
Reference
StreamReader Class
StreamWriter Class
Other Resources
Visual Basic Language Walkthroughs
Visual Basic Language Concepts

Walkthrough: Manipulating Files and Directories in Visual


Basic
This walkthrough provides an introduction to the fundamentals of file I/O in Microsoft Visual Basic 2005. To illustrate the
features, it creates a small application, named FileExplorer, which examines text files within a directory and provides
information such as attributes, last access time, and the first 80 characters of the file. It also includes an option that writes the
information to a log file.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

Creating the Application


To begin the project, create a form from which users can select a directory, select a file from the directory, and then select the
information they want to retrieve about that file.
To create the project
1. On the File menu, click New Project.
The New Project dialog box appears.
2. In the Project Types pane, click Visual Basic Projects, and then click Windows Application in the Templates pane.
3. In the Name box, type FileExplorer to set the project name.
Visual Studio adds the project to Solution Explorer, and the Windows Forms Designer opens.
4. Add the controls in the following table to the form, and set the corresponding values for their properties.
Object Properties Value
TextBox Name txtDirectory
Text Directory

Button Name btnSubmit


Text Submit

Button Name btnExamine


Text Examine

ComboBox Name lstFilePick


Text Select A File

CheckBox Name chkFileLength


Text File Length
Checked True

CheckBox Name chkLastAccess


Text Last Access Time
Checked True
CheckBox Name chkSave
Text Save Results
Checked False

Displaying the Current Directory


The FileExplorer application needs a starting point. Accordingly, the txtDirectory TextBox uses the
My.Computer.FileSystem.CurrentDirectory function to return and display a string representing the current path.
To return the current directory
1. Create an event handler for Form1_Load by double-clicking the form.
The Code Editor opens.
2. Add the following code so that the txtDirectory TextBox displays the current location.
VB
txtDirectory.Text = My.Computer.FileSystem.CurrentDirectory

3. Run the program to verify that the correct path is returned.


The txtDirectory TextBox displays the current directory.
Changing Directories
Since a user may want to select files in a different directory, the application uses the same property to switch directories. To
change to a different directory, a user enters a new path in the txtDirectory TextBox.
To change directories
1. Create a click event handler for btnSubmit by double-clicking the control on the form.
The Code Editor opens.
2. Add the following code to the click event handler.
VB
Dim NewPath As String
' NewPath holds the path the user has entered.
NewPath = txtDirectory.Text
' Change the location to NewPath.
My.Computer.FileSystem.CurrentDirectory = NewPath

Verifying That a Valid Path Has Been Entered


Use a Try...Catch statement to catch exceptions that arise from the submission of a blank or invalid path.
To ensure valid paths
1. In the btnSubmit_Click event, after the code line Dim NewPath As String, add Dim ErrorMessage As String on a new
line.
2. Before the code line My.Computer.FileSystem.CurrentDirectory = NewPath add a Try statement on its own line as
follows. If you hit return, the Code Editor will automatically insert Catch ex As Exception and End Try statements.
Remove these; you will add your own in the next step.
VB
Try

3. After the code line My.Computer.FileSystem.CurrentDirectory = NewPath, add the following.

VB
' This checks to make sure the path is not blank.
Catch ex As Exception When NewPath = ""
ErrorMessage = "You must enter a path."
' This catches errors caused by a path that is not valid.
Catch
ErrorMessage = "You must enter a valid path. If trying " & _
"to access a different drive, remember to include the drive " & _
"letter."
Finally
' Display the error message only if one exists.
If ErrorMessage <> Nothing Then
MsgBox(ErrorMessage)
End If
End Try

Displaying the Contents of the Directory in a ComboBox


To enable the application to display the contents of the current directory, you can use the My.Computer.FileSystem.GetFiles
method, which returns a collection of strings representing the names of the files in the directory. You can use wildcards with
GetFiles to select only files of a particular pattern. In this example, only files with the extension .txt are returned.
To display directory contents
1. At the beginning of the btnSubmit_Click event, insert the following.
Dim fileList As System.Collections.ObjectModel.ReadOnlyCollection(Of String).

2. After the line End Try insert the following.

VB
fileList = My.Computer.FileSystem.GetFiles( _
My.Computer.FileSystem.CurrentDirectory, _
FileIO.SearchOption.SearchTopLevelOnly, "*.txt")
For Each foundFile As String In fileList
lstFilePick.Items.Add(foundFile)
Next

The gathered information appears in the lstFilePick ComboBox, from which you can pick a specific file to examine.
Test the application by running it first on a directory that contains no .txt files and then on one that contains more than one .txt
file. In the first instance, the application displays the appropriate error message. In the second, the application creates a list in
the ComboBox of all .txt files within the directory specified in the txtDirectory TextBox.
Enabling a User to Select a File to Examine
Although the lstFilePick ComboBox displays all files in a directory, a user probably wants to select and examine a specific
file.
To enable selection of a specific file
Create a click event handler for btnExamine_Click and add the following code to confirm a file's selection.
VB
Dim thisFile As System.IO.FileInfo
thisFile = My.Computer.FileSystem.GetFileInfo(CStr(lstFilePick.SelectedItem))

Enabling a User to Determine What Information to Gather


Now that files display in the lstFilePick ComboBox, additional code enables a user to specify the reported information. For
example, one user may merely want to know the date when the file was last accessed. Another user may also want to know a
file's size. A user selects or clears check boxes (chkLastAccess, chkFileLength) to customize the results.
To display specific information
1. Declare these variables at the beginning of the btnExamine_Click event after (lstFilePick.SelectedItem).
VB
Dim stringlength As String
stringLength = "The file's length, in bytes, is: "
Dim stringLastAccess As String
stringLastAccess = "The file was last accessed on: "
Dim LastAccess As Date
Dim Length As Long
Dim FirstLine As String = ""
Dim FinalString As String = ""
Dim NewName As String
NewName = CType(lstFilePick.SelectedItem, String)

If NewName = Nothing Then


MsgBox("You must select a file to examine.")
Exit Sub
End If

The My.Computer.FileSystem.GetFileInfo method returns a FileInfo object that can be queried to get information
about a file.
2. Add the following code to the end of the btnExamine_Click event.
VB
' Check last access time.
If chkLastAccess.Checked = True Then
LastAccess = thisFile.LastAccessTime
End If

The LastAccessTime property determines the last time the file was accessed. The returned Date value indicates the date and
time when the file was created or last modified.
1. Add the following code to the end of the btnExamine_Click event.
VB
' Check Length.
If chkFileLength.Checked = True Then
Length = thisFile.Length
End If
The Length property, which determines the length of the file, returns a Long value specifying the length of the file in bytes.
Displaying the Results
To complete the application's functionality, a MsgBox reports the gathered information.
To display the results
1. At the end of the If statement that determines whether or not the chkLastAccess CheckBox has been selected, add the
following before the final End If.
VB
' Add to the messagebox.
FinalString = FinalString & stringLastAccess & LastAccess & "." _
& vbCrLf

2. At the end of the If statement that determines whether or not the chkFileLength CheckBox has been selected, add the
following before the final End If.
VB
' Add to the messagebox.
FinalString = FinalString & stringlength & CStr(Length) & "." _
& vbCrLf

3. At the end of the If statement that determines whether or not the chkFirstLine CheckBox has been selected, add the
following before the final End If.
VB
' Add to the messagebox.
FinalString &= FirstLine & vbCrLf

Saving the Results


A user may want to save the results of an examination of a file. Accordingly, add code that checks to see if a log file exists,
creates one if necessary, and then writes the results to the log file.
To create a log file
Add the following to the end of the btnExamine_Click event.
VB
' Check to see if results should be saved.
If chkSave.Checked = True And FinalString <> "" Then
My.Computer.FileSystem.WriteAllText("log.txt", FinalString, True)
End If

To test your application


1. In the directory of your choice, create a text file named test.txt with the following first line:
"This is the first line of the first file. The FileExplorer application examines only text files."
2. In the same directory, create a second text file named test2.txt with the following first line:
"This is the first line of the second file. The FileExplorer application examines only text files."
3. Start the application.
4. Type an invalid path and click Submit.
The following message appears: "You must enter a valid path. If trying to access a different drive, remember to include
the drive letter."
5. Type the path to the directory that stores test.txt and click Submit.
The lstFilePick ComboBox displays the text files.
6. Select test.txt in the lstFilePick ComboBox. Make sure all of the check boxes are selected, and then click Examine.
The results form includes the last access date and the length.
7. Select test2.txt in the lstFilePick ComboBox, clear all check boxes, and then click Examine.
The following error message appears: "No file attribute checkboxes selected."
8. Select Last Access and Save Results and click Examine.
The results form displays only the last access time.
9. Close FileExplorer.
Because you checked the Save Results option, FileExplorer generates a log file named log.txt in the same directory as
the text files.

To check the log


In the current directory, open log.txt and confirm that FileExplorer recorded the correct information.
See Also
Reference
My.Computer.FileSystem.CurrentDirectory Property
My.Computer.FileSystem.GetFileInfo Method
Visual Basic Language Concepts

Development with My
Visual Basic provides new features for rapid application development that improve productivity and ease of use while
delivering power. One of these features, called My, provides access to information and default object instances that are related
to the application and its run-time environment. This information is organized in a format that is discoverable through
IntelliSense and logically delineated according to use.
Top-level members of My are exposed as objects. Each object behaves similarly to a namespace or a class with Shared
members, and it exposes a set of related members.
This table shows the top-level My objects and their relationship to each other.

In This Section
Performing Tasks with My.Application, My.Computer, and My.User
Describes the three central My objects, My.Application, My.Computer, and My.User, which provide access to information
and functionality
Default Object Instances Provided by My.Forms and My.WebServices
Describes the My.Forms and My.WebServices objects, which provide access to forms, data sources, and XML Web services
used by your application.
Rapid Application Development with My.Resources and My.Settings
Describes the My.Resources and My.Settings objects, which provide access to an application's resources and settings.
Overview of the Visual Basic Application Model
Describes the Visual Basic Application Startup/Shutdown model.
How My Depends on Project Type
Gives details on which My features are available in different project types.
See Also
Reference
My.Application Object
My.Computer Object
My.User Object
My.Forms Object
My.WebServices Object
Concepts
How My Depends on Project Type
Visual Basic Language Concepts

Performing Tasks with My.Application, My.Computer, and


My.User
The three central My objects that provide access to information and commonly used functionality are My.Application Object,
My.Computer Object, and My.User Object. You can use these objects to access information that is related to the current
application, the computer that the application is installed on, or the current user of the application, respectively.
My.Application, My.Computer, and My.User
The following examples demonstrate how information can be retrieved using My.
VB
' Displays a message box that shows the full command line for the
' application.
Dim args As String = ""
For Each arg As String In My.Application.CommandLineArgs
args &= arg & " "
Next
MsgBox(args)

VB
' Gets a list of subfolders in a folder
My.Computer.FileSystem.GetDirectories _
(My.Computer.FileSystem.SpecialDirectories.MyDocuments, True, "*Logs*")

In addition to retrieving information, the members exposed through these three objects also allow you to execute methods
related to that object. For instance, you can access a variety of methods to manipulate files or update the registry through
My.Computer.
File I/O is significantly easier and faster with My, which includes a variety of methods and properties for manipulating files,
directories, and drives. The TextFieldParser Object allows you to read from large structured files that have delimited or fixed-
width fields. This example opens the TextFieldParser reader and uses it to read from C:\TestFolder1\test1.txt.
VB
Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser
reader = My.Computer.FileSystem.OpenTextFieldParser _
("C:\TestFolder1\test1.txt")
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
reader.Delimiters = New String() {","}
Dim currentRow As String()
While Not reader.EndOfData
Try
currentRow = reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While

My.Application allows you to change the culture for your application. The following example demonstrates how this method
can be called.
VB
' Changes the current culture for the application to Jamaican English.
My.Application.ChangeCulture("en-JM")

See Also
Reference
My.Application Object
My.Computer Object
My.User Object
Concepts
How My Depends on Project Type
Visual Basic Language Concepts

Default Object Instances Provided by My.Forms and


My.WebServices
The My.Forms and My.WebServices objects provide access to forms, data sources, and XML Web services used by your
application. They do this by providing collections of default instances of each of these objects.
Default Instances
A default instance is an instance of the class that is provided by the runtime and does not need to be declared and instantiated
using the Dim and New statements. The following example demonstrates how you might have declared and instantiated an
instance of a Form class called Form1, and how you are now able to get a default instance of this Form class through
My.Forms.
VB
' The old method of declaration and instantiation
Dim myForm As New Form1
myForm.show()

VB
' With My.Forms, you can directly call methods on the default
' instance()
My.Forms.Form1.Show()

The My.Forms object returns a collection of default instances for every Form class that exists in your project. Similarly,
My.WebServices provides a default instance of the proxy class for every Web service that you have created a reference to in
your application.
See Also
Reference
My.Forms Object
My.WebServices Object
Concepts
How My Depends on Project Type
Visual Basic Language Concepts

Rapid Application Development with My.Resources and


My.Settings
The My.Resources object provides access to the application's resources and allows you to dynamically retrieve resources for
your application.
Retrieving Resources
A number of resources such as audio files, icons, images, and strings can be retrieved through the My.Resources object. For
example, you can access the application's culture-specific resource files. The following example sets the icon of the form to the
icon named Form1Icon stored in the application's resource file.
VB
Sub SetFormIcon()
Me.Icon = My.Resources.Form1Icon
End Sub

The My.Resources object exposes only global resources. It does not provide access to resource files associated with forms.
You must access the form resources from the form. For more information, see Walkthrough: Localizing Windows Forms.
Similarly, the My.Settings object provides access to the application's settings and allows you to dynamically store and retrieve
property settings and other information for your application. For more information, see My.Resources Object and
My.Settings Object.
See Also
Reference
My.Resources Object
My.Settings Object
Concepts
Accessing Application Resources
Accessing Application Settings
Visual Basic Language Concepts

Overview of the Visual Basic Application Model


Visual Basic provides a well-defined model for controlling the behavior of Windows Forms applications: the Visual Basic
Application model. This model includes events for handling the application's startup and shutdown, as well as events for
catching unhandled exceptions. It also provides support for developing single-instance applications. The application model is
extensible, so developers that need more control can customize its overridable methods.
Uses for the Application Model
A typical application needs to perform tasks when it starts up and shuts down. For example, when it starts up, the application
can display a splash screen, make database connections, load a saved state, and so on. When the application shuts down, it can
close database connections, save the current state, and so on. In addition, the application can execute specific code when the
application shuts down unexpectedly, such as during an unhandled exception.
The Visual Basic Application model makes it easy to create a single-instance application. A single-instance application differs
from a normal application in that only one instance of the application can be running at a time. An attempt to launch another
instance of a single-instance application results in the original instance being notified—by means of the StartupNextInstance
event—that another launch attempt was made. The notification includes the subsequent instance's command-line arguments.
The subsequent instance of the application is then closed before any initialization can occur.
A single-instance application starts and checks whether it is the first instance or a subsequent instance of the application:
If it is the first instance, it starts as usual.
Each subsequent attempt to start the application, while the first instance runs, results in very different behavior. The
subsequent attempt notifies the first instance about the command-line arguments, and then immediately exits. The first
instance handles the StartupNextInstance event to determine what the subsequent instance's command-line
arguments were, and continues to run.
This diagram shows how a subsequent instance signals the first instance.

By handling the StartupNextInstance event, you can control how your single-instance application behaves. For example,
Microsoft Outlook typically runs as a single-instance application; when Outlook is running and you attempt to start Outlook
again, focus shifts to the original instance but another instance does not open.
Events in the Application Model
The following events are found in the application model:
Application startup. The application raises the Startup event when it starts. By handling this event, you can add code
that initializes the application before the main form is loaded. The Startup event also provides for canceling execution of
the application during that phase of the startup process, if desired.
You can configure the application to show a splash screen while the application startup code runs. By default, the
application model suppresses the splash screen when either the /nosplash or -nosplash command-line argument is
used.
Single-instance applications. The StartupNextInstance event is raised when a subsequent instance of a single-instance
application starts. The event passes the command-line arguments of the subsequent instance.
Unhandled exceptions. If the application encounters an unhandled exception, it raises the UnhandledException event.
Your handler for that event can examine the exception and determine whether to continue execution.
The UnhandledException event is not raised in some circumstances. For more information, see
My.Application.UnhandledException Event.
Network-connectivity changes. If the computer's network availability changes, the application raises the
NetworkAvailabilityChanged event.
The NetworkAvailabilityChanged event is not raised in some circumstances. For more information, see
My.Application.NetworkAvailabilityChanged Event.
Application shut down. The application provides the Shutdown event to signal when it is about to shut down. In that
event handler, you can make sure that the operations your application needs to perform—closing and saving, for
example—are completed. You can configure your application to shut down when the main form closes, or to shut down
only when all forms close.
Availability
By default, the Visual Basic Application model is available for Windows Forms projects. If you configure the application to use a
different startup object, or start the application code with a custom Sub Main, then that object or class may need to provide an
implementation of the WindowsFormsApplicationBase class to use the application model. For information about changing the
startup object, see How to: Change the Startup Object for an Application.
See Also
Reference
My.Application Object
My.Application.Startup Event
My.Application.StartupNextInstance Event
My.Application.UnhandledException Event
My.Application.Shutdown Event
My.Application.NetworkAvailabilityChanged Event
WindowsFormsApplicationBase
Concepts
Extending the Visual Basic Application Model
Visual Basic Language Concepts

How My Depends on Project Type


My exposes only those objects required by a particular project type. For example, the My.Forms object is available in a
Windows Forms application but not available in a console application. This topic describes which My objects are available in
different project types.
My in Windows Applications and Web Sites
My exposes only objects that are useful in the current project type; it suppresses objects that are not applicable. For example,
the following image shows the My object model in a Windows Forms project.

In a Web site project, My exposes objects that are relevant to a Web developer (such as the My.Request and My.Response
objects) while suppressing objects that are not relevant (such as the My.Forms object). The following image shows the My
object model in a Web site project:

Project Details
The following table shows which My objects are enabled by default for eight project types: Windows application, class Library,
console application, Windows control library, Web control library, Windows service, empty, and Web site.
There are three versions of the My.Application object, two versions of the My.Computer object, and two versions of
My.User object; details about these versions are given in the footnotes after the table.
My Object Windows Appli Class Libr Console Applic Windows Control Web Control Li Windows Se Emp Web S
cation ary ation Library brary rvice ty ite
My.Applicat Yes 1 Yes 2 Yes 3 Yes 2 No Yes 3 No No
ion

My.Comput Yes 4 Yes 4 Yes 4 Yes 4 Yes 5 Yes 4 No Yes 5


er

My.Forms Yes No No Yes No No No No

My.Log No No No No No No No Yes

My.Request No No No No No No No Yes

My.Resourc Yes Yes Yes Yes Yes Yes No No


es

My.Respons No No No No No No No Yes
e

My.Settings Yes Yes Yes Yes Yes Yes No No

My.User Yes 6 Yes 6 Yes 6 Yes 6 Yes 7 Yes 6 No Yes 7

My.WebSer Yes Yes Yes Yes Yes Yes No No


vices

1 Windows Forms version of My.Application. Derives from the console version (see Note 3); adds support for interacting with
the application's windows and provides the Visual Basic Application model.
2 Library version of My.Application. Provides the basic functionality needed by an application: provides members for writing
to the application log and accessing application information.
3 Console version of My.Application. Derives from the library version (see Note 2), and adds additional members for
accessing the application's command-line arguments and ClickOnce deployment information.
4 Windows version of My.Computer. Derives from the Server version (see Note 5), and provides access to useful objects on a
client machine, such as the keyboard, screen, and mouse.
5 Server version of My.Computer. Provides basic information about the computer, such as the name, access to the clock, and
so on.
6 Windows version of My.User. This object is associated with the thread's current identity.

7 Web version of My.User. This object is associated with the user identity of the application's current HTTP request.

See Also
Reference
/define (Visual Basic)
My.Application Object
My.Computer Object
My.Forms Object
My.Log Object
My.Request Object
My.Response Object
My.User Object
My.WebServices Object
Concepts
Customizing Which Objects are Available in My
Conditional Compilation Overview
Visual Basic Language Concepts

Accessing Data in Visual Basic Applications


Visual Basic includes several new features to assist in developing applications that access data. Data-bound forms for Windows
applications are created by dragging items from the Data Sources Window onto the form. You bind controls to data by
dragging items from the Data Sources Window onto existing controls.
Related Sections
Creating Client Data Applications
Provides links to pages that discuss incorporating data access functionality into your applications.
Data Walkthroughs
Provides links to pages about particular scenarios related to data access.
Getting Started with Data Access
Provides links to pages on creating applications that work with data, using Visual Studio.
Creating Data Applications with Visual Studio
Discusses the fundamental concepts that you should understand about working with data in Visual Studio.
Connecting to Data in Visual Studio
Provides links to pages on connecting your application to data with design-time tools and ADO.NET connection objects,
using Visual Studio.
Preparing Your Application to Receive Data
Provides links to pages explaining what datasets are, how to create new datasets, and how to create and edit the individual
objects they are made of.
Fetching Data into Your Application
Provides links to pages describing how to load data into datasets and how to execute SQL statements and stored procedures.
Displaying Data on Forms in Windows Applications
Provides links to pages that explain how to display data on Windows Forms through data-bound controls.
Editing Data in Your Application
Provides links to pages describing how to manipulate the data in the data tables of a dataset.
Validating Data
Provides links to pages describing how to add validation to a dataset during column and row changes.
Saving Data
Provides links to pages explaining how to send updated data from an application to the database.
What's New in Data
Provides information and links to new data features for client and data tier applications.
What's New in Visual Basic
Covers new features for Visual Basic.
What's New in ADO.NET
Introduces features that are new in ADO.NET.
What's New in Visual Database Tools
Describes new and improved features of Visual Database Tools.
What's New in ASP.NET Data Access
Describes new features for accessing data in ASP.NET applications.
ADO.NET
Describes the ADO.NET classes, which expose data-access services to the .NET Framework programmer.
ASP.NET Data Access (Visual Studio)
Provides links to information on working with data on ASP.NET Web pages.
Data in Managed Device Projects
Describes how to manage data for devices in Visual Studio.
Data in Office Solutions
Contains links to pages that explain how data works in Office solutions, including information about schema-oriented
programming, data caching, and server-side data access.
Visual Basic Language Concepts

Debugging Your Visual Basic Application


This page provides pointers to documentation for the debugging features built into Visual Studio.
You can use the most important of these, the debugger, to observe the run-time behavior of your program and to determine
the location of semantic errors.
Using the debugger, you can examine the content of variables in your program without inserting additional calls to output the
values. Similarly, you can insert a breakpoint in your code to halt execution at the desired point.
Controlling Execution
The following table lists debugging tasks involving execution control and points to their associated Help pages.
To See
Break execution. How to: Break Execution

Start execution. How to: Start Execution

Debug at design time. Walkthrough: Debugging at Design Time

Launch the debugger. How to: Launch the Debugger Automatically

Step into only the code you have written and ignore other code, such as system c How to: Step Into Just My Code
alls.

Step into code. How to: Step Into Code

Stop debugging. How to: Stop Debugging or Stop Execution

Enable just-in-time debugging, which launches the Visual Studio debugger when Just-In-Time Debugging
a program running outside Visual Studio encounters a fatal error.

Handling Exceptions
The following table lists debugging tasks involving exception handling and points to their associated Help pages.
To See
Break on unhandled exceptions. How to: Break on User-Unhandled Exceptions

Break when an exception is thrown. How to: Break When an Exception is Thrown

Break on first-chance exceptions. How to: Break When an Exception is Thrown

Use the exception assistant. How to: Correct Run-Time Errors with the Exception Assistant

Add a new exception. How to: Add New Exceptions

Continue execution after an exception has been thrown. Continuing Execution After an Exception

Edit and Continue


The following table lists debugging tasks involving Edit and Continue and points to their associated Help pages.
To See
Turn Edit and Continue off and on. How to: Enable and Disable Edit and Continue
Stop Edit and Continue from applying code changes. How to: Stop Code Changes

Apply edits in break mode. How to: Apply Edits in Break Mode with Edit and Continue

Examining Debugging Data


The following table lists debugging tasks involving viewing debugging data and points to their associated Help pages.
To See
Use the Registers window to display register contents. How to: Use the Registers Window

Use the Call Stack window to view function or procedure calls that are currently on t How to: Use the Call Stack Window
he stack.

Use the Disassembly window to view assembly code corresponding to the instructio How to: Use the Disassembly Window
ns created by the compiler.

Use the Modules window to list and describe modules used by your program. How to: Use the Modules Window

Use the Script Explorer window to list script files that are currently loaded into the pr How to: Use the Script Explorer Window
ogram.

Use the Processes window to show all processes that you have attached to or launch How to: Use the Processes Window
ed from Visual Studio.

Use the Threads window to examine and control threads in the program. How to: Use the Threads Window

Setting Breakpoints
The following table lists debugging tasks involving breakpoints and points to their associated Help pages.
To See
Set a breakpoint. How to: Set a Simple Breakpoint

Delete a breakpoint. How to: Delete a Breakpoint

Enable or disable a breakpoint. How to: Enable or Disable a Breakpoint

Change a breakpoint location. How to: Edit a Breakpoint Location

Use a filter to limit the behavior of a breakpoint to specified computers, processes, and How to: Specify a Breakpoint Filter
threads.

Conditionally control whether or not a breakpoint is executed. How to: Specify a Breakpoint Condition

Use the Breakpoints window to accomplish breakpoint-related tasks. How to: Use the Breakpoints Window

See Also
Tasks
Walkthrough: Debugging a Windows Form
How to: Apply Edits in Break Mode with Edit and Continue
Concepts
Debugging SQL
Execution Control
Other Resources
Debugging Managed Code
Debugging Native Code
Debugging Web Applications
Debugging User Interface Reference
Debug Settings and Preparation
Debugger Roadmap
Debugging Preparation: C#, J#, and Visual Basic Project Types
Visual Basic Language Concepts

Exception and Error Handling in Visual Basic


Visual Basic supports structured exception (error) handling, which allows the program to detect and possibly recover from
errors during execution. Visual Basic uses an enhanced version of the Try...Catch...Finally syntax already supported by other
languages such as C++. Structured exception handling combines a modern control structure (similar to Select Case or While)
with exceptions, protected blocks of code, and filters.
Structured exception handling, which is the recommended method of error handling in Visual Basic, makes it easy to create
and maintain programs with robust, comprehensive error handlers. Unstructured exception handling using On Error can
degrade application performance and result in code that is difficult to debug and maintain.
In This Section
Introduction to Exception Handling
Summarizes how to handle exceptions in your programs.
Choosing When to Use Structured and Unstructured Exception Handling
Describes both types of exception handling and suggests when they are most appropriate.
Types of Errors
Provides an overview of syntax errors, run-time errors, and logic errors.
Smart Compile Auto Correction
Describes the Smart Compile Auto Correction feature and how to use it.
How to: Correct Compiler Errors with Auto Correction
Shows how to correct compiler errors in the Code Editor through the Smart Compile Auto Correction feature.
Configuring Warnings in Visual Basic
Details how to turn compiler warnings on and off in Visual Basic.
Structured Exception Handling Overview for Visual Basic
Discusses and demonstrates structured exception handling in Visual Basic.
Unstructured Exception Handling Overview
Discusses and demonstrates unstructured exception handling in Visual Basic.
Related Sections
Language Changes for Visual Basic 6.0 Users
Summarizes language element changes in Visual Basic.
Debugger Roadmap
Discusses the fundamentals of using the Visual Studio debugger. Topics include debugging basics, execution control,
attaching to a running program, Just-In-Time debugging, launching the debugger automatically, dumps, breakpoints,
inspecting your program, handling exceptions, Edit and Continue, and using expressions in the debugger.
Just-In-Time Debugging
Describes just-in-time debugging, a feature that launches the Visual Studio debugger automatically when a program running
outside Visual Studio encounters a fatal error.
Debugging Managed Code
Covers common debugging problems and techniques for managed applications.
Exception Assistant
Describes the Exception Assistant feature, which facilitates troubleshooting run-time errors.
Edit and Continue
Describes Edit and Continue, a time-saving feature that allows you to make changes to source code while the program is in
break mode.
COM and ActiveX Debugging
Provides tips on debugging COM applications and ActiveX controls.
Visual Basic Language Concepts

Introduction to Exception Handling


Visual Basic supports both structured and unstructured exception (error) handling. By placing exception handling code in your
application, you can handle most of the errors users may encounter and enable the application to continue running. You can
use structured and unstructured error handling to plan for potential errors, preventing them from interfering with the
application.
Consider using exception handling in any method that uses operators that may generate an exception, or that calls into or
accesses other procedures that may generate an exception.
If an exception occurs in a method that is not equipped to handle the exception, the exception is propagated back to the calling
method, or the previous method. If the previous method also has no exception handler, the exception is propagated back to
that method's caller, and so on. The search for a handler continues up the call stack, which is the series of procedures called
within the application. If it fails to find a handler for the exception, an error message is displayed and the application is
terminated.
Note
A single method can contain either structured or unstructured exception handling, but not both.

Structured Exception Handling


In structured exception handling, blocks of code are encapsulated, with each block having one or more associated handlers.
Each handler specifies some form of filter condition on the type of exception it handles. When an exception is raised by code in
a protected block, the set of corresponding handlers is searched in order, and the first one with a matching filter condition is
executed. A single method can have multiple structured exception handling blocks, and the blocks can also be nested within
each other.
The Try...Catch...Finally statement is used specifically for structured exception handling. For more information, see
Structured Exception Handling Overview for Visual Basic.
Unstructured Exception Handling
The On Error statement is used specifically for unstructured exception handling. In unstructured exception handling, On Error
is placed at the beginning of a block of code. It then has "scope" over that block; it handles any errors occurring within the
block. If the program encounters another On Error statement, that statement becomes valid and the first statement becomes
invalid. For more information, see Unstructured Exception Handling Overview.
See Also
Tasks
Troubleshooting Exception Handling
Walkthrough: Structured Exception Handling
Reference
On Error Statement (Visual Basic)
Concepts
Types of Errors
Structured Exception Handling Overview for Visual Basic
Unstructured Exception Handling Overview
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts

Choosing When to Use Structured and Unstructured Exception


Handling
Structured exception handling is simply that — using a control structure containing exceptions, isolated blocks of code, and
filters to create an exception handling mechanism. This allows your code to differentiate between different types of errors and
react in accordance with circumstances. In unstructured exception handling, an On Error statement at the beginning of the
code handles all exceptions.
Remarks
Structured exception handling is significantly more versatile, robust, and flexible than unstructured. If possible, use structured
exception handling. However, you might use unstructured exception handling under these circumstances:
You are upgrading an application written in an earlier version of Visual Basic.
You are developing a preliminary or draft version of an application and you don't mind if the program fails to shut down
gracefully.
You know in advance exactly what will cause the exception.
A deadline is pressing, you need to take shortcuts, and are willing to sacrifice flexibility for speed.
Code is trivial or so short that you only need to test the branch of code generating the exception.
You need to use the Resume Next statement, which is not supported in structured exception handling.
You cannot combine structured and unstructured exception handling in the same function. If you use an On Error statement,
you cannot use a Try...Catch statement in the same function.
Regardless of which you choose to handle exceptions within your code, you must take a step back and examine what
assumptions that code makes. For example, when your application asks the user to input a telephone number, the following
assumptions come into play:
The user will input a number rather than characters.
The number will have a certain format.
The user will not input a null string.
The user has a single telephone number.
User input might violate any or all of these assumptions. Robust code requires adequate exception handling, which allows your
application to recover gracefully from such a violation.
Unless you can guarantee that a method will never throw an exception under any circumstances, allow for informative
exception handling. Exception handling should be meaningful. Beyond stating that something went wrong, messages resulting
from exception handling should indicate why and where it went wrong. An uninformative message along the lines of "An error
has occurred" only frustrates the user.
See Also
Tasks
Troubleshooting Exception Handling
Concepts
Types of Errors
Structured Exception Handling Overview for Visual Basic
Unstructured Exception Handling Overview
Visual Basic Language Concepts

Types of Errors
In Visual Basic, errors (also called exceptions) fall into one of three categories: syntax errors, run-time errors, and logic errors.
Syntax Errors
Syntax errors are those that appear while you write code. Visual Basic checks your code as you type it in the Code Editor
window and alerts you if you make a mistake, such as misspelling a word or using a language element improperly. Syntax
errors are the most common type of errors. You can fix them easily in the coding environment as soon as they occur.
Note
The Option Explicit statement is one means of avoiding syntax errors. It forces you to declare, in advance, all the variables t
o be used in the application. Therefore, when those variables are used in the code, any typographic errors are caught immedi
ately and can be fixed.

Run-Time Errors
Run-time errors are those that appear only after you compile and run your code. These involve code that may appear to be
correct in that it has no syntax errors, but that will not execute. For example, you might correctly write a line of code to open a
file. But if the file is corrupted, the application cannot carry out the Open function, and it stops running. You can fix most run-
time errors by rewriting the faulty code, and then recompiling and rerunning it.
Logic Errors
Logic errors are those that appear once the application is in use. They are most often unwanted or unexpected results in
response to user actions. For example, a mistyped key or other outside influence might cause your application to stop working
within expected parameters, or altogether. Logic errors are generally the hardest type to fix, since it is not always clear where
they originate.
See Also
Concepts
Introduction to Exception Handling
Structured Exception Handling Overview for Visual Basic
Unstructured Exception Handling Overview
Other Resources
Exception Handling Tasks
Debugger Roadmap
Visual Basic Language Concepts

Smart Compile Auto Correction


The Smart Compile Auto Correction feature suggests corrections when errors occur, allowing you to pick a solution to be
applied to the code.
When an error occurs, if there is a symbol under the right side of the squiggle, resting your mouse over the squiggle or
double-clicking the error message in the task list will turn the symbol into a smart tag panel. Clicking or resting your mouse
pointer over the smart tag panel will open the Error Correction Options helper window, which displays a description of the
error as well as a set of suggestions for fixing the error. Where appropriate, the helper window allows you to preview the fix in
a separate window.
You can undo changes after they have been applied with an Undo operation (CTRL+Z).
To dismiss the Smart Compile Auto Correction helper window, click elsewhere in the editor.
This table lists and explains the elements shown in the Smart Compile Auto Correction window:
Element Description
Error message Displays the message associated with the error.

Suggested fix Displays possible ways to fix the error. Click one to have it applied to your code.

Preview Displays a preview of the corrected code. In situations where the fix does not affect the code, a preview will n
ot be shown.

Expand all previe Checking this box will expand all previews.
ws

See Also
Tasks
How to: Correct Compiler Errors with Auto Correction
Concepts
Types of Errors
Configuring Warnings in Visual Basic
Visual Basic Language Concepts

How to: Correct Compiler Errors with Auto Correction


The Smart Compile Auto Correction feature suggests corrections when errors occur, allowing you to pick a solution to be
applied to the code.
To correct an error with Smart Compile Auto Correction
1. When an error occurs that can be corrected with Smart Compile Auto Correction, a glyph is displayed under the right
side of the squiggle. Resting the mouse pointer over the squiggle will turn the symbol into a smart-tag panel.
2. Click or rest the mouse pointer over the smart-tag panel. The Error Correction Options helper window opens and
displays a description of the error as well as a set of suggestions for fixing the error. Click the fix you would like to apply.
3. You can undo changes that have been applied with an Undo operation (CTRL+Z). To dismiss the Error Correction
Options helper window, click elsewhere in the editor.
See Also
Tasks
How to: Get Information about Visual Basic Compiler Errors
Reference
Smart Compile Auto Correction
Visual Basic Language Concepts

Configuring Warnings in Visual Basic


The Visual Basic compiler includes a set of warnings about code that may cause run-time errors. You can use that information
to write cleaner, faster, better code with fewer bugs. For example, the compiler will produce a warning when the user attempts
to invoke a member of an unassigned object variable, return from a function without setting the return value, or execute a Try
block with errors in the logic to catch exceptions.
Sometimes the compiler provides extra logic on the user's behalf so that the user can focus on the task at hand, rather than on
anticipating possible errors. In previous versions of Visual Basic, Option Strict was used to limit the additional logic that the
Visual Basic compiler provides. Configuring warnings allows you to limit this logic in a more granular way, at the level of the
individual warnings.
You may want to customize your project and turn off some warnings not pertinent to your application while turning other
warnings into errors. This page explains how to turn individual warnings on and off.
Turning Warnings Off and On
There are two different ways to configure warnings: you can configure them using the Project Designer, or you can use the
/warnaserror and /nowarn compiler options.
The Compile tab of the Project Designer page allows you to turn warnings on and off. Select the Disable All Warnings
check box to disable all warnings; select the Treat All Warnings as Errors to treat all warnings as errors. Some individual
warnings can be toggled as error or warning as desired in the displayed table.
When Option Strict is set to Off, Option Strict related warnings cannot be treated independently of each other. When
Option Strict is set to On, the associated warnings are treated as errors, no matter what their status is. When Option Strict is
set to Custom by specifying /optionstrict:custom in the command line compiler, Option Strict warnings can be toggled on
or off independently.
The /warnaserror command-line option of the compiler can also be used to specify whether warnings are treated as errors.
You can add a comma delimited list to this option to specify which warnings should be treated as errors or warnings by using
+ or -. The following table details the possible options.
Command-line option Specifies
/warnaserror+ Treat all warnings as errors

/warnsaserror- Do not treat as warnings as errors. This is the default.

/warnaserror+:<warning list Treat specific warnings as errors, listed by their error ID number in a comma delimited list r.
>

/warnaserror-:<warning list Do not treat specific warnings as errors, listed by their error ID number in a comma delimited
>
list.

/nowarn Do not report warnings.

/nowarn:<warning list> Do not report specified warnings, listed by their error ID number in a comma delimited list.

The warning list contains the error ID numbers of the warnings that should be treated as errors, which can be used with the
command-line options to turn specific warnings on or off. If the warning list contains an invalid number, an error is reported.
Examples
This table of examples of command line arguments describes what each argument does.
Argument Description
vbc /warnaserror Specifies that all warnings should be treated as errors.

vbc /warnaserror:42024 Specifies that warning 42024 should be treated as an error.


vbc /warnaserror:42024,42025 Specifies that warnings 42024 and 42025 should be treated as errors.

vbc /nowarn Specifies that no warnings should be reported.

vbc /nowarn:42024 Specifies that warning 42024 should not be reported.

vbc /nowarn:42024,42025 Specifies that warnings 42024 and 42025 should not be reported.

Types of Warnings
Following is a list of warnings that you might want to treat as errors.
Implicit Conversion Warning
Generated for instances of implicit conversion. They do not include implicit conversions from an intrinsic numeric type to a
string when using the & operator. Default for new projects is off.
ID: 42016
Late bound Method Invocation and Overload Resolution Warning
Generated for instances of late binding. Default for new projects is off.
ID: 42017
Operands of Type Object Warnings
Generated when operands of type Object occur that would create an error with Option Strict On. Default for new projects is
on.
ID: 42018 and 42019
Declarations Require 'As' Clause Warnings
Generated when a variable, function, or property declaration lacking an As clause would have created an error with Option
Strict On. Variables that do not have a type assigned to them are assumed to be type Object. Default for new projects is on.
ID: 42020 (variable declaration), 42021 (function declaration), and 42022 (property declaration).
Possible Null Reference Exception Warnings
Generated when a variable is used before it has been assigned a value. Default for new projects is on.
ID: 42104, 42030
Unused Local Variable Warning
Generated when a local variable is declared but never referred to. Default is on.
ID: 42024
Access of Shared member through Instance Variable Warning
Generated when accessing a shared member through an instance may have side effects, or when accessing a shared member
through an instance variable is not the right-hand side of an expression or is being passed in as a parameter. Default for new
projects is on.
ID: 42025
Recursive Operator or Property Access Warnings
Generated when the body of a routine uses the same operator or property it is defined in. Default for new projects is on.
ID: 42004 (operator), 42026 (property)
Function or Operator without Return Value Warning
Generated when the function or operator does not have a return value specified. This includes omitting a Set to the implicit
local variable with the same name as the function. Default for new projects is on.
ID: 42105 (function), 42016 (operator)
Overloads Modifier Used in a Module Warning
Generated when Overloads is used in a Module. Default for new projects is on.
ID: 42028
Duplicate or Overlapping Catch Blocks Warnings
Generated when a Catch block is never reached due to its relation to other Catch blocks that have been defined. Default for
new projects is on.
ID: 42029, 42031
See Also
Tasks
How to: Enable or Disable Compiler Warnings
Reference
Exception Assistant Dialog Box
/nowarn
/warnaserror (Visual Basic)
Compiler Warnings That Are Off by Default
Concepts
Types of Errors
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts

Structured Exception Handling in Visual Basic


Structured exception handling is a control structure that contains exceptions, isolated blocks of code, and filters to create an
exception-handling mechanism. With structured exception handling, your code can differentiate between different types of
errors and react accordingly.
In This Section
Exception Handling Tasks
Lists common exception-handling tasks, such as how to catch an exception and how to filter exceptions in a Catch block.
Structured Exception Handling Overview for Visual Basic
Provides an overview of the advantages and structures of structured exception handling.
Exception Class in Visual Basic
Describes the Exception class.
Walkthrough: Structured Exception Handling
Provides a walkthrough of creating a simple application and inserting exception-handling code.
Troubleshooting Exception Handling
Lists errors commonly encountered when using structured exception handling and describes how to correct them.
Reference
Throw Statement (Visual Basic)
Describes the Throw statement and demonstrates how to use it to throw an exception.
Try...Catch...Finally Statement (Visual Basic)
Describes Try…Catch…Finally statements and demonstrates how to use them to test code blocks.
Related Sections
Choosing When to Use Structured and Unstructured Exception Handling
Describes the advantages of structured and unstructured exception handling.
Unstructured Exception Handling Overview
Describes unstructured exception handling and demonstrates how to use it.
Visual Basic Language Concepts

Exception Handling Tasks


Visual Basic supports both structured and unstructured exception (error) handling. By placing specific exception handling code
in your application, you can handle most of the errors users may encounter. Use structured and unstructured exception
handling to prevent potential errors from interfering with your application.
In This Section
How to: Catch an Exception in Visual Basic
Demonstrates how to use a Try…Catch block to catch an exception.
How to: Throw an Exception in Visual Basic
Demonstrates how to use the Throw statement to throw an exception.
How to: Implement I/O Try...Catch Blocks in Visual Basic
Demonstrates how to use a Try…Catch block to test an input or output operation.
How to: Test Code with a Try…Catch Block in Visual Basic
Demonstrates how to use a Try…Catch block to test a section of code.
How to: Clean up Resources with a Try…Finally Block in Visual Basic
Demonstrates how to use a Try…Catch…Finally block to clean up resources used by code.
How to: Filter Errors in a Catch Block in Visual Basic
Demonstrates how to filter for specific types of errors within a Try…Catch block.
How to: Display an Exception's Message in Visual Basic
Demonstrates how to retrieve the string associated with an error message.
How to: Create New Exception Classes in Visual Basic
Demonstrates how to create a new exception class.
How to: Check an Exception's Inner Exception
Demonstrates how to determine the original exception through looking at an exception's InnerException property.
Reference
Throw Statement (Visual Basic)
Describes the Throw statement and how it is used.
Try...Catch...Finally Statement (Visual Basic)
Describes the Try, Catch, and Finally statements and how they are used.
Visual Basic Language Concepts

How to: Catch an Exception in Visual Basic


This example shows how to use a Try and Catch block to catch exceptions.
Example
This example shows how to use a Try…Catch block to catch an OverflowException.
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
VB
Dim Top As Double = 5
Dim Bottom As Double = 0
Dim Result As Integer
Try
Result = CType(Top / Bottom, Integer)
Catch Exc As System.OverflowException
MsgBox("Attempt to divide by zero resulted in overflow")
End Try

This example requires:


A reference to the System namespace.
The following code example implements a Try...Catch block that handles Exception, IOException, and all the exceptions that
derive from IOException.
VB
Try
' Add code for your I/O task here.
Catch dirNotFound As System.IO.DirectoryNotFoundException
Throw dirNotFound
Catch fileNotFound As System.IO.FileNotFoundException
Throw fileNotFound
Catch pathTooLong As System.IO.PathTooLongException
Throw pathTooLong
Catch ioEx As System.IO.IOException
Throw ioEx
Catch security As System.Security.SecurityException
Throw security
Catch ex As Exception
Throw ex
Finally
' Dispose of any resources you used or opened in the Try block.
End Try

Add the code you want to execute to the Try block.


Robust Programming
Use this block of code as a starting point for wrapping a data operation in a Try...Catch statement. This Try...Catch block is
designed to catch and rethrow all exceptions. That may not be the right choice for your project. For a discussion on exception-
handling options, see Best Practices for Using IntelliSense Code Snippets.
You can reduce the likelihood of exceptions by using Windows Forms controls such as the
OpenFileDialog Component (Windows Forms) component and the SaveFileDialog Component (Windows Forms) component
controls that limit the user choices to valid file names. The FileInfo.Exists property can check whether a file exists before you try
to open it. Using these controls and classes is not foolproof, however. The file system can change between the time the user
selects a file and the time that the code runs. Exception handling will therefore nearly always be required when with working
with files.
Security
For many file tasks, the assembly requires a privilege level granted by the FileIOPermission class. If you are running in a
partial-trust context, the code might throw an exception due to insufficient privileges. For more information, see
Code Access Security Basics. The user also needs access to the file, should it exist. For more information, see
Access Control Lists (ACLs).
Do not make decisions about the contents of the file based on the file name extension. For example, the file Form1.vb may not
be a Visual Basic source file.
See Also
Tasks
How to: Throw an Exception in Visual Basic
How to: Test Code with a Try…Catch Block in Visual Basic
How to: Clean up Resources with a Try…Finally Block in Visual Basic
How to: Filter Errors in a Catch Block in Visual Basic
How to: Check an Exception's Inner Exception
Troubleshooting Exception Handling
Concepts
Choosing When to Use Structured and Unstructured Exception Handling
Visual Basic Language Concepts

How to: Throw an Exception in Visual Basic


This example throws an ApplicationException exception.
Example
VB
Throw New ApplicationException
' Code to react to possible causes of the exception.

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
A reference to the System namespace.
Robust Programming
Unhandled exceptions can cause application execution to halt. Use Try…Catch blocks to anticipate and handle possible
exceptions.
See Also
Tasks
How to: Catch an Exception in Visual Basic
How to: Test Code with a Try…Catch Block in Visual Basic
How to: Clean up Resources with a Try…Finally Block in Visual Basic
How to: Filter Errors in a Catch Block in Visual Basic
How to: Check an Exception's Inner Exception
Troubleshooting Exception Handling
Reference
Exception Class
Throw Statement (Visual Basic)
Concepts
Choosing When to Use Structured and Unstructured Exception Handling
Visual Basic Language Concepts

How to: Implement I/O Try...Catch Blocks in Visual Basic


The following code example implements a Try...Catch block that handles Exception, IOException, and all the exceptions that
derive from IOException.
Example
This example moves from the most specific to the least specific; each exception is tested in turn.
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in File system -
Processing Drives, Folders, and Files. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
VB
Try
' Add code for your I/O task here.
Catch dirNotFound As System.IO.DirectoryNotFoundException
' Code to handle DirectoryNotFoundException.
Catch fileNotFound As System.IO.FileNotFoundException
' Code to handle FileNotFoundException.
Catch pathTooLong As System.IO.PathTooLongException
' Code to handle PathTooLongException.
Catch ioEx As System.IO.IOException
' Code to handle IOException.
Catch security As System.Security.SecurityException
' Code to handle SecurityException.
Catch ex As Exception
' Rethrow exception if anything else has occurred.
Throw ex
Finally
' Dispose of any resources you used or opened in the Try block.
End Try

Compiling the Code


Add the code you want to execute to the Try block.
Robust Programming
Use this block of code as a starting point for wrapping a data operation in a Try...Catch statement. This Try...Catch block is
designed to catch and rethrow all exceptions. That may not be the right choice for your project. For a discussion on exception-
handling options, see Best Practices for Using IntelliSense Code Snippets.
You can reduce the likelihood of exceptions by using Windows Forms controls such as the
OpenFileDialog Component (Windows Forms) component and the SaveFileDialog Component (Windows Forms) component
controls that limit the user choices to valid file names. The FileInfo.Exists property can check whether a file exists before you try
to open it. Using these controls and classes is not foolproof, however. The file system can change between the time the user
selects a file and the time that the code runs. Exception handling will therefore nearly always be required when with working
with files.
Security
For many file tasks, the assembly requires a privilege level granted by the FileIOPermission class. If you are running in a
partial-trust context, the code might throw an exception due to insufficient privileges. For more information, see
Code Access Security Basics. The user also needs access to the file, should it exist. For more information, see
Access Control Lists (ACLs).
Do not make decisions about the contents of the file based on the file name extension. For example, the file Form1.vb may not
be a Visual Basic source file.
See Also
Tasks
How to: Filter Errors in a Catch Block in Visual Basic
How to: Check an Exception's Inner Exception
Reference
Try...Catch...Finally Statement (Visual Basic)
Concepts
Best Practices for Using IntelliSense Code Snippets
Structured Exception Handling Overview for Visual Basic
Choosing When to Use Structured and Unstructured Exception Handling
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts

How to: Test Code with a Try…Catch Block in Visual Basic


A Catch statement can be used within a Try block in order to catch and respond to a specific exception or multiple exceptions.
If an exception occurs during the execution of any of the code within the Try section, the Visual Basic compiler examines each
Catch statement within the block until it finds one whose condition matches that exception. If none is found, an error is
produced.
To catch a specific exception
1. Use a Try block to test the block of code, enclosing it within Try and End Try, as in the following example, which copies
the file MyLog to the same directory and renames it BackupLog.
VB
Try
My.Computer.FileSystem.CopyFile("MyLog", "BackupLog")
Catch ex As System.IO.IOException
MsgBox("An error occurred")
End Try

2. Within the Try block, supply Catch statements aimed at specific types of errors, going from the most specific to the least
specific. Here, the Catch statement first catches any IOException exceptions before looking for general exceptions.
VB
Catch ex As System.IO.FileNotFoundException
MsgBox("No such file in this directory.")
Catch ex As System.Exception
MsgBox("An unspecified error occurred.")

See Also
Tasks
How to: Clean up Resources with a Try…Finally Block in Visual Basic
How to: Filter Errors in a Catch Block in Visual Basic
How to: Check an Exception's Inner Exception
Troubleshooting Exception Handling
Reference
Try...Catch...Finally Statement (Visual Basic)
Concepts
Choosing When to Use Structured and Unstructured Exception Handling
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts

How to: Clean up Resources with a Try…Finally Block in Visual


Basic
A Finally statement can be used within a Try block to ensure allocated resources are clean. The code in a Finally block runs
after the exception-handling code, but before control returns to the calling procedure. The code in a Finally block will run even
if your code throws an exception, and even if you add an explicit Exit Function (or Exit Sub) statement within a Catch block.
If you do not need to catch specific exceptions, the Using statement behaves like a Try…Finally block, and guarantees
disposal of the resources, no matter how you exit the block. This is true even in the case of an unhandled exception. For more
information, see Using Statement (Visual Basic).
To clean up resources with a Finally statement
Place the code that you would like executed regardless of exceptions within the Finally block. The following code creates
a StreamReader and uses it to read from a file.
VB
Dim reader As New System.IO.StreamReader("C:\testfile")
Try
reader.ReadToEnd()
Catch ex As System.IO.IOException
MsgBox("Could not read file")
Finally
'This command is executed whether or not the file can be read
reader.Close()
End Try

See Also
Tasks
How to: Test Code with a Try…Catch Block in Visual Basic
How to: Check an Exception's Inner Exception
How to: Dispose of a System Resource
Reference
Using Statement (Visual Basic)
Concepts
Exception Handling for Visual Basic 6.0 Users
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts

How to: Filter Errors in a Catch Block in Visual Basic


Catch statements provide more than one option for filtering errors. One method for filtering is doing so by types of exception.
In such cases, it is important to move from the most specific type of exception to the most general, since the Catch statements
are executed in order.
A When clause can also be used to filter on a conditional expression, such as a specific error number. You can combine both
approaches as well.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To filter on exception type


Insert a Catch statement for each type of exception you wish to check, going from the most specific to the most general.
VB
Try
Throw New Exception
Catch ex As System.IO.IOException
' Code reacting to IOException
Catch ex As System.NullReferenceException
' Code reacting to NullReferenceException
Catch ex As Exception
' Code reacting to any exception
End Try

To filter on a conditional expression


Use a Catch When statement to filter on a conditional expression. If the conditional expression evaluates as True, the
code following the Catch block will be executed.
VB
Try
' Code goes here.
' Check for type mismatch error.
Catch ex As Exception When Err.Number = 5
' Code reacting to exception.
End Try

See Also
Tasks
How to: Check an Exception's Inner Exception
Troubleshooting Exception Handling
Reference
Try...Catch...Finally Statement (Visual Basic)
Concepts
Exception Handling for Visual Basic 6.0 Users
Choosing When to Use Structured and Unstructured Exception Handling
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts

How to: Display an Exception's Message in Visual Basic


The exception object includes a number of properties that help identify the code location, the type, the Helpfile URL, and the
reason for the exception. One of these, the Message property, describes the current exception.
To display the string associated with an exception
Use the Message property to display information about the current exception. This example catches a WebException and
displays the associated message.
VB
Try
Throw New System.Net.WebException
Catch ex As System.Net.WebException
MsgBox("An exception occurred:" & vbCrLf & ex.Message)
End Try

See Also
Tasks
How to: Catch an Exception in Visual Basic
How to: Throw an Exception in Visual Basic
How to: Test Code with a Try…Catch Block in Visual Basic
How to: Check an Exception's Inner Exception
Troubleshooting Exception Handling
Reference
Try...Catch...Finally Statement (Visual Basic)
Other Resources
Structured Exception Handling in Visual Basic
Visual Basic Language Concepts

How to: Create New Exception Classes in Visual Basic


You can create your own application exception classes by inheriting them from the Exception class. Follow good coding
practices by ending the class name of your exception with the word Exception, such as OutOfMoneyException or
TooMuchRainException.

The following code example provides a basic implementation of an exception class.


Example
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
VB
Public Class YourProblemException
Inherits Exception
Public Sub New()
' Add other code for custom properties here.
End Sub

Public Sub New(ByVal message As String)


MyBase.New(message)
' Add other code for custom properties here.
End Sub

Public Sub New(ByVal message As String, ByVal inner As Exception)


MyBase.New(message, inner)
' Add other code for custom properties here.
End Sub

Public Sub New( _


ByVal info As System.Runtime.Serialization.SerializationInfo, _
ByVal context As System.Runtime.Serialization.StreamingContext)
MyBase.New(info, context)
' Insert code here for custom properties here.
End Sub
End Class

Compiling the Code


Replace YourProblemException with the name of the exception class you want to create. Typically, exception class names
end with "Exception". Add properties to convey additional information about the error that has occurred.
Security
Do not divulge information about the application or its data when handling an exception. This information could be used to
attack your application.
See Also
Tasks
Troubleshooting Exception Handling
Reference
ApplicationException Class
Concepts
Structured Exception Handling Overview for Visual Basic
Exception Handling for Visual Basic 6.0 Users
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts

How to: Check an Exception's Inner Exception


In cases where an exception is thrown as a direct result of a previous exception, the InnerException property describes the
original error. This information may allow you to handle the error more efficiently. If there is no original error, the value of
InnerException will be a null reference or Nothing in Visual Basic. This property is read-only.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To check an InnerException
Check the InnerException property of the exception to determine the cause of the original error.
VB
Try
My.Computer.FileSystem.CopyFile("file1", "file2")
Catch ex As System.IO.IOException
MsgBox(ex.InnerException)
End Try

See Also
Tasks
How to: Display an Exception's Message in Visual Basic
Troubleshooting Exception Handling
Reference
InnerException
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts

Structured Exception Handling Overview for Visual Basic


Visual Basic supports structured exception handling, which you can use to create and maintain programs with robust,
comprehensive error handlers. Structured exception handling is code designed to detect and respond to errors during
execution by combining a control structure (similar to Select Case or While) with exceptions, protected blocks of code, and
filters.
Using the Try...Catch...Finally statement, you can protect blocks of code that have the potential to raise errors. You can nest
exception handlers, and the variables declared in each block will have local scope.
The Try...Catch...Finally Statement
The following code shows the structure of a Try...Catch...Finally statement.

Try
' Starts a structured exception handler.
' Place executable statements that may generate
' an exception in this block.
Catch [optional filters]
' This code runs if the statements listed in
' the Try block fail and the filter on the Catch statement is true.
[Additional Catch blocks]
Finally
' This code always runs immediately before
' the Try statement exits.
End Try
' Ends a structured exception handler.

The Try block of a Try...Catch...Finally exception handler contains the section of code to be monitored for exceptions. If an
error occurs during execution of this section, Visual Basic examines each Catch statement within the Try...Catch...Finally until
it finds one with a condition that matches that error. If one is found, control transfers to the first line of code in the Catch block.
If no matching Catch statement is found, the search proceeds to the Catch statements of the outer Try...Catch...Finally block
that contains the block in which the exception occurred. This process continues through the entire stack until a matching Catch
block is found in the current procedure. If no match is found, an error is produced.
The code in the Finally section always executes last, just before the error-handling block loses scope, regardless of whether the
code in the Catch blocks has executed. Place cleanup code, such as that for closing files and releasing objects, in the Finally
section. If you do not need to catch exceptions, but do need to clean up resources, consider using the Using statement rather
than a Finally section. For more information, see Using Statement (Visual Basic).
Error Filtering in the Catch Block
Catch blocks allow three options for specific error filtering. In one, errors are filtered based on the class of the exception (in
this case ClassLoadException), as shown in the following code.

Try
' "Try" block.
Catch e as ClassLoadException
' "Catch" block.
Finally
' "Finally" block.
End Try

If a ClassLoadException error occurs, the code within the specified Catch block is executed.
In the second error-filtering option, the Catch section can filter on any conditional expression. One common use of this type of
Catch filter is to test for specific error numbers, as shown in the following code.

Try
' "Try" block.
Catch When ErrNum = 5 'Type mismatch.
' "Catch" block.
Finally
' "Finally" block.
End Try

When Visual Basic finds the matching error handler, it executes the code within that handler, and then passes control to the
Finally block.
Note
When trying to find a Catch block to handle an exception, each block's handler is evaluated until a match is found. Since thes
e handlers can be calls to functions, there may be unexpected side effects; for example, such a call can change a public variabl
e that is then used in the code of a different Catch block that ends up handling the exception.

As a third alternative, you can combine options one and two, using both for exception handling. Your Catch statements should
move from most specific to least specific. A Catch block by itself will catch all exceptions derived from Exception, and therefore
should always be the last block before Finally.
Branching Out of Try…Catch Blocks
It is possible to branch from a Catch block back into the initial Try statement or the End Try statement, but it is not possible to
branch into an enclosing Try…Catch block. This is illustrated here:

Structured Exception Handler Example


The following example shows another simple error handler based on the Try...Catch...Finally statement.

Function GetStringsFromFile(ByVal FileName As String) As Collection


Dim Strings As New Collection
Dim Stream As System.IO.StreamReader = System.IO.File.OpenText(FileName) 'Open the file.
Try
While True
' Loop terminates with an EndOfStreamException
' error when end of stream is reached.
Strings.Add(Stream.ReadLine())
End While
Catch eos As System.IO.EndOfStreamException
' No action is necessary; end of stream has been reached.
Catch IOExcep As System.IO.IOException
' Some kind of error occurred. Report error and clear collection.
MsgBox(IOExcep.Message)
Strings = Nothing
Finally
Stream.Close()
' Close the file.
End Try
Return Strings
End Function

The Finally block is always run, regardless of any actions occurring in preceding Catch blocks. You cannot use Resume or
Resume Next in structured exception handling.
Note
In the preceding example, any exception other than the IOException class or the EndOfStreamException class is propagated
back to the caller unhandled.

See Also
Tasks
Troubleshooting Exception Handling
Reference
Try...Catch...Finally Statement (Visual Basic)
Concepts
Introduction to Exception Handling
Types of Errors
Unstructured Exception Handling Overview
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts

Exception Class in Visual Basic


To facilitate the use of structured exception handling, Visual Basic provides the ability to separate standard code from exception
handling code. Exception handling code accesses an instance of the Exception class, which allows you to retrieve information
about any exception you encounter.
Remarks
Whenever an exception is thrown, the global Err object is set, and a new instance of an Exception class is created.
The properties of the Exception class aid in identifying the code location, type, and cause of exceptions. For example, the
StackTrace property lists the called methods that led up to the exception, helping you find where the error occurs in the code.
The Message property returns a text message describing the error; you can alter it to make a cryptic message easier to
understand. If you do not supply an error message text string, the default is used. HelpLink gets or sets a link to an associated
help file. Source gets or sets a string containing the name of the object causing the error or the name of the assembly where
the exception originated.
Note
Avoid writing code that tests for specific error messages, since messages can change between versions of the class that origi
nally produced them. Instead, test for the exception type or use the exception number from the global Err object.

Exception Class Properties


The following table lists and describes properties of the Exception class.
Property Description
HelpLink Gets or sets a link to the help file associated with this exception.

HResult Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

InnerException Gets the Exception instance that caused the current exception.

Message Gets a message that describes the current exception.

Source Gets or sets the name of the application or object that caused the error.

StackTrace Gets a string representation of the frames on the call stack at the time the current exception was thrown.

TargetSite Gets the method that throws the current exception.

See Also
Tasks
Troubleshooting Exception Handling
Concepts
Introduction to Exception Handling
Types of Errors
Structured Exception Handling Overview for Visual Basic
Unstructured Exception Handling Overview
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts

Walkthrough: Structured Exception Handling


While you can still employ the On Error statement to handle exceptions in your code in order to provide unstructured
exception handling, Visual Basic 2005 also supports structured exception handling, which you can use to create and maintain
programs with comprehensive error handling. In structured exception handling, blocks of code test for specific circumstances
and react accordingly.
This walkthrough demonstrates how to add structured exception handling to a program. Specifically, it shows how to use the
Try...Catch...Finally statement to handle exceptions, and how to perform error filtering within Catch blocks.
Note
You cannot combine both structured and unstructured exception handling within a single procedure.

Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

Creating the Application


The following application is a customer order form for a company that sells teddy bears. The user interface consists of the
following controls:
One TextBox for the customer's name.
Two ComboBox controls to select the color and size of the bear.
One Order Button.
Three labels that convey the purpose of each control to the user.
When the user enters the requested information and clicks the Order button, the application displays a summary of the
order.
To create the application
1. From the File menu, select New Project. The New Project dialog box appears.
2. In the Project Types window, select Visual Basic and Windows if these are not already selected, select Windows
Application from the Templates window.
3. In the Properties window under Name, enter TeddyBearProject and click OK. The project is added to the Solution
Explorer, and the Windows Forms Designer opens.
4. Add the controls to the form, and set their properties as specified.
Control Properties Property Values
Label Name customerLabel
Text Bear Order Form

TextBox Name customerName


Text Customer Name

Label Name bearColorLabel


Text Available Colors
ComboBox Name bearColor
Items Black, Brown, Spotted
Text Bear Color

Label Name bearSizeLabel


Text Available Sizes

ComboBox Name bearSize


Items Small, Normal, Large
Text Size

Button Name order


Text Order

Adding Functionality
Now that the controls and their properties are added and set, you must place code behind them to make them function. The
following code handles the Click event for the Order button and displays a message to the customer.
To add functionality to the form and its controls
Add the following code to the Order button's Click event.
VB
Dim bearOrder As String
bearOrder = _
String.Format("You have ordered a {0} {1} bear.", _
bearSize.SelectedItem, bearColor.SelectedItem)
MsgBox(bearOrder)

The application is now ready for you to add structured exception handling code.
Adding a Try...Catch Block
To ensure that the customer has specified a color for the bear, add a Try...Catch statement. Remember the following:
A Catch clause with no identifier catches all exceptions.
A Catch clause with a When clause catches exceptions only when the expression evaluates to True; the expression type
must be implicitly convertible to Boolean.
To add a simple Try...Catch block
Add the following code to the Order button's Click event after the section that tests the size and color values, that is, after
String.Format ("You have ordered a {0} {1} bear.", BearSize.SelectedItem, BearColor.SelectedItem). This
code throws an exception if it encounters an invalid color value. In adding Try statements, be aware that the editor
automatically supplies End Try at the end of the statement.
VB
Try
If ((bearColor.SelectedIndex < 0) Or _
(bearColor.SelectedIndex > 2)) Then
Throw New System.Exception()
End If
' The Catch statement handles errors caused by a lack of bear color.
Catch ex As Exception When bearColor.SelectedIndex < 0
bearOrder = String.Format("You must select a bear color!")
Finally
Beep() ' Beep at the end.
End Try

To add an additional Catch clause


1. Add a new item, "Purple", to the bearColor ComboBox control.
2. Add the following code after the code line bearOrder = String.Format("You must select a bear color!").

VB
Catch ex As Exception When bearColor.SelectedIndex = 3
bearOrder = String.Format("There are no bears of that color.")

You can add as many Catch clauses as necessary to your code.


Testing
You can now test the application to make sure it works correctly.
To build and run the application
1. From the Build menu, select Build TeddyBearProject.
2. Press F5 to run the application. The main form appears.

To test the application


1. Enter a name in the Customer Name text box, and then select a color and size for the bear from the Available Colors
and Available Sizes combo boxes.
2. Click the Order button. If you selected either Black, Brown, or Spotted as the color in the previous step, a message
appears stating the size and color of the bear you ordered.
If you do not specify a color, a message appears prompting you to do so.
3. Click OK to cancel the message.
4. In the Available Colors text box, select Purple, and then click the Order button. A message appears stating that purple
bears are not available.
See Also
Reference
On Error Statement (Visual Basic)
Try...Catch...Finally Statement (Visual Basic)
Throw Statement (Visual Basic)
Concepts
Structured Exception Handling Overview for Visual Basic
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts

Troubleshooting Exception Handling


This topic describes problems commonly encountered when working with exceptions and how to address them.
Visual Basic supports structured exception handling, which you can use to create and maintain programs with robust,
comprehensive error handlers. Structured exception handling is code designed to detect and respond to errors during
execution by combining a control structure (similar to Select Case or While) with exceptions, protected blocks of code, and
filters.
Inner Exceptions
In cases where an exception is thrown as a direct result of a previous exception, the InnerException property describes the
original error. This information helps you to handle the error more efficiently. If there is no original error, the value of
InnerException will be a null reference or Nothing in Visual Basic. This property is read-only. For more information, see
How to: Check an Exception's Inner Exception.
Try…Catch Statements
Your code may not correctly catch exceptions if you order your Catch blocks incorrectly. Your Catch statements should move
from most specific to least specific. A Catch block by itself will catch all exceptions derived from Exception, and therefore
should always be placed as the last block before Finally.
See Also
Tasks
Walkthrough: Structured Exception Handling
Concepts
Choosing When to Use Structured and Unstructured Exception Handling
Other Resources
Exception Handling Tasks
Visual Basic Language Concepts

Unstructured Exception Handling in Visual Basic


Topics in this section discuss unstructured exception handling, the Err object, and how to retrieve information from errors.
In This Section
Unstructured Exception Handling Overview
Discusses unstructured exception handling and how to use the Err object.
Err Object in Unstructured Exception Handling
Describes the Err Object and its properties.
How to: Retrieve Information from an Error Object
Demonstrates how to get information from an Err object's properties.
Trappable Errors in Visual Basic
Lists trappable errors.
Reference
Err Object (Visual Basic)
Describes the Err object and lists its members.
Description Property (Err Object)
Describes the Err object's Description property and how to use it.
HelpContext Property (Err Object)
Describes the Err object's HelpContext property and how to use it.
HelpFile Property (Err Object)
Describes the Err object's Helpfile property and how to use it.
LastDllError Property (Err Object)
Describes the Err object's LastDLLError property and how to use it.
Number Property (Err Object)
Describes the Err object's Number property and how to use it.
Source Property (Err Object)
Describes the Err object's Source property and how to use it.
On Error Statement (Visual Basic)
Describes the On Error statement and how to use it.
Resume Statement
Describes the Resume statement and how to use it.
Exit Statement (Visual Basic)
Describes the Exit statement and how to use it.
Related Sections
Choosing When to Use Structured and Unstructured Exception Handling
Describes the advantages and disadvantages of structured and unstructured exception handling.
Types of Errors
Lists types of errors encountered in code.
Visual Basic Language Concepts

Unstructured Exception Handling Overview


In unstructured exception handling, you place an On Error statement at the beginning of a block of code, and it handles any
errors occurring within that block. When an exception is raised in a procedure after the On Error statement executes, the
program branches to the line argument specified in the On Error statement. The line argument, which is a line number or line
label, indicates the exception handler location.
Sometimes a call is made from the original procedure to another procedure, and an exception occurs in the called procedure.
In such cases, if the called procedure does not handle the exception, the exception propagates back to the calling procedure,
and execution branches to the line argument.
Note
Unstructured error handling using On Error can degrade application performance and result in code that is difficult to debug
and maintain. Structured error handling is the recommended method. For more information, see
Structured Exception Handling Overview for Visual Basic.

On Error GoTo Line


The On Error GoTo Line statement assumes that error-handling code starts at the line specified in the required line argument.
If a run-time error occurs, control branches to the line label or line number specified in the argument, activating the error
handler. The specified line must be in the same procedure as the On Error GoTo Line statement; otherwise, Visual Basic
generates a compiler error. The following example illustrates the use of an error handler with a line label:

Sub TestSub
On Error GoTo ErrorHandler
' Code that may or may not contain errors.
Exit Sub

ErrorHandler:
' Code that handles errors.
Resume
End Sub

The example contains an error handler named ErrorHandler. If any code in the TestSub subroutine generates an error, Visual
Basic immediately executes the code that follows the ErrorHandler label. At the end of the error-handling block, the Resume
statement passes control back to the line of code where the error first occurred. The rest of the subroutine then continues
executing as if the error did not occur.
Note
You must place an Exit Sub statement immediately before the error-handling block. Otherwise, Visual Basic runs the error-h
andling code when it reaches the end of the subroutine, causing unwanted or unexpected results.

On Error Resume Next


The On Error Resume Next statement specifies that in the event of a run-time error, control passes to the statement
immediately following the one in which the error occurred. At that point, execution continues. On Error Resume Next enables
you to put error-handling routines where errors will occur, rather than transferring control to another location in the
procedure.
Note
If your procedure calls another procedure, the On Error Resume Next statement becomes inactive during the execution of t
he called procedure. Therefore, you should place an On Error Resume Next statement in each called procedure that needs o
ne. This is necessary because the Resume Next behavior applies only to the procedure containing the On Error Resume Ne
xt statement. If an unhandled error occurs in a called procedure, the exception propagates back to the calling procedure, and
execution resumes on the statement following the call. In such cases, the error is not handled.

Resume also can be used on its own, outside the On Error statement. When Resume is used this way, Visual Basic returns
control to the statement that caused the error. You generally use Resume after an error handler corrects the error.
Visual Basic also provides the Resume Next statement, which directs control to the line immediately following the line of code
that caused the error. You might use Resume Next for cases in which an error will not cause your application to stop working.
You might also use it if an error will not change the expected results of your subroutine.
Another variation on the Resume statement is Resume Line, which is similar to On Error GoTo Line. Resume Line passes
control to a line you specify in the line argument. You can use Resume Line only within an error handler.
Note
When debugging your code, you must disable the On Error Resume Next statement.

On Error GoTo 0
The On Error GoTo 0 statement disables any error handler in the current procedure. If you do not include an On Error GoTo 0
statement, the error handler is still disabled when the procedure containing the exception handler ends.
Note
The On Error GoTo 0 statement is not meant to specify line 0 as the start of the error-handling code, even if the procedure c
ontains a line numbered 0.

On Error GoTo -1
The On Error GoTo -1 statement disables any exception handlers in the current procedure. If you do not include an On Error
GoTo -1 statement, the exception is automatically disabled when its procedure ends.
Note
The On Error GoTo -1 statement is not meant to specify line -1 as the start of the error-handling code, even if the procedure
contains a line numbered -1.

Unstructured Exception Handler Example


In the following code, the exception handler is named DivideByZero and handles a specific error — that of attempting to divide
by zero. If a different error occurs, Visual Basic raises a run-time error and stops the application.

Sub ErrorTest ()
' Declare variables.
Dim x As Integer, y As Integer, z As Integer
' The exception handler is named "DivideByZero".
On Error GoTo DivideByZero
' The main part of the code, which might cause an error.
x = 2
y = 0
z = x \ y

' This line disables the exception handler.


On Error GoTo 0
Console.WriteLine(x & "/" & y & " = " & z)

' Exit the subroutine before the error-handling code.


' Failure to do so can create unexpected results.
Exit Sub

' This is the exception handler, which deals with the error.
DivideByZero:
' Include a friendly message to let the user know what is happening.
Console.WriteLine("You have attempted to divide by zero!")

' Provide a solution to the error.


y = 2

' The Resume statement returns to the point at which


' the error first occurred, so the application
' can continue to run.
Resume

End Sub

See Also
Tasks
How to: Retrieve Information from an Error Object
Reference
End Statement
Err Object (Visual Basic)
Exit Statement (Visual Basic)
On Error Statement (Visual Basic)
Resume Statement
Concepts
Err Object in Unstructured Exception Handling
Introduction to Exception Handling
Types of Errors
Choosing When to Use Structured and Unstructured Exception Handling
Visual Basic Language Concepts

Err Object in Unstructured Exception Handling


To write error-handling code, you need to know which error occurred. In unstructured exception handling, you can find this out
by using the Err Object (Visual Basic).
The Err object contains properties whose values are determined by the error that just occurred. The Number property contains
the cause of the error, and the Description property contains a text message that describes the error in detail. Helpfile and
HelpContext allow you to display a related help file when a user presses the Help button or the F1 key. LastDLLError
displays the last DLL called, and whether or not the call was successful. Source specifies a string expression representing the
object or application that generated the error.
Your error handler should test or save the relevant property values before any other error can occur. Your code can handle
only a single error at a time, so you must deal with one before moving on to another.
Note
The Err object can be used only with exceptions caught with the On Error GoTo statement.

Application-Specific Errors
In addition to handling errors generated by Visual Basic, you might also want to handle errors specific to your application.
If you create an object that accesses other objects, you should write code to deal with any unhandled errors the other objects
pass back. If necessary, you can map the error codes in Err.Number to one of your own application-specific errors, and then
pass it back to the caller of your object.
See Also
Reference
On Error Statement (Visual Basic)
Description Property (Err Object)
Number Property (Err Object)
HelpFile Property (Err Object)
HelpContext Property (Err Object)
LastDllError Property (Err Object)
Source Property (Err Object)
Concepts
Introduction to Exception Handling
Types of Errors
Structured Exception Handling Overview for Visual Basic
Unstructured Exception Handling Overview
Visual Basic Language Concepts

How to: Retrieve Information from an Error Object


When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and
information that can be used to handle the error.
The Err object's properties are reset to zero or zero-length strings ("") after an On Error Resume Next statement and after an
Exit Sub or Exit Function statement within an error-handling routine. The Clear method can be used to explicitly reset Err.
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To retrieve information from an error object


1. You can filter for specific errors. This example checks to see if the error is a FileNotFound error and reacts if it is.
VB
If Err.Number = 53 Then
MsgBox("File Not Found")
End If

2. You can also examine specific properties of the error object, such as Description, Erl, HelpContext, Helpfile,
LastDLLError, Number, and Source. This example displays the description in a message box.
VB
MsgBox(Err.Description)

See Also
Reference
Err Object (Visual Basic)
Err Object Members
Description Property (Err Object)
Erl Property (Err Object)
HelpContext Property (Err Object)
HelpFile Property (Err Object)
LastDllError Property (Err Object)
Number Property (Err Object)
Source Property (Err Object)
Concepts
Choosing When to Use Structured and Unstructured Exception Handling
Visual Basic Language Concepts

Deploying Your Application


The .NET Framework provides several basic features that make it easier to deploy a variety of applications, including ClickOnce
deployment.
Deployment Features in the .NET Framework
The following basic .NET Framework features help to make deployment easier:
No-impact applications
Controlled code sharing
Side-by-side versioning
On-the-fly updates
Partially trusted code
For more information, see .NET Framework Deployment Features.
Deployment Basics
Deployment is the process by which you distribute a finished application or component to be installed on other computers. In
Visual Studio, deployment can be done based on Microsoft Windows Installer technology or on ClickOnce technology. For
more information, see Choosing a Deployment Strategy.
An application can be packaged as a single assembly, as a collection of assemblies, as cabinet (CAB) files, as a Microsoft
Windows Installer 2.0 package, or as an installer package in another format. For more information, see
Deployment Scenarios for .NET Framework Applications.
An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality.
Assemblies form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions, and
they provide the common language runtime (CLR) with the information it needs to be aware of type implementations.
This table shows common deployment tasks.
To See
Create an assembly Creating Assemblies

Sign an assembly with a strong name How to: Sign an Assembly with a Strong Name

Sign an assembly, but defer assigning a private key until a later time How to: Delay Sign an Assembly (Visual Studio)

Create a public/private key pair to use in creating a strong name How to: Create a Public/Private Key Pair

View binding information in the log file Assembly Binding Log Viewer (Fuslogvw.exe)

Deploy a Windows Forms control How to: Develop a Simple Windows Forms Control

Deploy an application for COM access Deploying an Application for COM Access

Deploy an XML Web service Deploying XML Web Services

Deploy a .NET Framework application Deploying .NET Framework Applications


Versioning
Versioning, which records the specific version of an assembly and the versions of dependent assemblies in the assembly's
manifest, is done only on assemblies with strong names. Strong-named assemblies have identifiers consisting of the
assembly's identity plus a public key and a digital signature.
By default, the CLR attempts to locate and bind with the exact version of the assembly that the application was built with,
although this behavior can be overridden by configuration file settings.
For more information, see Assemblies in the Common Language Runtime, Assembly Versioning, and
Strong-Named Assemblies.
ClickOnce Deployment
ClickOnce deployment allows you to publish Windows applications to a Web server or network file share for simplified
installation. When you want to publish your Windows application to a network server, Visual Studio automatically generates
the XML manifest files necessary for ClickOnce and publishes the application to the specified server.
ClickOnce applications are self-contained and install on a per-user basis, which means no administrative rights are required.
Applications deployed using ClickOnce technology run with a limited set of permissions based on a security zone. For more
information, see ClickOnce Deployment and Security.
ClickOnce applications can be self-updating; you can control when and how updates are deployed.
This table shows tasks associated with ClickOnce deployment.
To See
Choose which ClickOnce deployment strategy (installing from t Choosing a ClickOnce Deployment Strategy
he Web or a network share, installing from CD, or starting from
the Web or a network share) to use with your application

Choose which ClickOnce update strategy to use with your appli Choosing a ClickOnce Update Strategy
cation

Deploy a ClickOnce application How to: Publish a ClickOnce Application

Choose whether to use a ClickOnce data directory, isolated stor Accessing Local and Remote Data in ClickOnce Applications
age, or other local files when reading and writing data

Discover what prerequisites must be met before successfully d Deploying Prerequisites (Visual Studio)
eploying an application

Specify an alternate location for deployment updates How to: Specify an Alternate Location for Deployment Updates

Elevate a ClickOnce application's permission level on a client co Trusted Application Deployment Overview
mputer

Difficulties when deploying applications with ClickOnce may be caused by HTTP compression issues, manifest parsing issues,
server configuration issues, and versioning issues. For more information, see Troubleshooting ClickOnce Deployment.
Windows Installer Deployment
Microsoft Windows Installer technology creates installers that give you complete control over the installation process.
This table shows tasks associated with Windows Installer deployment.
To See
Distribute files or applications o Deployment Via Distributable Media
n CD-ROM or other media

Create a new setup project or ad How to: Create or Add a Setup Project
d an existing deployment projec
t to a solution

Create a new .cab file for Web d How to: Create or Add a Cab Project
ownload or add an existing one
to a solution
Create a merge module for a co How to: Add Merge Modules to a Deployment Project
mponent

Deploy a Windows-based applic Walkthrough: Deploying a Windows-based Application


ation to another computer

Deploy a Web site to a Web serv Deploying ASP.NET Web Sites (Visual Studio)
er

Create a custom action to send Walkthrough: Creating a Custom Action


a user to a Web site following in
stallation

Pass data to a dynamic property Walkthrough: Using a Custom Action to Display a Message at Installation
during installation using a custo
m action

Use a custom action to pre-com Walkthrough: Using a Custom Action to Pre-Compile an Assembly at Installation
pile an assembly during installat
ion

Use a custom action to create a Walkthrough: Using a Custom Action to Create a Database at Installation
database during installation

Create a Web application that ca Walkthrough: Redirecting an Application to Target a Different XML Web Service at Installation
n be redirected to target a differ
ent XML Web service

Deploy files and applications to Deployment of a Web Setup Project


a Web server

See Also
Concepts
Deployment Alternatives
Other Resources
Windows Installer Deployment Walkthroughs
Visual Basic Language Concepts

Creating and Using Components in Visual Basic


A component is a class that implements the System.ComponentModel.IComponent interface or that derives directly or
indirectly from a class that implements IComponent. A .NET Framework component is an object that is reusable, can interact
with other objects, and provides control over external resources and design-time support.
An important feature of components is that they are designable, which means that a class that is a component can be used in
the Visual Studio Integrated Development Environment. A component can be added to the Toolbox, dragged and dropped onto
a form, and manipulated on a design surface. Notice that base design-time support for components is built into the .NET
Framework; a component developer does not have to do any additional work to take advantage of the base design-time
functionality.
A control is similar to a component, as both are designable. However, a control provides a user interface, while a component
does not. A control must derive from one of the base control classes: Control or Control.
When to Create a Component
If your class will be used on a design surface (such as the Windows Forms or Web Forms Designer) but has no user interface, it
should be a component and implement IComponent, or derive from a class that directly or indirectly implements
IComponent.
The Component and MarshalByValueComponent classes are base implementations of the IComponent interface. The main
difference between these classes is that the Component class is marshaled by reference, while IComponent is marshaled by
value. The following list provides broad guidelines for implementers.
If your component needs to be marshaled by reference, derive from Component.
If your component needs to be marshaled by value, derive from MarshalByValueComponent.
If your component cannot derive from one of the base implementations due to single inheritance, implement
IComponent.
For more information about design-time support, see Design-Time Attributes for Components and
Extending Design-Time Support.
Component Classes
The System.ComponentModel namespace provides classes that are used to implement the run-time and design-time behavior
of components and controls. This namespace includes the base classes and interfaces for implementing attributes and type
converters, binding to data sources, and licensing components.
The core component classes are:
Component. A base implementation for the IComponent interface. This class enables object sharing between
applications.
MarshalByValueComponent. A base implementation for the IComponent interface.
Container. The base implementation for the IContainer interface. This class encapsulates zero or more components.
Some of the classes used for component licensing are:
License. The abstract base class for all licenses. A license is granted to a specific instance of a component.
LicenseManager. Provides properties and methods to add a license to a component and to manage a LicenseProvider.
LicenseProvider. The abstract base class for implementing a license provider.
LicenseProviderAttribute. Specifies the LicenseProvider class to use with a class.
Classes commonly used for describing and persisting components.
TypeDescriptor. Provides information about the characteristics for a component, such as its attributes, properties, and
events.
EventDescriptor. Provides information about an event.
PropertyDescriptor. Provides information about a property.
Related Sections
Class vs. Component vs. Control
Defines component and control, and discusses the differences between them and classes.
Component Authoring
Roadmap for getting started with components.
Component Authoring Walkthroughs
Links to topics that provide step-by-step instruction for component programming.
Component Classes
Describes what makes a class a component, ways to expose component functionality, controlling access to components, and
controlling how component instances are created.
Troubleshooting Control and Component Authoring
Explains how to fix common problems.
See Also
Tasks
How to: Access Design-Time Support in Windows Forms
How to: Extend the Appearance and Behavior of Controls in Design Mode
How to: Perform Custom Initialization for Controls in Design Mode
Visual Basic Language Concepts

Going Further with Visual Basic


While the My feature offers a wide variety of functionality, you may find yourself wanting to go beyond My and explore what
the .NET Framework offers. These pages provide overviews and pointers to the relevant documentation for areas of the .NET
Framework, including forms, network operations, and Web services.
In This Section
Authentication and Authorization in the .NET Framework with Visual Basic
Describes how to use the .NET Framework for user authentication and authorization.
Code-Access Permissions and Security in the .NET Framework with Visual Basic
Describes how code access permissions and security work in the .NET Framework.
Collections in the .NET Framework with Visual Basic
Describes the specialized classes for data storage and retrieval provided by the .NET Framework.
File I/O in the .NET Framework with Visual Basic
Describes how to use the .NET Framework for file I/O.
Graphics in the .NET Framework with Visual Basic
Describes how to use the .NET Framework when working with graphics.
Logging and Tracing in the .NET Framework with Visual Basic
Describes how to use the .NET Framework when creating and manipulating logs or tracing.
Customizing Projects and Extending My with Visual Basic
Describes how to specify your own extensions to the application model and customize project templates to provide
additional My objects.
Network Operations in the .NET Framework with Visual Basic
Describes how to use the .NET Framework when performing network operations.
Port Operations in the .NET Framework with Visual Basic
Describes how to use the .NET Framework when performing port operations.
Serialization in the .NET Framework with Visual Basic
Describes how to use the .NET Framework for serialization.
Developing for Smart Devices with Visual Basic
Provides an overview of the basics of programming for smart devices.
Advanced Multithreading with Visual Basic
Provides an overview of the threading model.
Windows Forms Application Concepts in Visual Basic
Provides an overview of Windows applications.
Adding Printable Reports to Visual Studio Applications
Discusses options available for writing reports.
Visual Basic Language Concepts

Authentication and Authorization in the .NET Framework with


Visual Basic
The .NET Framework provides an extensible framework for authorizing and authenticating users. The topics in this section
provide an overview of these concepts and list the commonly used classes
In This Section
Basics of .NET Framework User Operations
Discusses how to work with application authorization in the .NET Framework and how to use role-based security.
Walkthrough: Implementing Custom Authentication and Authorization
Demonstrates how to implement custom authentication and authorization, and how to override the application thread's
default identity.
Classes Used in .NET Framework User Operations
Lists the classes used in the .NET Framework that form the basis of the user-authentication system.
See Also
Reference
My.User Object
System.Security.Principal
Concepts
Accessing User Data
Other Resources
Going Further with Visual Basic
Visual Basic Language Concepts

Basics of .NET Framework User Operations


The .NET Framework provides a role-based security implementation in the System.Security.Principal namespace, which you
can use for authorizing and authenticating users in your application. This topic discusses how to work with application
authorization in the .NET Framework and create IIdentity and IPrincipal objects to represent users.
An IIdentity encapsulates an authenticated user. An IPrincipal is a combination of the identity of the user and any roles he or
she has. You can use the predefined identity and principal classes in the System.Security.Principal namespace or you can
add custom authentication by creating classes that implement the interfaces.
To use these interfaces, you must fully qualify the interface names or import the appropriate namespaces by including the
Imports statement(s) at the beginning of the affected source code file. For more information, see Imports Statement.
Using Role-Based Security in .NET Framework Applications
Each application thread can have an associated principal object (accessible through the CurrentPrincipal property) that
represents the security context of the user on whose behalf the code is running. A principal object encapsulates a user's user
security context (or identity) object. Using two objects allows for a separation of authentication (in the identity object) and
authorization (in the principal).
An identity object must implement the IIdentity interface. An identity object represents a particular user and exposes the
following properties as required by the IIdentity interface: Name, IsAuthenticated, and AuthenticationType. Identity objects
typically have additional private members that perform the user authentication.
A principal object must implement the IPrincipal interface. A principal object encapsulates the user's security context by
exposing the following members as required by the IPrincipal interface: the IsInRole method, which performs authorization,
and the Identity property, which provides access to the user's identity object.
Working with Identities
The .NET Framework provides four classes that implement the IIdentity interface:
WindowsIdentity
GenericIdentity
PassportIdentity
FormsIdentity
Each class enables you to work with different kinds of user identities. To access the current WindowsIdentity object for an
application that uses Windows authentication, use the static GetCurrent method of the WindowsIdentity class. You can also
set the current thread's principal by calling the My.User.InitializeWithWindowsUser Method.
You can also create custom identity classes by implementing the IIdentity interface in your own custom class. For more
information about creating custom identities, see Walkthrough: Implementing Custom Authentication and Authorization.
Working with Principals
The .NET Framework provides the IPrincipal interface to link user roles and identities. If your application performs
authorization, it should use an object that implements IPrincipal. For example, the WindowsIdentity and GenericIdentity
classes provide built-in implementations of IPrincipal. Alternatively, you can create your own custom principal classes based
on IPrincipal.
You can link the current thread to an IPrincipal object by assigning the object to the thread's CurrentPrincipal property or
the My.User.CurrentPrincipal Property. You can then perform an authorization check by testing whether the user is a member
of a particular role. You do so by using the principal's IsInRole method.
ASP.NET applications handle IPrincipal objects differently than do other .NET Framework applications. ASP.NET creates the
appearance of a session over the stateless HTTP protocol. As a part of this session, the IPrincipal object representing the user
is available from the User property of the HttpContext object for all code executing the user's request. The common language
runtime automatically updates CurrentPrincipal with the User value after the OnAuthenticate event of the Global.asax file.
ASP.NET applications often use the User property to perform authorization checks.
Note
Manually changing User automatically updates the CurrentPrincipal property for all threads executing within the same HTT
P context. However, changing CurrentPrincipal does not affect the User property. It affects only the chosen thread for the re
mainder of the request.

In ASP.NET applications, the My.User.CurrentPrincipal Property updates the User property.


For more information about creating your own IPrincipal types, see
Walkthrough: Implementing Custom Authentication and Authorization.
Granting Permissions to Work with IIdentity and IPrincipal Objects
Care should be used when granting permissions to work with IIdentity objects, because these objects make sensitive user-
related information available. You should protect the application's current IPrincipal object from changes because the
application's authorization capability is based on its current principal.
The .NET Framework provides this protection by requiring that these operations have code-access security permission. Grant
the System.Security.Permissions.SecurityPermissionAttribute.ControlPrincipal permission to applications that need to
manipulate these objects by using Code Access Security Policy Tool (Caspol.exe).
By default, all locally installed applications have this permission because they run under the FullTrust permission set.
Executing the following methods requires the ControlPrincipal permission:
System.AppDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy)
System.Security.Principal.WindowsIdentity.GetCurrent
System.Security.Principal.WindowsIdentity.Impersonate
System.Threading.Thread.CurrentPrincipal

See Also
Tasks
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User Object
Other Resources
Authentication and Authorization in the .NET Framework with Visual Basic
Visual Basic Language Concepts

Walkthrough: Implementing Custom Authentication and


Authorization
This walkthrough demonstrates how to implement custom authentication and authorization by using classes that derive from
IIdentity and IPrincipal. This walkthrough also demonstrates how to override the application thread's default identity, the
Windows identity, by setting My.User.CurrentPrincipal to an instance of the class that derives from IPrincipal. The new user
information is available immediately through the My.User object, which returns information about the thread's current user
identity.
Business applications often provide access to data or resources based on credentials supplied by the user. Typically, such
applications check the role of a user and provide access to resources based on that role. The common language runtime
provides support for role-based authorization based on a Windows account or a custom identity. For more information, see
Role-Based Security.
Getting Started
First, set up a project with a main form and a login form, and configure it to use custom authentication.
To create the sample application
1. Create a new Visual Basic Windows Application project. For more information, see
How to: Create a Windows Application Project.
The default name of the main form is Form1.
2. On the Project menu, click Add New Item.
3. Select the Login Form template and click Add.
The default name of the login form is LoginForm1.
4. On the Project menu, click Add New Item.
5. Select the Class template, change the name to SampleIIdentity, and then click Add.
6. On the Project menu, click Add New Item.
7. Select the Class template, change the name to SampleIPrincipal, and then click Add.
8. On the Project menu, click <ApplicationName> Properties.
9. In the Project Designer, click the Application tab.
10. Change the Authentication mode drop-down to Application-defined.
To configure the main form
1. Switch to Form1 in the Forms Designer.
2. Add a Button to Form1 from the Toolbox.
The default name of the button is Button1.
3. Change the button text to Authenticate.
4. From the Toolbox, add a Label to Form1.
The default name of the label is Label1.
5. Change the label text to an empty string.
6. From the Toolbox, add a Label to Form1.
The default name of the label is Label2.
7. Change the label text to an empty string.
8. Double-click Button1 to create the event handler for the Click event, and then open the Code Editor.
9. Add the following code to the Button1_Click method.
VB
My.Forms.LoginForm1.ShowDialog()
' Check if the user was authenticated.
If My.User.IsAuthenticated Then
Me.Label1.Text = "Authenticated " & My.User.Name
Else
Me.Label1.Text = "User not authenticated"
End If

If My.User.IsInRole(ApplicationServices.BuiltInRole.Administrator) Then
Me.Label2.Text = "User is an Administrator"
Else
Me.Label2.Text = "User is not an Administrator"
End If

You can run the application, but because there is no authentication code, it will not authenticate any user. Adding
authentication code is discussed in the following section.
Creating an Identity
The .NET Framework uses the IIdentity and IPrincipal interfaces as the basis for authentication and authorization. Your
application can use custom user authentication by implementing these interfaces, as these procedures demonstrate.
To create a class that implements IIdentity
1. Select the SampleIIdentity.vb file in Solution Explorer.
This class encapsulates a user's identity.
2. In the line following Public Class SampleIIdentity, add the following code to inherit from IIdentity.

VB
Implements System.Security.Principal.IIdentity

After you add that code and press ENTER, the Code Editor creates stub properties that you must implement.
3. Add private fields to store the user name and a value that indicates if the user is authenticated.
VB
Private nameValue As String
Private authenticatedValue As Boolean
Private roleValue As ApplicationServices.BuiltInRole

4. Enter the following code in the AuthenticationType property.


The AuthenticationType property needs to return a string that indicates the current authentication mechanism.
This example uses explicitly specified authentication, so the string is "Custom Authentication". If the user authentication
data were stored in a SQL Server database, the value might be "SqlDatabase".
VB
Return "Custom Authentication"
5. Enter the following code in the IsAuthenticated property.
VB
Return authenticatedValue

The IsAuthenticated property needs to return a value that indicates whether the user has been authenticated.
6. The Name property needs to return the name of the user associated with this identity.
Enter the following code in the Name property.
VB
Return nameValue

7. Create a property that returns the user's role.


VB
Public ReadOnly Property Role() As ApplicationServices.BuiltInRole
Get
Return roleValue
End Get
End Property

8. Create a Sub New method that initializes the class by authenticating the user and then setting the user name and role,
based on a name and a password.
This method calls a method named IsValidNameAndPassword to determine if a user name and password combination is
valid.
VB
Public Sub New(ByVal name As String, ByVal password As String)
' The name is not case sensitive, but the password is.
If IsValidNameAndPassword(name, password) Then
nameValue = name
authenticatedValue = True
roleValue = ApplicationServices.BuiltInRole.Administrator
Else
nameValue = ""
authenticatedValue = False
roleValue = ApplicationServices.BuiltInRole.Guest
End If
End Sub

9. Create a method named IsValidNameAndPassword that determines if a user name and password combination is valid.
Security Note
The authentication algorithm must treat passwords securely. For example, the password should not be stored in a class
field.

You should not store user passwords in your system, because if that information is leaked, there is no more security. You
could store the hash of each user's password. (A hash function scrambles data so the input cannot be deduced from the
output.) A password cannot be directly determined from the hash of a password.
However, a malicious user could take the time to generate a dictionary of the hashes of all possible passwords, and then
look up the password for a given hash. To protect against this type of attack, you should add salt to the password before
hashing it, to generate a salted hash. Salt is extra data that is unique to each password, which make it impossible to
precompute a hash dictionary.
To protect the passwords from malicious users, you should store only salted hashes of the passwords, preferably on a
secure computer. It is very difficult for a malicious user to recover a password from a salted hash. This example uses the
GetHashedPassword and GetSalt methods to load a user's hashed password and salt.

VB
Private Function IsValidNameAndPassword( _
ByVal username As String, _
ByVal password As String) _
As Boolean

' Look up the stored hashed password and salt for the username.
Dim storedHashedPW As String = GetHashedPassword(username)
Dim salt As String = GetSalt(username)

'Create the salted hash.


Dim rawSalted As String = salt & Trim(password)
Dim saltedPwBytes() As Byte = _
System.Text.Encoding.Unicode.GetBytes(rawSalted)
Dim sha1 As New _
System.Security.Cryptography.SHA1CryptoServiceProvider
Dim hashedPwBytes() As Byte = sha1.ComputeHash(saltedPwBytes)
Dim hashedPw As String = Convert.ToBase64String(hashedPwBytes)

' Compare the hashed password with the stored password.


Return hashedPw = storedHashedPW
End Function

10. Create functions named GetHashedPassword and GetSalt that return the hashed password and salt for the specified user.
Security Note
You should avoid hard coding the hashed passwords and salts into your client applications for two reasons. First, malici
ous users may be able to access them and find a hash collision. Second, you cannot change or revoke a user's passwor
d. The application should obtain the hashed password and salt for a given user from a secure source that an administra
tor maintains.

Although, for simplicity, this example has a hard-coded, hashed password and salt, you should use a more secure
approach in production code. For example, you could store the user information in a SQL Server database and access it
with stored procedures. For more information, see How to: Connect to Data in a Database.
Note
The password corresponding to this hard-coded hashed password is given in the "Testing the Application" section.

VB
Private Function GetHashedPassword(ByVal username As String) As String
' Code that gets the user's hashed password goes here.
' This example uses a hard-coded hashed passcode.
' In general, the hashed passcode should be stored
' outside of the application.
If Trim(username).ToLower = "testuser" Then
Return "ZFFzgfsGjgtmExzWBRmZI5S4w6o="
Else
Return ""
End If
End Function

Private Function GetSalt(ByVal username As String) As String


' Code that gets the user's salt goes here.
' This example uses a hard-coded salt.
' In general, the salt should be stored
' outside of the application.
If Trim(username).ToLower = "testuser" Then
Return "Should be a different random value for each user"
Else
Return ""
End If
End Function

The SampleIIdentity.vb file should now contain the following code:


VB
Public Class SampleIIdentity
Implements System.Security.Principal.IIdentity

Private nameValue As String


Private authenticatedValue As Boolean
Private roleValue As ApplicationServices.BuiltInRole

Public ReadOnly Property AuthenticationType() As String Implements System.Security.Prin


cipal.IIdentity.AuthenticationType
Get
Return "Custom Authentication"
End Get
End Property

Public ReadOnly Property IsAuthenticated() As Boolean Implements System.Security.Princi


pal.IIdentity.IsAuthenticated
Get
Return authenticatedValue
End Get
End Property

Public ReadOnly Property Name() As String Implements System.Security.Principal.IIdentit


y.Name
Get
Return nameValue
End Get
End Property

Public ReadOnly Property Role() As ApplicationServices.BuiltInRole


Get
Return roleValue
End Get
End Property

Public Sub New(ByVal name As String, ByVal password As String)


' The name is not case sensitive, but the password is.
If IsValidNameAndPassword(name, password) Then
nameValue = name
authenticatedValue = True
roleValue = ApplicationServices.BuiltInRole.Administrator
Else
nameValue = ""
authenticatedValue = False
roleValue = ApplicationServices.BuiltInRole.Guest
End If
End Sub
Private Function IsValidNameAndPassword( _
ByVal username As String, _
ByVal password As String) _
As Boolean
' Look up the stored hashed password and salt for the username.
Dim storedHashedPW As String = GetHashedPassword(username)
Dim salt As String = GetSalt(username)

'Create the salted hash.


Dim rawSalted As String = salt & Trim(password)
Dim saltedPwBytes() As Byte = _
System.Text.Encoding.Unicode.GetBytes(rawSalted)
Dim sha1 As New _
System.Security.Cryptography.SHA1CryptoServiceProvider
Dim hashedPwBytes() As Byte = sha1.ComputeHash(saltedPwBytes)
Dim hashedPw As String = Convert.ToBase64String(hashedPwBytes)

' Compare the hashed password with the stored password.


Return hashedPw = storedHashedPW
End Function

Private Function GetHashedPassword(ByVal username As String) As String


' Code that gets the user's hashed password goes here.
' This example uses a hard-coded hashed passcode.
' In general, the hashed passcode should be stored
' outside of the application.
If Trim(username).ToLower = "testuser" Then
Return "ZFFzgfsGjgtmExzWBRmZI5S4w6o="
Else
Return ""
End If
End Function

Private Function GetSalt(ByVal username As String) As String


' Code that gets the user's salt goes here.
' This example uses a hard-coded salt.
' In general, the salt should be stored
' outside of the application.
If Trim(username).ToLower = "testuser" Then
Return "Should be a different random value for each user"
Else
Return ""
End If
End Function

End Class

Creating a Principal
Next, you need to implement a class that derives from IPrincipal, and have it return instances of the SampleIIdentity class.
To create a class that implements IPrincipal
1. Select the SampleIPrincipal.vb file in Solution Explorer.
This class encapsulates a user's identity. You can use the My.User object to attach this principal to the current thread and
access the user's identity.
2. In the line following Public Class SampleIPrincipal, add the following code to inherit from IPrincipal.

VB
Implements System.Security.Principal.IPrincipal
After you add that code and press ENTER, the Code Editor creates a stub property and method that you must implement.
3. Add a private field to store the identity associated with this principal.
VB
Private identityValue As SampleIIdentity

4. Enter the following code in the Identity property.


VB
Return identityValue

The Identity property needs to return the user identity of the current principal.
5. Enter the following code in the IsInRole method.
The IsInRole method determines whether the current principal belongs to the specified role.
VB
Return role = identityValue.Role.ToString

6. Create a Sub New method that initializes the class with a new instance of SampleIIdentity given a user name and
password.
VB
Public Sub New(ByVal name As String, ByVal password As String)
identityValue = New SampleIIdentity(name, password)
End Sub

This code sets the user identity for the SampleIPrincipal class.
The SampleIPrincipal.vb file should now contain the following code:
VB
Public Class SampleIPrincipal
Implements System.Security.Principal.IPrincipal

Private identityValue As SampleIIdentity

Public ReadOnly Property Identity() As System.Security.Principal.IIdentity Implements S


ystem.Security.Principal.IPrincipal.Identity
Get
Return identityValue
End Get
End Property

Public Function IsInRole(ByVal role As String) As Boolean Implements System.Security.Pr


incipal.IPrincipal.IsInRole
Return role = identityValue.Role.ToString
End Function
Public Sub New(ByVal name As String, ByVal password As String)
identityValue = New SampleIIdentity(name, password)
End Sub

End Class
Connecting the Login Form
The application can use the login form to gather a user name and password. It can use this information to initialize an instance
of the SampleIPrincipal class and use the My.User object to set the current thread's identity to that instance.
To configure the login form
1. Select LoginForm1 in the designer.
2. Double-click the OK button to open the Code Editor for the Click event.
3. Replace the code in the OK_Click method with the following code.
VB
Dim samplePrincipal As New SampleIPrincipal( _
Me.UsernameTextBox.Text, Me.PasswordTextBox.Text)
Me.PasswordTextBox.Text = ""
If (Not samplePrincipal.Identity.IsAuthenticated) Then
' The user is still not validated.
MsgBox("The username and password pair is incorrect")
Else
' Update the current principal.
My.User.CurrentPrincipal = samplePrincipal
Me.Close()
End If

Testing the Application


Now that the application has authentication code, you can run the application and attempt to authenticate a user.
To test the application
1. Start the application.
2. Click Authenticate.
The login form opens.
3. Enter TestUser in the User name box and BadPassword in the Password box, and then click OK.
A message box opens stating that user name and password pair is incorrect.
4. Click OK to dismiss the message box.
5. Click Cancel to dismiss the login form.
The labels in the main form now state User not authenticated and User is not an Administrator.
6. Click Authenticate.
The login form opens.
7. Enter TestUser in the User Name text box and Password in the Password text box, and then click OK. Make sure that
the password is entered with the correct capitalization.
The labels in the main form now say Authenticated TestUser and User is an Administrator.

See Also
Tasks
How to: Connect to Data in a Database
Reference
My.User Object
IIdentity
IPrincipal
Concepts
Accessing User Data
Other Resources
Authentication and Authorization in the .NET Framework with Visual Basic
Authentication and Authorization in the .NET Framework with Visual Basic
Visual Basic Language Concepts

Classes Used in .NET Framework User Operations


The IIdentity and IPrincipal interfaces form the basis of the .NET Framework user-authentication system. You can use
implementations of these interfaces that the .NET Framework provides, or you can implement these classes yourself.
Basic Classes Used for User Operations
Most of the classes that support user operations are located in the System.Security.Principal namespace. For a more
comprehensive listing, consult the .NET Framework documentation.
The following classes implement the IIdentity interface, which defines the basic functionality of an identity object.
Class Description
GenericIdentity Represents a generic user.

WindowsIdentity Represents a Windows user.

IdentityReference Represents an identity and is the base class for the NTAccount and SecurityIdentifier classes.

NTAccount Represents a user or group account.

SecurityIdentifier Represents a security identifier (SID) and provides marshaling and comparison operations for SIDs.

The following classes implement the IPrincipal interface, which defines the basic functionality of a principal object.
Class Description
GenericPrincipal Represents a generic principal.

WindowsPrincipal Allows code to check the Windows group membership of a Windows user.

This table lists the most important enumerations used for .NET Framework user operations.
Enumeration Description
PrincipalPolicy Specifies how principal and identity objects should be created for an application domain.

WellKnownSidType Defines a set of commonly used security identifiers (SIDs).

WindowsAccountType Specifies the type of Windows account used.

WindowsBuiltInRole Specifies common roles to be used with IsInRole.

See Also
Tasks
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User Object
Other Resources
Authentication and Authorization in the .NET Framework with Visual Basic
Visual Basic Language Concepts

Code-Access Permissions and Security in the .NET Framework


with Visual Basic
In the .NET Framework, code-access security limits the access that code has to protected resources and operations. Every
application that targets the common language runtime must interact with the runtime's security system. When an application
executes, it is automatically evaluated and given a set of permissions by the runtime. Depending on the permissions that the
application receives, it either runs properly or generates a security exception.
The local security settings on a particular computer ultimately control which permissions your code receives. Because these
settings can change from computer to computer, you can never be sure that your code will receive sufficient permissions to
run. For more information, see Code Access Security Basics.
Code-Access Permissions
Code-access-permission objects are used to protect resources and operations from use by unauthorized users. They are a
fundamental part of the common language runtime's mechanism for enforcing security restrictions on managed code.
Code-access permissions allow a user to access a protected resource, such as a file, or to perform a protected action, such as
accessing managed code. All code-access permissions can be requested by code; whether or not permissions are granted is
determined by the runtime. Each code-access permission derives from the CodeAccessPermission class, and therefore
permissions have common methods: Assert, Demand, Deny, PermitOnly, IsSubSetOf, Intersect, and Union.
Permissions Provided by the .NET Framework
This table shows the code-access permissions provided by the .NET Framework.
Permission class Allows
AspNetHostingPermission Access to resources in ASP.NET-hosted environments.

DirectoryServicesPermission Access to the System.DirectoryServices classes.

DnsPermission Access to Domain Name System (DNS) servers on a network.

EnvironmentPermission Reading from or writing to environment variables.

EventLogPermission Reading from or writing to event log services.

FileDialogPermission Reading from or writing to files by means of an Open dialog box.

FileIOPermission Reading from or writing to files or directories.

IsolatedStorageFilePermission Reading from or writing to files or directories in isolated storage.

MessageQueuePermission Access to message queues through the managed Message Queuing (also known as MSMQ) i
nterfaces.

OdbcPermission Accessing ODBC (Open Database Connectivity) data sources.

OleDbPermission Accessing databases using OLE DB.

OraclePermission Accessing Oracle databases.

PerformanceCounterPermission Accessing performance counters.

PrintingPermission Accessing printers.


ReflectionPermission Determining information about a type at run time.

RegistryPermission Reading from, writing to, creating, or deleting registry keys and values.

SecurityPermission Executing, asserting permissions, calling into unmanaged code, skipping verification, and othe
r security-related rights.

ServiceControllerPermission Accessing running or stopped services.

SocketPermission Making or accepting connections on a transport address.

SqlClientPermission Accessing SQL databases.

UIPermission Accessing user interface functionality.

WebPermission Making or accepting connections on a Web address.


Creating Your Own Permissions
The .NET Framework supplies a set of code-access-permission classes designed to help protect a specific set of resources and
operations, focusing on those resources exposed by the .NET Framework. For most environments, the built-in code-access
permissions are adequate. However, in some situations, it might make sense to define your own code-access-permission class.
For more information, see Creating Your Own Code Access Permissions.
Identity Permissions
Identity permissions represent characteristics that identify an assembly. The common language runtime grants identity
permissions to an assembly when it is loaded, based on the information it obtains about the assembly. For more information,
see Identity Permissions.
Role-based Permissions
Business applications often provide access to data or resources based on credentials supplied by the user. Typically, such
applications check the role of a user and provide access to resources based on that role. The common language runtime
provides support for role-based authorization based on a Windows account or a custom identity. For more information, see
Role-Based Security.
Security Tasks
The following table lists tasks associated with permissions and security.
To See
Request permission to access unmana How to: Request Permission to Access Unmanaged Code
ged code

Request optional permissions How to: Request Optional Permissions by Using the RequestOptional Flag

Request permission for a named per How to: Request Permission for a Named Permission Set
mission set

Request XML-encoded permissions Requesting XML-Encoded Permissions

Refuse permissions How to: Refuse Permissions by Using the RequestRefuse Flag

Perform an imperative security check How to: Perform Imperative Security Checks

Perform a declarative security check Performing Declarative Security Checks


Override a security check Overriding Security Checks

Share a library with partially trusted c Sharing a Library with Partially Trusted Code
ode

Require full trust for types within an Requiring Full Trust for Types Within an AllowPartiallyTrustedCallersAttribute Assembly
AllowPartiallyTrustedCallersAttribute
assembly

Create WindowsIdentity and How to: Create a WindowsPrincipal Object


WindowsPrincipal objects

Create GenericPrincipal and How to: Create GenericPrincipal and GenericIdentity Objects
GenericIdentity objects

The .NET Framework Security Policy Model


Five elements make up the .NET Framework security policy model. They are:
Security policy levels: enterprise, machine, user, and application domain.
Code groups, which exist as a hierarchy within the enterprise, machine, and user policy levels.
Named permission sets associated with each code group.
Evidence that provides information about the identity of code.
Application domain hosts that provide evidence about code to the common language runtime.
Security Policy Levels
Four security policy levels are provided by the .NET Framework to compute the permission grant of an assembly or application
domain. Each level contains its own hierarchy of code groups and permission sets. The runtime computes the allowed
permission set as the sum of permissions allowed by all participating levels in a policy
The levels are:
Enterprise policy. Applies to all managed code in an enterprise setting where an enterprise configuration file is
distributed.
Machine policy. Applies to all managed code on the computer.
User policy. Applies to code in all the processes associated with the current operating-system user when the common
language runtime starts.
Application domain policy. Applies to managed code in the host's application domain.
For more information, see Security Policy Levels.
Code Groups
A code group is a logical grouping of code that has a specified condition for membership. Any code that meets the
membership condition is included in the group. Code groups have associated permission sets that are evaluated during a
policy grant. For more information, see Code Groups.
Named Permission Sets
A named permission set is a set of permissions that administrators can associate with a code group. A named permission set
consists of at least one permission, as well as a name and description for the set. More than one code group can be associated
with a specific permission set.
This table shows the named permission sets provided by the common language runtime.
Name Description
Nothing No permissions (code cannot run).
Execution Permission to run (execute), but no permissions to use protected resources.

Internet Default policy permission set suitable for content from unknown origin.

Local Intranet Default policy permission set within an enterprise.

Everything All standard (built-in) permissions, except permission to skip verification.

FullTrust Full access to all resources.

For more information, see Named Permission Sets.


Evidence
Evidence is the information that the common language runtime uses to make decisions based on security policy. Evidence
indicates to the runtime that code has a particular characteristic and can include application directory, publisher, site, and URL.
For more information, see Evidence.
Application-Domain Hosts
Each .NET Framework application runs in an application domain under the control of a host that creates the application domain
and loads assemblies into it. Application domains can include:
Browser hosts. Run code within the context of a Web site.
Custom-designed hosts. Create domains and load assemblies into domains, including dynamic assemblies.
Server hosts, Run code that handles requests submitted to a server.
Shell hosts. Launch applications (.exe files) from the shell.
This table lists tasks associated with application domains:
To See
Create an application domain How to: Create an Application Domain

Set application-domain-level security policy Setting Application Domain-Level Security Policy

Configure an application domain How to: Configure an Application Domain

Call functions in a specific application domain Calling Functions in a Specific Application Domain

Retrieve setup information from an application domain Retrieving Setup Information from an Application Domain

Unload an application domain How to: Unload an Application Domain

For more information, see AppDomain, Application Domain Hosts and Programming with Application Domains.
See Also
Tasks
Troubleshooting Code Access Security Exceptions
Concepts
Isolation by User, Domain, and Assembly
Other Resources
Configuring Security Policy Using the .NET Framework Configuration Tool (Mscorcfg.msc)
Configuring Security Policy Using the Code Access Security Policy Tool (Caspol.exe)
Visual Basic Language Concepts

Collections in the .NET Framework with Visual Basic


The .NET Framework provides specialized classes for data storage and retrieval. These classes provide support for stacks,
queues, lists, and hash tables. Most collection classes implement the same interfaces. You can create your own collection
classes, if needed, by implementing these interfaces.
You should to determine which type of collection is most appropriate for your needs.
Differences Between Visual Basic and .NET Framework Collection Classes
The .NET Framework collection classes are defined in the System.Collections, System.Collections.Generic,
System.Collections.Specialized, and System.Collections.ObjectModel namespaces. The main differences between the Visual
Basic and .NET Framework collection classes include the following:
Index base. .NET Framework collections are zero-based, while the Visual Basic collection is one-based. This means that
the elements of a Visual Basic collection have index values from 1 through the value of the
Count Property (Collection Object), whereas the elements of a .NET Framework collection have index values from 0
through one less than the value of the collection's Count property.
Element type. The Visual Basic collection supports elements of type Object. This collection is not type-safe—you can add
an element of any data type. This usually results in degraded performance because you must convert the elements from
the Object data type to their true type.
Some of the .NET Framework collections also have elements of type Object, but many others are strongly typed,
meaning they support elements of a specific type, which makes them type-safe and usually results in optimal
performance.
Keyed elements. The Visual Basic collection allows you to specify a key when you add an element to it. The key is a
unique string value which you can use later to access that particular element. The .NET Framework collections vary in
regard to keys. Some support keys and some do not.
System.Collections Classes
The classes in the System.Collections namespace do not store elements as specifically typed objects, but as objects of type
Object.
The following table lists some of the commonly used classes:
Class Description
ArrayList Implements the IList interface, using an array whose size is dynamically increased as required.

BitArray Manages a compact array of bit values, which are represented as Boolean values, where True indicates that the bit
is on (1) and False indicates the bit is off (0).

Hashtable Represents a collection of key/value pairs that are organized based on the hash code of the key.

Queue Represents a first-in-first-out (FIFO) collection of objects.

Stack Represents a simple last-in-first-out (LIFO) non-generic collection of objects.

System.Collections.Generic and System.Collections.ObjectModel Classes


The System.Collections.Generic and System.Collections.ObjectModel namespaces provide generic types, which allow
you to create strongly typed collections and specify the element data type when you create them.
The following table lists some of the commonly used classes:
Class Description
Collection Provides the base class for a generic collection.
Dictionary Represents a collection of key/value pairs that are organized based on the key.

KeyedCollection Provides the abstract base class for a collection whose keys are embedded within the values.

LinkedList Represents a doubly linked list.

LinkedListNode Represents a node in a LinkedList. This class cannot be inherited.

List Implements the IList interface using an array whose size is dynamically increased as required.

Queue Represents a first-in-first-out collection of objects.

SortedDictionary Represents a collection of key/value pairs that are sorted on the key.

SortedList Represents a collection of key/value pairs that are sorted by key based on the associated IComparer imple
mentation.

Stack Represents a variable size last-in-first-out (LIFO) collection of instances of the same arbitrary type.

ReadOnlyCollection Provides the base class for a generic read-only collection.

System.Collections.Specialized Classes
The System.Collections.Specialized namespace provides specialized and strongly typed collection classes, such as string-
only collections and linked-list and hybrid dictionaries.
The following table lists some of the commonly used classes:
Class Description
CollectionsUtil Creates collections that ignore the case in strings.

HybridDictionary Implements IDictionary by using a ListDictionary while the collection is small, and then switching t
o a Hashtable when the collection gets large.

ListDictionary Implements IDictionary using a singly linked list. Recommended for collections that typically cont
ain 10 items or less.

NameObjectCollectionBase Provides the abstract base class for a collection of associated string keys and object values that can
be accessed either with the key or with the index.

NameValueCollection Represents a collection of associated string keys and string values that can be accessed either with
the key or with the index.

OrderedDictionary Represents a collection of key/value pairs that are ordered based on the key or index.

StringCollection Represents a collection of strings.

StringDictionary Implements a hash table with the key and the value strongly typed to be strings rather than object
s.

See Also
Reference
Collection Object (Visual Basic)
Concepts
Collections in Visual Basic
Other Resources
Going Further with Visual Basic
Visual Basic Language Concepts

File I/O in the .NET Framework with Visual Basic


When performing complex file I/O operations, such as isolated storage, Visual Basic users may need to investigate the .NET
Framework and the classes it offers. This section provides an overview of file I/O and FileSystem concepts in the .NET
Framework and a listing of commonly used classes.
In This Section
Basics of .NET Framework File I/O and the File System
Provides an overview of file I/O concepts in the .NET Framework, including streams, isolated storage, file events, file
attributes, and file access.
Classes Used in .NET Framework File I/O and the File System
Lists the classes used in .NET Framework file I/O and the FileSystem, including basic file I/O classes, classes that create
streams, and classes that create stream writers and stream readers.
See Also
Tasks
How to: Read Text from Files with a StreamReader (Visual Basic)
How to: Write Text to Files with a StreamWriter in Visual Basic
How to: Read From Text Files in Visual Basic
Reference
System.IO Namespace
Visual Basic Language Concepts

Basics of .NET Framework File I/O and the File System


The System.IO namespace contains the File and Directory classes, which provide the .NET Framework functionality that
manipulates files and directories. Because the methods of these objects are static or shared members, you can use them
directly without creating an instance of the class first. Associated with these classes are the FileInfo and DirectoryInfo classes,
which will be familiar to users of the My feature. To use these classes, you must fully qualify the names or import the
appropriate namespaces by including the Imports statement(s) at the beginning of the affected code. For more information,
see Imports Statement.
Definition of a Stream
The .NET Framework uses streams to support reading from and writing to files. You can think of a stream as a one-dimensional
set of contiguous data, which has a beginning and an end, and where the cursor indicates the current position in the stream.

Stream Operations
The data contained in the stream may come from memory, a file, or a TCP/IP socket. Streams have fundamental operations
that can be applied to them:
Reading. You can read from a stream, transferring data from the stream into a data structure, such as a string or an array
of bytes.
Writing. You can write to a stream, transferring data from a data source into the stream.
Seeking. You can query and modify your position in the stream.
For more information, see Composing Streams.
Types of Streams
In the .NET Framework, a stream is represented by the Stream class, which forms the abstract class for all other streams. You
cannot directly create an instance of the Stream class, but must use one of the classes it implements.
There are many types of streams, but for the purposes of working with file input/output (I/O), the most important types are the
FileStream class, which provides a way to read from and write to files, and the IsolatedStorageFileStream class, which provides
a way to create files and directories in isolated storage. Other streams that can be used when working with file I/O include:
BufferedStream
CryptoStream
MemoryStream
NetworkStream.
The following table lists tasks commonly accomplished with a stream:
To See
Read and write to a data file How to: Read and Write to a Newly Created Data File

Read from an XML file Common XmlReader Tasks

Create a stream writer in order to write text to a file Creating a Writer


Read text from a file How to: Read Text from a File

Write text to a file How to: Write Text to a File

Read characters from a string How to: Read Characters from a String

Write characters to a string How to: Write Characters to a String

Encrypt data Encrypting Data

Decrypt data Decrypting Data

File Access and Attributes


You can control how files are created, opened, and shared with the FileAccess, FileMode, and FileShare enumerations, which
contain the flags used by the constructors of the FileStream class. For example, when you open or create a new FileStream,
the FileMode enumeration allows you to specify whether the file is opened for appending, whether a new file is created if the
specified file does not exist, whether the file is overwritten, and so forth.
The FileAttributes enumeration enables the gathering of file-specific information. The FileAttributes enumeration returns the
file's stored attributes, such as whether it is compressed, encrypted, hidden, read-only, an archive, a directory, a system file, or a
temporary file.
The following table lists tasks involving file access and file attributes:
To See
Open and append text to a log file How to: Open and Append to a Log File

Determine the attributes of a file FileAttributes

File Permissions
Controlling access to files and directories can be done with the FileIOPermission class. This may be particularly important for
developers working with Web Forms, which by default run within the context of a special local user account named ASPNET,
which is created as part of the ASP.NET and .NET Framework installations. When such an application requests access to a
resource, the ASPNET user account has limited permissions, which may prevent the user from performing actions such as
writing to a file from a Web application. For more information, see Security Permissions, Requesting Permissions, and the
FileIOPermission Class.
The following table lists tasks involving file permissions.
To See
Request minimum permissions How to: Request Permission to Access Unmanaged Code

Request optional permissions How to: Request Optional Permissions by Using the RequestOptional Flag

Refuse permissions How to: Refuse Permissions by Using the RequestRefuse Flag

Request built-in permissions How to: Request Permission for a Named Permission Set

Request XML-encoded permissions Requesting XML-Encoded Permissions

Isolated File Storage


Isolated storage is an attempt to solve problems created when working with files where the user or code may lack necessary
permissions. Isolated storage assigns each user a data compartment, which can hold one or more stores. Stores can be isolated
from each other by user and by assembly. Only the user and assembly that created a store have access to it. A store acts as a
complete virtual file system—within one store you can create and manipulate directories and files.
The following table lists tasks commonly associated with isolated file storage.
To See
Create an isolated store How to: Obtain Stores for Isolated Storage

Enumerate isolated stores How to: Enumerate Stores for Isolated Storage

Delete an isolated store How to: Delete Stores in Isolated Storage

Create a file or directory in isolated storage How to: Create Files and Directories in Isolated Storage

Find a file in isolated storage How to: Find Existing Files and Directories in Isolated Storage

Read from or write to a file in insolated storage How to: Read and Write to Files in Isolated Storage

Delete a file or directory in isolated storage How to: Delete Files and Directories in Isolated Storage

File Events
The FileSystemWatcher component allows you to watch for changes in files and directories on your system or on any
computer to which you have network access. For example, if a file is modified, you might want to send a user an alert that the
change has taken place. When changes occur, one or more events are raised, stored in a buffer, and handed to the
FileSystemWatcher component for processing. For more information, see Reacting to File System Events.
To See
Create a handler for file system events How to: Create Handlers for File System Events

Configure a FileSystemWatcher component instance How to: Configure FileSystemWatcher Component Instances

See Also
Concepts
Composing Streams
Basic File I/O
Asynchronous File I/O
Classes Used in .NET Framework File I/O and the File System
Other Resources
Isolated Storage
Visual Basic Language Concepts

Classes Used in .NET Framework File I/O and the File System
The following tables list the classes commonly used for .NET Framework file I/O, categorized into file I/O classes, classes used
for creating streams, and classes used to read and write to streams.
To enter the .NET Framework 2.0 documentation and find a more comprehensive listing, see
.NET Framework Class Library Overview.
Basic I/O Classes for Files, Drives, and Directories
The following table lists and describes the main classes used for file I/O.
Class Description
System.IO.Directory Provides static methods for creating, moving, and enumerating through directo
ries and subdirectories.

System.IO.DirectoryInfo Provides instance methods for creating, moving, and enumerating through dire
ctories and subdirectories.

System.IO.DriveInfo Provides instance methods for creating, moving, and enumerating through driv
es.

System.IO.File Provides static methods for creating, copying, deleting, moving, and opening fil
es, and aids in the creation of a FileStream.

System.IO.FileAccess Defines constants for read, write, or read/write access to a file.

System.IO.FileAttributes Provides attributes for files and directories such as Archive, Hidden, and
ReadOnly.

System.IO.FileInfo Provides static methods for creating, copying, deleting, moving, and opening fil
es, and aids in the creation of a FileStream.

System.IO.FileMode Controls how a file is opened. This parameter is specified in many of the constru
ctors for FileStream and IsolatedStorageFileStream, and for the Open meth
ods of File and FileInfo.

System.IO.FileShare Defines constants for controlling the type of access other file streams can have t
o the same file.

System.IO.Path Provides methods and properties for processing directory strings.

System.Security.Permissions.FileIOPermission Controls the access of files and folders by defining Read, Write, Append and
PathDiscovery permissions.

Classes Used to Create Streams


The following table lists and describes the main classes used to create streams.
Class Description
System.IO.BufferedStream Adds a buffering layer to read and write operations on another stream.

System.IO.FileStream Supports random access to files through its Seek method. FileStream opens file
s synchronously by default but also supports asynchronous operation.

System.IO.MemoryStream Creates a stream whose backing store is memory, rather than a file.
System.Net.Sockets.NetworkStream Provides the underlying stream of data for network access.

System.Security.Cryptography.CryptoStream Defines a stream that links data streams to cryptographic transformations.

Classes Used to Read from and Write to Streams


The following table shows the specific classes used for reading from and writing to files with streams.
Class Description
System.IO.BinaryReader Reads encoded strings and primitive data types from a FileStream.

System.IO.BinaryWriter Writes encoded strings and primitive data types to a FileStream.

System.IO.StreamReader Reads characters from a FileStream, using CurrentEncoding to convert characters to and from bytes.
StreamReader has a constructor that attempts to ascertain the correct CurrentEncoding for a give
n stream, based on the presence of a CurrentEncoding-specific preamble, such as a byte order mar
k.

System.IO.StreamWriter Writes characters to a FileStream, using Encoding to convert characters to bytes.

System.IO.StringReader Reads characters from a String. Output can be either a stream in any encoding or a String.

System.IO.StringWriter Writes characters to a String. Output can be either a stream in any encoding or a String.

See Also
Concepts
Composing Streams
Basic File I/O
Asynchronous File I/O
Basics of .NET Framework File I/O and the File System
Other Resources
Isolated Storage
Visual Basic Language Concepts

Graphics in the .NET Framework with Visual Basic


The .NET Framework provides the GDI+ application programming interface (API) for manipulating graphics. GDI+ is an
advanced implementation of the Windows Graphics Device Interface (GDI). With GDI+ you can create graphics, draw text, and
manipulate graphical images as objects.
GDI+ is designed to offer performance, as well as ease of use. You can use GDI+ to render graphical images on Windows
Forms and controls. Although you cannot use GDI+ directly on Web Forms, you can display graphical images through the
Image Web Server control.
Introduction to GDI+
When you create a Windows Forms control, you can use GDI+ to access and update its image. You can also use GDI+ to create
your own images, independent of your application's user interface.
To draw on an image in .NET Framework, you must use the Graphics object associated with the image.
In some cases, you can directly get the image's Graphics object. For example, when you are creating a Windows Forms control,
you can override the OnPaint method to access the Graphics object for the control's image.
In other cases, such as when you are creating your own image, you also need to create a graphics object. The shared
FromImage method takes an image and returns a Graphics object associated with that image.
The Graphics class has many drawing- and image-manipulation methods. Some of the commonly used methods are listed
below:
Methods for drawing lines: DrawArc, DrawBezier, DrawEllipse, DrawImage, DrawLine, DrawPolygon, DrawRectangle, and
DrawString.
Methods for filling shapes: FillClosedCurve, FillEllipse, FillPath, FillPolygon, and FillRectangle.
Method for clearing the drawing surface: Clear.
Method for creating a new Graphics object from an image: FromImage.
Several of the methods listed above take as arguments structures or classes defined in the System.Drawing namespace. The
following table lists some of the most used GDI+ classes and structures.
Class/Structure Description
System.Drawing.Bitmap Encapsulates a GDI+ bitmap, which consists of the pixel data for a graphics image and its attribu
tes. A Bitmap is an object used to work with images defined by pixel data.

System.Drawing.Brushes Defines brushes for all the standard colors.

System.Drawing.Color Represents an ARGB color.

System.Drawing.Font Defines a particular format for text, including font face, size, and style attributes.

System.Drawing.Pen Defines an object used to draw lines and curves.

System.Drawing.Pens Defines pens for all the standard colors.

System.Drawing.Point Represents an ordered pair of integer x- and y-coordinates that defines a point in a two-dimensi
onal plane.

System.Drawing.Rectangle Stores a set of four integers that represent the location and size of a rectangle. For more advanc
ed region functions, use a Region object.

System.Drawing.SolidBrush Defines a brush of a single color. Brushes are used to fill graphics shapes, such as rectangles, elli
pses, pies, polygons, and paths.
System.Drawing.TextureBrush Each property of the TextureBrush class is a Brush object that uses an image to fill the interior
of a shape.

Resource Management
Many of the drawing classes implement IDisposable because they encapsulate unmanaged system resources. If you create a
new instance of one of these classes, you should call the class's Dispose method when you are through with the object.
Alternatively, you can create the object with the Using statement, which implicitly calls the object's Dispose method. For more
information, see Object Lifetime: How Objects Are Created and Destroyed and Using Statement (Visual Basic).
Related Sections
Graphics for Visual Basic 6.0 Users
Describes changes to the graphics rendering model in Visual Basic 2005.
Graphics and Drawing in Windows Forms
Roadmap for using graphics in Windows Forms applications.
Graphics Overview (Windows Forms)
Provides an introduction to the graphics-related managed classes.
About GDI+ Managed Code
Provides information regarding the managed GDI+ classes.
Using Managed Graphics Classes
Demonstrates how to complete a variety of tasks using the GDI+ managed classes.
Custom Control Painting and Rendering
Details how to provide code for painting controls.
Image Web Server Control Overview
Describes the control that you can use to display images on a Web Forms page and to manage the images with code.
Image Editor
Provides links to topics on how to use the image editor to create image files for use in your application.
See Also
Reference
Using Statement (Visual Basic)
System.Drawing
Concepts
Object Lifetime: How Objects Are Created and Destroyed
Visual Basic Language Concepts

Logging and Tracing in the .NET Framework with Visual Basic


The My.Application.Log and My.Log objects build upon the .NET Framework logging classes. When you need to customize
the Log objects, either by adding new listeners or filtering the log output, you will use the .NET Framework. This section
provides an overview of tracing and debugging concepts in the .NET Framework and a listing of commonly used classes.
In This Section
Basics of .NET Framework Logs
Provides an overview of logging, tracing, and instrumenting concepts in the .NET Framework.
Classes Used in .NET Framework Logging
Lists the classes used in .NET Framework logging, tracing, and instrumenting.
See Also
Reference
My.Application.Log Object
My.Log Object
System.Diagnostics
Concepts
Logging Information from the Application
Other Resources
Tracing and Instrumenting Applications
Visual Basic Language Concepts

Basics of .NET Framework Logs


There are many ways to log information from your Visual Basic applications, in addition to using the Visual Basic
My.Application.Log and My.Log objects; many different .NET Framework classes are available. By logging information, you
can monitor and measure your application's performance and diagnose errors.
Tracing, Debugging, and Instrumenting
The .NET Framework documentation uses several different terms that are related to logging: tracing, debugging, and
instrumenting.
Tracing is a way for you to monitor the execution of your application while it is running. It is typically implemented using
the Trace class. You can add tracing statements to your application when you develop it, and you can use that
instrumentation both while you are developing the application and after you have deployed it.
Debugging is similar to tracing, but it is typically more verbose and it is turned off in release builds. It is typically
implemented using the Trace class.
Instrumenting refers to adding code to your application that monitors or measures the level of a product's performance.
Logging, tracing, and debugging are all forms of instrumentation. You can instrument your application by placing trace
statements at strategic locations in your code. This is especially useful for distributed applications.
With trace statements, you can instrument an application to display information not only when things go wrong but also
to monitor how well the application is performing.
The Trace and Debug classes can, like the Visual Basic Log objects, record information about errors and application execution
to logs, text files, or other devices for later analysis. In addition, they have methods that allow for finer control over the output.
For more tracing classes, see Classes Used in .NET Framework Logging.
Logging and Tracing Basics
Once you instrument your application, you can:
Trace code. Receive informative messages about the execution of an application at run time. For more information, see
Introduction to Instrumentation and Tracing.
Receive debug output. Track down and fix programming errors in an application under development. For more
information, see Debugging in Visual Studio.
Access performance counters. Track the performance of your application. For more information, see
Introduction to Monitoring Performance Thresholds.
Write to event logs. Track major events in the execution of your application. For more information, see
Logging Application, Server, and Security Events.
The Trace and Debug classes provide the means to monitor and examine application performance either during development
or after deployment. For example, you can use the Trace class to track particular types of actions in a deployed application as
they occur (for example, creation of new database connections), letting you monitor the application's efficiency.
See Also
Reference
System.Diagnostics
Concepts
Logging and Tracing in the .NET Framework with Visual Basic
Introduction to Instrumentation and Tracing
Classes Used in .NET Framework Logging
Other Resources
Tracing and Instrumenting Applications
Visual Basic Language Concepts

Classes Used in .NET Framework Logging


This topic contains tables listing the classes commonly used for .NET Framework logging and tracing. The tables are divided
into log-output classes, log-listener classes, and log-filtering classes. To enter the .NET Framework 2.0 documentation and find
a more comprehensive listing, see .NET Framework Class Library Overview.
Basic Classes for Log Output
The following table lists and describes the main classes used for log output.
Class Description
Debug Provides a set of methods and properties that help debug your code. This class cannot be inherited.

Trace Provides a set of methods and properties that help you trace the execution of your code. This class cannot be inhe
rited.

TraceSource Provides a set of methods and properties that help you trace the execution of your code.

Log-Listener Classes
The following table lists and describes the main log-listener classes.
Class Description
TraceListener Provides the abstract base class for the listeners who monitor trace and debug output.

ConsoleTraceListener Directs tracing or debugging output to either the standard output or the standard error stream.

DefaultTraceListener Provides the default output methods and behavior for tracing.

DelimitedListTraceListener Directs tracing or debugging output to a TextWriter, such as StreamWriter, or to a Stream, such as
FileStream.

EventLogTraceListener Provides a simple listener that directs tracing or debugging output to an EventLog.

FileLogTraceListener Provides a simple listener that directs logging output to file.

TextWriterTraceListener Directs tracing or debugging output to a TextWriter or to a Stream such as Out or FileStream.

XmlWriterTraceListener Directs tracing or debugging output to a TextWriter or to a Stream such as FileStream.

Log Filtering and Switching Classes


The following table lists and describes the main log filtering and switching classes.
Class Description
Switch Provides an abstract base class to create new debugging and tracing switches.

BooleanSwitch Provides a simple on/off switch that controls debugging and tracing output.

SourceSwitch Provides a multilevel switch to control tracing and debug output without recompiling your code.

TraceSwitch Provides a multilevel switch to control tracing and debug output without recompiling your code.

EventTypeFilter Provides a severity level based switch that controls tracing output.
SourceFilter Specifies if a listener should trace a message based on the source of a trace.

TraceFilter Defines a method for trace-filter implementations.

See Also
Reference
System.Diagnostics
Concepts
Logging and Tracing in the .NET Framework with Visual Basic
Basics of .NET Framework Logs
Other Resources
Tracing and Instrumenting Applications
Visual Basic Language Concepts

Network Operations in the .NET Framework with Visual Basic


When performing complex network operations, Visual Basic users may need to investigate the .NET Framework and the classes
it offers. This section provides an overview of network concepts in the .NET Framework and a listing of commonly used classes.
In This Section
Basics of .NET Framework Network Operations
Provides an overview of network concepts in the .NET Framework, including the WebRequest and WebResponse classes,
security, and network tracing.
Classes Used in .NET Framework Network Operations
Lists the classes used in .NET Framework network operations.
Reference
WebRequest
Makes a request to a Uniform Resource Identifier (URI).
WebResponse
Provides a response from a URI.
WebClient
Provides common methods for sending data to and receiving data from a resource identified by a URI.
Visual Basic Language Concepts

Basics of .NET Framework Network Operations


The Microsoft .NET Framework provides a layered, extensible, and managed implementation of Internet services that can be
quickly and easily integrated into your applications. To use these classes, you must fully qualify the names or import the
appropriate namespaces by including one or more Imports statements at the beginning of the affected code. For more
information, see Imports Statement.
Accessing Internet Resources
Three pieces of information are required to access Internet resources through a request/response model. These are provided
by specific .NET Framework classes:
The Uri class contains the URI (Uniform Resource Identifier) of an Internet resource, which consists of at least three,
sometimes four, parts: the scheme identifier, which identifies the communications protocol; the server identifier; the path
identifier; and an optional query string.
The WebRequest class contains a request for the resource.
The WebResponse class provides a container for the incoming response.
Uploading and Downloading Data
For applications that need to make simple requests for Internet resources, the WebClient class provides methods for uploading
or downloading data. Because WebClient relies on the WebRequest class to provide access to Internet resources, it can use
any registered pluggable protocol.
The System.Net.Sockets namespace provides the TcpClient, TcpListener, and UdpClient classes for applications that do not use
the request/response model or applications that need to listen on the network. These classes handle the details of making
connections using different transport protocols and expose the network connection to the application as a stream.
For more information, see Requesting Data.
The following table lists common tasks involving requesting data from an Internet resource.
To See
Create an Internet request Creating Internet Requests

Send data to the network Using Streams on the Network

Make asynchronous requests for an Internet resource Making Asynchronous Requests

Access HTTP-specific properties HTTP

Associate a specific request to a connection pool Connection Grouping

Configure a proxy instance Accessing the Internet Through a Proxy

Make asynchronous requests for an Internet resource Making Asynchronous Requests

Request data using TCP Using TCP Services

Request data using UDP Using UDP Services

Pluggable Protocols
The abstract WebRequest and WebResponse classes provide the base classes for pluggable protocols. By deriving protocol-
specific classes from WebRequest and WebResponse, an application can request data from an Internet resource and read the
response without specifying the protocol used.
For more information, see Programming Pluggable Protocols.
The following table lists common tasks involving pluggable protocols.
To See
Derive from WebRequest Deriving from WebRequest

Derive from WebResponse Deriving from WebResponse

Access protocol specific properties How to: Typecast a WebRequest to Access Protocol Specific Properties

Network Tracing
Network tracing provides access to information about invoking methods and information about network traffic generated by a
managed application. This feature is useful for debugging applications under development and for analyzing deployed
applications. The output provided by network tracing is customizable to support different usage scenarios at development time
and in a production environment.
For more information, see Network Tracing.
The following table lists common tasks involving network tracing.
To See
Enable network tracing Enabling Network Tracing

Read trace information Interpreting Network Tracing

Configure network tracing How to: Configure Network Tracing

Cache Management
A cache provides temporary storage of resources that have been requested by an application. If an application requests the
same resource more than once, the resource can be returned from the cache, avoiding the overhead of requesting it again
from the server.
A cache policy defines rules that are used to determine whether a request can be satisfied using a cached copy of the requested
resource.
For more information, see Cache Management for Network Applications.
The following table lists common tasks involving cache management.
To See
Set a location-based cache policy How to: Set a Location-based Cache Policy for an Application

Set a default time-based cache policy How to: Set the Default Time-Based Cache Policy for an Application

Customize a time-based cache policy How to: Customize a Time-Based Cache Policy

Set cache policy for a request How to: Set Cache Policy for a Request

Security
The System.Net classes provide a secure environment for Internet applications by providing built-in support for commonly
used Internet-application authentication mechanisms and for .NET Framework code-access permissions.
For more information, see Best Practices for System.Net Classes.
The following table lists common tasks involving security.
To See
Use Secure Sockets Layer (SSL) connections to an HTTP server Using Secure Sockets Layer
Use HTTP authentication methods to establish an authenticated connectio Internet Authentication
n to an HTTP server.

Set code-access security for applications that use Internet connections. Web and Socket Permissions

Use Basic and Digest authentication. Basic and Digest Authentication

Use NTML and Kerberos Authentication. NTLM and Kerberos Authentication

Use System.Net to secure XML Web Services. Securing XML Web Services Created Using ASP.NET

See Also
Reference
System.Net
System.Net.Sockets
Concepts
Best Practices for System.Net Classes
Configuring Internet Applications
Other Resources
Network Programming
Network Namespaces in Visual Studio
Visual Basic Language Concepts

Classes Used in .NET Framework Network Operations


System.Net, System.Net.Sockets, and Uri provide a layered, extensible, and managed implementation of Internet services that
can be quickly and easily integrated into your applications.
Basic Classes Used in Network Operations
This table lists the most important classes used for .NET Framework network operations. For a more comprehensive listing,
consult the .NET Framework documentation.
Class Description
System.Net Provides a simple programming interface for many of the protocols used for networks.

System.Net.Authorization Contains an authentication message for an Internet server.

Cookie Provides a set of methods and properties used to manage cookies.

WebClient Provides common methods for sending data to and receiving data from a resource identified
by a URI (Uniform Resource Identifier).

WebRequest Makes a request to a URI.

WebResponse Provides a response from a URI.

System.Net.Sockets Provides a managed implementation of the Windows Sockets (Winsock) interface for develop
ers who need to tightly control access to the network.

System.Net.Sockets.TcpClient Provides client connections for TCP network services.

System.Net.Sockets.TcpListener Listens for connections from TCP network clients.

System.Net.Sockets.UdpClient Provides User Datagram Protocol (UDP) network services.

System.Uri Provides an object representation of a URI.

UriBuilder Provides a custom constructor and modifiers for URIs.

See Also
Concepts
Basics of .NET Framework Network Operations
Visual Basic Language Concepts

Port Operations in the .NET Framework with Visual Basic


You can access your computer's serial ports through the .NET Framework classes in the System.IO.Ports namespace. The most
important class, SerialPort, provides a framework for synchronous and event-driven I/O, access to pin and break states, and
access to serial driver properties. It can be wrapped in a Stream object, accessible through the BaseStream property. Wrapping
SerialPort in a Stream object allows the serial port to be accessed by classes that use streams. The namespace includes
enumerations that simplify the control of serial ports.
The simplest way to create a SerialPort object is through the My.Computer.Ports.OpenSerialPort method.
Note
You cannot use .NET Framework classes to directly access other types of ports, such as parallel ports, USB ports, and so on. T
o access your computer's network, see Classes Used in .NET Framework Network Operations.

Enumerations
This table lists and describes the main enumerations used for accessing a serial port:
Enumeration Description
Handshake Specifies the control protocol used in establishing a serial port communication for a SerialPort object.

Parity Specifies the parity bit for a SerialPort object.

SerialData Specifies the type of character that was received on the serial port of the SerialPort object.

SerialError Specifies errors that occur on the SerialPort object

SerialPinChange Specifies the type of change that occurred on the SerialPort object.

StopBits Specifies the number of stop bits used on the SerialPort object.

Tasks
This table lists and describes the main tasks for accessing a serial port:
To See
Show available serial ports How to: Show Available Serial Ports in Visual Basic

Dial a modem attached to the serial port of a computer How to: Dial Modems Attached to Serial Ports in Visual Basic

Send a string to a computer's serial port How to: Send Strings to Serial Ports in Visual Basic

Receive a string from a computer's serial port How to: Receive Strings From Serial Ports in Visual Basic

See Also
Reference
My.Computer.Ports Object
Other Resources
Accessing the Computer's Ports
Going Further with Visual Basic
Visual Basic Language Concepts

Serialization in the .NET Framework with Visual Basic


Serialization is the process of converting an object into a stream of bytes in order to persist it to memory, a database, or a file.
You can save and re-create such objects using functionality provided by the .NET Framework.
In This Section
Basics of .NET Framework Serialization
Provides an overview of serialization using .NET Framework classes.
Classes Used in .NET Framework Serialization
Lists .NET Framework classes used in serialization.
Related Sections
Examples of XML Serialization
Demonstrates the XML serialization of various objects, such as a dataset.
Visual Basic Language Concepts

Basics of .NET Framework Serialization


Serialization is the process of converting an object into a stream of bytes in order to persist it to memory, a database, or a file.
Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called
deserialization.
How Serialization Works
This illustration shows the overall process of serialization.

The object is serialized to a stream, which carries not just the data, but information about the object's type, such as its version,
culture, and assembly name. From that stream, it can be stored in a database, a file, or memory.
Uses for Serialization
Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well
as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by
means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string,
or maintaining security or user-specific information across applications.
Making an Object Serializable
To serialize an object, you need the object to be serialized, a stream to contain the serialized object, and a Formatter.
System.Runtime.Serialization contains the classes necessary for serializing and deserializing objects.
Apply the SerializableAttribute attribute to a type to indicate that instances of this type can be serialized. A
SerializationException exception is thrown if you attempt to serialize but the type does not have the SerializableAttribute
attribute.
If you do not want a field within your class to be serializable, apply the NonSerializedAttribute attribute. If a field of a
serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and the
field cannot be meaningfully reconstituted in a different environment, then you may want to make it nonserializable.
If a serialized class contains references to objects of other classes that are marked SerializableAttribute, those objects will
also be serialized.
Binary and XML Serialization
Either binary or XML serialization can be used. In binary serialization, all members, even those that are read-only, are serialized,
and performance is enhanced. XML serialization provides more readable code, as well as greater flexibility of object sharing
and usage for interoperability purposes.
Binary Serialization
Binary serialization uses binary encoding to produce compact serialization for uses such as storage or socket-based network
streams. It is not suitable for passing data through a firewall but provides better performance when storing data.
XML Serialization
XML serialization serializes the public fields and properties of an object, or the parameters and return values of methods, into
an XML stream that conforms to a specific XML Schema definition language (XSD) document. XML serialization results in
strongly typed classes with public properties and fields that are converted to XML. System.Xml.Serialization contains the
classes necessary for serializing and deserializing XML.
You can apply attributes to classes and class members in order to control the way the XmlSerializer serializes or deserializes an
instance of the class. For more information, see Controlling XML Serialization Using Attributes and
Attributes That Control XML Serialization.
This table lists tasks associated with XML serialization:
To See
Serialize an object How to: Serialize an Object

Deserialize an object How to: Deserialize an Object

Generate classes and XML Sch How to: Use the XML Schema Definition Tool to Generate Classes and XML Schema Documents
ema documentation

Qualify XML element and XML How to: Qualify XML Element and XML Attribute Names
attribute names

Specify an alternate element n How to: Specify an Alternate Element Name for an XML Stream
ame for an XML Stream

Control serialization of derived How To: Control Serialization of Derived Classes


classes
SOAP Serialization
XML serialization can also be used to serialize objects into XML streams that conform to the SOAP specification. SOAP is a
protocol based on XML, designed specifically to transport procedure calls using XML. As with regular XML serialization,
attributes can be used to control the literal-style SOAP messages generated by an XML Web service. For more information, see
XML Serialization with XML Web Services and Attributes That Control Encoded SOAP Serialization.
This table lists tasks associated with SOAP-encoded XML serialization:
To See
Serialize an object as a SOAP-encoded XML stream How to: Serialize an Object as a SOAP-Encoded XML Stream

Override SOAP-encoded XML serialization How to: Override Encoded SOAP XML Serialization

Basic and Custom Serialization


Serialization can be performed in two ways, basic and custom. Basic serialization uses the .NET Framework to automatically
serialize the object.
Basic Serialization
The only requirement in basic serialization is that the object have the SerializableAttribute attribute applied. The
NonSerializedAttribute can be used to keep specific fields from being serialized.
When you use basic serialization, the versioning of objects may create problems, in which case custom serialization may be
preferable. Basic serialization is the easiest way to perform serialization, but it does not provide much control over the process.
Custom Serialization
In custom serialization, you can specify exactly which objects will be serialized and how it will be done. The class must be
marked SerializableAttribute and implement the ISerializable interface.
If you want your object to be deserialized in a custom manner as well, you must use a custom constructor.
Designer Serialization
Designer serialization is a special form of serialization that involves the kind of object persistence usually associated with
development tools. Designer serialization is the process of converting an object graph into a source file that can later be used
to recover the object graph. A source file can contain code, markup, or even SQL table information. For more information, see
Designer Serialization Overview.
See Also
Tasks
How To: Chunk Serialized Data
Concepts
Examples of XML Serialization
Classes Used in .NET Framework Serialization
Visual Basic Language Concepts

Classes Used in .NET Framework Serialization


This topic lists the classes commonly used for .NET Framework serialization. To enter the .NET Framework 2.0 documentation
and find a more comprehensive listing, see System.Runtime.Serialization.
Basic Classes for Serialization
This table lists and describes the main classes and namespaces used for serialization:
Class or namespace Description
System.Runtime.Serialization Contains the classes necessary for serializing and deserializing objects.

System.Xml.Serialization Contains the classes necessary for serializing and deserializing XML.

SerializableAttribute Must be applied to an object in order to make it serializable.

NonSerializedAttribute Can be used to keep specific fields in an object from being serialized.

See Also
Concepts
Basics of .NET Framework Serialization
Visual Basic Language Concepts

Developing for Smart Devices with Visual Basic


Visual Studio 2005 supports Visual Basic for smart device application development. It provides the tools and Framework you
need to develop applications for Pocket PC, Smartphone, and other Windows CE-based platforms.
Developing Applications for Devices
You can develop two kinds of applications for devices, broadly speaking:
Mobile Web applications run on a Web server and are rendered in different formats on a range of browser-equipped
mobile devices. For more information, see Creating ASP.NET Mobile Web Pages.
Windows CE-based rich-client applications run on the device itself. This approach is generally what we mean by the term
"application for smart devices."
When developing for smart devices, you use the same Visual Studio environment that is used when developing desktop
applications, but some differences manifest themselves when you are targeting devices. These differences include:
Additional tools for connecting to and debugging on a remote device.
Besides choosing a project type and template when creating a project, you must select a device on which to run and
debug the application. This device can be a physical device connected to the development computer, a networked device,
or a device emulator running on the development computer.
Classes and their members differ when developing for devices. To determine whether or not a class and its members are
available, consult the documentation, use IntelliSense, or use the Visual Studio Object Browser while the project is active.
For more information, see .NET Compact Framework.
Creating a Device Application
An enhanced New Project dialog box in Visual Studio 2005 replaces the Smart Device Application Wizard of Visual Studio
.NET 2003. In Visual Studio 2005, you make all choices regarding project types and templates from the New Project dialog
box. For more information, see How to: Create Device Applications Using Visual Basic or Visual C#.
For a list of tasks involving smart devices, see Smart Device Applications (How Do I in Visual Basic).
Data and Devices
The .NET Compact Framework provides a rich implementation of ADO.NET for devices, supporting the DataSet and Dataview
classes. This support includes the DataRelation and Constraint classes, and other classes that define and manipulate the
DataSet. The .NET Compact Framework also includes the SQL Server .NET data provider. For more information, see
Data Access and XML Support and SQL Server Mobile Edition with the .NET Compact Framework.
Networking
The .NET Compact Framework provides the networking socket-level API and higher-level abstractions, such as HTTP, DNS, and
Web requests and responses. Connectivity is provided over Infrared Data Association (IrDA) and TCP/IP transports through the
sockets API. For more information, see Networking and Connectivity.
Developing for the Pocket PC
This table lists tasks specific to the Pocket PC.
To See
Use a DocumentList control to handle file management tasks in your application How to: Use a DocumentList Control

Use form elements in your application Pocket PC Form Style

Activate applications from a physical hardware button with a HardwareButton co How to: Use the HardwareButton Component
mponent in your application

Use an InputPanel component in your application How to: Use the InputPanel Component

Select Pocket PC input methods for user input in your application How to: Set Pocket PC Input Methods
Send and respond to a notification in your application How to: Send a Notification

Detect navigation keys How to: Detect Navigation Keys

Developing for the Smartphone


The .NET Compact Framework can be installed on Windows Mobile 2003 Smartphones and later.
This table lists tasks specific to Smartphone development.
To See
Set Smartphone input methods in your application How to: Set Smartphone Input Modes

Override the back key How to: Override the Smartphone Back Key

Use Smartphone menus How to: Use Smartphone Menus

See Also
Concepts
.NET Compact Framework How-To Topics
Other Resources
Pocket PC Development and the .NET Compact Framework
Smartphone Development and the .NET Compact Framework
Windows CE Development
.NET Compact Framework Product Information
Visual Basic Language Concepts

Advanced Multithreading with Visual Basic


Multithreaded applications can run several different tasks simultaneously. The topics in this section describe how to manage
those tasks so they work together smoothly and without conflicts.
In This Section
Thread Synchronization
Covers how to synchronize multithreaded applications.
Thread Pooling
Describes how tasks can be added to a queue and then started as new threads are created.
Thread Timers
Describes how to run procedures on separate threads at fixed intervals.
Advanced Synchronization Techniques
Describes how multithreaded applications can use wait handles and monitor objects to synchronize multiple threads.
Related Sections
Multithreading in Visual Basic
Introduction to using multithreading in Visual Basic applications.
Multithreading in Components
Provides links to topics that describe how to use multithreading in component programming.
Walkthrough: Authoring a Simple Multithreaded Component with Visual Basic
Shows how to create multithreaded components.
System.Threading
Provides .NET Framework classes and interfaces that enable multithreaded programming.
Visual Basic Language Concepts

Thread Timers
The System.Threading.Timer class is useful for periodically running a task on a separate thread. For example, you could use a
thread timer to check the status and integrity of a database or to back up critical files.
Thread Timer Example
The following example starts a task every two seconds and uses a flag to initiate the Dispose method that stops the timer. This
example posts status to the output window, so you should make this window visible by pressing CTRL+ALT+O before you test
the code.
VB
Class StateObjClass
' Used to hold parameters for calls to TimerTask
Public SomeValue As Integer
Public TimerReference As System.Threading.Timer
Public TimerCanceled As Boolean
End Class

Sub RunTimer()
Dim StateObj As New StateObjClass
StateObj.TimerCanceled = False
StateObj.SomeValue = 1
Dim TimerDelegate As New Threading.TimerCallback(AddressOf TimerTask)
' Create a timer that calls a procedure every 2 seconds.
' Note: There is no Start method; the timer starts running as soon as
' the instance is created.
Dim TimerItem As New System.Threading.Timer(TimerDelegate, StateObj, _
2000, 2000)
StateObj.TimerReference = TimerItem ' Save a reference for Dispose.

While StateObj.SomeValue < 10 ' Run for ten loops.


System.Threading.Thread.Sleep(1000) ' Wait one second.
End While

StateObj.TimerCanceled = True ' Request Dispose of the timer object.


End Sub

Sub TimerTask(ByVal StateObj As Object)


Dim State As StateObjClass = CType(StateObj, StateObjClass)
' Use the interlocked class to increment the counter variable.
System.Threading.Interlocked.Increment(State.SomeValue)
System.Diagnostics.Debug.WriteLine("Launched new thread " & Now)
If State.TimerCanceled Then ' Dispose Requested.
State.TimerReference.Dispose()
System.Diagnostics.Debug.WriteLine("Done " & Now)
End If
End Sub

Thread timers are particularly useful when the System.Windows.Forms.Timer object is unavailable, such as when you are
developing console applications.
See Also
Reference
SyncLock Statement
System.Threading
Concepts
Advanced Multithreading with Visual Basic
Multithreaded Applications
Visual Basic Language Concepts

Thread Pooling
Thread pooling is a form of multithreading in which tasks are added to a queue and automatically started when threads are
created. With thread pooling, you call the System.Threading.ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback)
method with a delegate for the procedure you want to run, and Visual Basic creates the thread and runs your procedure.
Thread Pooling Example
The following example shows how you can use thread pooling to start several tasks.
VB
Sub DoWork()
' Queue a task
System.Threading.ThreadPool.QueueUserWorkItem( _
New System.Threading.WaitCallback(AddressOf SomeLongTask))
' Queue another task
System.Threading.ThreadPool.QueueUserWorkItem( _
New System.Threading.WaitCallback(AddressOf AnotherLongTask))
End Sub
Sub SomeLongTask(ByVal state As Object)
' Insert code to perform a long task.
End Sub
Sub AnotherLongTask(ByVal state As Object)
' Insert code to perform another long task.
End Sub

Thread pooling is useful when you want to start many separate tasks without individually setting the properties of each thread.
Each thread starts with a default stack size and priority. By default, up to 25 thread-pool threads can run per system processor.
Additional threads in excess of the limit can be queued, but they do not start until other threads finish.
One advantage of thread pooling is that you can pass arguments in a state object to the task procedure. If the procedure you
are calling requires more than one argument, you can cast a structure or an instance of a class into an Object data type.
Thread Pool Parameters and Return Values
Returning values from a thread-pool thread is not straightforward. The standard way of returning values from a function call is
not allowed because Sub procedures are the only type of procedure that can be queued to a thread pool. One way you can
provide parameters and return values is by wrapping the parameters, return values, and methods in a wrapper class as
described in Parameters and Return Values for Multithreaded Procedures.
An easer way to provide parameters and return values is by using the optional ByVal state object variable of the
QueueUserWorkItem method. If you use this variable to pass a reference to an instance of a class, the members of the
instance can be modified by the thread-pool thread and used as return values.
At first it may not be obvious that you can modify an object referred to by a variable that is passed by value. You can do this
because only the object reference is passed by value. When you make changes to members of the object referred to by the
object reference, the changes apply to the actual class instance.
Structures cannot be used to return values inside state objects. Because structures are value types, changes that the
asynchronous process makes do not change the members of the original structure. Use structures to provide parameters when
return values are not needed.
See Also
Reference
SyncLock Statement
QueueUserWorkItem
System.Threading
Concepts
Advanced Multithreading with Visual Basic
Multithreaded Applications
Thread Synchronization
Multithreading with Forms and Controls
Visual Basic Language Concepts

Thread Synchronization
As you write a threaded application, you may need to synchronize individual threads with other parts of your program.
Synchronization provides a compromise between the unstructured nature of multithreaded programming and the structured
order of synchronous processing.
You use synchronization techniques:
To explicitly control the order in which code runs whenever tasks must be performed in a specific sequence
-or-
To prevent the problems that can occur when two threads share the same resource at the same time.
For example, you could use synchronization to cause a display procedure to wait until a data retrieval procedure that is running
on another thread is complete.
Synchronization Techniques
There are two approaches to synchronization, polling and using synchronization objects. See
Advanced Synchronization Techniques for more information on synchronization objects.
Polling
Polling repeatedly checks the status of an asynchronous call from within a loop. Polling is the least efficient way to manage
threads because it wastes resources by repeatedly checking the status of the various thread properties.
For example, the IsAlive property can be used when polling to see if a thread has exited. Use this property with caution because
a thread that is alive is not necessarily running.
You can use the thread's ThreadState property to get more detailed information about a thread's status. Because threads can
be in more than one state at any given time, the value stored in ThreadState can be a combination of the values in the
System.Threading.ThreadState enumeration. Consequently, you should carefully check all relevant thread states when polling.
For example, if a thread's state indicates that it is not Running, it may be done. On the other hand, it may be suspended or
sleeping.
Waiting for a Thread to Finish
The System.Threading.Thread.Join method is useful for determining if a thread has completed before starting another task. The
Join method waits a specified amount of time for a thread to end. If the thread ends before the timeout, Join returns True;
otherwise it returns False.
As you can imagine, polling sacrifices many of the advantages of multithreading in return for control over the order that
threads run. Because it is so inefficient, polling is generally not recommended. A more efficient approach would use the Join
method to control threads. Join causes a calling procedure to wait either until a thread is done or until the call times out if a
time-out is specified. The name "join" is based on the idea that creating a new thread is a fork in the execution path. You use
Join to merge separate execution paths into a single thread again.

Figure 1 Threading
One point should be clear: Join is a synchronous or blocking call. Once you call Join, or a wait method of a wait handle, the
calling procedure stops and waits for the thread to signal that it is done.
VB
Sub JoinThreads()
Dim Thread1 As New System.Threading.Thread(AddressOf SomeTask)
Thread1.Start()
Thread1.Join() ' Wait for the thread to finish.
MsgBox("Thread is done")
End Sub
Sub SomeTask()
' Insert code to perform a task here.
End Sub

These simple ways of controlling threads, which are useful when you are managing a small number of threads, are difficult to
use with large projects. Advanced Synchronization Techniques discusses some techniques you can use to synchronize threads.
See Also
Concepts
Advanced Multithreading with Visual Basic
Parameters and Return Values for Multithreaded Procedures
Other Resources
Multithreading in Visual Basic
Visual Basic Language Concepts

Advanced Synchronization Techniques


Multithreaded applications often use wait handles and monitor objects to synchronize multiple threads. These sections explain
how to use the following .NET Framework classes when synchronizing threads: AutoResetEvent, Interlocked,
ManualResetEvent, Monitor, Mutex, ReaderWriterLock, Timer, WaitHandle.
Wait Handles
Wait handles are objects that signal the status of one thread to another thread. Threads can use wait handles to notify other
threads that they need exclusive access to a resource. Other threads must then wait to use this resource until the wait handle is
no longer in use. Wait handles have two states, signaled and nonsignaled. A wait handle that is not owned by any thread is in
the signaled state. A wait handle that is owned by a thread is in the nonsignaled state.
Threads request ownership of a wait handle by calling one of the wait methods, such as WaitOne, WaitAny, or WaitAll. The wait
methods are blocking calls that are similar to the Join method of an individual thread:
If no other thread owns the wait handle, the call immediately returns True, the wait handle's status is changed to
nonsignaled, and the thread that owns the wait handle continues to run.
If a thread calls one of a wait handle's wait methods, but the wait handle is owned by another thread, the calling thread
will either wait for a specified time (if a time-out is specified) or wait indefinitely (if no time-out is specified) for the other
thread to release the wait handle. If a time-out is specified and the wait handle is released before the time-out expires, the
call returns True. Otherwise, the call to wait returns False, and the calling thread continues to run.
Threads that own a wait handle call the Set method when they are done or when they no longer need the wait handle. Other
threads can reset the status of a wait handle to nonsignaled by either calling the Reset method or by calling WaitOne,
WaitAny, or WaitAll and successfully waiting for a thread to call Set. AutoResetEvent handles are automatically reset to
nonsignaled by the system after a single waiting thread has been released. If no threads are waiting, the event object's state
remains signaled.
There are three kinds of wait handles commonly used with Visual Basic: mutex objects, ManualResetEvent, and
AutoResetEvent. The last two are often referred to as synchronization events.
Mutex Objects
Mutex objects are synchronization objects that can be owned by only a single thread at a time. The name "mutex" is derived
from the fact that ownership of mutex objects is mutually exclusive. Threads request ownership of the mutex object when they
require exclusive access to a resource. Because only one thread can own a mutex object at any time, other threads must wait
for ownership of a mutex object before using the resource.
The WaitOne method causes a calling thread to wait for ownership of a mutex object. If a thread terminates normally while
owning a mutex object, the state of the mutex object is set to signaled and the next waiting thread gets ownership.
Synchronization Events
Synchronization events notify other threads that something has occurred or that a resource is available. Despite the term
including the word "event," synchronization events are unlike other Visual Basic events—they are really wait handles. Like
other wait handles, synchronization events have two states, signaled and nonsignaled.
Threads that call one of the wait methods of a synchronization event must wait until another thread signals the event by calling
the Set method. There are two synchronization event classes: ManualResetEvent and AutoResetEvent.
Threads set the status of ManualResetEvent instances to signaled using the Set method. Threads set the status of
ManualResetEvent instances to nonsignaled using the Reset method or when control returns to a waiting WaitOne call.
Instances of the AutoResetEvent class can also be set to signaled using Set, but they automatically return to nonsignaled as
soon as a waiting thread is notified that the event has become signaled.
Monitor Objects and SyncLock
Monitor objects are used to ensure that a block of code runs without being interrupted by code running on other threads. In
other words, code in other threads cannot run until code in the synchronized code block has finished.
Suppose, for example, that you have a program that repeatedly and asynchronously reads data and displays the results. With
operating systems that use preemptive multitasking, a running thread can be interrupted by the operating system to allow
time for some other thread to run. Without synchronization, it is possible that you could get a partially updated view of the
data if the object that represents the data is modified by another thread while the data is being displayed. Monitor objects
guarantee that a section of code will run without being interrupted. Visual Basic provides the SyncLock and End SyncLock
statements to simplify access to monitor objects. Visual C# uses the Lock keyword in the same way.
Note
Access to an object is locked out only if the accessing code is contained within a SyncLock block on the same object instance
.

For information on the SyncLock statement, see SyncLock Statement


Interlocked Class
You can use the methods of the Interlocked class to prevent problems that can occur when multiple threads attempt to
simultaneously update or compare the same value. The methods of this class let you safely increment, decrement, exchange,
and compare values from any thread. The following example shows how to use the Increment method to increment a variable
that is shared by procedures running on separate threads.
VB
Sub ThreadA(ByRef IntA As Integer)
System.Threading.Interlocked.Increment(IntA)
End Sub

Sub ThreadB(ByRef IntA As Integer)


System.Threading.Interlocked.Increment(IntA)
End Sub

ReaderWriter Locks
In some cases, you may want to lock a resource only when data is being written and permit multiple clients to simultaneously
read data when data is not being updated. The ReaderWriterLock class enforces exclusive access to a resource while a thread
is modifying the resource, but it allows non-exclusive access when reading the resource. ReaderWriter locks are a useful
alternative to exclusive locks, which cause other threads to wait, even when those threads do not need to update data.
Deadlocks
Thread synchronization is invaluable in multithreaded applications, but there is always the danger of creating a deadlock,
where multiple threads are waiting for each other and the application comes to a halt. A deadlock is analogous to a situation in
which cars are stopped at a four-way stop and each person is waiting for the other to go. Avoiding deadlocks is important; the
key is careful planning. You can often predict deadlock situations by diagramming multithreaded applications before you start
coding.
See Also
Reference
SyncLock Statement
System.Threading
Concepts
Advanced Multithreading with Visual Basic
Thread Synchronization
Thread States
Multithreaded Applications
Other Resources
Multithreading in Components
Visual Basic Language Concepts

Windows Forms Application Concepts in Visual Basic


Windows Forms applications are client applications that run on the user's computer, display information, request input from
users, and communicate with remote computers over a network. When developing larger applications, you may need to
investigate the .NET Framework and the classes it offers. This section provides an overview of the .NET Framework classes and
concepts related to Windows Forms applications.
In This Section
Windows Forms Application Basics
Provides an overview of creating Windows Forms applications using .NET Framework classes.
Classes Used in .NET Framework Forms
Lists .NET Framework classes used in Windows Forms applications.
Related Sections
Overview of Windows-based Applications
Discusses the particulars of Windows Forms application creation with Visual Studio 2005.
Windows Forms Overview
Discusses the advantages of smart-client applications and the main features of Windows Forms programming.
See Also
Reference
Windows Forms Overview
Concepts
Overview of the Visual Basic Application Model
Other Resources
Going Further with Visual Basic
Visual Basic Language Concepts

Windows Forms Application Basics


An important part of Visual Basic is the ability to create Windows Forms applications that run locally on users' computers. You
can use Visual Studio 2005 to create the application and user interface using Windows Forms. A Windows Forms application is
built on classes from the System.Windows.Forms namespace.
Designing Windows Forms Applications
You can create Windows Forms and Windows service applications with Visual Studio. For more information, see the following
topics:
Getting Started with Windows Forms. Provides information on how to create and program Windows Forms.
Windows Forms Walkthroughs and How-to Topics. Lists topics that provide a step-by-step development of commonly
created Windows Forms applications based on Windows Forms.
Windows Forms Controls. Collection of topics detailing the use of Windows Forms controls.
Windows Service Applications. Lists topics that explain how to create Windows services.
Building Rich, Interactive User Interfaces
Windows Forms is the smart-client component of the .NET Framework, a set of managed libraries that enable common
application tasks such as reading and writing to the file system. Using a development environment like Visual Studio, you can
create Windows Forms applications that display information, request input from users, and communicate with remote
computers over a network.
In Windows Forms, a form is a visual surface on which you display information to the user. You commonly build Windows
Forms applications by placing controls on forms and developing responses to user actions, such as mouse clicks or key
presses. A control is a discrete user interface (UI) element that displays data or accepts data input.
Events
When a user does something to your form or one of its controls, it generates an event. Your application reacts to these events
by using code, and processes the events when they occur. For more information, see
Creating Event Handlers in Windows Forms.
Controls
Windows Forms contains a variety of controls that you can place on forms: controls that display text boxes, buttons, drop-
down boxes, radio buttons, and even Web pages. For a list of all the controls you can use on a form, see
Controls to Use on Windows Forms. If an existing control does not meet your needs, Windows Forms also supports creating
your own custom controls using the UserControl class.
Windows Forms has rich UI controls that emulate features in high-end applications like Microsoft Office. Using the ToolStrip
and MenuStrip control, you can create toolbars and menus that contain text and images, display submenus, and host other
controls such as text boxes and combo boxes.
With the Visual Studio drag-and-drop forms designer, you can easily create Windows Forms applications: just select the
controls with your cursor and place them where you want on the form. The designer provides tools such as grid lines and
"snap lines" to take the hassle out of aligning controls. And whether you use Visual Studio or compile at the command line, you
can use the FlowLayoutPanel, TableLayoutPanel and SplitContainer controls to create advanced form layouts with minimal
time and effort.
Custom UI Elements
Finally, if you must create your own custom UI elements, the System.Drawing namespace contains all of the classes you need
to render lines, circles, and other shapes directly on a form.
For step-by-step information about using these features, see the following Help topics.
To See
Create a new Windows Forms applic Walkthrough: Creating a Simple Windows Form
ation with Visual Studio
Use controls on forms How to: Add Controls to Windows Forms

Handle events from a form and its c How to: Create Event Handlers Using the Designer
ontrols

Use the ToolStrip Control How to: Create a Basic Windows Forms ToolStrip with Standard Items Using the Designer

Create graphics with System.Drawi Getting Started with Graphics Programming


ng

Create custom controls How to: Inherit from the UserControl Class

Displaying and Manipulating Data


Many applications must display data from a database, XML file, XML Web service, or other data source. Windows Forms
provides a flexible control called the DataGridView control for rendering such tabular data in a traditional row and column
format, so that every piece of data occupies its own cell. Using DataGridView you can customize the appearance of individual
cells, lock arbitrary rows and columns in place, and display complex controls inside cells, among other features.
Connecting to data sources over a network is a simple task with Windows Forms smart clients. The BindingSource component,
new with Windows Forms in Visual Studio 2005 and the .NET Framework 2.0, represents a connection to a data source, and
exposes methods for binding data to controls, navigating to the previous and next records, editing records, and saving changes
back to the original source. The BindingNavigator control provides a simple interface over the BindingSource component for
users to navigate between records.
Data-Bound Controls
You can create data-bound controls easily using the Data Sources window, which displays data sources such as databases,
Web services, and objects in your project. You can create data-bound controls by dragging items from this window onto forms
in your project. You can also data-bind existing controls to data by dragging objects from the Data Sources window onto
existing controls.
Settings
Another type of data binding you can manage in Windows Forms is settings. Most smart-client applications must retain some
information about their run-time state, such as the last-known size of forms, and retain user-preference data, such as default
locations for saved files. The application-settings feature addresses these requirements by providing an easy way to store both
types of settings on the client computer. Once defined using either Visual Studio or a code editor, these settings are persisted
as XML and automatically read back into memory at run time.
For step-by-step information about using these features, see the following Help topics.
To See
Use the BindingSource comp How to: Bind Windows Forms Controls with the BindingSource Component Using the Designer
onent

Work with ADO.NET data sour How to: Sort and Filter ADO.NET Data with the Windows Forms BindingSource Component
ces

Use the Data Sources window Walkthrough: Displaying Data on a Form in a Windows Application

Use application settings How to: Create Application Settings Using the Designer

Deploying Applications to Client Computers


Once you have written your application, you must send it to your users so that they can install and run it on their own client
computers. Using the ClickOnce technology, you can deploy your applications from within Visual Studio by using just a few
clicks and provide users with a URL pointing to your application on the Web. ClickOnce manages all of the elements and
dependencies in your application and ensures that the application is properly installed on the client computer.
ClickOnce applications can be configured to run only when the user is connected to the network, or to run both online and
offline. When you specify that an application should support offline operation, ClickOnce adds a link to your application in the
user's Start menu, so that the user can open it without using the URL.
When you update your application, you publish a new deployment manifest and a new copy of your application to your Web
server. ClickOnce detects that there is an update available and upgrades the user's installation; no custom programming is
required to update old assemblies.
For a full introduction to ClickOnce, see ClickOnce Deployment Overview. For step-by-step information about using these
features, see the following Help topics:
To See
Deploy an application with ClickOnce How to: Publish a ClickOnce Application
Walkthrough: Deploying a ClickOnce Application Manually

Update a ClickOnce deployment How to: Manage Updates for a ClickOnce Application

Check for application updates How to: Check for ClickOnce Application Updates

Manage security with ClickOnce How to: Enable ClickOnce Security Settings

Other Controls and Features


There are many other features in Windows Forms that make implementing common tasks fast and easy, such as support for
creating dialog boxes, printing, adding Help and documentation, and localizing your application to multiple languages. In
addition, Windows Forms relies on the robust security system of the .NET Framework, enabling you to release more secure
applications to your customers.
For step-by-step information about using these features, see the following Help topics:
To See
Print the contents of a form How to: Print Graphics in Windows Forms
How to: Print a Multi-Page Text File in Windows Forms

Globalize a Windows Forms application Walkthrough: Localizing Windows Forms

Learn more about Windows Forms security Security in Windows Forms Overview

See Also
Reference
Windows Forms Overview
My.Forms Object
My.Application Object
Concepts
Overview of Windows-based Applications
Classes Used in .NET Framework Forms
Visual Basic Language Concepts

Classes Used in .NET Framework Forms


The following tables list the classes commonly used for .NET Framework Windows Forms applications, categorized into the
base classes, control classes, component classes, and dialog box classes.
To enter the .NET Framework documentation and find a more comprehensive listing, see the System.Windows.Forms
namespace.
The Base Classes
The following table lists and describes the main Windows Forms classes in the System.Windows.Forms namespace.
Class Description
Control Defines the base class for controls, which are components with visual representation. Provides the base functional
ity for all controls that are displayed on a Form.

Form Represents a normal window, modeless window, dialog box, Multiple Document Interface (MDI) client, or MDI par
ent window. Forms make up an application's user interface.

UserControl Provides an empty control that can be used to create other controls or create a custom control that is a composite
of other controls.

Control Classes
The following table lists and describes a sampling of the System.Windows.Forms namespace's control classes. You can use
these controls to create rich user interfaces.
Class Description
TextBox Data-entry control. Represents a Windows text-box control.

ComboBox Data-entry control. Represents a Windows combo-box control.

Label Data-display control. Represents a standard Windows label.

ListView Data-display control. Represents a Windows list-view control, which displays a collection of items that can be dis
played using one of four different views.

Button Command-button control. Represents a Windows button control.

ToolStrip Command-button control. Provides a container for Windows toolbar objects.

PropertyGrid Designer control. Provides a user interface for browsing the properties of an object.

Component Classes
In addition to controls, the System.Windows.Forms namespace provides other classes that do not derive from the Control
class but still provide visual features to a Windows-based application. The following table shows some of the available
component classes.
Class Description
ToolTip Data-display component. Represents a small rectangular pop-up window that displays a brief descri
ption of a control's purpose when the user rests the pointer on the control.

ErrorProvider Data-display component. Provides a user interface for indicating that a control on a form has an err
or associated with it.
ToolStripDropDownMenu Menu component. Provides basic functionality for the ContextMenuStrip control.

ContextMenuStrip Menu component. Represents a shortcut menu.


Help Help component. Encapsulates the HTML Help 1.0 engine.

HelpProvider Help component. Provides pop-up or online Help for controls.

Dialog Box Classes


Windows provides a number of common dialog boxes that you can use to give your application a consistent user interface
when performing tasks such as opening and saving files, manipulating the font or text color, or printing. The following table
lists some of the commonly used classes used for reading from and writing to files with streams.
Class Description
OpenFileDialog Provides the functionality to display a dialog box that enables the user to browse to and enter the name of a
file to open or save.

SaveFileDialog Provides the functionality to display a dialog box that enables the user to browse to and enter the name of a
file to open or save.

FontDialog Displays a dialog box to change elements of the font used by your application

PageSetupDialog Displays a dialog box that enables the user to control aspects of printing documents.

PrintDialog Displays a dialog box that enables the user to control aspects of printing documents.

MessageBox Displays a message box that can display and retrieve data from the user.

See Also
Reference
Windows Forms Overview
System.Windows.Forms
System.Drawing.Printing
Concepts
Windows Forms Application Concepts in Visual Basic
Windows Forms Application Basics
Overview of Windows-based Applications
Visual Basic Language Concepts

Adding Printable Reports to Visual Studio Applications


Visual Studio supports a variety of reporting solutions to help you add rich data reporting to your Visual Basic applications.
You can create and add reports using ReportViewer controls, Crystal Reports, or SQL Server Reporting Services.
Note
SQL Server Reporting Services is part of SQL Server 2005 rather than Visual Studio 2005. Reporting Services not installed o
n your system unless you have installed SQL Server 2005.

This page describes ReportViewer controls and Reporting Services. For more information about Crystal Reports, see
Overview of Crystal Reports.
Overview of Microsoft Reporting Technology in Visual Basic Applications
Choose from the following approaches to use a Microsoft reporting technology in your application:
Add one or more instances of a ReportViewer control to a Visual Basic Windows application.
Integrate SQL Server Reporting Services programmatically by making calls to the Report Server Web service.
Use the ReportViewer control and Microsoft SQL Server 2005 Reporting Services together, using the control as a report
viewer and a report server as a report processor. (Note that you must use the SQL Server 2005 version of Reporting
Services if you want to use a report server and the ReportViewer control together).
Using ReportViewer Controls
The easiest way to embed report functionality into a Visual Basic Windows application is to add the ReportViewer control to a
form in your application. The control adds report processing capabilities directly to your application and provides an integrated
report designer so that you can build reports using data from any ADO.NET data object. A full-featured API provides
programmatic access to the control and reports so that you can configure run-time functionality.
ReportViewer provides built-in report processing and viewing capability in a single, freely distributable data control. Choose
ReportViewer controls if you require the following report functionality:
Report processing in the client application. A processed report appears in a view area provided by the control.
Data binding to ADO.NET data tables. You can create reports that consume DataTable instances supplied to the control.
You can also bind directly to business objects.
Redistributable controls that you can include in your application.
Runtime functionality such as page navigation, printing, searching, and export formats. A ReportViewer toolbar provides
support for these operations.
To use the ReportViewer control, you can drag it from the Data section of the Visual Studio Toolbox onto a form in your Visual
Basic Windows application. To learn more about ReportViewer, see ReportViewer Controls (Visual Studio) and
Samples and Walkthroughs.
Creating Reports in Visual Studio for ReportViewer Controls
To build a report that runs in ReportViewer, add a Report template to your project. Visual Studio creates a client report
definition file (.rdlc), adds the file to your project, and opens an integrated report designer in the Visual Studio workspace.
The Visual Studio Report Designer integrates with the Data Sources window. When you drag a field from the Data Sources
window to the report, the Report Designer copies metadata about the data source into the report definition file. This metadata
is used by the ReportViewer control to automatically generate data-binding code.
The Visual Studio Report Designer does not include report preview functionality. To preview your report, run the application
and preview the report embedded in it.
To add basic report functionality to your application
1. Drag a ReportViewer control from the Data tab of the Toolbox onto your form.
2. On the Project menu, choose Add New Item. In the Add New Item dialog box, select the Report icon and click Add.
The Report Designer opens in the development environment, and a report (.rdlc) file is added to the project.
3. Drag report items from the Toolbox on the report layout and arrange them as you want.
4. Drag fields from the Data Sources window to the report items in the report layout.
Next Steps in Working with ReportViewer and the Report Designer
To See
Add and configure a ReportViewer control Adding and Configuring the ReportViewer Control

Create and preview a local report Creating Reports for Local Processing Mode

Add data sources for ReportViewer reports Creating Data Sources for a ReportViewer Report

Define the layout of a report Defining a Report Layout

Use Visual Basic expressions in ReportViewer reports Using Expressions in a ReportViewer Report

Put custom code in a report Adding Custom Code to a ReportViewer Report

Distribute reports and the ReportViewer controls as part of your applicatio Deploying Reports and the ReportViewer Control
n

Print a report Printing Reports from ReportViewer

For more step-by-step instruction on how to create reports and configure controls for a variety of scenarios, see
Samples and Walkthroughs.
Using Reporting Services in Visual Basic Applications
Reporting Services is a server-based reporting technology that is included with SQL Server. Reporting Services includes
additional features that are not found in the ReportViewer controls. Choose Reporting Services if you require any of the
following features:
Scale-out deployment and server-side report processing that provides improved performance for complex or long-
running reports and for high-volume report activity.
Integrated data and report processing, with support for custom report controls and rich rendering output formats.
Scheduled report processing so that you can specify exactly when reports are run.
Subscriber-based report distribution through e-mail or to file share locations.
Ad hoc reporting so that business users can create reports as needed.
Data-driven subscriptions that route customized report output to a dynamic list of recipients.
Custom extensions for data processing, report delivery, custom authentication, and report rendering.
The report server is implemented as Web service. Your application code must include calls to the Web service to access reports
and other metadata. The Web service provides complete programmatic access to a report server instance.
Because Reporting Services is a Web-based reporting technology, the default viewer shows reports that are rendered in HTML
format. If you do not want to use HTML as the default report presentation format, you will have to write a custom report viewer
for your application.
To learn more about Reporting Services, see SQL Server Reporting Services in SQL Server 2005 Books Online and
SQL Server Reporting Services Tutorials.
Creating Reports in Visual Studio for Reporting Services
To build reports that run on a report server, you create report definition (.rdl) files in Visual Studio through the Business
Intelligence Development Studio, which is included with SQL Server 2005.
Note
You must have SQL Server 2005 installed in order to use SQL Server Reporting Services and the Business Intelligence Devel
opment Studio.

The Business Intelligence Development Studio adds project templates that are specific to SQL Server components. To create
reports, you can choose from the Report Server Project or Report Server Project Wizard templates. You can specify data
source connections and queries to a variety of data source types, including SQL Server, Oracle, Analysis Services, XML, and SQL
Server Integration Services. A Data tab, Layout tab, and Preview tab allow you to define data, create a report layout, and
preview the report all in the same workspace.
Report definitions that you build for the control or the report server can be reused in either technology. For more information,
see Converting RDL and RDLC Files.
To create a report that runs on a report server
1. On the File menu, choose New.
The New Project dialog box opens.
2. In the Project types pane, click Business Intelligence Projects.
3. In the Templates pane, select Report Server Project or Report Server Project Wizard.
Using ReportViewer Controls and SQL Server Reporting Services Together
The ReportViewer controls and SQL Server 2005 Reporting Services can be used together in the same application.
The ReportViewer control provides a viewer that is used to display reports in your application.
Reporting Services provides the reports and performs all processing on a remote server.
The ReportViewer control can be configured to show reports that are stored and processed on a remote Reporting Services
report server. This type of configuration is called remote processing mode. In remote processing mode, the control requests a
report that is stored on a remote report server. The report server performs all report processing, data processing, and report
rendering. A finished, rendered report is returned to the control and displayed in the view area.
Reports that run on a report server support additional export formats, have a different report parameterization
implementation, use the data source types that are supported by the report server, and are accessed through the role-based
authorization model on the report server.
To use remote processing mode, specify the URL and path to a server report when configuring the ReportViewer control. For
more information about control configuration and how server reports compare with client reports, see
Configuring ReportViewer for Remote Processing.
See Also
Reference
Microsoft.Reporting.WebForms
Microsoft.Reporting.WinForms
Other Resources
ReportViewer Web Server and Windows Forms Controls
Creating Reports for Local Processing Mode
Introducing Reporting Services Programming
Creating, Managing, and Delivering Reports Overview
Defining Report Data
Working with Data in Reporting Services
Visual Basic Language Concepts

Customizing Projects and Extending My with Visual Basic


You can customize project templates to provide additional My objects. This makes it easy for other developers to find and use
your objects.
Typically, these types of customizations are most beneficial for add-ins.
In This Section
Extending the Visual Basic Application Model
Describes how to specify your own extensions to the application model by overriding members of the
WindowsFormsApplicationBase class.
Customizing Which Objects are Available in My
Describes how to control which My objects are enabled by setting your project's _MYTYPE conditional-compilation constant.
Related Sections
Development with My
Describes which My objects are available in different project types by default.
Overview of the Visual Basic Application Model
Describes Visual Basic's model for controlling the behavior of Windows Forms applications.
How My Depends on Project Type
Describes which My objects are available in different project types by default.
Conditional Compilation Overview
Discusses how the compiler uses conditional-compilation to select particular sections of code to compile, while excluding
other sections.
My.Application Object
Describes the My object that provides properties, methods, and events related to the current application.
See Also
Other Resources
Going Further with Visual Basic
Visual Basic Language Concepts

Extending the Visual Basic Application Model


You can add functionality to the application model by overriding the Overridable members of the
WindowsFormsApplicationBase class. This technique allows you to customize the behavior of the application model and add
calls to your own methods as the application starts up and shuts down.
Visual Overview of the Application Model
This section visually presents the sequence of function calls in the Visual Basic Application Model. The next section describes
the purpose of each function in detail.
The following graphic shows the application model call sequence in a normal Visual Basic Windows Forms application. The
sequence starts when the Sub Main procedure calls the Run method.

The Visual Basic Application Model also provides the StartupNextInstance and UnhandledException events. The following
graphics show the mechanism for raising these events.

Overriding the Base Methods


The My.Application.Run Method defines the order in which the Application methods run. By default, the Sub Main procedure
for a Windows Forms application calls the Run method.
If the application is a normal application (multiple-instance application), or the first instance of a single-instance application,
the Run method executes the Overridable methods in the following order:
1. OnInitialize. By default, this method sets the visual styles, text display styles, and current principal for the main application
thread (if the application uses Windows authentication), and calls ShowSplashScreen if neither /nosplash nor -
nosplash is used as a command-line argument.

The application startup sequence is canceled if this function returns False. This can be useful if there are circumstances in
which the application should not run.
The OnInitialize method calls the following methods:
a. ShowSplashScreen. Determines if the application has a splash screen defined and if it does, displays the splash
screen on a separate thread.
The ShowSplashScreen method contains the code that displays the splash screen for at least the number of
milliseconds specified by the MinimumSplashScreenDisplayTime property. To use this functionality, you must add
the splash screen to your application using the Project Designer (which sets the
My.Application.MinimumSplashScreenDisplayTime property to two seconds), or set the
My.Application.MinimumSplashScreenDisplayTime property in a method that overrides the OnInitialize or
OnCreateSplashScreen method. For more information, see
My.Application.MinimumSplashScreenDisplayTime Property.
b. OnCreateSplashScreen. Allows a designer to emit code that initializes the splash screen.
By default, this method does nothing. If you select a splash screen for your application in the Visual Basic Project
Designer, the designer overrides the OnCreateSplashScreen method with a method that sets the SplashScreen
property to a new instance of the splash-screen form.
2. OnStartup. Provides an extensibility point for raising the Startup event. The application startup sequence stops if this
function returns False.
By default, this method raises the Startup event. If the event handler sets the Cancel property of the event argument to
True, the method returns False to cancel the application startup.

3. OnRun. Provides the starting point for when the main application is ready to start running, after the initialization is done.
By default, before it enters the Windows Forms message loop, this method calls the OnCreateMainForm (to create the
application's main form) and HideSplashScreen (to close the splash screen) methods:
a. OnCreateMainForm. Provides a way for a designer to emit code that initializes the main form.
By default, this method does nothing. However, when you select a main form for your application in the Visual
Basic Project Designer, the designer overrides the OnCreateMainForm method with a method that sets the
MainForm property to a new instance of the main form.
b. HideSplashScreen. If application has a splash screen defined and it is open, this method closes the splash screen.
By default, this method closes the splash screen.
4. OnStartupNextInstance. Provides a way to customize how a single-instance application behaves when another instance
of the application starts.
By default, this method raises the StartupNextInstance event.
5. OnShutdown. Provides an extensibility point for raising the Shutdown event. This method does not run if an unhandled
exception occurs in the main application.
By default, this method raises the Shutdown event.
6. OnUnhandledException. Executed if an unhandled exception occurs in any of the above listed methods.
By default, this method raises the UnhandledException event as long as a debugger is not attached and the application is
handling the UnhandledException event.
If the application is a single-instance application, and the application is already running, the subsequent instance of the
application calls the OnStartupNextInstance method on the original instance of the application, and then exits.
The WindowsFormsApplicationBase constructor calls the UseCompatibleTextRendering property to determine which text
rendering engine to use for the application's forms. By default, the UseCompatibleTextRendering property returns False,
indicating that the GDI text rendering engine be used, which is the default in Visual Basic 2005. You can override the
UseCompatibleTextRendering property to return True, which indicates that the GDI+ text rendering engine be used, which
is the default in Visual Basic .NET 2002 and Visual Basic .NET 2003.
Configuring the Application
As a part of the Visual Basic Application model, the WindowsFormsApplicationBase class provides protected properties that
configure the application. These properties should be set in the constructor of the implementing class.
In a default Windows Forms project, the Project Designer creates code to set the properties with the designer settings. The
properties are used only when the application is starting; setting them after the application starts has no effect.
Property Determines Setting with the Project Designer
IsSingleInstance Whether the application runs as a single-instanc How to: Specify Instancing Behavior for an Application
e or multiple-instance application.

EnableVisualStyles If the application will use XP visual styles. How to: Enable Visual Styles

SaveMySettingsOnExit If application automatically saves application's u Select the Save My.Settings on Shutdown check bo
ser-settings changes when the application exits. x in the Application pane in the Project Designer.

ShutdownStyle What causes the application to terminate, such a How to: Specify Shutdown Behavior for an Application
s when the main form closes or when all forms c
lose.

See Also
Reference
My.Application Object
My.Application.Startup Event
My.Application.StartupNextInstance Event
My.Application.UnhandledException Event
My.Application.Shutdown Event
My.Application.NetworkAvailabilityChanged Event
WindowsFormsApplicationBase
Concepts
Overview of the Visual Basic Application Model
Visual Basic Language Concepts

Customizing Which Objects are Available in My


This topic describes how you can control which My objects are enabled by setting your project's _MYTYPE conditional-
compilation constant. The Visual Studio Integrated Development Environment (IDE) keeps the _MYTYPE conditional-
compilation constant for a project in sync with the project's type.
Predefined _MYTYPE Values
You must use the /define compiler option to set the _MYTYPE conditional-compilation constant. When specifying your own
value for the _MYTYPE constant, you must enclose the string value in backslash/quotation mark (\") sequences. For example,
you could use:

/define:_MYTYPE=\"WindowsForms\"

This table shows what the _MYTYPE conditional-compilation constant is set to for several project types.
Project type _MYTYPE value
Class Library "Windows"

Console Application "Console"

Web "Web"

Web Control Library "WebControl"

Windows Application "WindowsForms"

Windows Application, when starting with custom Sub Main "WindowsFormsWithCustomSubMain"

Windows Control Library "Windows"

Windows Service "Console"

Empty "Empty"
Note
All conditional-compilation string comparisons are case-sensitive, regardless of how the Option Compare statement is set.

Dependent _MY Compilation Constants


The _MYTYPE conditional-compilation constant, in turn, controls the values of several other _MY compilation constants:
_MYTYPE _MYAPPLICATIONTY _MYCOMPUTERTY _MYFORM _MYUSERTYP _MYWEBSERVIC
PE PE S E ES
"Console" "Console" "Windows" Undefined "Windows" TRUE

"Custom" Undefined Undefined Undefined Undefined Undefined

"Empty" Undefined Undefined Undefined Undefined Undefined

"Web" Undefined "Web" FALSE "Web" FALSE

"WebControl" Undefined "Web" FALSE "Web" TRUE


"Windows" or "" "Windows" "Windows" Undefined "Windows" TRUE

"WindowsForms" "WindowsForms" "Windows" TRUE "Windows" TRUE

"WindowsFormsWithCustomSubM "Console" "Windows" TRUE "Windows" TRUE


ain"

By default, undefined conditional-compilation constants resolve to FALSE. You can specify values for the undefined constants
when compiling your project to override the default behavior.
Note
When _MYTYPE is set to "Custom", the project contains the My namespace, but it contains no objects. However, setting _MY
TYPE to "Empty" prevents the compiler from adding the My namespace and its objects.

This table describes the effects of the predefined values of the _MY compilation constants.
Constant Meaning
_MYAPPLICA Enables My.Application, if the constant is "Console," Windows," or "WindowsForms":
TIONTYPE
The "Console" version derives from ConsoleApplicationBase. and has fewer members than the "Windows"
version.
The "Windows" version derives from ApplicationBase.and has fewer members than the "WindowsForms"
version.
The "WindowsForms" version of My.Application derives from WindowsFormsApplicationBase. If the TA
RGET constant is defined to be "winexe", then the class includes a Sub Main method.

_MYCOMPU Enables My.Computer, if the constant is "Web" or "Windows":


TERTYPE
The "Web" version derives from ServerComputer, and has fewer members than the "Windows" version.
The "Windows" version of My.Computer derives from Computer.

_MYFORMS Enables My.Forms, if the constant is TRUE.

_MYUSERTY Enables My.User, if the constant is "Web" or "Windows":


PE
The "Web" version of My.User is associated with the user identity of the current HTTP request.
The "Windows" version of My.User is associated with the thread's current principal.

_MYWEBSER Enables My.WebServices, if the constant is TRUE.


VICES

_MYTYPE Enables My.Log, My.Request, and My.Response, if the constant is "Web".

See Also
Reference
/define (Visual Basic)
My.Application Object
My.Computer Object
My.Forms Object
My.Log Object
My.Request Object
My.Response Object
My.User Object
My.WebServices Object
Concepts
How My Depends on Project Type
Conditional Compilation Overview
Visual Basic Language Concepts

Visual Basic Programming Guide


As with any modern programming language, Visual Basic supports a number of common programming constructs and
language elements. This guide walks through all the essential elements of programming with Visual Basic.
In This Section
Program Structure and Code Conventions
Contains documentation on the basic structure and code conventions of Visual Basic, such as naming conventions,
comments in code, and limitations within Visual Basic.
Visual Basic Language Features
Introduces and discusses the essential components of Visual Basic.
Object-Oriented Programming in Visual Basic
Covers object-oriented programming, including classes and interfaces, object creation, events and delegates, inheritance, and
groups of objects.
COM Interop
Explains the interoperability issues associated with creating and using component object model (COM) objects with Visual
Basic.
Multithreading in Visual Basic
Shows how to write code that performs multiple tasks simultaneously, to improve the performance and responsiveness of
your applications.
Related Sections
Visual Basic Reference
Provides reference information on various aspects of Visual Basic programming.
Visual Basic Compiler
Offers information on using the Visual Basic command-line compiler, the compiler options, and the Keyword Upgrade tool.
Visual Basic Language Concepts

Program Structure and Code Conventions


This section introduces the typical Visual Basic program structure, provides a simple Visual Basic program, "Hello, World", and
discusses Visual Basic code conventions. Code conventions are suggestions that focus not on a program's logic but on its
physical structure and appearance. Following them makes your code easier to read, understand, and maintain. Code
conventions can include, among others:
Standardized formats for labeling and commenting code.
Guidelines for spacing, formatting, and indenting code.
Naming conventions for objects, variables, and procedures.
The following topics present a set of programming guidelines for Visual Basic programs, along with examples of good usage.
In This Section
Structure of a Visual Basic Program
Provides an overview of the elements that make up a Visual Basic program.
Visual Basic Version of Hello, World
Provides a step-by-step recreation of the classic program "Hello World," redone in Visual Basic.
Main Procedure in Visual Basic
Discusses the procedure that serves as the starting point and overall control for your application.
Visual Basic Naming Conventions
Includes general guidelines for naming procedures, constants, variables, arguments, and objects.
Visual Basic Coding Conventions
Reviews the guidelines used in developing the samples in this documentation.
Conditional Compilation (Visual Basic)
Provides links to topics about how to compile particular blocks of code selectively while directing the compiler to ignore
others.
How to: Break and Combine Statements in Code
Shows how to divide long statements into multiple lines and combine short statements on one line.
How to: Label Statements
Shows how to mark a line of code to identify it for use with statements such as On Error Goto.
Special Characters in Code
Shows how and where to use non-numeric and non-alphabetic characters.
Comments in Code
Discusses how to add descriptive comments to your code.
Visual Basic Limitations
Discusses the removal of known coding limits within Visual Basic.
Related Sections
Typographic and Code Conventions
Provides standard coding conventions for Visual Basic.
Editing Text, Code, and Markup
Provides an overview of the Visual Studio Code Editor.
Visual Basic Language Concepts

Structure of a Visual Basic Program


A Visual Basic program is built up from standard building blocks. A solution comprises one or more projects. A project in turn
can contain one or more assemblies. Each assembly is compiled from one or more source files. A source file provides the
definition and implementation of classes, structures, modules, and interfaces, which ultimately contain all your code.
File-Level Programming Elements
When you start a project or file and open the code editor, you see some code already in place and in the correct order. Any
code that you write should follow the following sequence:
1. Option statements
2. Imports statements
3. Namespace statements and namespace-level elements
If you enter statements in a different order, compilation errors can result.
A program can also contain conditional compilation statements. You can intersperse these in the source file among the
statements of the preceding sequence.
Option Statements
Option statements establish ground rules for subsequent code, helping prevent syntax and logic errors. The
Option Explicit Statement (Visual Basic) ensures that all variables are declared and spelled correctly, which reduces debugging
time. The Option Strict Statement helps to minimize logic errors and data loss that can occur when you work between variables
of different data types. The Option Compare Statement specifies the way strings are compared to each other, based on either
their Binary or Text values.
Imports Statements
You can include an Imports Statement to import names defined outside your project. An Imports statement allows your code
to refer to classes and other types defined within the imported namespace, without having to qualify them. You can use as
many Imports statements as appropriate. For more information, see References and the Imports Statement.
Namespace Statements
Namespaces help you organize and classify your programming elements for ease of grouping and accessing. You use the
Namespace Statement to classify the following statements within a particular namespace. For more information, see
Namespaces in Visual Basic.
Conditional Compilation Statements
Conditional compilation statements can appear almost anywhere in your source file. They cause parts of your code to be
included or excluded at compile time depending on certain conditions. You can also use them for debugging your application,
because conditional code runs in debugging mode only. For more information, see Conditional Compilation Overview.
Namespace-Level Programming Elements
Classes, structures, and modules contain all the code in your source file. They are namespace-level elements, which can appear
within a namespace or at the source file level. They hold the declarations of all other programming elements. Interfaces, which
define element signatures but provide no implementation, also appear at module level. For more information on the module-
level elements, see the following:
Class Statement (Visual Basic)
Structure Statement
Module Statement
Interface Statement (Visual Basic)
Data elements at namespace level are enumerations and delegates.
Module-Level Programming Elements
Procedures, operators, properties, and events are the only programming elements that can hold executable code (statements
that perform actions at run time). They are the module-level elements of your program. For more information on the
procedure-level elements, see the following:
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
Declare Statement
Operator Statement
Property Statement
Event Statement
Data elements at module level are variables, constants, enumerations, and delegates.
Procedure-Level Programming Elements
Most of the contents of procedure-level elements are executable statements, which constitute the run-time code of your
program. All executable code must be in some procedure (Function, Sub, Operator, Get, Set, AddHandler,
RemoveHandler, RaiseEvent). For more information, see Executable Statements.
Data elements at procedure level are limited to local variables and constants.
The Main Procedure
The Main procedure is the first code to run when your application has been loaded. Main serves as the starting point and overall
control for your application. There are four varieties of Main:
Sub Main()

Sub Main(ByVal cmdArgs() As String)

Function Main() As Integer

Function Main(ByVal cmdArgs() As String) As Integer

The most common variety of this procedure is Sub Main(). For more information, see Main Procedure in Visual Basic.

See Also
Concepts
Visual Basic Version of Hello, World
Main Procedure in Visual Basic
Visual Basic Naming Conventions
Visual Basic Limitations
Visual Basic Language Concepts

Visual Basic Version of Hello, World


The following console program is the Visual Basic version of the traditional "Hello, World!" program, which displays the string
"Hello, World!".
VB
' A "Hello, World!" program in Visual Basic.
Module Hello
Sub Main()
MsgBox("Hello, World!") ' Display message on computer screen.
End Sub
End Module

The important points of this program are the following:


Comments
The Main procedure
Input and output
Compilation and execution
Comments
The first line of the example contains a comment:
VB
' A "Hello, World!" program in Visual Basic.

The single quotation mark (') means that the rest of the line is a comment and will be ignored by the compiler. You can make
an entire line a comment, or you can append a comment to the end of another statement, as follows:
VB
MsgBox("Hello, World!") ' Display message on computer screen.

The Main Procedure


Every Visual Basic application must contain a procedure called Main. This procedure serves as the starting point and overall
control for your application. It is called when your module is loaded.
There are four varieties of Main:
Sub Main()

Sub Main(ByVal cmdArgs() As String)

Function Main() As Integer

Function Main(ByVal cmdArgs() As String) As Integer

The most common variety of this procedure is Sub Main(). Unless you are creating a Windows Forms application, you must
write the Main procedure for applications that run on their own. For more information, see Main Procedure in Visual Basic.
Input and Output
This example uses the standard Visual Basic run-time library, which is available through the Microsoft.VisualBasic namespace.
If you compile the program in the integrated development environment (IDE), you can use all the procedures and properties of
Microsoft.VisualBasic without having to import it. If you compile from the command line, you must use the
Imports Statement in your source code, or the /imports (Visual Basic) command-line compiler option, to make the
Microsoft.VisualBasic members available to your program.
The Main procedure calls the MsgBox Function (Visual Basic) to display a message box containing the string "Hello, World!":
VB
MsgBox("Hello, World!") ' Display message on computer screen.

Compilation and Execution


You can compile the "Hello, World!" program using either the Visual Studio integrated development environment (IDE) or the
command line.
To compile and run the program from the command line
1. Create the source file using any text editor and save it with a file name such as Hello.vb.
2. To invoke the compiler, enter the following command:
vbc Hello.vb

If your source file does not include an Imports statement for the Microsoft.VisualBasic namespace, you can include the
/imports command-line compiler option in the vbc command:
vbc Hello.vb /imports:Microsoft.VisualBasic

3. If your program does not contain any compilation errors, the compiler creates a Hello.exe file.
4. To run the program, enter the following command:
Hello

You can optionally include the /main command-line compiler option in the vbc command to specify the namespace and
module supplying Main.
To compile and run the program from the IDE
1. Create a Visual Basic console application project.
2. Copy the code into the project.
3. Choose the appropriate Build command from the Build menu, or press F5 to build and run (corresponding to Start in
the Debug menu).
For more information on the Visual Basic compiler and its options, see Building from the Command Line (Visual Basic).
See Also
Reference
Structure of a Visual Basic Program
Imports Statement
/imports (Visual Basic)
MsgBox Function (Visual Basic)
/main
Microsoft.VisualBasic
Concepts
Main Procedure in Visual Basic
Other Resources
Building from the Command Line (Visual Basic)
Visual Basic Language Concepts

Main Procedure in Visual Basic


Every Visual Basic application must contain a procedure called Main. This procedure serves as the starting point and overall
control for your application. The .NET Framework calls your Main procedure when it has loaded your application and is ready to
pass control to it. Unless you are creating a Windows Forms application, you must write the Main procedure for applications
that run on their own.
Main contains the code that runs first. In Main, you can determine which form is to be loaded first when the program starts, find
out if a copy of your application is already running on the system, establish a set of variables for your application, or open a
database that the application requires.
Requirements for the Main Procedure
A file that runs on its own (usually with extension .exe) must contain a Main procedure. A library (for example with extension
.dll) does not run on its own and does not require a Main procedure. The requirements for the different types of projects you
can create are as follows:
Console applications run on their own, and you must supply at least one Main procedure. .
Windows Forms applications run on their own. However, the Visual Basic compiler automatically generates a Main
procedure in such an application, and you do not need to write one.
Class libraries do not require a Main procedure. These include Windows Control Libraries and Web Control Libraries.
Web applications are deployed as class libraries.
Declaring the Main Procedure
There are four ways to declare the Main procedure. It can take arguments or not, and it can return a value or not.
Note
If you declare Main in a class, you must use the Shared keyword. In a module, Main does not need to be Shared.

The simplest way is to declare a Sub procedure that does not take arguments or return a value.

Module mainModule
Sub Main()
MsgBox("The Main procedure is starting the application.")
' Insert call to appropriate starting place in your code.
MsgBox("The application is terminating.")
End Sub
End Module

Main can also return an Integer value, which the operating system uses as the exit code for your program. Other
programs can test this code by examining the Windows ERRORLEVEL value. To return an exit code, you must declare
Main as a Function procedure instead of a Sub procedure.

Module mainModule
Function Main() As Integer
MsgBox("The Main procedure is starting the application.")
Dim returnValue As Integer = 0
' Insert call to appropriate starting place in your code.
' On return, assign appropriate value to returnValue.
' 0 usually means successful completion.
MsgBox("The application is terminating with error level " _
& CStr(returnValue) & ".")
Return returnValue
End Function
End Module
Main can also take a String array as an argument. Each string in the array contains one of the command-line arguments
used to invoke your program. You can take different actions depending on their values.

Module mainModule
Function Main(ByVal cmdArgs() As String) As Integer
MsgBox("The Main procedure is starting the application.")
Dim returnValue As Integer = 0
' See if there are any arguments.
If cmdArgs.Length > 0 Then
For argNum As Integer = 0 To UBound(cmdArgs, 1)
' Insert code to examine cmdArgs(argNum) and take
' appropriate action based on its value.
Next argNum
End If
' Insert call to appropriate starting place in your code.
' On return, assign appropriate value to returnValue.
' 0 usually means successful completion.
MsgBox("The application is terminating with error level " _
& CStr(returnValue) & ".")
Return returnValue
End Function
End Module

You can declare Main to examine the command-line arguments but not return an exit code, as follows.

Module mainModule
Sub Main(ByVal cmdArgs() As String)
MsgBox("The Main procedure is starting the application.")
Dim returnValue As Integer = 0
' See if there are any arguments.
If cmdArgs.Length > 0 Then
For argNum As Integer = 0 To UBound(cmdArgs, 1)
' Insert code to examine cmdArgs(argNum) and take
' appropriate action based on its value.
Next argNum
End If
' Insert call to appropriate starting place in your code.
MsgBox("The application is terminating."
End Sub
End Module

See Also
Reference
Structure of a Visual Basic Program
/main
Shared (Visual Basic)
MsgBox Function (Visual Basic)
Sub Statement (Visual Basic)
Function Statement (Visual Basic)
Integer Data Type (Visual Basic)
String Data Type (Visual Basic)
UBound Function (Visual Basic)
Length
Concepts
Visual Basic Version of Hello, World
Visual Basic Language Concepts

Visual Basic Naming Conventions


When you name an element in your Visual Basic application, the first character of that name must be an alphabetic character or
an underscore. Note, however, that names beginning with an underscore are not compliant with the
Common Language Specification (CLS).
The following suggestions apply to naming.
Begin each separate word in a name with a capital letter, as in FindLastRecord and RedrawMyForm.
Begin function and method names with a verb, as in InitNameArray or CloseDialog.
Begin class, structure, module, and property names with a noun, as in EmployeeName or CarAccessory.
Begin interface names with the prefix "I", followed by a noun or a noun phrase, like IComponent, or with an adjective
describing the interface's behavior, like IPersistable. Do not use the underscore, and use abbreviations sparingly,
because abbreviations can cause confusion.
Begin event handler names with a noun describing the type of event followed by the "EventHandler" suffix, as in
"MouseEventHandler".
In names of event argument classes, include the "EventArgs" suffix.
If an event has a concept of "before" or "after," use a prefix in present or past tense, as in "ControlAdd" or
"ControlAdded".
For long or frequently used terms, use abbreviations to keep name lengths reasonable, for example, "HTML", instead of
"Hypertext Markup Language". In general, variable names greater than 32 characters are difficult to read on a monitor set
to a low resolution. Also, make sure your abbreviations are consistent throughout the entire application. Randomly
switching in a project between "HTML" and "Hypertext Markup Language" can lead to confusion.
Avoid using names in an inner scope that are the same as names in an outer scope. Errors can result if the wrong
variable is accessed. If a conflict occurs between a variable and the keyword of the same name, you must identify the
keyword by preceding it with the appropriate type library. For example, if you have a variable called Date, you can use the
intrinsic Date function only by calling System.DateTime.Date.
See Also
Concepts
Keywords as Element Names in Code
Me, My, MyBase, and MyClass in Visual Basic
Declared Element Names
Other Resources
Program Structure and Code Conventions
Visual Basic Reference
Visual Basic Language Concepts

Keywords as Element Names in Code


Any program element — such as a variable, class, or member — can have the same name as a restricted keyword. For
example, you can create a variable named Loop. However, to refer to your version of it — which has the same name as the
restricted Loop keyword — you must either precede it with a full qualification string or enclose it in square brackets ([ ]), as
the following example shows.
VB
' The following statement precedes Loop with a full qualification string.
sampleForm.Loop.Visible = True
' The following statement encloses Loop in square brackets.
[Loop].Visible = True

If you do not do either of these, then Visual Basic assumes use of the intrinsic Loop keyword and produces an error, as in the
following example:
' The following statement causes a compiler error.
Loop.Visible = True

You can use square brackets when referring to forms and controls, and when declaring a variable or defining a procedure with
the same name as a restricted keyword. It can be easy to forget to qualify names or include square brackets, and thus introduce
errors into your code and make it harder to read. For this reason, we recommend that you not use restricted keywords as the
names of program elements. However, if a future version of Visual Basic defines a new keyword that conflicts with an existing
form or control name, then you can use this technique when updating your code to work with the new version.
Note
Your program also might include element names provided by other referenced assemblies. If these names conflict with restri
cted keywords, then placing square brackets around them causes Visual Basic to interpret them as your defined elements.

See Also
Concepts
Visual Basic Naming Conventions
Other Resources
Program Structure and Code Conventions
Keywords (Visual Basic)
Visual Basic Language Concepts

Me, My, MyBase, and MyClass in Visual Basic


The apparent similarities between Me, My, MyBase, and MyClass in Visual Basic may confuse you if you are coming to the
concepts for the first time. This page describes each of these entities in order to distinguish between them.
Me
The Me keyword provides a way to refer to the specific instance of a class or structure in which the code is currently executing.
Me behaves like either an object variable or a structure variable referring to the current instance. Using Me is particularly
useful for passing information about the currently executing instance of a class or structure to a procedure in another class,
structure, or module.
My
The My feature provides easy and intuitive access to a number of .NET Framework classes, enabling the Visual Basic user to
interact with the computer, application, settings, resources, and so on.
MyBase
The MyBase keyword behaves like an object variable referring to the base class of the current instance of a class. MyBase is
commonly used to access base class members that are overridden or shadowed in a derived class. MyBase.New is used to
explicitly call a base class constructor from a derived class constructor.
MyClass
The MyClass keyword behaves like an object variable referring to the current instance of a class as originally implemented.
MyClass is similar to Me, but all method calls on it are treated as if the method were NotOverridable.
See Also
Reference
MyBase
MyClass
Me
Concepts
Development with My
Inheritance Basics
Visual Basic: Samples

Visual Basic Coding Conventions


These guidelines are used by Microsoft to develop samples and documentation. The Visual Basic Language Specification does
not define a coding standard.
Coding conventions create a consistent look to the code, so that readers can focus on content, not layout.
Conventions let the readers understand the code more quickly, because it allows them to make assumptions based on
previous experience.
Conventions make copying, changing, and maintaining the code easier.
Conventions demonstrate Visual Basic "best practices."
Discussion
Naming Conventions
Naming guidelines are covered in Design Guidelines for Developing Class Libraries.
You do not have to change the name of objects created by the Visual Studio designer tools to make them fit the
guidelines.
Use namespace qualifications rather than adding Imports statements. If a namespace is imported by default in a project,
you do not have to fully qualify the code because it will run unqualified with Intellisense when copied and pasted. When
you are breaking long lines of code to make them easier to read, qualified names can be broken after the "." For example:

Dim collection As System.Diagnostics. _


InstanceDataCollectionCollection

Do not use "My" or "my" as part of a variable name. This creates confusion with the My objects.
Layout Conventions
Good layout uses formatting to emphasize the structure of the code and makes code easier to read.
Use the pretty listing feature to format code with the the default settings (smart indenting, 4 character indents, save tabs
as spaces). For more information, see VB Specific, Basic, Text Editor, Options Dialog Box.
Use only one statement per line. Do not use ":".
Use only one declaration per line.
Indent continuation lines one tab stop.
Add at least one blank line between method and property definitions.
Commenting Conventions
Do not use comments at the end of a line of code. Put comments on a separate line.
Begin the comment text with an uppercase letter.
End the comment with a period.
Insert one space between the comment delimiter (') and the comment text.

' Here is a comment.

Do not create formatted blocks of asterisks that surround comments.


Program Structure
When using the Main method, use the default construct for new console applications, and use My for command-line
arguments.
Sub Main()
For Each argument As String In My.Application.CommandLineArgs
' Add code here to use the string variable.
Next
End Sub

Language Guidelines
String Data Type
Use & to concatenate strings:

MsgBox("hello" & vbCrLf & "goodbye")

For appending strings in loops, use the StringBuilder object:

Dim longString As New System.Text.StringBuilder


For count As Integer = 1 To 1000
longString.Append(count)
Next

Unsigned Data Type


Use Integer rather than unsigned types unless memory is at a premium.
Arrays
Use the short syntax when initializing arrays on the declaration line:

Dim letters() As String = {"a", "b", "c"}

Rather than this:

Dim letters() As String = New String() {"a", "b", "c"}

Put the array designator on the variable, not on the type:

Dim letters() As String = {"a", "b", "c"}

Rather than this:

Dim letters As String() = {"a", "b", "c"}

Use the { } syntax when declaring and initializing arrays of basic data types:

Dim letters() As String = {"a", "b", "c"}

Rather than this:

Dim letters(2) As String


letters(0) = "a"
letters(1) = "b"
letters(2) = "c"

Use the With Keyword


When faced with a series of calls to one object, consider using the With keyword.
When faced with a series of calls to one object, consider using the With keyword.
Declare Looping Variables in the For or For Each Statement
Example:

For count As Integer = 0 To 2


MsgBox(names(count))
Next

Example:

For Each name As String In names


MsgBox(name)
Next

Use Try...Catch
Always use a Try...Catch with object that implements a Dispose method.
Don’t use On Error Goto.
Use the Using Statement
If you are using a Try...Catch statement, and the only code in the Finally block is a call to Dispose, use Using instead.
IsNot Keyword
Use the IsNot keyword in preference to Not ... Is Nothing.
Default Instances of Forms
Use Form1.ShowDialog rather than My.Forms.Form1.ShowDialog.
New Keyword
Use short instantiation:

Dim employees As New Collection()

Rather than this:

Dim employees As Collection = New Collection()

Use the parameterless constructor and then set the properties using With:

Dim orderLog As New EventLog()


With orderLog
.Log = "Application"
.Source = "Application Name"
.MachineName = "Machine Name"
End With

Event Handling
Use Handles rather than AddHandler:

Private Sub MenuItem1_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles MenuItem1.Click

Use AddressOf, and do not instantiate the delegate explicitly:


Dim closeItem As New MenuItem("Close", AddressOf MenuItem1_Click)
Me.MainMenu1.MenuItems.Add(closeItem)

When you define an event, use the short syntax and let the compiler define the delegate:

Public Event WhatHappened(ByVal source As Object, _


ByVal e As WhatHappenedEventArgs)

Using Shared Members


Called Shared members using the class name, not from an instance variable.
MsgBox Function
Use MsgBox instead of MessageBox.Show or Console.WriteLine.
Use the My Namespace
Use My features in preference to the .NET Framework class library or the Visual Basic run-time library.
Use the Visual Basic Run-Time Library Members
Use the Visual Basic run-time library in preference to the .NET Framework class library.
Guidelines for Samples
General
Follow the design guidelines in Design Guidelines for Class Library Developers
(http://msdn.microsoft.com/library/default.asp?url=/library/en-
us/cpgenref/html/cpconnetframeworkdesignguidelines.asp).
Specify the prompt and title of MsgBox calls.
Use resource files when appropriate.
Use Option Strict On, either in each file, or as a project setting.
Compile with all warnings on.
Define only one Class, Structure, or Interface in a file.
Use the default encoding to save files.
Localization
Use the AutoSize property where possible.
Do not hide or overlap controls.
Do not line up controls to create a sentence.
Do not build strings by stripping out characters from another string.
Use culture-neutral graphics.
Use only Tahoma or MS Sans Serif fonts.
Accessibility
Use colors from the System tab of the color picker dialog box.
Use accelerators for all menus, labels, buttons, and so on.
Set control properties as described in the following table.
Property Setting
AccessibleDescription A description of the control.
AccessibleName A name for the control.

AccessibleRole Default, or reset this property if a control has another role.

TabIndex Set in a logical order.

Text All clickable controls should have a keyboard access key (shortcut).

Font size Default or set to 10 points or larger

Forecolor Default

Backcolor Default

BackgroundImage Default
Security
Follow the guidelines in Secure Coding Guidelines.
See Also
Other Resources
Design Guidelines for Developing Class Libraries
Secure Coding Guidelines
Visual Basic Language Concepts

Conditional Compilation (Visual Basic)


In conditional compilation, particular blocks of code in a program are compiled selectively while others are ignored.
In This Section
Conditional Compilation Overview
Explains what conditional compilation is used for, and discusses the #Const and #If...Then...#Else directives.
How to: Declare Conditional Compilation Constants
Shows how to declare conditional compilation constants in the Property Pages dialog box, at the command line, or in your
code.
How to: Collapse and Hide Sections of Code
Explains how to specify a block of code that you can expand or collapse using the Visual Studio outlining feature.
Related Sections
Program Structure and Code Conventions
Provides suggestions for making your code easy to read and maintain.
Compiling to MSIL
Explains how your source code is translated into Microsoft intermediate language (MSIL) by the compiler.
Compiling MSIL to Native Code
Provides an overview of the .NET Framework JIT (just-in-time) compiler that converts MSIL to native (CPU-specific) code.
Visual Basic Language Concepts

Conditional Compilation Overview


You can use conditional compilation to select particular sections of code to compile, while excluding other sections. For
example, you may want to write debugging statements that compare the speed of different approaches to the same
programming task, or you may want to localize an application for multiple languages. Conditional compilation statements are
designed to run during compile time, not at run time.
You declare a conditional compiler constant in code with the #Const directive, and you denote blocks of code to be
conditionally compiled with the #If...Then...#Else directive. For example, to create French- and German-language versions of
the same application from the same source code, you embed platform-specific code segments in #If...Then statements using
the predefined constants FrenchVersion and GermanVersion. The following example demonstrates how:
VB
#If FrenchVersion Then
' <code specific to the French language version>.
#ElseIf GermanVersion Then
' <code specific to the German language version>.
#Else
' <code specific to other versions>.
#End If

If you set the value of the FrenchVersion constant to True at compile time, the conditional code for the French version is
compiled. If you set the value of the GermanVersion constant to True, the compiler uses the German version. If neither is set to
True, the code in the last Else block runs.
Note
Autocompletion will not function when editing code and using conditional compilation directives if the code is not part of the
current branch.

See Also
Tasks
How to: Declare Conditional Compilation Constants
How to: Collapse and Hide Sections of Code
Reference
#Const Directive
#If...Then...#Else Directives
Other Resources
Building from the Command Line (Visual Basic)
Visual Basic Language Concepts

How to: Declare Conditional Compilation Constants


You can set conditional compilation constants in one of three ways:
In the Project Designer
At the command line when using the command-line compiler
In your code
Conditional compilation constants have a special scope and cannot be accessed from standard code. The scope of a conditional
compilation constant is dependent on the way it is set. The following table lists the scope of constants declared using each of
the three ways mentioned above.
How constant is set Scope of constant
Project Designer Public to all files in the project

Command line Public to all files passed to the command-line compiler

#Const statement in code Private to the file in which it is declared

To set constants in the Project Designer


Before creating your executable file, set constants in the Project Designer by following the steps provided in
How to: Modify Project Properties and Configuration Settings.
To set constants at the command line
Use the /d switch to enter conditional compilation constants, as in the following example:

vbc MyProj.vb /d:conFrenchVersion=–1:conANSI=0

No space is required between the /d switch and the first constant. For more information, see /define (Visual Basic).
Command-line declarations override declarations entered in the Project Designer, but do not erase them. Arguments
set in Project Designer remain in effect for subsequent compilations.
When writing constants in the code itself, there are no strict rules as to their placement, since their scope is the entire
module in which they are declared.
To set constants in your code
Place the constants in the declaration block of the module in which they are used. This helps keep your code organized
and easier to read.
See Also
Tasks
How to: Collapse and Hide Sections of Code
Reference
Conditional Compilation Constants
/define (Visual Basic)
#If...Then...#Else Directives
#Const Directive
Concepts
Conditional Compilation Overview
Other Resources
Building from the Command Line (Visual Basic)
Visual Basic Language Concepts

How to: Collapse and Hide Sections of Code


The #Region directive enables you to collapse and hide sections of code in Visual Basic files. The #Region directive lets you
specify a block of code that you can expand or collapse when using the Visual Studio code editor. The ability to hide code
selectively makes your files more manageable and easier to read. For more information, see How to: Outline and Hide Code.
#Region directives support code block semantics such as #If...#End If. This means they cannot begin in one block and end in
another; the start and end must be in the same block. #Region directives are not supported within functions.
To collapse and hide a section of code
Place the section of code between the #Region and #End Region statements, as in the following example:
VB
#Region "This is the code to be collapsed"
Private components As System.ComponentModel.Container
Dim WithEvents Form1 As System.Windows.Forms.Form

Private Sub InitializeComponent()


components = New System.ComponentModel.Container
Me.Text = "Form1"
End Sub
#End Region

The #Region block can be used multiple times in a code file; thus, users can define their own blocks of procedures and
classes that can, in turn, be collapsed. #Region blocks can also be nested within other #Region blocks.
Note
Hiding code does not prevent it from being compiled and does not affect #If...#End If statements.

See Also
Tasks
How to: Declare Conditional Compilation Constants
How to: Outline and Hide Code
Reference
#Region Directive
#If...Then...#Else Directives
Concepts
Conditional Compilation Overview
Visual Basic Language Concepts

How to: Break and Combine Statements in Code


When writing your code, you might at times create lengthy statements that necessitate horizontal scrolling in the Code Editor.
While this does not affect the way your code runs, it makes it difficult for you or anyone else to read the code as it appears on
the monitor. In such cases, you should consider breaking the single long statement into several lines.
At other times, you might want to consolidate statements on a single line, for instance, when you have several very short
statements and want to conserve space. This feature can also be handy when organizing variables or commands within a
module.
To break a single statement into multiple lines
Use the line-continuation character, which is an underscore (_), at the point at which you want the line to break. The
underscore must be immediately preceded by a space and immediately followed by a line terminator (carriage return).
In the following example, the statement is broken into four lines with line-continuation characters terminating all but the
last line.
VB
cmd.CommandText = _
"SELECT * FROM Titles JOIN Publishers " _
& "ON Publishers.PubId = Titles.PubID " _
& "WHERE Publishers.State = 'CA'"

Using this sequence makes your code easier to read, both online and when printed.
Note
The line-continuation character is necessarily the last thing on a line. You cannot follow it with anything else on the sa
me line.

Some limitations exist as to where the line-continuation character can be used, such as in the middle of an argument
name. You can break an argument list with the line-continuation character, but the individual names of the arguments
must remain intact.
Note
You cannot continue a comment by using a line-continuation character. Once a comment begins, the compiler does not
examine the characters for special meaning. For a multiple-line comment, repeat the comment symbol (') on each line.

While placing each statement on a separate line is the recommended method, Visual Basic also allows you to place multiple
statements on the same line.
To place multiple statements on the same line
Separate the statements with a colon (:), as in the following example.
VB
text1.Text = "Hello" : text1.BackColor = System.Drawing.Color.Red

See Also
Other Resources
Program Structure and Code Conventions
Statements in Visual Basic
Visual Basic Language Concepts

How to: Label Statements


Statement blocks are made up of lines of code delimited by colons. Lines of code preceded by an identifying string or integer
are said to be labeled. Statement labels are used to mark a line of code to identify it for use with statements such as On Error
Goto.
Labels may be either valid Visual Basic 2005 identifiers—such as those that identify programming elements—or integer
literals. A label must appear at the beginning of a line of source code and must be followed by a colon, regardless of whether it
is followed by a statement on the same line.
The compiler identifies labels by checking whether the beginning of the line matches any already-defined identifier. If it does
not, the compiler assumes it is a label.
Labels have their own declaration space and do not interfere with other identifiers. A label's scope is the body of the method.
Label declaration takes precedence in any ambiguous situation.
Note
Labels can be used only on executable statements inside methods.

To label a line of code


Place an identifier, followed by a colon, at the beginning of the line of source code.
For example, the following lines of code are labeled with Jump and 120, respectively:
VB
Jump: FileOpen(1, "testFile", OpenMode.Input)
' ...
120: FileClose(1)

See Also
Concepts
Statements Overview
Other Resources
Statements in Visual Basic
Program Structure and Code Conventions
Visual Basic Language Concepts

Special Characters in Code


At times, you need to use special characters in your code, that is, characters that are not on the standard alphanumeric list. The
punctuation and special characters in the Visual Basic character set have various uses, from organizing program text to
defining the tasks that the compiler or the compiled program carries out. They do not specify an operation to be performed.
Parentheses
Use parentheses when defining a procedure, such as a Sub or Function. You must enclose all procedure argument lists in
parentheses. You also use parentheses for putting variables or arguments into logical groups, especially to override the default
order of operator precedence in a complex expression. The following example illustrates this.
VB
Dim a, b, c, d, e As Double
a = 3.2
b = 7.6
c = 2
d = b + c / a
e = (b + c) / a

Following execution of the preceding code, the value of d is 8.225 and the value of e is 3. The calculation for d uses the default
precedence of / over + and is equivalent to d = b + (c / a). The parentheses in the calculation for e override the default
precedence.
Separators
Separators do what their name suggests: they separate sections of code. In Visual Basic, the separator character is the colon (:).
Use separators when you want to place multiple statements on a single line instead of separate lines, saving space and
improving the readability of your code. The following example shows three statements separated by colons (:).
VB
a = 3.2 : b = 7.6 : c = 2

Concatenation
Use the & operator for concatenation, or linking strings together. Do not confuse it with the + operator, which adds together
numeric values. Using the + operator to concatenate can cause incorrect results when operating on numeric values. The
following example demonstrates this.
VB
var1 = "10.01"
var2 = 11
resultA = var1 + var2
resultB = var1 & var2

Following execution of the preceding code, the value of resultA is 21.01 and the value of resultB is "10.0111".
Member Access Operators
To access a member of a type, you use the dot (.) or exclamation point (!) operator between the type name and the member
name.
Dot (.) Operator
Use the . operator on a class, structure, interface, or enumeration as a member access operator. The member can be a field,
property, event, or method.The following example illustrates this.
VB
Dim nextForm As New System.Windows.Forms.Form
' Access Text member (property) of Form class (on nextForm object).
nextForm.Text = "This is the next form"
' Access Close member (method) on nextForm.
nextForm.Close()

Exclamation Point (!) Operator


Use the ! operator only on a class or interface as a dictionary access operator. The class or interface must have a default
property that accepts a single String argument. The identifier immediately following the ! operator becomes the string
argument to the default property. The following example demonstrates this.
VB
Public Class hasDefault
Default Public ReadOnly Property index(ByVal s As String) As Integer
Get
Return 32768 + AscW(s)
End Get
End Property
End Class
Public Class testHasDefault
Public Sub compareAccess()
Dim hD As hasDefault = New hasDefault()
MsgBox("Traditional access returns " & hD.index("X") & vbCrLf & _
"Default property access returns " & hD("X") & vbCrLf & _
"Dictionary access returns " & hD!X)
End Sub
End Class

The three output lines of MsgBox all display the value 32856. The first line uses the traditional access to property index, the
second makes use of the fact that index is the default property of class hasDefault, and the third uses dictionary access to the
class.
Note that the second operand of the ! operator must be a string not enclosed in double quotation marks (" "). In other words,
you cannot use a string literal or string variable. The following change to the last line of the MsgBox call generates an error
because "X" is an enclosed string literal.
"Dictionary access returns " & hD!"X")

Note
References to default collections must be explicit. In particular, you cannot use the ! operator on a late-bound variable.

The ! character is also used as the Single type character.


See Also
Concepts
Type Characters
Other Resources
Program Structure and Code Conventions
Visual Basic Language Concepts

Comments in Code
As you read the code examples, you often encounter the comment symbol ('). This symbol tells the Visual Basic compiler to
ignore the text following it, or the comment. Comments are brief explanatory notes added to code for the benefit of those
reading it.
It is good programming practice to begin all procedures with a brief comment describing the functional characteristics of the
procedure (what it does). This is for your own benefit and the benefit of anyone else who examines the code. You should
separate the implementation details (how the procedure does it) from comments that describe the functional characteristics.
When you include implementation details in the description, remember to update them when you update the function.
Comments can follow a statement on the same line, or occupy an entire line. Both are illustrated in the following code.
VB
' This is a comment beginning at the left edge of the screen.
text1.Text = "Hi!" ' This is an inline comment.

If your comment requires more than one line, use the comment symbol on each line, as the following example illustrates.
VB
' This comment is too long to fit on a single line, so we break
' it into two lines. Some comments might need three or more lines.

Commenting Guidelines
The following table provides general guidelines for what types of comments can precede a section of code. These are
suggestions; Visual Basic does not enforce rules for adding comments. Write what works best, both for you and for anyone
else who reads your code.
Comment type Comment description
Purpose Describes what the procedure does (not how it does it)

Assumptions Lists each external variable, control, open file, or other element accessed by the procedure

Effects Lists each affected external variable, control, or file, and the effect it has (only if it is not obvious)

Inputs Specifies the purpose of the argument

Returns Explains the values returned by the procedure

Remember the following points:


Every important variable declaration should be preceded by a comment describing the use of the variable being declared.
Variables, controls, and procedures should be named clearly enough that commenting is needed only for complex
implementation details.
Comments cannot follow a line-continuation sequence on the same line.
You can add or remove comment symbols for a block of code by selecting one or more lines of code and choosing the
Comment ( ) and Uncomment ( ) buttons on the Edit toolbar.
Note
You can also add comments to your code by preceding the text with the REM keyword. However, the ' symbol and the Com
ment/Uncomment buttons are easier to use and require less space and memory.
See Also
Reference
REM Statement (Visual Basic)
Other Resources
Program Structure and Code Conventions
Visual Basic Language Concepts

How to: Add a Comment to Your Code (Visual Basic)


This example shows comments occupying an entire source code line, part of a line, and more than one line.
Example
VB
' This entire line is a comment.
Dim DailyTotal As Decimal = 0 ' Sales total for today.
' This comment is so long that it requires more than one line, so
' the comment character (') must be repeated on the second line.

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
A reference to the System namespace.
Note
You cannot continue a comment using the line-continuation sequence ( _). You must repeat the comment character (')
at the beginning of each line of a comment.

See Also
Tasks
How to: Break and Combine Statements in Code
Concepts
Comments in Code
Visual Basic Language Concepts

Documenting Your Code with XML (Visual Basic)


In Visual Basic, you can document your code using XML
XML Documentation Comments
Visual Basic provides an easy way to automatically create XML documentation for projects. You can automatically generate an
XML skeleton for your types and members, and then provide summaries, descriptive documentation for each parameter, and
other remarks. With the appropriate setup, the XML documentation is automatically emitted into an XML file with the same
name as your project and the .xml extension. For more information, see /doc.
The XML file can be consumed or otherwise manipulated as XML. This file is located in the same directory as the output .exe or
.dll file of your project.
XML documentation starts with '''. The processing of these comments has some restrictions:
The documentation must be well-formed XML. If the XML is not well formed, a warning is generated and the
documentation file contains a comment saying that an error was encountered.
Developers are free to create their own set of tags. There is a recommended set of tags (see "Related Sections" in this
topic). Some of the recommended tags have special meanings:
The <param> tag is used to describe parameters. If used, the compiler will verify that the parameter exists and
that all parameters are described in the documentation. If the verification fails, the compiler issues a warning.
The cref attribute can be attached to any tag to provide a reference to a code element. The compiler verifies that
this code element exists. If the verification fails, the compiler issues a warning. The compiler also respects any
Imports statements when looking for a type described in the cref attribute.
The <summary> tag is used by IntelliSense in Visual Studio to display additional information about a type or
member.
Related Sections
For details on creating an XML file with documentation comments, see the following topics:
/doc
Recommended XML Tags for Documentation Comments (Visual Basic)
Processing the XML File (Visual Basic)
How to: Create XML Documentation in Visual Basic
XML Comments Sample
XML Tools in Visual Studio
See Also
Other Resources
Developing Applications with Visual Basic
Visual Basic Programming Guide
Visual Basic Language Concepts

Processing the XML File (Visual Basic)


The compiler generates an ID string for each construct in your code that is tagged to generate documentation. (For information
on how to tag your code, see Recommended XML Tags for Documentation Comments (Visual Basic).) The ID string uniquely
identifies the construct. Programs that process the XML file can use the ID string to identify the corresponding .NET Framework
metadata/reflection item.
The XML file is not a hierarchical representation of your code; it is a flat list with a generated ID for each element.
The compiler observes the following rules when it generates the ID strings:
No white space is placed in the string.
The first part of the ID string identifies the kind of member being identified, with a single character followed by a colon.
The following member types are used.
Charac Description
ter
N namespace
You cannot add documentation comments to a namespace, but you can make CREF references to them, where s
upported.

T type: Class, Module, Interface, Structure, Enum, Delegate

F field: Dim

P property: Property (including default properties)

M method: Sub, Function, Declare, Operator

E event: Event

! error string
The rest of the string provides information about the error. The Visual Basic compiler generates error informatio
n for links that cannot be resolved.

The second part of the String is the fully qualified name of the item, starting at the root of the namespace. The name of
the item, its enclosing type(s), and the namespace are separated by periods. If the name of the item itself contains
periods, they are replaced by the number sign (#). It is assumed that no item has a number sign directly in its name. For
example, the fully qualified name of the String constructor would be System.String.#ctor.
For properties and methods, if there are arguments to the method, the argument list enclosed in parentheses follows. If
there are no arguments, no parentheses are present. The arguments are separated by commas. The encoding of each
argument follows directly how it is encoded in a .NET Framework signature.
Example
The following code shows how the ID strings for a class and its members are generated.
VB
Namespace SampleNamesapce
''' <summary>Signature is
''' "T:SampleNamesapce.SampleClass"
''' </summary>
Public Class SampleClass
''' <summary>Signature is
''' "M:SampleNamesapce.SampleClass.#ctor"
''' </summary>
Public Sub New()
End Sub

''' <summary>Signature is
''' "M:SampleNamesapce.SampleClass.#ctor(System.Int32)"
''' </summary>
Public Sub New(ByVal i As Integer)
End Sub
''' <summary>Signature is
''' "F:SampleNamesapce.SampleClass.SampleField"
''' </summary>
Public SampleField As String

''' <summary>Signature is
''' "F:SampleNamesapce.SampleClass.SampleConstant"
''' </summary>
Public Const SampleConstant As Integer = 42

''' <summary>Signature is
''' "M:SampleNamesapce.SampleClass.SampleFunction"
''' </summary>
Public Function SampleFunction() As Integer
End Function

''' <summary>Signature is
''' "M:SampleNamesapce.SampleClass.
''' SampleFunction(System.Int16[],System.Int32[0:,0:])"
''' </summary>
Public Function SampleFunction( _
ByVal array1D() As Short, _
ByVal array2D(,) As Integer) _
As Integer
End Function
''' <summary>Signature is
''' "M:SampleNamesapce.SampleClass.
''' op_Addition(SampleNamesapce.SampleClass,
''' SampleNamesapce.SampleClass)"
''' </summary>
Public Shared Operator +( _
ByVal operand1 As SampleClass, _
ByVal operand2 As SampleClass) _
As SampleClass

Return Nothing
End Operator

''' <summary>Signature is
''' "P:SampleNamesapce.SampleClass.SampleProperty"
''' </summary>
Public Property SampleProperty() As Integer
Get
End Get
Set(ByVal value As Integer)
End Set
End Property

''' <summary>Signature is
''' "P:SampleNamesapce.SampleClass.Item(System.String)"
''' </summary>
Default Public ReadOnly Property Item( _
ByVal s As String) As Integer

Get
End Get
End Property
''' <summary>Signature is
''' "T:SampleNamesapce.SampleClass.NestedClass"
''' </summary>
Public Class NestedClass
End Class

''' <summary>Signature is
''' "E:SampleNamesapce.SampleClass.SampleEvent(System.Int32)"
''' </summary>
Public Event SampleEvent As SampleDelegate

''' <summary>Signature is
''' "T:SampleNamesapce.SampleClass.SampleDelegate"
''' </summary>
Public Delegate Sub SampleDelegate(ByVal i As Integer)
End Class
End Namespace

See Also
Tasks
How to: Create XML Documentation in Visual Basic
Reference
/doc
Visual Basic Language Reference

How to: Create XML Documentation in Visual Basic


This example shows how to add XML documentation comments to your code.
To create XML documentation for a type or member
1. In the Code Editor, position your cursor on the line above the type or member for which you want to create
documentation.
2. Type ''' (three single-quotation marks).
An XML skeleton for the type or member is added in the Code Editor.
3. Add descriptive information between the appropriate tags.
Note
If you add additional lines within the XML documentation block, each line must begin with '''.

4. Add additional code that uses the type or member with the new XML documentation comments.
IntelliSense displays the text from the <summary> tag for the type or member.
5. Compile the code to generate an XML file containing the documentation comments. For more information, see /doc.
See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
/doc
Concepts
Documenting Your Code with XML (Visual Basic)
Visual Basic Language Concepts

Visual Basic Limitations


Earlier versions of Visual Basic enforced boundaries in code, such as the length of variable names, the number of variables
allowed in modules, and module size. In Visual Basic 2005, these restrictions have been relaxed, giving you greater freedom in
writing and arranging your code.
Physical limits are dependent more on run-time memory than on compile-time considerations. If you use prudent
programming practices, and divide large applications into multiple classes and modules, then there is very little chance of
encountering an internal Visual Basic limitation.
The following are some limitations that you might encounter in extreme cases:
Name Length. There is a maximum number of characters for the name of every declared programming element. This
maximum applies to an entire qualification string if the element name is qualified. See Declared Element Names.
Line Length. There is a maximum of 65535 characters in a physical line of source code. The logical source code line can
be longer if you use line continuation characters. See How to: Break and Combine Statements in Code.
Array Dimensions. There is a maximum number of dimensions you can declare for an array. This limits how many
indexes you can use to specify an array element. See Array Dimensions in Visual Basic.
String Length. There is a maximum number of Unicode characters you can store in a single string. See
String Data Type (Visual Basic).
Environment String Length. There is a maximum of 32768 characters for any environment string used as a command-
line argument. This is a limitation on all platforms. See How to: Access Command-Line Arguments (Visual Basic).
See Also
Concepts
Visual Basic Naming Conventions
Other Resources
Program Structure and Code Conventions
Visual Basic Language Concepts

Visual Basic Language Features


The following topics introduce and discuss the essential components of Visual Basic, an object-oriented programming
language. After creating the user interface for your application using forms and controls, you need to write the code that
defines the application's behavior. As with any modern programming language, Visual Basic supports a number of common
programming constructs and language elements.
If you have programmed in other languages, much of the material covered in this section might seem familiar. While most of
the constructs are similar to those in other languages, the event-driven nature of Visual Basic introduces some subtle
differences.
If you are new to programming, the material in this section serves as an introduction to the basic building blocks for writing
code. Once you understand the basics, you can create powerful applications using Visual Basic.
In This Section
Visual Basic and the .NET Framework
Describes the role of Visual Basic in the .NET Framework, and discusses assemblies and attributes.
Declared Elements in Visual Basic
Covers programming elements you can declare, their names and characteristics, and how the compiler resolves references to
them.
Data Types in Visual Basic
Describes what kinds of data a programming element can hold and how that data is stored.
Variables in Visual Basic
Discusses how to declare variables to store values, and how to use them to refer to objects.
Arrays in Visual Basic
Discusses making your code more compact and powerful by declaring and using arrays, which hold multiple related values.
Objects in Visual Basic
Provides an overview of objects and classes, how they are used, their relationships to each other, and the properties,
methods, and events they expose.
Strings in Visual Basic
Covers declaring and manipulating variables that contain a sequence of characters.
Constants and Enumerations in Visual Basic
Discusses storing unchanging values for repeated use, including sets of related constant values.
Operators and Expressions in Visual Basic
Describes the code elements that manipulate value-holding elements, how to use them efficiently, and how to combine them
to yield new values.
Statements in Visual Basic
Provides an overview of the two basic units of instruction in Visual Basic: declaration statements and executable statements.
Procedures in Visual Basic
Describes Sub, Function, Property, and Operator procedures, as well as advanced topics such as recursive and overloaded
procedures.
Control Flow in Visual Basic
Shows how to regulate the flow of your program's execution.
Related Sections
Object-Oriented Programming in Visual Basic
Covers object-oriented programming, including classes and interfaces, object creation, events and delegates, inheritance, and
groups of objects.
Visual Basic Reference
Provides reference information on various aspects of Visual Basic programming.
Visual Basic Language Concepts

Visual Basic and the .NET Framework


Visual Basic is designed around the .NET Framework, which helps provide security, memory management, versioning, and
deployment support. The .NET Framework also enables interoperability between objects you create with any .NET Framework
programming language. This means you can create objects with Visual Basic that are easy to use from other .NET Framework
languages, and you can use objects from other .NET Framework languages just like you use objects created with Visual Basic.
In This Section
Assemblies
Defines assemblies and describes how to use them.
References and the Imports Statement
Discusses how to reference objects in other assemblies.
Namespaces in Visual Basic
Describes how namespaces organize objects within assemblies.
Attributes in Visual Basic
Discusses how .NET Framework attributes provide additional information about entities defined inside a Visual Basic
application.
Related Sections
How to: Add or Remove References in Visual Studio
Covers adding references so you can write code against external components, and describes how to remove unnecessary
references.
.NET Framework Conceptual Overview
Introduces the .NET Framework architecture and its components.
Language Changes for Visual Basic 6.0 Users
Provides a list and descriptions of changed language elements.
Visual Basic Language Concepts

Assemblies
Assemblies form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions for a
.NET-based application. Assemblies take the form of an executable (.exe) file or dynamic link library (.dll) file, and are the
building blocks of the .NET Framework. They provide the common language runtime with the information it needs to be aware
of type implementations. You can think of an assembly as a collection of types and resources that form a logical unit of
functionality and are built to work together.
With Visual Basic, you use the contents of assemblies, and add references to them, in much the same way as you use type
libraries with previous versions of Visual Basic. However, what makes assemblies different from .exe or .dll files in earlier
versions of Windows is that they contain all the information you would find in a type library, plus information about everything
else necessary to use the application or component.
Assembly Manifest
Within every assembly is an assembly manifest. Similar to a table of contents, the assembly manifest contains the following:
The assembly's identity (its name and version).
A file table describing all the other files that make up the assembly, for example, any other assemblies you created that
your .exe or .dll file relies on, or even bitmap or Readme files.
An assembly reference list, which is a list of all external dependencies—.dlls or other files your application needs that may
have been created by someone else. Assembly references contain references to both global and private objects. Global
objects reside in the global assembly cache, an area available to other applications, somewhat like the System32
directory. The Microsoft.VisualBasic namespace is an example of an assembly in the global assembly cache. Private
objects must be in a directory at either the same level as or below the directory in which your application is installed.
Because assemblies contain information about content, versioning, and dependencies, the applications you create with Visual
Basic do not rely on registry values to function properly. Assemblies reduce DLL conflicts and make your applications more
reliable and easier to deploy. In many cases, you can install a .NET-based application simply by copying its files to the target
computer.
References
To use an assembly, you must add a reference to it, as described in How to: Add or Remove References in Visual Studio. Next,
you use the Imports statement to choose the namespace of the items you want to use, as described in
References and the Imports Statement. Once an assembly is referenced and imported, all the accessible classes, properties,
methods, and other members of its namespaces are available to your application as if their code were part of your source file.
A single assembly can contain multiple namespaces, and each namespace can contain a different grouping of items, including
other namespaces.
For information on creating assemblies, see How to: Create and Use Assemblies.
See Also
Tasks
How to: Create and Use Assemblies
How to: Add or Remove References in Visual Studio
How to: View Assembly Contents
Reference
Imports Statement
Microsoft.VisualBasic
Concepts
Namespaces in Visual Basic
References and the Imports Statement
Other Resources
Assemblies in the Common Language Runtime
Language Changes for Visual Basic 6.0 Users
Visual Basic Language Concepts

How to: Create and Use Assemblies


An assembly is one or more .exe or .dll files that make up a Visual Studio-based application. Assemblies are created
automatically when you compile Visual Basic source files.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To create an assembly
Compile your application by clicking Build on the Build menu or by building it from the command line using the
command-line compiler. For details about building assemblies from the command line, see
Building from the Command Line (Visual Basic).
To add a reference to another assembly
Click the Add Reference command on the Project menu, and select the assembly you want to use. For details, see
How to: Add or Remove References in Visual Studio.
To use objects in another assembly
Specify the fully qualified name for the object, or use an alias that has been defined for the object using an Imports
statement. For details about fully qualified names, see Namespaces in Visual Basic. For details about adding references
and using the Imports statement, see References and the Imports Statement.
See Also
Tasks
How to: Add or Remove References in Visual Studio
How to: View Assembly Contents
Reference
Imports Statement
Concepts
Assemblies
Creating Assemblies
Namespaces in Visual Basic
References and the Imports Statement
Other Resources
Assemblies in the Common Language Runtime
Language Changes for Visual Basic 6.0 Users
Building from the Command Line (Visual Basic)
Visual Basic Language Concepts

References and the Imports Statement


You can make external objects available to your project by choosing the Add Reference command on the Project menu.
References in Visual Basic can point to assemblies, which are like type libraries but contain more information.
The Imports Statement
Assemblies include one or more namespaces. When you add a reference to an assembly, you can also add an Imports
statement to a module that controls the visibility of that assembly's namespaces within the module. The Imports statement
provides a scoping context that lets you use only the portion of the namespace necessary to supply a unique reference.
The Imports statement has the following syntax:
Imports [| Aliasname =] Namespace
Aliasname refers to a short name you can use within code to refer to an imported namespace. Namespace is a namespace
available through either a project reference, through a definition within the project, or through a previous Imports statement.
A module may contain any number of Imports statements. They must appear after any Option statements, if present, but
before any other code.
Note
Do not confuse project references with the Imports statement or the Declare statement. Project references make external o
bjects, such as objects in assemblies, available to Visual Basic projects. The Imports statement is used to simplify access to pr
oject references, but does not provide access to these objects. The Declare statement is used to declare a reference to an ext
ernal procedure in a dynamic-link library (DLL).

Using Aliases with the Imports Statement


The Imports statement makes it easier to access methods of classes by eliminating the need to explicitly type the fully qualified
names of references. Aliases let you assign a friendlier name to just one part of a namespace. For example, the carriage
return/line feed sequence that causes a single piece of text to be displayed on multiple lines is part of the
ControlChars Module (Visual Basic) module in the Microsoft.VisualBasic namespace. To use this constant in a program without
an alias, you would need to type the following code:
VB
MsgBox("Some text" & Microsoft.VisualBasic.ControlChars.CrLf _
& "Some more text")

Imports statements must always be the first lines immediately following any Option statements in a module. The following
code fragment shows how to import and assign an alias to the Microsoft.VisualBasic.ControlChars module:
VB
Imports CtrlChrs = Microsoft.VisualBasic.ControlChars

Future references to this namespace can be considerably shorter:


VB
MsgBox("Some text" & CtrlChrs.CrLf & "Some more text")

If an Imports statement does not include an alias name, elements defined within the imported namespace can be used in the
module without qualification. If the alias name is specified, it must be used as a qualifier for names contained within that
namespace.
See Also
Tasks
How to: Add or Remove References in Visual Studio
How to: Create and Use Assemblies
Reference
Imports Statement
ControlChars Module (Visual Basic)
Microsoft.VisualBasic
Concepts
Namespaces in Visual Basic
Assemblies
Other Resources
Language Changes for Visual Basic 6.0 Users
Visual Basic Language Concepts

Namespaces in Visual Basic


Namespaces organize the objects defined in an assembly. Assemblies can contain multiple namespaces, which can in turn
contain other namespaces. Namespaces prevent ambiguity and simplify references when using large groups of objects such as
class libraries.
For example, the .NET Framework defines the ListBox class in the System.Windows.Forms namespace. The following code
fragment shows how to declare a variable using the fully qualified name for this class:
VB
Dim LBox As System.Windows.Forms.ListBox

Avoiding Name Collisions


.NET Framework namespaces address a problem sometimes called namespace pollution, in which the developer of a class
library is hampered by the use of similar names in another library. These conflicts with existing components are sometimes
called name collisions.
For example, if you create a new class named ListBox, you can use it inside your project without qualification. However, if you
want to use the .NET Framework ListBox class in the same project, you must use a fully qualified reference to make the
reference unique. If the reference is not unique, Visual Basic produces an error stating that the name is ambiguous. The
following code example demonstrates how to declare these objects:
VB
' Define a new object based on your ListBox class.
Dim LBC As New ListBox
' Define a new Windows.Forms ListBox control.
Dim MyLB As New System.Windows.Forms.ListBox

The following illustration shows two namespace hierarchies, both containing an object named ListBox.

By default, every executable file you create with Visual Basic contains a namespace with the same name as your project. For
example, if you define an object within a project named ListBoxProject, the executable file ListBoxProject.exe contains a
namespace called ListBoxProject.
Multiple assemblies can use the same namespace. Visual Basic treats them as a single set of names. For example, you can
define classes for a namespace called SomeNameSpace in an assembly named Assemb1, and define additional classes for the
same namespace from an assembly named Assemb2.
Fully Qualified Names
Fully qualified names are object references that are prefixed with the name of the namespace in which the object is defined.
You can use objects defined in other projects if you create a reference to the class (by choosing Add Reference from the
Project menu) and then use the fully qualified name for the object in your code. The following code fragment shows how to
use the fully qualified name for an object from another project's namespace:
VB
Dim LBC As New ListBoxProject.Form1.ListBox

Fully qualified names prevent naming conflicts because they make it possible for the compiler to determine which object is
being used. However, the names themselves can get long and cumbersome. To get around this, you can use the Imports
statement to define an alias—an abbreviated name you can use in place of a fully qualified name. For example, the following
code example creates aliases for two fully qualified names, and uses these aliases to define two objects.
VB
Imports LBControl = System.Windows.Forms.ListBox
Imports MyListBox = ListBoxProject.Form1.ListBox

VB
Dim LBC As LBControl
Dim MyLB As MyListBox

If you use the Imports statement without an alias, you can use all the names in that namespace without qualification, provided
they are unique to the project. If your project contains Imports statements for namespaces that contain items with the same
name, you must fully qualify that name when you use it. Suppose, for example, your project contained the following two
Imports statements:
VB
' This namespace contains a class called Class1.
Imports MyProj1
' This namespace also contains a class called Class1.
Imports MyProj2

If you attempt to use Class1 without fully qualifying it, Visual Basic produces an error stating that the name Class1 is
ambiguous.
Namespace Level Statements
Within a namespace, you can define items such as modules, interfaces, classes, delegates, enumerations, structures, and other
namespaces. You cannot define items such as properties, procedures, variables and events at the namespace level. These items
must be declared within containers such as modules, structures, or classes.
Note
If you have defined a nested hierarchy of namespaces, code inside that hierarchy might be blocked from accessing classes in
side of other namespaces with the same name. For example, if you define a namespace named System within a namespace n
amed SpecialSpace, the members of the .NET Framework System namespace will not be accessible unless you fully-qualify
the members with the Global keyword. For more information, see Global.

See Also
Tasks
How to: Create and Use Assemblies
Reference
Global
Imports Statement
ListBox
System.Windows.Forms
Concepts
Assemblies
References and the Imports Statement
Other Resources
Language Changes for Visual Basic 6.0 Users
Visual Basic Language Concepts

Attributes in Visual Basic


Attributes are keyword-like tags in which you can specify additional information about entities defined in Visual Basic
applications. Attributes, which are saved with an assembly's metadata, annotate programming elements such as types, fields,
methods, and properties. Other applications, such as the Visual Basic or ASP.NET compilers, can refer to the information in
attributes to determine how objects should be used.
The following sections provide more information about attributes and how they are defined, applied, and retrieved.
In This Section
Attributes Overview in Visual Basic
Provides information about attributes and their functionality and capabilities.
Attributes Used in Visual Basic
Lists some of the attributes you are most likely to use in Visual Basic.
Common Uses for Attributes
Describes some of the more common ways that attributes are used.
Application of Attributes
Discusses how attributes are applied to program elements.
Global Attributes in Visual Basic
Provides information about attributes that apply to modules or assemblies.
Custom Attributes in Visual Basic
Shows how to define your own attributes.
Related Sections
Object-Oriented Programming in Visual Basic
Provides information about object-oriented programming and how it is used.
Metadata and Self-Describing Components
Provides detailed information about the kinds of metadata used in Visual Studio, including attributes.
Visual Basic Language Concepts

Attributes Overview in Visual Basic


Attributes are descriptive tags that provide additional information about programming elements such as types, fields, methods,
and properties. Other applications, such as the Visual Basic compiler, can refer to the extra information in attributes to
determine how these items can be used.
Attributes and Metadata
Attributes are saved with the metadata of Visual Basic assemblies. Metadata is information that describes every element
managed by the runtime. This includes information required for debugging and garbage collection, as well as security
attributes, marshaling data, extended class and member definitions, version binding, and any other information the runtime
requires.
With attributes, you specify the metadata in much the same way as you use keywords like Public and Private to provide
information about access levels. However, unlike keywords, most attributes are not language-specific. Using attributes, you can
extend the capabilities of the Visual Basic language without requiring changes to the compiler.
The .NET Framework and the Visual Basic language define many useful attributes, and you can define your own custom
attributes that are meaningful to your application. Custom attributes are based on the System.Attribute class, and they use the
AttributeUsageAttribute attribute to provide additional information about how the attribute can be used.
Functionality and Capabilities of Attributes
Some key points about attributes include:
You can apply one or more attributes to entire assemblies, modules, or smaller program elements such as classes and
properties.
Attributes can accept arguments in the same way as methods and properties.
The process of retrieving metadata from attributes is called reflection. Reflection involves using tools that allow objects to
retrieve and examine metadata about their own members. For more information, see Reflection Sample.
See Also
Tasks
How to: Define Your Own Attributes
Reference
AttributeUsageAttribute
System.Attribute
Concepts
Common Uses for Attributes
Application of Attributes
Global Attributes in Visual Basic
Attributes Used in Visual Basic
Attributes and Design-Time Support
Other Resources
Custom Attributes in Visual Basic
Visual Basic Language Concepts

Attributes Used in Visual Basic


The following table lists some of the more common attributes used in Visual Basic. For information about a specific attribute,
type the attribute name in the Index or Search box of the Help system.
Attribute Purpose
ComClassAttribute Class Indicates to the compiler that the class should be exposed as a COM object. Specific to Visual
Basic.

HideModuleNameAttribute Class Allows module members to be accessed using only the qualification needed for the module.

VBFixedStringAttribute Class Specifies the size of a fixed-length string in a structure for use with file input and output func
tions. Specific to Visual Basic.

VBFixedArrayAttribute Class Specifies the size of a fixed array in a structure for use with file input and output functions. S
pecific to Visual Basic.

WebMethodAttribute Makes a method callable using the SOAP protocol. Used in XML Web services.

SerializableAttribute Indicates that a class can be serialized.

MarshalAsAttribute Determines how a parameter should be marshaled between the managed code ofVisual Basi
c and unmanaged code such as a Windows API. Used by the common language runtime.

AttributeUsageAttribute Specifies how an attribute can be used.

DllImportAttribute Indicates that the attributed method is implemented as an export from an unmanaged DLL.

Attributes Specific to Visual Basic


Three attributes are specific to Visual Basic: COMClassAttribute, VBFixedStringAttribute, and VBFixedArray.
COMClassAttribute
Use COMClassAttribute to simplify the process of creating COM components from Visual Basic. COM objects are
considerably different from .NET Framework assemblies, and without COMClassAttribute, you need to follow a number of
steps to generate a COM object from Visual Basic. For classes marked with COMClassAttribute, the compiler performs many
of these steps automatically.
HideModuleNameAttribute
Use HideModuleNameAttribute to allows module members to be accessed using only the qualification needed for the
module.
VBFixedStringAttribute
Use VBFixedStringAttribute to force Visual Basic to create a fixed-length string. Strings are of variable length by default, and
this attribute is useful when storing strings to files. The following code demonstrates this:
VB
Structure Worker
' The runtime uses VBFixedString to determine
' if the field should be written out as a fixed size.
<VBFixedString(10)> Public LastName As String
<VBFixedString(7)> Public Title As String
<VBFixedString(2)> Public Rank As String
End Structure

VBFixedArrayAttribute
Use VBFixedArrayAttribute to declare arrays that are fixed in size. Like Visual Basic strings, arrays are of variable length by
default. This attribute is useful when serializing or writing data to files.
See Also
Reference
ComClassAttribute Class
VBFixedArrayAttribute Class
VBFixedStringAttribute Class
System.Runtime.InteropServices
Concepts
Global Attributes in Visual Basic
Applying Attributes
Retrieving Information Stored in Attributes
Writing Custom Attributes
Other Resources
Extending Metadata Using Attributes
Visual Basic Language Concepts

Common Uses for Attributes


In using the common language runtime and class libraries, you probably will need to use attributes at some point. The
following list includes a few of the common uses of attributes in code:
Marking methods using the WebMethod attribute in XML Web services to indicate that the method should be callable
over the SOAP protocol. For more information, see WebMethodAttribute.
Describing how to marshal method parameters when interoperating with native code. For more information, see
MarshalAsAttribute.
Describing the COM properties for classes, methods, and interfaces.
Marking components as COM so the Visual Basic compiler will generate the additional code required to create a COM
component. For more information, see ComClassAttribute.
Calling unmanaged code using the DllImportAttribute class.
Describing your assembly in terms of title, version, description, or trademark.
Describing which members of a class to serialize for persistence.
Describing how to map between class members and XML nodes for XML serialization.
Describing the security requirements for methods.
Specifying characteristics used to enforce security.
Controlling optimizations by the just-in-time (JIT) compiler so the code remains easy to debug.
You can use attributes in many additional ways, and you can also create custom attributes.
See Also
Tasks
How to: Define Your Own Attributes
Concepts
Attributes and Design-Time Support
Attributes Overview in Visual Basic
Application of Attributes
Global Attributes in Visual Basic
Attributes Used in Visual Basic
Other Resources
Custom Attributes in Visual Basic
Visual Basic Language Concepts

Application of Attributes
You apply attributes by adding attribute blocks to program elements such as properties, methods, events, classes, and
assemblies. An attribute block consists of angle brackets ("< >") enclosing a list of comma-separated attribute declarations. An
attribute declaration consists of an optional attribute modifier such as Module or Assembly, an attribute name, a (possibly
overloaded) list of required positional parameters, and a list of optional named arguments. You must place attributes with
modifiers in an attributes section at the top of a source file. For example, the following code sets an assembly attribute that
defines a title for the assembly, and a module attribute that indicates that the module is compliant with the common language
specification (CLS):
VB
Imports System.Reflection
<Assembly: AssemblyTitleAttribute("Production assembly 4"), _
Module: CLSCompliant(True)>

Assembly attributes also can be applied by means of the AssemblyInfo.vb file, which is added to projects automatically by the
Visual Studio user interface. This file contains assembly-level attributes with either default or empty values.
When applied to program elements such as properties, attributes precede the element. For example, the following code applies
an attribute to a class definition:
VB
<CustomAttr(Update:=True)> Class Class1

By convention, all attribute names end with the word "Attribute" to distinguish them from other items in the .NET Framework.
However, you do not need to specify the attribute suffix when using attributes. For example, if you had an attribute named
CustomAttrAttribute, then specifying <CustomAttr(Update:=True)> is equivalent to specifying
<CustomAttrAttribute(Update:=True)>.

Attribute Arguments
Attributes use optional, required, positional, and named arguments in much the same way that objects use these types of
arguments. Positional arguments are arguments that are specified in the order they are declared for the constructor of an
attribute. For example, the following code calls the Sub New constructor of an attribute with two values:
VB
<CustomAttr(True, False)> Class Class1

Arguments passed to Sub New in attribute classes are often used to initialize the values of fields and properties.
You can use named arguments to directly set the value of properties and fields. You specify a named argument by appending
":=" to the name of the argument, followed by the value being specified. Unlike positional arguments, named arguments can
be specified in any order. For example, the following code sets the value True for the Update field, and False for the Keep field:
VB
<CustomAttr(Update:=True, Keep:=False)> Class Class1

Note
Attribute arguments have one important difference from arguments used with standard method calls. You must use position
al arguments for arguments that are used with the Sub New constructor of attribute classes. Named arguments can only be
used to set the values of fields and properties of attribute classes.

Required arguments are those that must always be specified. Optional arguments are those that can be skipped using a
comma as a placeholder (when using positional arguments), or simply omitted (when using named arguments).
Attribute arguments must be constant expressions.
Attribute Examples
The following procedures provide examples of attribute declarations.
To use the MarshalAs attribute to control how parameters are marshaled
1. Add an Imports statement for the System.Runtime.InteropServices namespace to the top of your source code:
VB
Imports System.Runtime.InteropServices

2. Prefix parameters with the MarshalAsAttribute attribute and specify the data type the target requires. For example, the
following code marshals two parameters as the data type long pointer to a string (LPStr) for a Windows API function:
VB
Declare Auto Sub CopyFile Lib "Kernel32.Lib" ( _
<MarshalAs(UnmanagedType.LPStr)> ByVal existingfile As String, _
<MarshalAs(UnmanagedType.LPStr)> ByVal newfile As String, _
ByVal failifexists As Boolean _
)

The common language runtime uses the MarshalAsAttribute attribute to determine how a parameter should be marshaled
between the managed code of Visual Basic and the unmanaged code in a Windows API call.
To expose a method to remote Web clients
1. From the File menu, click Project, select the ASP.NET Web Service template, and add an Imports statement for the
System.Web namespace:
VB
Imports System.Web.Services

2. Define a method and use the WebMethodAttribute attribute to make it callable from remote Web clients:
VB
<WebMethod()> Public Function HelloWorld() As String
HelloWorld = "Hello World..."
End Function

Making an XML Web service method Public is not sufficient to expose it to Web clients. You must explicitly apply the
WebMethodAttribute attribute to a method before it can be called by a remote Web client.
See Also
Tasks
How to: Define Your Own Attributes
Reference
Imports Statement
WebMethodAttribute
MarshalAsAttribute
System.Web
Concepts
Attributes Overview in Visual Basic
Common Uses for Attributes
Argument Passing by Position and by Name
Other Resources
Custom Attributes in Visual Basic
Visual Basic Language Concepts

Global Attributes in Visual Basic


Most attributes are attached to specific language elements such as classes or methods. However, some attributes are global—
they can apply to an entire assembly or module.
You can set many of the attributes within the Visual Studio Integrated Development Environment (IDE) through the
Assembly Information Dialog Box. For more information, see Managing Application Properties and
Managing Assembly and Manifest Signing.
Assembly Attributes
You specify assembly-level attributes using the following syntax:

<Assembly: Attribute1, Assembly: Attribute2..., Assembly: AttributeN>

You specify module-level attributes using similar syntax:

<Module: Attribute1, Module: Attribute2..., Module: AttributeN>

You place global attributes in source code after any top-level directives, such as Option Explicit and Imports statements, but
before any type or namespace declarations. Global attributes can appear in multiple source files in a project, but they are
generally placed in the file AssemblyInfo.vb file created automatically with Visual Basic projects.
Assembly attributes are values that provide information about an assembly. They fall into the following categories:
Assembly identity attributes
Informational attributes
Assembly manifest attributes
Strong name attributes
Assembly Identity Attributes
Three attributes (with a strong name, if applicable) determine the identity of an assembly: name, version, and culture. These
attributes form the full name of the assembly and are required when referencing it in code. You can set an assembly's version
and culture using attributes. The name value, however, is set by the compiler, the Visual Studio IDE in the
Assembly Information Dialog Box, or the Assembly Linker (Al.exe) when the assembly is created, based on the file containing
the assembly manifest. The AssemblyFlagsAttribute attribute specifies whether multiple copies of the assembly can coexist.
The following table shows the identity attributes.
Attribute Purpose
AssemblyName Fully describes an assembly's identity

AssemblyVersionAttribute Specifies the version of an assembly

AssemblyCultureAttribute Specifies which culture the assembly supports

AssemblyFlagsAttribute Specifies whether an assembly supports side-by-side execution on the same computer, in the same
process, or in the same application domain

The following code applies the version and culture attributes to an assembly:
VB
'Set version number for assembly.
<Assembly: Reflection.AssemblyVersionAttribute("4.3.2.1")>
'Set culture as German.
<Assembly: Reflection.AssemblyCultureAttribute("de")>
Informational Attributes
You can use informational attributes to provide additional company or product information for an assembly. The following
table shows the informational attributes defined in the System.Reflection namespace.
Attribute Purpose
AssemblyProductAttribute Defines a custom attribute that specifies a product name for an assembly manifest

AssemblyTrademarkAttribute Defines a custom attribute that specifies a trademark for an assembly manifest

AssemblyInformationalVersionAttribute Defines a custom attribute that specifies an informational version for an assembly ma
nifest

AssemblyCompanyAttribute Defines a custom attribute that specifies a company name for an assembly manifest

AssemblyCopyrightAttribute Defines a custom attribute that specifies a copyright for an assembly manifest

AssemblyFileVersionAttribute Instructs the compiler to use a specific version number for the Win32 file version reso
urce

CLSCompliantAttribute Indicates whether the assembly is compliant with the Common Language Specificatio
n (CLS).
Assembly Manifest Attributes
You can use assembly manifest attributes to provide information in the assembly manifest, including title, description, default
alias, and configuration. The following table shows the assembly manifest attributes defined in the System.Reflection
namespace.
Attribute Purpose
AssemblyTitleAttribute Defines a custom attribute that specifies an assembly title for an assembly manifest

AssemblyDescriptionAttribute Defines a custom attribute that specifies an assembly description for an assembly manifest

AssemblyConfigurationAttribute Defines a custom attribute that specifies an assembly configuration (such as retail or debug) f
or an assembly manifest

AssemblyDefaultAliasAttribute Defines a friendly default alias for an assembly manifest


Strong Name Attributes
Strong names are unique identifiers that protect the identity and integrity of an assembly. You can sign an assembly from
within the Visual Studio IDE through the Signing Page, Project Designer. For more information, see
Managing Assembly and Manifest Signing.
Alternatively, you can use strong-name attributes to set a strong name for an assembly. The following table shows the strong-
name attributes defined in the System.Reflection namespace.
Attribute Purpose
AssemblyDelaySignAttribute Boolean that indicates whether you want to reserve space in the executable file for the strong na
me signature, but defer the actual signing until some later stage. For more information, see
Delay Signing an Assembly.

AssemblyKeyFileAttribute Indicates the file that contains a key. The location of the KeyFile should be relative to the project o
utput directory, which is %Project Directory%\obj\<configuration>. For example, if your KeyFile i
s located in the project directory, you would specify the AssemblyKeyFile attribute as
[assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
AssemblyKeyNameAttribute Refers to a key that has been installed in the Crypto Service Provider (CSP) on your computer. Yo
u must specify a key in order for your file to be signed.

If the KeyFile and the KeyName values are both specified, the following processing occurs:
If the KeyName can be found in the CSP, that key is used.
If the KeyName does not exist and the KeyFile does exist, the key in the KeyFile is installed into the CSP and used.
For more information, see Assembly Security Considerations.

Signing Assemblies
You can sign an assembly in two different but complementary ways: with a strong name or with signing. You can sign using
the Visual Studio IDE Signing Page, Project Designer or by using the File Signing Tool (Signcode.exe). Signing an assembly with
a strong name adds a public key encryption to the file containing the assembly manifest. Strong-name signing helps to verify
name uniqueness, prevent name spoofing, and provide callers with some identity when a reference is resolved. For more
information, see Managing Assembly and Manifest Signing and How to: Sign an Assembly with a Strong Name.
To sign an assembly with a strong name
1. Use the Strong Name Tool (Sn.exe) to generate a key file containing a key pair.
2. Add strong name attributes to the AssemblyInfo.vb file created automatically with Visual Basic projects. You can edit this
file by double-clicking its name in the Solution Explorer.
The following example uses delay signing to create a strong-named assembly with a public key file called myKey.snk.
VB
<Assembly: Reflection.AssemblyKeyFile("myKey.snk")>
<Assembly: Reflection.AssemblyDelaySign(True)>

Note
Assembly-level attributes are ignored if you are not creating an assembly, such as when compiling from the command
line using the /target:module option.

See Also
Tasks
How to: Define Your Own Attributes
How to: Sign an Assembly with a Strong Name
Reference
Strong Name Tool (Sn.exe)
File Signing Tool (Signcode.exe)
Signing Page, Project Designer
Assembly Information Dialog Box
Concepts
Application of Attributes
Assembly Security Considerations
Other Resources
Custom Attributes in Visual Basic
Managing Application Properties
Managing Assembly and Manifest Signing
Visual Basic Language Concepts

Custom Attributes in Visual Basic


Custom attributes are user-defined attributes that provide additional information about program elements. For example, you
might define a custom security attribute that specifies the permissions required by the caller to execute a procedure.
You define custom attributes in attribute classes based on the System.Attribute class. Attribute classes themselves use an
attribute called AttributeUsageAttribute to provide information about how the attribute can be used. Specifying Inherited =
True indicates that an attribute can propagate to derived classes. Setting the AllowMultiple property to True allows you to
apply more than one instance of the attribute to a program element. The AttributeTargets enumeration lets you define which
kinds of program elements your attribute can apply to.
In the following code, the AttributeUsageAttribute attribute specifies an attribute that can be applied to any type of item,
inherited, and applied only once:
VB
<AttributeUsage(AttributeTargets.All, Inherited:=True, AllowMultiple:=False)> _
Class TestAttribute1
Inherits Attribute
End Class

You can use the Or operator to combine multiple items from the AttributeTargets enumeration, as in the following code:
VB
<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method)> _
Class TestAttribute2
Inherits Attribute
End Class

In This Section
How to: Define Your Own Attributes
Explains how to create your own attributes using attribute classes.
How to: Retrieve Custom Attributes
Demonstrates how to retrieve custom attributes using GetCustomAttribute or GetCustomAttributes.
Examples of Custom Attribute Usage
Provides example code that defines a custom attribute that can be applied only to classes, and shows how to use the new
attribute.
Related Sections
Visual Basic and the .NET Framework
Describes the role of Visual Basic in the .NET Framework.
Object-Oriented Programming in Visual Basic
Provides information about object-oriented programming and how it is used.
Metadata and Self-Describing Components
Provides detailed information about the kinds of metadata used in Visual Studio, including attributes.
Visual Basic Language Concepts

How to: Define Your Own Attributes


Using attribute classes, you can create your own custom attributes and use them in addition to the .NET Framework attributes
to provide additional information about program elements.
To define a custom attribute
1. Declare a class and apply the AttributeUsageAttribute attribute to it. The name of your class is the name of the new
attribute, as shown in the following code:
VB
<AttributeUsage(AttributeTargets.All)> Class TestAttribute

2. Declare that the class inherits from System.Attribute:


VB
Inherits System.Attribute

3. Define Private fields to store property values:


VB
Private m_SomeValue As String

4. If appropriate, create a constructor for the attribute:


VB
Public Sub New(ByVal Value As String)
m_SomeValue = Value
End Sub

5. Define methods, fields, and properties for the attribute:


VB
Public Sub Attr(ByVal AttrValue As String)
'Add method code here.
End Sub
Public Property SomeValue() As String ' A named parameter.
Get
Return m_SomeValue
End Get
Set(ByVal Value As String)
m_SomeValue = Value
End Set
End Property

6. End the class with the End Class construct:


VB
End Class
See Also
Reference
AttributeUsageAttribute
Concepts
Application of Attributes
Object Lifetime: How Objects Are Created and Destroyed
Visual Basic Language Concepts

How to: Retrieve Custom Attributes


You can retrieve custom attributes using the GetCustomAttribute or GetCustomAttributes methods of the Attribute class.
To retrieve a single instance of a custom attribute from a class
1. Add an Imports statement to the top of your source code to import the Attribute class from the System namespace:
VB
Imports System.Attribute

2. Create a procedure to retrieve the attribute:


VB
Sub RetrieveAttribute()

End Sub

3. Inside the procedure, declare a variable of type Attribute, and another variable of the same type as the attribute you
wish to retrieve:
VB
Dim Attr As Attribute
Dim CustAttr As CustomAttribute

4. Use the GetType operator to pass the type of the class and attribute to a call to the GetCustomAttribute method, and
then assign the returned value to the variable declared as Attribute:
VB
Attr = GetCustomAttribute(Me.GetType, _
GetType(CustomAttribute), False)

5. Use the CType function to convert the attribute's data type from generic attribute to the specific attribute of the type you
retrieved. Then assign the result to the variable declared as the custom attribute type:
VB
CustAttr = CType(Attr, CustomAttribute)

6. Check to see if the attribute was retrieved, and if it was, use the fields, properties, and methods of the attribute:
VB
If CustAttr Is Nothing Then
MsgBox("The attribute was not found.")
Else
'Get the label and value from the custom attribute.
MsgBox("The attribute label is: " & CustAttr.Label)
MsgBox("The attribute value is: " & CustAttr.Value)
End If
In the above example, the RetrieveAttribute procedure calls the GetCustomAttribute method of the
System.Attribute class to get the custom attribute applied to the class ThisClass. GetCustomAttribute is a shared
method, so you do not need to create an instance of System.Attribute first. The CType function converts the returned
attribute from type System.Attribute to the custom attribute type CustomAttribute.

See Also
Tasks
How to: Define Your Own Attributes
Reference
GetType Operator
CType Function
IsNothing Function
GetAttr Function
GetCustomAttribute
GetCustomAttributes
AttributeUsageAttribute
Concepts
Application of Attributes
Retrieving Information Stored in Attributes
Visual Basic Language Concepts

Examples of Custom Attribute Usage


The following example defines a custom attribute that can be applied only to classes:
Example
VB
<AttributeUsage(AttributeTargets.Class)> Public Class CustomAttribute
Inherits System.Attribute

'Declare two private fields to store the property values.


Private m_LlabelValue As String
Private m_VValueValue As Integer

'The Sub New constructor is the only way to set the properties.
Public Sub New(ByVal _Label As String, ByVal _Value As Integer)
m_LlabelValue = _Label
m_VValueValue = _Value
End Sub

Public ReadOnly Property Label() As String


Get
Return m_LlabelValue
End Get
End Property

Public ReadOnly Property Value() As Integer


Get
Return m_VValueValue
End Get
End Property
End Class

Only the constructor for the attribute class can set the properties defined in this attribute. The following code shows how you
could use the attribute:
VB
' Apply the custom attribute to this class.
<Custom("Some metadata", 66)> Class ThisClass
' Add class members here.
End Class

See Also
Tasks
How to: Define Your Own Attributes
How to: Retrieve Custom Attributes
Reference
AttributeUsageAttribute
Concepts
Application of Attributes
Retrieving Information Stored in Attributes
Visual Basic Language Concepts

How to: Apply Multiple Attributes


This example shows how to apply multiple attributes to the same element.
You can specify several attributes in the same attribute block by separating each attribute with a comma.
Example
This example shows how to apply the EditorBrowsableAttribute attribute and the ObsoleteAttribute attribute to the same
function.
VB
<System.ComponentModel.EditorBrowsable( _
System.ComponentModel.EditorBrowsableState.Never), _
Obsolete("This method should not be used.")> _
Public Shadows Function Update(ByVal x As Integer) As Integer
' The function code goes here.
End Function

See Also
Concepts
Attributes Overview in Visual Basic
Application of Attributes
Other Resources
Attributes in Visual Basic
Visual Basic Language Concepts

Declared Elements in Visual Basic


A declared element is a programming element that is defined in a declaration statement. Declared elements include variables,
constants, enumerations, classes, structures, modules, interfaces, procedures, procedure parameters, function returns, external
procedure references, operators, properties, events, and delegates.
Declaration statements include the following:
Dim Statement (Visual Basic)
Const Statement (Visual Basic)
Enum Statement (Visual Basic)
Class Statement (Visual Basic)
Structure Statement
Module Statement
Interface Statement (Visual Basic)
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
Declare Statement
Operator Statement
Property Statement
Event Statement
Delegate Statement
In This Section
Declared Element Names
Describes how to name elements and use alphabetic case.
Declared Element Characteristics
Covers characteristics, such as scope, possessed by declared elements.
References to Declared Elements
Describes how the compiler matches a reference to a declaration and how to qualify a name.
Related Sections
Object-Oriented Programming in Visual Basic
Covers object-oriented programming basics.
Program Structure and Code Conventions
Presents guidelines for making your code easier to read, understand, and maintain.
Declaration Statements in Visual Basic
Describes statements that name and define procedures, variables, arrays, and constants.
Declaration Contexts and Default Access Levels
Lists the types of declared elements and shows for each one its declaration statement, in what context you can declare it, and
its default access level.
Visual Basic Language Concepts

Declared Element Names


Every declared element has a name, also called an identifier, which is what the code uses to refer to it.
Rules
An element name in Visual Basic must observe the following rules:
It must begin with an alphabetic character or an underscore (_).
It must only contain alphabetic characters, decimal digits, and underscores.
It must contain at least one alphabetic character or decimal digit if it begins with an underscore.
It must not be more than 1023 characters long.
The length limit of 1023 characters also applies to the entire string of a fully qualified name, such as
outerNamespace.middleNamespace.innerNamespace.thisClass.thisElement.

The following example shows some valid element names.


aB123__45
_567

The following example shows some invalid element names. The first contains only an underscore, the second begins with a
decimal digit, and the third contains an invalid character ($).
' Three INVALID element names
_
12ABC
xyz$wv

Caution
Element names starting with an underscore (_) are not part of the Common Language Specification (CLS), so CLS-compliant
code cannot use a component that defines such names. However, an underscore in any other position in an element name is
CLS-compliant.

Name Length Guidelines


As a practical matter, your name should be as short as possible while still clearly identifying the nature of the element. This
improves the readability of your code and reduces line length and source-file size.
On the other hand, your name should not be so short that it does not adequately describe what the element represents and
how your code uses it. This is important for the readability of your code. If somebody else is trying to understand it, or if you
yourself are looking at it a long time after you wrote it, suitable element names can save a considerable amount of time.
Escaped Names
Generally, an element name must not match any of the keywords reserved by Visual Basic, such as Case or Friend. However,
you can define an escaped name, which is enclosed by brackets ([ ]). An escaped name can match any Visual Basic keyword,
since the brackets remove any ambiguity. You also use the brackets when you refer to the name later in your code.
In general, you should use escaped names only when:
Your code has migrated from a previous version of Visual Basic that did not reserve the keyword being used as a name;
or
You are working with code written in another language in which the given keyword is not reserved.
Otherwise, you should consider renaming the element if its name conflicts with a keyword. The integrated development
environment (IDE) provides an easy way to do this. For more information, see How to: Rename an Identifier.
Case Sensitivity in Names
Element names in Visual Basic are case-insensitive. This means that when the compiler compares two names that differ in
alphabetic case only, it interprets them as the same name. For example, it considers ABC and abc to refer to the same declared
element.
However, the common language runtime (CLR) uses case-sensitive binding. Therefore, when you produce an assembly or a
DLL and make it available to other assemblies, your names are no longer case-insensitive. For example, if you define a class
with an element called ABC, and other assemblies make use of your class through the common language runtime, they must
refer to the element as ABC. If you subsequently recompile your class and change the element's name to abc, the other
assemblies using your class could no longer access that element. Therefore, when you release an updated version of an
assembly, you should not change the alphabetic case of any public elements.
Names and Locales
Comparison of names is independent of locale. If two names match in one locale, they are guaranteed to match in all locales.
See Also
Concepts
Declared Element Characteristics
Declaration Statements in Visual Basic
Other Resources
Declared Elements in Visual Basic
References to Declared Elements
Visual Basic Language Concepts

Declared Element Characteristics


A characteristic of a declared element is an aspect of that element that affects how code can interact with it. Every declared
element has one or more of the following characteristics associated with it:
Data type — the values the element can hold, and how it stores those values. For more information, see
Data Type Summary (Visual Basic).
Lifetime — the period of execution time during which the element is available for use. For more information, see
How to: Lengthen a Variable's Lifetime.
Scope — the set of all code that can refer to the element without qualifying its name. For more information, see
How to: Control the Scope of a Variable.
Access level — the permission for code to make use of the element. For more information, see
How to: Control the Availability of a Variable.
Characteristics of the Elements
The following table shows the declared elements and the characteristics that apply to each one.
Element Data Type Lifetime Scope 1 Access Level
Variable Yes Yes Yes Yes

Constant Yes No Yes Yes

Enumeration Yes No Yes Yes

Structure No No Yes Yes

Property Yes Yes Yes Yes

Method No Yes Yes Yes

Procedure (Sub or Function) No Yes Yes Yes

Procedure parameter Yes Yes Yes No

Function return Yes Yes Yes No

Operator Yes No Yes Yes

Interface No No Yes Yes

Class No No Yes Yes

Event No No Yes Yes

Delegate No No Yes Yes

1 Scope is sometimes referred to as visibility.

See Also
Concepts
Declared Element Names
Lifetime in Visual Basic
Scope in Visual Basic
Access Levels in Visual Basic
Data Types in Visual Basic
Variable Declaration in Visual Basic
Other Resources
Declared Elements in Visual Basic
References to Declared Elements
Visual Basic Language Concepts

Lifetime in Visual Basic


The lifetime of a declared element is the period of time during which it is available for use. Variables are the only elements that
have lifetime. For this purpose, the compiler treats procedure parameters and function returns as special cases of variables. The
lifetime of a variable represents the period of time during which it can hold a value. Its value can change over its lifetime, but it
always holds some value.
Different Lifetimes
A member variable (declared at module level, outside any procedure) typically has the same lifetime as the element in which it
is declared. A nonshared variable declared in a class or structure exists as a separate copy for each instance of the class or
structure in which it is declared. Each such variable has the same lifetime as its instance. However, a Shared variable has only a
single lifetime, which lasts for the entire time your application is running.
A local variable (declared inside a procedure) exists only while the procedure in which it is declared is running. This applies
also to that procedure's parameters and to any function return. However, if that procedure calls other procedures, the local
variables retain their values while the called procedures are running.
Beginning of Lifetime
A local variable's lifetime begins when control enters the procedure in which it is declared. Every local variable is initialized to
the default value for its data type as soon as the procedure begins running. When the procedure encounters a
Dim Statement (Visual Basic) that specifies initial values, it sets those variables to those values, even if your code had already
assigned other values to them.
Each member of a structure variable is initialized as if it were a separate variable. Similarly, each element of an array variable is
initialized individually.
Variables declared within a block inside a procedure (such as a For loop) are initialized on entry to the procedure. These
initializations take effect whether or not your code ever executes the block.
End of Lifetime
When a procedure terminates, the values of its local variables are not preserved, and Visual Basic reclaims their memory. The
next time you call the procedure, all its local variables are created afresh and reinitialized.
When an instance of a class or structure terminates, its nonshared variables lose their memory and their values. Each new
instance of the class or structure creates and reinitializes its nonshared variables. However, Shared variables are preserved
until your application stops running.
Extension of Lifetime
If you declare a local variable with the Static (Visual Basic) keyword, its lifetime is longer than the execution time of its
procedure. The following table shows how the procedure declaration determines how long a Static variable exists.
Procedure location and sharing Static variable lifetime begins Static variable lifetime en
ds
In a module (shared by default) The first time the procedure is called When your application stops
running

In a class or structure, Shared (procedure i The first time the procedure is called either on a spec When your application stops
s not an instance member) ific instance or on the class or structure name itself running

In an instance of a class or structure, not S The first time the procedure is called on the specific i When the instance is release
hared (procedure is an instance member) nstance d for garbage collection (GC)

See Also
Tasks
How to: Lengthen a Variable's Lifetime
Troubleshooting Data Types
Reference
Shared (Visual Basic)
Nothing (Visual Basic)
Concepts
Declared Element Names
Scope in Visual Basic
Access Levels in Visual Basic
Variables in Visual Basic
Variable Declaration in Visual Basic
Other Resources
References to Declared Elements
Visual Basic Language Concepts

How to: Lengthen a Variable's Lifetime


Normally, a variable ceases to exist when the programming element in which it is declared ceases to exist. However, you can
make its lifetime longer than that of its containing element by declaring it with the Static (Visual Basic) keyword.
For more information, see Lifetime in Visual Basic.
To make a variable live longer than its containing element
If the variable is a local variable (declared inside a procedure), include the Static keyword in the
Dim Statement (Visual Basic) that declares it. A static variable exists as long as the class or module containing the
procedure that declares the variable.
If a local variable is inside a Shared (Visual Basic) procedure, the procedure and its variables exist as long as your
application runs. Do not use Static in this case.
If the variable is a member variable (declared in a class or structure, outside any procedure), include the Shared keyword
in the Dim statement that declares it. A shared variable is not associated with any one instance of its class or structure,
and it exists as long as your application runs. You cannot use Static on a member variable.
If a member variable is declared in a module, it always exists as long as your application runs. Do not use Shared in this
case.
Example
The following example declares a variable with the Static (Visual Basic) keyword. (Note that you do not need the Dim keyword
when the Dim Statement (Visual Basic) uses a modifier such as Static.)

Function runningTotal(ByVal num As Integer) As Integer


Static applesSold As Integer
applesSold = applesSold + num
Return applesSold
End Function

In the preceding example, the variable applesSold continues to exist after the procedure runningTotal returns to the calling
code. The next time runningTotal is called, applesSold retains its previously calculated value.
If applesSold had been declared without using Static, the previous accumulated values would not be preserved across calls to
runningTotal. The next time runningTotal was called, applesSold would have been recreated and initialized to 0, and
runningTotal would have simply returned the same value with which it was called.

Compiling the Code


You can initialize the value of a static local variable as part of its declaration. If you declare an array to be Static, you can
initialize its rank (number of dimensions), the length of each dimension, and the values of the individual elements.
Static Variables of the Same Name
You can declare static variables with the same name in more than one procedure. If you do this, the Visual Basic compiler
considers each such variable to be a separate element. The initialization of one of these variables does not affect the values of
the others. The same applies if you define a procedure with a set of overloads and declare a static variable with the same name
in each overload.
Containing Elements for Static Variables
You can declare a static local variable within a class, that is, inside a procedure in that class. However, you cannot declare a
static local variable within a structure, either as a structure member or as a local variable of a procedure within that structure.
Security
In the preceding example, you can produce the same lifetime by declaring applesSold at module level. If you changed the
scope of a variable this way, however, the procedure would no longer have exclusive access to it. Because other procedures
could access applesSold and change its value, the running total could be unreliable and the code could be more difficult to
maintain.
See Also
Concepts
Lifetime in Visual Basic
Declared Element Characteristics
Scope in Visual Basic
Access Levels in Visual Basic
Variables in Visual Basic
Variable Declaration in Visual Basic
Procedure Overloading
Visual Basic Language Concepts

Scope in Visual Basic


The scope of a declared element is the set of all code that can refer to it without qualifying its name or making it available
through an Imports Statement. An element can have scope at one of the following levels:
Level Description
Block scope Available only within the code block in which it is declared

Procedure scope Available to all code within the procedure in which it is declared

Module scope Available to all code within the module, class, or structure in which it is declared

Namespace scope Available to all code in the namespace in which it is declared

These levels of scope progress from the narrowest (block) to the widest (namespace), where narrowest scope means the
smallest set of code that can refer to the element without qualification. For more information, see "Levels of Scope" on this
page.
Specifying Scope and Defining Variables
You specify the scope of an element when you declare it. The scope can depend on the following factors:
The region (block, procedure, module, class, or structure) in which you declare the element
The namespace containing the element's declaration
The access level you declare for the element
Use care when you define variables with the same name but different scope, because doing so can lead to unexpected results.
For more information, see Resolving a Reference When Multiple Variables Have the Same Name.
Levels of Scope
A programming element is available throughout the region in which you declare it. All code in the same region can refer to the
element without qualifying its name.
Block Scope
A block is a set of statements enclosed within initiating and terminating declaration statements, such as the following:
Do and Loop
For [Each] and Next
If and End If
Select and End Select
SyncLock and End SyncLock
Try and End Try
While and End While
With and End With
If you declare a variable within a block, you can use it only within that block. In the following example, the scope of the integer
variable cube is the block between If and End If, and you can no longer refer to cube when execution passes out of the block.

If n < 1291 Then


Dim cube As Integer
cube = n ^ 3
End If
Note
Even if the scope of a variable is limited to a block, its lifetime is still that of the entire procedure. If you enter the block more t
han once during the procedure, each block variable retains its previous value. To avoid unexpected results in such a case, it is
wise to initialize block variables at the beginning of the block.

Procedure Scope
An element declared within a procedure is not available outside that procedure. Only the procedure that contains the
declaration can use it. Variables at this level are also known as local variables. You declare them with the
Dim Statement (Visual Basic), with or without the Static (Visual Basic) keyword.
Procedure and block scope are closely related. If you declare a variable inside a procedure but outside any block within that
procedure, you can think of the variable as having block scope, where the block is the entire procedure.
Note
All local elements, even if they are Static variables, are private to the procedure in which they appear. You cannot declare an
y element using the Public (Visual Basic) keyword within a procedure.

Module Scope
For convenience, the single term module level applies equally to modules, classes, and structures. You can declare elements at
this level by placing the declaration statement outside of any procedure or block but within the module, class, or structure.
When you make a declaration at the module level, the access level you choose determines the scope. The namespace that
contains the module, class, or structure also affects the scope.
Elements for which you declare Private (Visual Basic) access level are available to every procedure in that module, but not to
any code in a different module. The Dim statement at module level defaults to Private if you do not use any access level
keywords. However, you can make the scope and access level more obvious by using the Private keyword in the Dim
statement.
In the following example, all procedures defined in the module can refer to the string variable strMsg. When the second
procedure is called, it displays the contents of the string variable strMsg in a dialog box.

' Put the following declaration at module level (not in any procedure).
Private strMsg As String
' Put the following Sub procedure in the same module.
Sub initializePrivateVariable()
strMsg = "This variable cannot be used outside this module."
End Sub
' Put the following Sub procedure in the same module.
Sub usePrivateVariable()
MsgBox(strMsg)
End Sub

Namespace Scope
If you declare an element at module level using the Friend (Visual Basic) or Public (Visual Basic) keyword, it becomes available
to all procedures throughout the namespace in which the element is declared. With the following alteration to the preceding
example, the string variable strMsg can be referred to by code anywhere in the namespace of its declaration.

' Include this declaration at module level (not inside any procedure).
Public strMsg As String

Namespace scope includes nested namespaces. An element available from within a namespace is also available from within
any namespace nested inside that namespace.
If your project does not contain any Namespace Statements, everything in the project is in the same namespace. In this case,
namespace scope can be thought of as project scope. Public elements in a module, class, or structure are also available to any
project that references their project.
Choice of Scope
When you declare a variable, you should keep in mind the following points when choosing its scope.
Advantages of Local Variables
Local variables are a good choice for any kind of temporary calculation, for the following reasons:
Name Conflict Avoidance. Local variable names are not susceptible to conflict. For example, you can create several
different procedures containing a variable called intTemp. As long as each intTemp is declared as a local variable, each
procedure recognizes only its own version of intTemp. Any one procedure can alter the value in its local intTemp without
affecting intTemp variables in other procedures.
Memory Consumption. Local variables consume memory only while their procedure is running. Their memory is
released when the procedure returns to the calling code. By contrast, Shared (Visual Basic) and Static (Visual Basic)
variables consume memory resources until your application stops running, so use them only when necessary. Instance
variables consume memory while their instance continues to exist, which makes them less efficient than local variables,
but potentially more efficient than Shared or Static variables.
Minimizing Scope
In general, when declaring any variable or constant, it is good programming practice to make the scope as narrow as possible
(block scope is the narrowest). This helps conserve memory and minimizes the chances of your code erroneously referring to
the wrong variable. Similarly, you should declare a variable to be Static (Visual Basic) only when it is necessary to preserve its
value between procedure calls.
See Also
Tasks
How to: Control the Scope of a Variable
Concepts
Declared Element Characteristics
Lifetime in Visual Basic
Access Levels in Visual Basic
Resolving a Reference When Multiple Variables Have the Same Name
Variable Declaration in Visual Basic
Visual Basic Language Concepts

How to: Control the Scope of a Variable


Normally, a variable is in scope, or visible for reference, throughout the region in which you declare it. In some cases, the
variable's access level can influence its scope.
For more information, see Scope in Visual Basic.
Scope at Block or Procedure Level
To make a variable visible only within a block
Place the Dim Statement (Visual Basic) for the variable between the initiating and terminating declaration statements of
that block, for example between the For and Next statements of a For loop.
You can refer to the variable only from within the block.
To make a variable visible only within a procedure
Place the Dim statement for the variable inside the procedure but outside any block (such as a With...End With block).
You can refer to the variable only from within the procedure, including inside any block contained in the procedure.
Scope at Module or Namespace Level
For convenience, the single term module level applies equally to modules, classes, and structures. The access level of a module
level variable determines its scope. The namespace that contains the module, class, or structure also influences the scope.
To make a variable visible throughout a module, class, or structure
1. Place the Dim statement for the variable inside the module, class, or structure, but outside any procedure.
2. Include the Private (Visual Basic) keyword in the Dim statement.
3. You can refer to the variable from anywhere within the module, class, or structure, but not from outside it.
To make a variable visible throughout a namespace
1. Place the Dim statement for the variable inside the module, class, or structure, but outside any procedure.
2. Include the Friend (Visual Basic) or Public (Visual Basic) keyword in the Dim statement.
3. You can refer to the variable from anywhere within the namespace containing the module, class, or structure.

Example
The following example declares a variable at module level and limits its visibility to code within the module.

Module demonstrateScope
Private strMsg As String
Sub initializePrivateVariable()
strMsg = "This variable cannot be used outside this module."
End Sub
Sub usePrivateVariable()
MsgBox(strMsg)
End Sub
End Module

In the preceding example, all the procedures defined in module demonstrateScope can refer to the String variable strMsg.
When the usePrivateVariable procedure is called, it displays the contents of the string variable strMsg in a dialog box.
With the following alteration to the preceding example, the string variable strMsg can be referred to by code anywhere in the
namespace of its declaration.

Public strMsg As String


Robust Programming
The narrower the scope of a variable, the fewer opportunities you have for accidentally referring to it in place of another
variable with the same name. You can also minimize problems of reference matching.
Security
The narrower the scope of a variable, the smaller the chances that malicious code can make improper use of it.
See Also
Reference
Dim Statement (Visual Basic)
Concepts
Scope in Visual Basic
Lifetime in Visual Basic
Access Levels in Visual Basic
Variables in Visual Basic
Variable Declaration in Visual Basic
Visual Basic Language Concepts

Type Promotion
When you declare a programming element in a module, Visual Basic promotes its scope to the namespace containing the
module. This is known as type promotion.
The following example shows a skeleton definition of a module and two members of that module.

Namespace projNamespace
Module projModule
Public Enum basicEnum As Integer
one = 1
two = 2
End Enum
Public Class innerClass
Public Sub numberSub(ByVal firstArg As Integer)
End Sub
End Class
End Module
End Namespace

Within projModule, programming elements declared at module level are promoted to projNamespace. In the preceding
example, basicEnum and innerClass are promoted, but numberSub is not, because it is not declared at module level.
Effect of Type Promotion
The effect of type promotion is that a qualification string does not need to include the module name. The following example
makes two calls to the procedure in the preceding example.

Sub usePromotion()
projNamespace.projModule.innerClass.numberSub(projNamespace.projModule.basicEnum.one)
projNamespace.innerClass.numberSub(projNamespace.basicEnum.two)
End Sub

In the preceding example, the first call uses complete qualification strings. However, this is not necessary because of type
promotion. The second call also accesses the module's members without including projModule in the qualification strings.
Defeat of Type Promotion
If the namespace already has a member with the same name as a module member, type promotion is defeated for that module
member. The following example shows a skeleton definition of an enumeration and a module within the same namespace.

Namespace thisNamespace
Public Enum abc
first = 1
second
End Enum
Module thisModule
Public Class abc
Public Sub abcSub()
End Sub
End Class
Public Class xyz
Public Sub xyzSub()
End Sub
End Class
End Module
End Namespace

In the preceding example, Visual Basic cannot promote class abc to thisNameSpace because there is already an enumeration
with the same name at namespace level. To access abcSub, you must use the full qualification string
thisNamespace.thisModule.abc.abcSub. However, class xyz is still promoted, and you can access xyzSub with the shorter
qualification string thisNamespace.xyz.xyzSub.
Defeat of Type Promotion for Partial Types
If a class or structure inside a module uses the Partial (Visual Basic) keyword, type promotion is automatically defeated for that
class or structure, whether or not the namespace has a member with the same name. Other elements in the module are still
eligible for type promotion.
Consequences. Defeat of type promotion of a partial definition can cause unexpected results and even compiler errors. The
following example shows skeleton partial definitions of a class, one of which is inside a module.

Namespace sampleNamespace
Public Partial Class sampleClass
Public Sub sub1()
End Sub
End Class
Module sampleModule
Public Partial Class sampleClass
Public Sub sub2()
End Sub
End Class
End Module
End Namespace

In the preceding example, the developer might expect the compiler to merge the two partial definitions of sampleClass.
However, the compiler does not consider promotion for the partial definition inside sampleModule. As a result, it attempts to
compile two separate and distinct classes, both named sampleClass but with different qualification paths.
The compiler merges partial definitions only when their fully qualified paths are identical.
Recommendations
The following recommendations represent good programming practice.
Unique Names. When you have full control over the naming of programming elements, it is always a good idea to use
unique names everywhere. Identical names require extra qualification and can make your code harder to read. They can
also lead to subtle errors and unexpected results.
Full Qualification. When you are working with modules and other elements in the same namespace, the safest
approach is to always use full qualification for all programming elements. If type promotion is defeated for a module
member and you do not fully qualify that member, you could inadvertently access a different programming element.

See Also
Tasks
How to: Control the Scope of a Variable
Reference
Module Statement
Namespace Statement
Partial (Visual Basic)
Concepts
Scope in Visual Basic
Resolving a Reference When Multiple Variables Have the Same Name
Visual Basic Language Concepts

Access Levels in Visual Basic


The access level of a declared element is the extent of the ability to access it, that is, what code has permission to read it or
write to it. This is determined not only by how you declare the element itself, but also by the access level of the element's
container. Code that cannot access a containing element cannot access any of its contained elements, even those declared as
Public. For example, a Public variable in a Private structure is accessible from inside the class containing the structure, but
not from outside that class.
Public
The Public (Visual Basic) keyword in the declaration statement specifies that the elements are accessible from code anywhere
within the same project, from other projects that reference the project, and from any assembly built from the project. The
following code shows a sample Public declaration.

Public Class classForEverybody

You can use Public only at module, interface, or namespace level. This means you can declare a public element at the level of a
source file or namespace, or inside an interface, module, class, or structure, but not within a procedure.
Protected
The Protected (Visual Basic) keyword in the declaration statement specifies that the elements are accessible only from within
the same class, or from a class derived from this class. The following code shows a sample Protected declaration.

Protected Class classForMyHeirs

You can use Protected only at class level, and only when declaring a member of a class. This means you can declare a
protected element in a class, but not at the level of a source file or namespace, or inside an interface, module, structure, or
procedure.
Friend
The Friend (Visual Basic) keyword in the declaration statement specifies that the elements are accessible from within the same
assembly, but not from outside the assembly. The following code shows a sample Friend declaration.

Friend stringForThisProject As String

You can use Friend only at module, interface, or namespace level. This means you can declare a friend element at the level of a
source file or namespace, or inside an interface, module, class, or structure, but not within a procedure.
Protected Friend
The Protected and Friend keywords together in the declaration statement specify that the elements are accessible either from
derived classes or from within the same assembly, or both. The following code shows a sample Protected Friend declaration.

Protected Friend stringForProjectAndHeirs As String

You can use Protected Friend only at class level, and only when declaring a member of a class. This means you can declare a
protected friend element in a class, but not at the level of a source file or namespace, or inside an interface, module, structure,
or procedure.
Private
The Private (Visual Basic) keyword in the declaration statement specifies that the elements are accessible only from within the
same module, class, or structure. The following code shows a sample Private declaration.

Private numberForMeOnly As Integer

You can use Private only at module level. This means you can declare a private element inside a module, class, or structure,
but not at the level of a source file or namespace, inside an interface, or within a procedure.
At the module level, the Dim statement without any access level keywords is equivalent to a Private declaration. However, you
might want to use the Private keyword to make your code easier to read and interpret.
Access Modifiers
The keywords that specify access level are called access modifiers. The following table compares the access modifiers.
Access Access level granted Elements you can de Declaration context withi
modifi clare with this access n which you can use this
er level modifier
Public Unrestricted: Interfaces Source file
Any code that can see a public element can access it Modules Namespace
Classes Interface
Structures Module
Structure members Class
Procedures Structure
Properties
Member variables
Constants
Enumerations
Events
External declarations
Delegates

Protec Derivational: Interfaces Class


ted
Code within the class that declares a protected element, or a clas Classes
s derived from it, can access the element
Structures
Procedures
Properties
Member variables
Constants
Enumerations
Events
External declarations
Delegates
Friend Assembly: Interfaces Source file
Code within the assembly that declares a friend element can acce Modules Namespace
ss it
Classes Interface
Structures Module
Structure members Class
Procedures Structure
Properties
Member variables
Constants
Enumerations
Events
External declarations
Delegates

Protec Union of Protected and Friend: Interfaces Class


ted Fri
end Code within the same class or the same assembly as a protected Classes
friend element, or within any class derived from the element's cl
ass, can access it Structures
Procedures
Properties
Member variables
Constants
Enumerations
Events
External declarations
Delegates

Private Declaration context: Interfaces Module


Code within the type that declares a private element, including c Classes Class
ode within contained types, can access the element
Structures Structure
Structure members
Procedures
Properties
Member variables
Constants
Enumerations
Events
External declarations
Delegates

See Also
Tasks
How to: Control the Availability of a Variable
Reference
Dim Statement (Visual Basic)
Static (Visual Basic)
Concepts
Declared Element Names
Declared Element Characteristics
Lifetime in Visual Basic
Scope in Visual Basic
Variables in Visual Basic
Variable Declaration in Visual Basic
Other Resources
References to Declared Elements
Visual Basic Language Concepts

How to: Control the Availability of a Variable


You control the availability of a variable by specifying its access level. The access level determines what code has permission to
read or write to the variable.
Member variables (defined at module level and outside any procedure) default to public access, which means any code
that can see them can access them. You can change this by specifying an access modifier.
Local variables (defined inside a procedure) nominally have public access, although only code within their procedure can
access them. You cannot change the access level of a local variable, but you can change the access level of the procedure
that contains it.
For more information, see Access Levels in Visual Basic.
Private and Public Access
To make a variable accessible only from within its module, class, or structure
1. Place the Dim Statement (Visual Basic) for the variable inside the module, class, or structure, but outside any procedure.
2. Include the Private (Visual Basic) keyword in the Dim statement.
You can read or write to the variable from anywhere within the module, class, or structure, but not from outside it.
To make a variable accessible from any code that can see it
1. For a member variable, place the Dim statement for the variable inside a module, class, or structure, but outside any
procedure.
2. Include the Public (Visual Basic) keyword in the Dim statement.
You can read or write to the variable from any code that interoperates with your assembly.
-or-
1. For a local variable, place the Dim statement for the variable inside a procedure.
2. Do not include the Public keyword in the Dim statement.
You can read or write to the variable from anywhere within the procedure, but not from outside it.
Protected and Friend Access
You can limit the access level of a variable to its class and any derived classes, or to its assembly. You can also specify the union
of these limitations, which allows access from code in any derived class or in any other place in the same assembly. You specify
this union by combining the Protected and Friend keywords in the same declaration.
To make a variable accessible only from within its class and any derived classes
1. Place the Dim statement for the variable inside a class, but outside any procedure.
2. Include the Protected (Visual Basic) keyword in the Dim statement.
You can read or write to the variable from anywhere within the class, as well as from within any class derived from it, but
not from outside any class in the derivation chain.
To make a variable accessible only from within the same assembly
1. Place the Dim statement for the variable inside a module, class, or structure, but outside any procedure.
2. Include the Friend (Visual Basic) keyword in the Dim statement.
You can read or write to the variable from anywhere within the module, class, or structure, as well as from any code in
the same assembly, but not from outside the assembly.
Example
The following example shows declarations of variables with Public, Protected, Friend, Protected Friend, and Private access
levels. Note that when the Dim statement specifies an access level, you do not need to include the Dim keyword.

Public Class classForEverybody


Protected Class classForMyHeirs
Friend stringForThisProject As String
Protected Friend stringForProjectAndHeirs As String
Private numberForMeOnly As Integer

Security
The more restrictive the access level of a variable, the smaller the chances that malicious code can make improper use of it.
See Also
Reference
Dim Statement (Visual Basic)
Public (Visual Basic)
Protected (Visual Basic)
Friend (Visual Basic)
Private (Visual Basic)
Concepts
Access Levels in Visual Basic
Visual Basic Language Concepts

References to Declared Elements


When your code refers to a declared element, the Visual Basic compiler matches the name in your reference to the appropriate
declaration of that name. If more than one element is declared with the same name, you can control which of those elements is
to be referenced by qualifying its name.
In This Section
Resolving a Reference When Multiple Variables Have the Same Name
Discusses how the compiler matches a reference to a declaration.
How to: Qualify a Declared Element Name
Explains how to qualify an element name to facilitate a reference match.
How to: Distinguish Between Two Elements with the Same Name
Describes how to qualify an element name when calling it to enable the Visual Basic compiler to match your reference to the
desired element.
Shadowing in Visual Basic
Describes the treatment of elements with the same name.
Related Sections
Declared Element Names
Describes how to name elements and use alphabetic case.
Declared Element Characteristics
Covers characteristics, such as scope, possessed by declared elements.
Visual Basic Language Concepts

Resolving a Reference When Multiple Variables Have the Same


Name
When the compiler attempts to match a name reference to a name declaration, it looks for the matching declaration with the
narrowest scope. This means it starts with the code making the reference and works outward through successive levels of
containing elements.
If you want to override this search process and specify a name declared in a broader scope, you must qualify the name with
the containing element of the broader scope. In some cases, you might have to qualify the containing element as well. For
more information on name qualification, see How to: Qualify a Declared Element Name.
You might also have to qualify a name reference if your application has access to more than one programming element with
the same name. For examples, see "Classes with the Same Name" on this Help page and
How to: Distinguish Between Two Elements with the Same Name.
Narrowest Scope
The following example shows references to two variables with the same name.

' Assume these two modules are both in the same assembly.
Module container
Public totalCount As Integer = 1
Public Sub showCount()
Dim totalCount As Integer = 6000
' The following statement displays the local totalCount (6000).
MsgBox("Unqualified totalCount is " & CStr(totalCount))
' The following statement displays the module's totalCount (1).
MsgBox("container.totalCount is " & CStr(container.totalCount))
End Sub
End Module
Module callingModule
Public Sub displayCount()
container.showCount()
' The following statement displays the containing module's totalCount (1).
MsgBox("container.totalCount is " & CStr(container.totalCount))
End Sub
End Module

The preceding example declares two variables, each named totalCount, at different levels of scope in module container.
When the procedure showCount displays totalCount without qualification, the Visual Basic compiler resolves the reference to
the declaration with the narrowest scope, namely the local declaration inside showCount. When it qualifies totalCount with the
containing module container, the compiler resolves the reference to the declaration with the broader scope.
Members of Other Containing Elements
When you use a nonshared member of another class or structure, you must first qualify the member name with a variable or
expression that points to an instance of the class or structure. In the following example, demoClass is an instance of a class
named class1.

Dim demoClass As class1 = New class1()


demoClass.someSub[(argumentlist)]

You cannot use the class name itself to qualify a member that is not Shared (Visual Basic). You must first create an instance in
an object variable (in this case demoClass) and then reference it by the variable name.
If a class or structure has a Shared member, you can qualify that member either with the class or structure name or with a
variable or expression that points to an instance.
A module does not have any separate instances, and all its members are Shared by default. Therefore, you qualify a module
member with the module name.
Qualified Reference Example
The following example shows qualified references to module member procedures.

' Assume these three modules are all in the same assembly.
Module module1
Public Sub perform()
MsgBox("module1.perform() now returning")
End Sub
End Module
Module module2
Public Sub perform()
MsgBox("module2.perform() now returning")
End Sub
Public Sub doSomething()
' The following statement calls perform in module2, the active module.
perform()
' The following statement calls perform in module1.
module1.perform()
End Sub
End Module
Module module3
Public Sub callPerform()
' The following statement calls perform in module1.
module1.perform()
' The following statement makes an unresolvable name reference
' and therefore generates a COMPILER ERROR.
perform() ' INVALID statement
End Sub
End Module

The preceding example declares two Sub procedures, both named perform, in different modules in a project. Each one can be
specified without qualification within its own module but must be qualified if referenced from anywhere else. Because the final
reference in module3 does not qualify perform, the compiler is unable to resolve that reference.
References to Projects
To use Public (Visual Basic) elements defined in another project, you must first set a reference to that project's assembly or
type library. You can set a reference by choosing Add Reference from the Project menu, or with the /reference (Visual Basic)
command-line compiler option.
For example, you can use the XML object model of the .NET Framework. If you set a reference to the System.Xml namespace,
you can declare and use any of its classes, such as XmlDocument. The following example uses XmlDocument.

' Assume this project has a reference to System.Xml


' The following statement creates xDoc as an XML document object.
Dim xDoc As System.Xml.XmlDocument

Importing Containing Elements


You can use the Imports Statement to import the namespaces containing the modules or classes you want to use. This allows
you to refer to the elements defined in an imported namespace without fully qualifying their names. The following example
rewrites the preceding example to import the System.Xml namespace.

' Assume this project has a reference to System.Xml


' The following statement must precede all your declarations.
Imports System.Xml
' The following statement creates xDoc as an XML document object.
Dim xDoc As XmlDocument

In addition, the Imports statement can define an import alias for each imported namespace. This can make your source code
shorter and easier to read. The following example rewrites the preceding example to use xD as an alias for the System.Xml
namespace.

' Assume this project has a reference to System.Xml


' The following statement must precede all your declarations.
Imports xD = System.Xml
' The following statement creates xDoc as an XML document object.
Dim xDoc As xD.XmlDocument

The Imports statement does not make elements from other projects available to your application. That is, it does not take the
place of setting a reference. Importing a namespace simply removes the need to qualify the names defined in that namespace.
You can also use the Imports statement to import modules, classes, structures, and enumerations. You can then use the
members of such imported elements without qualification. However, you must always qualify nonshared members of classes
and structures with a variable or expression that evaluates to an instance of the class or structure.
Classes with the Same Name
When you create a new instance of an object, you might have to qualify the class with the namespace or type library to which it
belongs. For example, the System.Windows.Forms and System.Web.UI.WebControls namespaces both contain a Label class
(System.Windows.Forms.Label and System.Web.UI.WebControls.Label). If your application uses both, or if it defines its own
Label class, you must distinguish the different Label objects. Include the namespace or import alias in the variable declaration.
The following example uses the import alias.

' The following statement must precede all your declarations.


Imports win = System.Windows.Forms, web = System.Web.UI.WebControls
' The following statement references the Windows.Forms.Label class.
Dim winLabel As New win.Label()

Naming Guidelines
When you define two or more programming elements with the same name, a name ambiguity can result when the compiler
attempts to resolve a reference to that name. If more than one definition is in scope, or if no definition is in scope, the reference
is unresolvable. For an example, see "Qualified Reference Example" on this Help page.
You can avoid name ambiguity by giving all your elements unique names. Then you can make reference to any element
without needing to qualify its name with a namespace, module, or class. You also reduce the chances of accidentally referring
to the wrong element.
See Also
Tasks
How to: Modify Project Properties and Configuration Settings
How to: Qualify a Declared Element Name
How to: Distinguish Between Two Elements with the Same Name
Reference
Imports Statement
New (Visual Basic)
Public (Visual Basic)
Concepts
Variables in Visual Basic
Other Resources
References to Declared Elements
Visual Basic Language Concepts

How to: Qualify a Declared Element Name


When your code refers to a declared element, the Visual Basic compiler must match the name in your reference to the
appropriate declaration of that name. If the element is defined outside your code, or if more than one element is declared with
the same name, you might need to qualify the name to allow the compiler to resolve any possible ambiguity or to locate the
element.
Qualifying a name means preceding it in your source statement with information that identifies where the target element is
defined. This information is called a qualification string. It can include one or more namespaces and a module, class, or
structure.
The qualification string should unambiguously specify the module, class, or structure containing the target element. The
container might in turn be located in another containing element, usually a namespace. You might need to include several
containing elements in the qualification string.
To access a declared element by qualifying its name
1. Determine the location in which the element has been defined. This might include a namespace, or even a hierarchy of
namespaces. Within the lowest-level namespace, the element must be contained in a module, class, or structure.

' Assume the following hierarchy exists outside your code.


Namespace outerSpace
Namespace innerSpace
Module holdsTotals
Public Structure totals
Public thisTotal As Integer
Public Shared grandTotal As Long
End Structure
End Module
End Namespace
End Namespace

2. Determine a qualification path based on the target element's location. Start with the highest-level namespace, proceed to
the lowest-level namespace, and end with the module, class, or structure containing the target element. Each element in
the path must contain the element that follows it.
outerSpace → innerSpace → holdsTotals → totals

3. Prepare the qualification string for the target element. Place a period (.) after every element in the path. Your application
must have access to every element in your qualification string.

outerSpace.innerSpace.holdsTotals.totals.

4. Write the expression or assignment statement referring to the target element in the normal way.

grandTotal = 9000

5. Precede the target element name with the qualification string. The name should immediately follow the period (.) that
follows the module, class, or structure that contains the element.

' Assume the following module is part of your code.


Module accessGrandTotal
Public Sub setGrandTotal()
outerSpace.innerSpace.holdsTotals.totals.grandTotal = 9000
End Sub
End Module
6. The compiler uses the qualification string to find a clear, unambiguous declaration to which it can match the target
element reference.
See Also
Tasks
How to: Distinguish Between Two Elements with the Same Name
How to: Hide a Variable with the Same Name as Your Variable
How to: Hide an Inherited Variable
How to: Access a Variable Hidden by a Derived Class
Concepts
Declared Element Characteristics
Resolving a Reference When Multiple Variables Have the Same Name
Declaration Statements in Visual Basic
Other Resources
References to Declared Elements
Visual Basic Language Concepts

How to: Distinguish Between Two Elements with the Same


Name
If your application has access to multiple elements with the same name, you can qualify a name to enable the Visual Basic
compiler to match your reference to the particular element you want to use. For more information, see
How to: Qualify a Declared Element Name.
Example
The following example shows two variables with the same name in different containing elements with the same name. The
variables are declared as Shared purely to make the code shorter in the example.

Namespace space1
Public Class innerClass
' String showMe is declared Shared to facilitate reference.
Public Shared showMe As String = "Shared string 1"
End Class
End Namespace
Namespace space2
Public Class innerClass
' String showMe is declared Shared to facilitate reference.
Public Shared showMe As String = "Shared string 2"
End Class
End Namespace
Public Module callShowMe
Public Sub showStrings()
MsgBox("From space1: " & space1.innerClass.showMe _
& vbCrLf & "From space2: " & space2.innerClass.showMe)
End Sub
End Module

The preceding example declares two variables, each named showMe, and each inside a class named innerClass. Because both
containing elements have the same name, the calling code must not only qualify the variable showMe with its container
innerClass, but it must also qualify innerClass with its container space1 or space2. The Visual Basic compiler can resolve each
reference because each qualification string provides an unambiguous path to a unique declaration.
Robust Programming
The fewer variables with the same name you have declared, the fewer opportunities you have for accidentally referring to one
in place of another. You can also minimize problems of reference matching.
Security
The fewer variables with the same name you have declared, the smaller the chances that malicious code can make improper
use of one of them.
See Also
Tasks
How to: Qualify a Declared Element Name
How to: Hide a Variable with the Same Name as Your Variable
How to: Hide an Inherited Variable
How to: Access a Variable Hidden by a Derived Class
Concepts
Declared Element Characteristics
Resolving a Reference When Multiple Variables Have the Same Name
Declaration Statements in Visual Basic
Other Resources
References to Declared Elements
Visual Basic Language Concepts

Shadowing in Visual Basic


When two programming elements share the same name, one of them can hide, or shadow, the other one. In such a situation,
the shadowed element is not available for reference; instead, when your code uses the element name, the Visual Basic compiler
resolves it to the shadowing element.
Purpose
The main purpose of shadowing is to protect the definition of your class members. The base class might undergo a change that
creates an element with the same name as one you have already defined. If this happens, the Shadows modifier forces
references through your class to be resolved to the member you defined, instead of to the new base class element.
Types of Shadowing
An element can shadow another element in two different ways. The shadowing element can be declared inside a subregion of
the region containing the shadowed element, in which case the shadowing is accomplished through scope. Or a deriving class
can redefine a member of a base class, in which case the shadowing is done through inheritance.
Shadowing Through Scope
It is possible for programming elements in the same module, class, or structure to have the same name but different scope.
When two elements are declared in this manner and the code refers to the name they share, the element with the narrower
scope shadows the other element (block scope is the narrowest).
For example, a module can define a Public variable named temp, and a procedure within the module can declare a local
variable also named temp. References to temp from within the procedure access the local variable, while references to temp
from outside the procedure access the Public variable. In this case, the procedure variable temp shadows the module variable
temp.

The following illustration shows two variables, both named temp. The local variable temp shadows the member variable temp
when accessed from within its own procedure p. However, the MyClass keyword bypasses the shadowing and accesses the
member variable.
Shadowing through scope

For an example of shadowing through scope, see How to: Hide a Variable with the Same Name as Your Variable.
Shadowing Through Inheritance
If a derived class redefines a programming element inherited from a base class, the redefining element shadows the original
element. You can shadow any type of declared element, or set of overloaded elements, with any other type. For example, an
Integer variable can shadow a Function procedure. If you shadow a procedure with another procedure, you can use a
different parameter list and a different return type.
The following illustration shows a base class b and a derived class d that inherits from b. The base class defines a procedure
named proc, and the derived class shadows it with another procedure of the same name. The first Call statement accesses the
shadowing proc in the derived class. However, the MyBase keyword bypasses the shadowing and accesses the shadowed
procedure in the base class.
Shadowing through inheritance
For an example of shadowing through inheritance, see How to: Hide a Variable with the Same Name as Your Variable and
How to: Hide an Inherited Variable.
Shadowing and Access Level
The shadowing element is not always accessible from the code using the derived class. For example, it might be declared
Private. In such a case, shadowing is defeated and the compiler resolves any reference to the same element it would have if
there had been no shadowing. This element is the accessible element the fewest derivational steps backward from the
shadowing class. If the shadowed element is a procedure, the resolution is to the closest accessible version with the same
name, parameter list, and return type.
The following example shows an inheritance hierarchy of three classes. Each class defines a Sub procedure display, and each
derived class shadows the display procedure in its base class.

Public Class firstClass


Public Sub display()
MsgBox("This is firstClass")
End Sub
End Class
Public Class secondClass
Inherits firstClass
Private Shadows Sub display()
MsgBox("This is secondClass")
End Sub
End Class
Public Class thirdClass
Inherits secondClass
Public Shadows Sub display()
MsgBox("This is thirdClass")
End Sub
End Class
Module callDisplay
Dim first As New firstClass
Dim second As New secondClass
Dim third As New thirdClass
Public Sub callDisplayProcedures()
' The following statement displays "This is firstClass".
first.display()
' The following statement displays "This is firstClass".
second.display()
' The following statement displays "This is thirdClass".
third.display()
End Sub
End Module

In the preceding example, the derived class secondClass shadows display with a Private procedure. When module
callDisplay calls display in secondClass, the calling code is outside secondClass and therefore cannot access the private
display procedure. Shadowing is defeated, and the compiler resolves the reference to the base class display procedure.

However, the further derived class thirdClass declares display as Public, so the code in callDisplay can access it.
Shadowing and Overriding
Do not confuse shadowing with overriding. Both are used when a derived class inherits from a base class, and both redefine
one declared element with another. But there are significant differences between the two. For a comparison, see
Differences Between Shadowing and Overriding.
Shadowing and Overloading
If you shadow the same base class element with more than one element in your derived class, the shadowing elements
become overloaded versions of that element. For more information, see Procedure Overloading.
Accessing a Shadowed Element
When you access an element from a derived class, you normally do so through the current instance of that derived class, by
qualifying the element name with the Me keyword. If your derived class shadows the element in the base class, you can access
the base class element by qualifying it with the MyBase keyword.
For an example of accessing a shadowed element, see How to: Access a Variable Hidden by a Derived Class.
Declaration of the Object Variable
How you create the object variable can also affect whether the derived class accesses a shadowing element or the shadowed
element. The following example creates two objects from a derived class, but one object is declared as the base class and the
other as the derived class.

Public Class baseCls


' The following statement declares the element that is to be shadowed.
Public z As Integer = 100
End Class
Public Class dervCls
Inherits baseCls
' The following statement declares the shadowing element.
Public Shadows z As String = "*"
End Class
Public Class useClasses
' The following statement creates the object declared as the base class.
Dim basObj As baseCls = New dervCls()
' Note that dervCls widens to its base class baseCls.
' The following statement creates the object declared as the derived class.
Dim derObj As dervCls = New dervCls()
Public Sub showZ()
' The following statement outputs 100 (the shadowed element).
MsgBox("Accessed through base class: " & basObj.z)
' The following statement outputs "*" (the shadowing element).
MsgBox("Accessed through derived class: " & derObj.z)
End Sub
End Class

In the preceding example, the variable basObj is declared as the base class. Assigning a dervCls object to it constitutes a
widening conversion and is therefore valid. However, the base class cannot access the shadowing version of the variable z in
the derived class, so the compiler resolves basObj.z to the original base class value.
See Also
Reference
Shadows
Overrides
Me
MyBase
Concepts
Scope in Visual Basic
Widening and Narrowing Conversions
Other Resources
References to Declared Elements
Visual Basic Language Concepts

Differences Between Shadowing and Overriding


When you define a class that inherits from a base class, you sometimes want to redefine one or more of the base class
elements in the derived class. Shadowing and overriding are both available for this purpose.
Comparison
It is easy to confuse shadowing with overriding. Both are used when a derived class inherits from a base class, and both
redefine one declared element with another. But there are significant differences between the two.
The following table compares shadowing with overriding.
Point of comparison Shadowing Overriding
Purpose Protecting against a subsequent base class modif Achieving polymorphism by defining a differen
ication that introduces a member you have alrea t implementation of a procedure or property wi
dy defined in your derived class th the same calling sequence1

Redefined element Any declared element type Only a procedure (Function, Sub, or Operator
) or property

Redefining element Any declared element type Only a procedure or property with the identical
calling sequence1

Access level of redefining ele Any access level Cannot change access level of overridden elem
ment ent

Readability and writability of Any combination Cannot change readability or writability of over
redefining element ridden property

Control over redefining Base class element cannot enforce or prohibit sh Base class element can specify MustOverride,
adowing NotOverridable, or Overridable

Keyword usage Shadows recommended in derived class; Shado Overridable or MustOverride required in bas
ws assumed if neither Shadows nor Overrides e class; Overrides required in derived class
specified2

Inheritance of redefining ele Shadowing element inherited by further derived Overriding element inherited by further derive
ment by classes deriving fro classes; shadowed element still hidden3 d classes; overridden element still overridden
m your derived class

1 The calling sequence consists of the element type (Function, Sub, Operator, or Property), name, parameter list, and return
type. You cannot override a procedure with a property, or the other way around. You cannot override one kind of procedure
(Function, Sub, or Operator) with another kind.
2 If you do not specify either Shadows or Overrides, the compiler issues a warning message to help you be sure which kind of
redefinition you want to use. If you ignore the warning, the shadowing mechanism is used.
3 If the shadowing element is inaccessible in a further derived class, shadowing is not inherited. For example, if you declare the
shadowing element as Private, a class deriving from your derived class inherits the original element instead of the shadowing
element.
Guidelines
You normally use overriding in the following cases:
You are defining polymorphic derived classes.
You want the safety of having the compiler enforce the identical element type and calling sequence.
You normally use shadowing in the following cases:
You anticipate that your base class might be modified and define an element using the same name as yours.
You want the freedom of changing the element type or calling sequence.
See Also
Tasks
How to: Distinguish Between Two Elements with the Same Name
How to: Hide a Variable with the Same Name as Your Variable
How to: Hide an Inherited Variable
How to: Access a Variable Hidden by a Derived Class
Reference
Shadows
Overrides
Concepts
Resolving a Reference When Multiple Variables Have the Same Name
Shadowing in Visual Basic
Other Resources
References to Declared Elements
Visual Basic Language Concepts

How to: Hide a Variable with the Same Name as Your Variable
You can hide a variable by shadowing it, that is, by redefining it with a variable of the same name. You can shadow the variable
you want to hide in two ways:
Shadowing Through Scope. You can shadow it through scope by redeclaring it inside a subregion of the region
containing the variable you want to hide.
Shadowing Through Inheritance. If the variable you want to hide is defined at class level, you can shadow it through
inheritance by redeclaring it with the Shadows keyword in a derived class.
Two Ways to Hide a Variable
To hide a variable by shadowing it through scope
1. Determine the region defining the variable you want to hide, and determine a subregion in which to redefine it with your
variable.
Variable's region Allowable subregion for redefining it
Module A class within the module

Class A subclass within the class


A procedure within the class

You cannot redefine a procedure variable in a block within that procedure, for example in an If...End If construction or a
For loop.
2. Create the subregion if it does not already exist.
3. Within the subregion, write a Dim Statement (Visual Basic) declaring the shadowing variable.
When code inside the subregion refers to the variable name, the compiler resolves the reference to the shadowing
variable.
The following example illustrates shadowing through scope, as well as a reference that bypasses the shadowing.

Module shadowByScope
' The following statement declares num as a module-level variable.
Public num As Integer
Sub show()
' The following statement declares num as a local variable.
Dim num As Integer
' The following statement sets the value of the local variable.
num = 2
' The following statement displays the module-level variable.
MsgBox(CStr(shadowByScope.num))
End Sub
Sub useModuleLevelNum()
' The following statement sets the value of the module-level variable.
num = 1
show()
End Sub
End Module

The preceding example declares the variable num both at module level and at procedure level (in the procedure show). The
local variable num shadows the module-level variable num within show, so the local variable is set to 2. However, there is
no local variable to shadow num in the useModuleLevelNum procedure. Therefore, useModuleLevelNum sets the value of the
module-level variable to 1.
The MsgBox call inside show bypasses the shadowing mechanism by qualifying num with the module name. Therefore, it
displays the module-level variable instead of the local variable.
To hide a variable by shadowing it through inheritance
1. Be sure the variable you want to hide is declared in a class, and at class level (outside any procedure). Otherwise you
cannot shadow it through inheritance.
2. Define a class derived from the variable's class if one does not already exist.
3. Inside the derived class, write a Dim statement declaring your variable. Include the Shadows keyword in the declaration.
When code in the derived class refers to the variable name, the compiler resolves the reference to your variable.
The following example illustrates shadowing through inheritance. It makes two references, one that accesses the
shadowing variable and one that bypasses the shadowing.

Public Class shadowBaseClass


Public shadowString As String = "This is the base class string."
End Class
Public Class shadowDerivedClass
Inherits shadowBaseClass
Public Shadows shadowString As String = "This is the derived class string."
Public Sub showStrings()
Dim s As String = "Unqualified shadowString: " & shadowString _
& vbCrLf & "MyBase.shadowString: " & MyBase.shadowString
MsgBox(s)
End Sub
End Class

The preceding example declares the variable shadowString in the base class and shadows it in the derived class. The
procedure showStrings in the derived class displays the shadowing version of the string when the name shadowString is
not qualified. It then displays the shadowed version when shadowString is qualified with the MyBase keyword.

Robust Programming
Shadowing introduces more than one version of a variable with the same name. When a code statement refers to the variable
name, the version to which the compiler resolves the reference depends on factors such as the location of the code statement
and the presence of a qualifying string. This can increase the risk of referring to an unintended version of a shadowed variable.
You can lower that risk by fully qualifying all references to a shadowed variable.
See Also
Tasks
How to: Distinguish Between Two Elements with the Same Name
How to: Hide an Inherited Variable
How to: Access a Variable Hidden by a Derived Class
Reference
Overrides
MyBase
Concepts
Resolving a Reference When Multiple Variables Have the Same Name
Shadowing in Visual Basic
Differences Between Shadowing and Overriding
Other Resources
References to Declared Elements
Visual Basic Language Concepts

How to: Hide an Inherited Variable


A derived class inherits all the definitions of its base class. If you want to define a variable using the same name as an element
of the base class, you can hide, or shadow, that base class element when you define your variable in the derived class. If you do
this, code in the derived class accesses your variable unless it explicitly bypasses the shadowing mechanism.
Another reason you might want to hide an inherited variable is to protect against base class revision. The base class might
undergo a change that alters the element you are inheriting. If this happens, the Shadows modifier forces references from the
derived class to be resolved to your variable, instead of to the base class element.
To hide an inherited variable
1. Be sure the variable you want to hide is declared at class level (outside any procedure). Otherwise you do not need to
hide it.
2. Inside your derived class, write a Dim Statement (Visual Basic) declaring your variable. Use the same name as that of the
inherited variable.
3. Include the Shadows keyword in the declaration.
When code in the derived class refers to the variable name, the compiler resolves the reference to your variable.
The following example illustrates shadowing of an inherited variable.

Public Class shadowBaseClass


Public shadowString As String = "This is the base class string."
End Class
Public Class shadowDerivedClass
Inherits shadowBaseClass
Public Shadows shadowString As String = "This is the derived class string."
Public Sub showStrings()
Dim s As String = "Unqualified shadowString: " & shadowString _
& vbCrLf & "MyBase.shadowString: " & MyBase.shadowString
MsgBox(s)
End Sub
End Class

The preceding example declares the variable shadowString in the base class and shadows it in the derived class. The
procedure showStrings in the derived class displays the shadowing version of the string when the name shadowString is
not qualified. It then displays the shadowed version when shadowString is qualified with the MyBase keyword.

Robust Programming
Shadowing introduces more than one version of a variable with the same name. When a code statement refers to the variable
name, the version to which the compiler resolves the reference depends on factors such as the location of the code statement
and the presence of a qualifying string. This can increase the risk of referring to an unintended version of a shadowed variable.
You can lower that risk by fully qualifying all references to a shadowed variable.
See Also
Tasks
How to: Distinguish Between Two Elements with the Same Name
How to: Hide a Variable with the Same Name as Your Variable
How to: Access a Variable Hidden by a Derived Class
Reference
Overrides
Concepts
Resolving a Reference When Multiple Variables Have the Same Name
Shadowing in Visual Basic
Differences Between Shadowing and Overriding
Other Resources
References to Declared Elements
Visual Basic Language Concepts

How to: Access a Variable Hidden by a Derived Class


When code in a derived class accesses a variable, the compiler normally resolves the reference to the closest accessible version,
that is, the accessible version the fewest derivational steps backward from the accessing class. If the variable is defined in the
derived class, the code normally accesses that definition.
If the derived class variable shadows a variable in the base class, it hides the base class version. However, you can access the
base class variable by qualifying it with the MyBase keyword.
To access a base class variable hidden by a derived class
In an expression or assignment statement, precede the variable name with the MyBase keyword and a period (.).
The compiler resolves the reference to the base class version of the variable.
The following example illustrates shadowing through inheritance. It makes two references, one that accesses the
shadowing variable and one that bypasses the shadowing.

Public Class shadowBaseClass


Public shadowString As String = "This is the base class string."
End Class
Public Class shadowDerivedClass
Inherits shadowBaseClass
Public Shadows shadowString As String = "This is the derived class string."
Public Sub showStrings()
Dim s As String = "Unqualified shadowString: " & shadowString _
& vbCrLf & "MyBase.shadowString: " & MyBase.shadowString
MsgBox(s)
End Sub
End Class

The preceding example declares the variable shadowString in the base class and shadows it in the derived class. The
procedure showStrings in the derived class displays the shadowing version of the string when the name shadowString is
not qualified. It then displays the shadowed version when shadowString is qualified with the MyBase keyword.

Robust Programming
To lower the risk of referring to an unintended version of a shadowed variable, you can fully qualify all references to a
shadowed variable. Shadowing introduces more than one version of a variable with the same name. When a code statement
refers to the variable name, the version to which the compiler resolves the reference depends on factors such as the location of
the code statement and the presence of a qualifying string. This can increase the risk of referring to the wrong version of the
variable.
See Also
Tasks
How to: Distinguish Between Two Elements with the Same Name
How to: Hide a Variable with the Same Name as Your Variable
How to: Hide an Inherited Variable
Reference
Shadows
Overrides
Concepts
Resolving a Reference When Multiple Variables Have the Same Name
Shadowing in Visual Basic
Differences Between Shadowing and Overriding
Other Resources
References to Declared Elements
Visual Basic Language Concepts

Data Types in Visual Basic


The data type of a programming element refers to what kind of data it can hold and how it stores that data. Data types apply to
all values that can be stored in computer memory or participate in the evaluation of an expression. Every variable, literal,
constant, enumeration, property, procedure parameter, procedure argument, and procedure return value has a data type.
Declared Data Types
Unless you use typeless programming, you must declare data types for all your programming elements. (For more
information, see Typeless Programming in Visual Basic.)
You define a programming element with a declaration statement, and you specify its data type with the As clause. The
following table shows the statements you use to declare various elements.
Programming el Data type declaration
ement
Variable In a Dim Statement (Visual Basic)
Dim amount As Double
Static yourName As String
Public billsPaid As Decimal = 0

Literal With a literal type character; see "Literal Type Characters" in Type Characters
Dim searchChar As Char = "." C

Constant In a Const Statement (Visual Basic)


Const modulus As Single = 4.17825F

Enumeration In an Enum Statement (Visual Basic)


Public Enum colors

Property In a Property Statement


Property region() As String

Procedure parame In a Sub Statement (Visual Basic), Function Statement (Visual Basic), or Operator Statement
ter Sub addSale(ByVal amount As Double)

Procedure argume In the calling code; each argument is a programming element that has already been declared, or an express
nt ion containing declared elements
subString = Left( inputString , 5 )

Procedure return v In a Function Statement (Visual Basic) or Operator Statement


alue Function convert(ByVal b As Byte) As String

See Also
Tasks
Troubleshooting Data Types
Reference
Data Type Summary (Visual Basic)
Concepts
Type Characters
Composite Data Types
Generic Types in Visual Basic
Typeless Programming in Visual Basic
Other Resources
Elementary Data Types
Data Type Implementation
Type Conversions in Visual Basic
Structures: Your Own Data Types
Visual Basic Language Concepts

Type Characters
In addition to specifying a data type in a declaration statement, you can force the data type of some programming elements
with a type character. The type character must immediately follow the element, with no intervening characters of any kind.
The type character is not part of the name of the element. An element defined with a type character can be referenced without
the type character.
Identifier Type Characters
Visual Basic supplies a set of identifier type characters, which you can use in a declaration to specify the data type of a variable
or constant. The following table shows the available identifier type characters with examples of usage.
Identifier type character Data type Example
% Integer Dim L%

& Long Dim M&

@ Decimal Const W@ = 37.5

! Single Dim Q!

# Double Dim X#

$ String Dim V$ = "Secret"

No identifier type characters exist for the Boolean, Byte, Char, Date, Object, SByte, Short, UInteger, ULong, or UShort data
types, or for any composite data types such as arrays or structures.
In some cases, you can append the $ character to a Visual Basic function, for example Left$ instead of Left, to obtain a
returned value of type String.
In all cases, the identifier type character must immediately follow the identifier name.
Literal Type Characters
A literal is a textual representation of a particular value of a data type.
Default Literal Types
The form of a literal as it appears in your code normally determines its data type. The following table shows these default
types.
Textual form of literal Default data type Example
Numeric, no fractional part Integer 2147483647

Numeric, no fractional part, too large for Integer Long 2147483648

Numeric, fractional part Double 1.2

Enclosed within double quotation marks String "A"

Enclosed within number signs Date #5/17/1993 9:32 AM#

Forced Literal Types


Visual Basic supplies a set of literal type characters, which you can use to force a literal to assume a data type other than the
one its form indicates. You do this by appending the character to the end of the literal. The following table shows the available
literal type characters with examples of usage.
Literal type character Data type Example
S Short I = 347S

I Integer J = 347I

L Long K = 347L

D Decimal X = 347D

F Single Y = 347F

R Double Z = 347R

US UShort L = 347US

UI UInteger M = 347UI

UL ULong N = 347UL

C Char Q = "."C

No literal type characters exist for the Boolean, Byte, Date, Object, SByte, or String data types, or for any composite data
types such as arrays or structures.
Literals can also use the identifier type characters (%, &, @, !, #, $), as can variables, constants, and expressions. However, the
literal type characters (S, I, L, D, F, R, C) can be used only with literals.
In all cases, the literal type character must immediately follow the literal value.
Hexadecimal and Octal Literals
The compiler normally construes an integer literal to be in the decimal (base 10) number system. You can force an integer
literal to be hexadecimal (base 16) with the &H prefix, and you can force it to be octal (base 8) with the &O prefix. The digits
following the prefix must be appropriate for the number system. The following table illustrates this.
Number base Prefix Valid digit values Example
Hexadecimal (base 16) &H 0-9 and A-F &HFFFF

Octal (base 10) &O 0-7 &O77

You can follow a prefixed literal with a literal type character. The following example shows this.

Dim counter As Short = &H8000S


Dim flags As UShort = &H8000US

In the preceding example, counter has the decimal value of -32768, and flags has the decimal value of +32768.
See Also
Tasks
Troubleshooting Data Types
Reference
Data Type Summary (Visual Basic)
Concepts
Data Types in Visual Basic
Typeless Programming in Visual Basic
Variable Declaration in Visual Basic
Other Resources
Elementary Data Types
Data Type Implementation
Type Conversions in Visual Basic
Visual Basic Language Concepts

Elementary Data Types


Visual Basic supplies a set of predefined data types, which you can use for many of your programming elements. This section
describes these types and how to use them.
In This Section
Numeric Data Types
Describes the integral and nonintegral numeric types.
Character Data Types
Describes the Char and String types.
Miscellaneous Data Types
Describes the Boolean, Date, and Object types.
Related Sections
Data Types in Visual Basic
Introduces the Visual Basic data types and describes how to use them.
Data Type Summary (Visual Basic)
Provides an overview of the elementary data types supplied by Visual Basic.
Visual Basic Language Concepts

Numeric Data Types


Visual Basic supplies several numeric data types for handling numbers in various representations. Integral types represent
only whole numbers (positive, negative, and zero), and nonintegral types represent numbers with both integer and fractional
parts.
For a table showing a side-by-side comparison of the Visual Basic data types, see Data Type Summary (Visual Basic).
Integral Numeric Types
Integral data types are those that represent only numbers without fractional parts.
The signed integral data types are SByte Data Type (Visual Basic) (8-bit), Short Data Type (Visual Basic) (16-bit),
Integer Data Type (Visual Basic) (32-bit), and Long Data Type (Visual Basic) (64-bit). If a variable always stores integers rather
than fractional numbers, declare it as one of these types.
The unsigned integral types are Byte Data Type (Visual Basic) (8-bit), UShort Data Type (Visual Basic) (16-bit),
UInteger Data Type (32-bit), and ULong Data Type (Visual Basic) (64-bit). If a variable contains binary data, or data of unknown
nature, declare it as one of these types.
Performance
Arithmetic operations are faster with integral types than with other data types. They are fastest with the Integer and UInteger
types in Visual Basic.
Large Integers
If you need to hold an integer larger than the Integer data type can hold, you can use the Long data type instead. Long
variables can hold numbers from -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807. Operations with Long are
slightly slower than with Integer.
If you need even larger values, you can use the Decimal Data Type (Visual Basic). You can hold numbers from -
79,228,162,514,264,337,593,543,950,335 through 79,228,162,514,264,337,593,543,950,335 in a Decimal variable if you do
not use any decimal places. However, operations with Decimal numbers are considerably slower than with any other numeric
data type.
Small Integers
If you do not need the full range of the Integer data type, you can use the Short data type, which can hold integers from -
32,768 through 32,767. For the smallest integer range, the SByte data type holds integers from -128 through 127. If you have
a very large number of variables that hold small integers, the common language runtime can sometimes store your Short and
SByte variables more efficiently and save memory consumption. However, operations with Short and SByte are somewhat
slower than with Integer.
Unsigned Integers
If you know that your variable never needs to hold a negative number, you can use the unsigned types Byte, UShort,
UInteger, and ULong. Each of these data types can hold a positive integer twice as large as its corresponding signed type
(SByte, Short, Integer, and Long). In terms of performance, each unsigned type is exactly as efficient as its corresponding
signed type. In particular, UInteger shares with Integer the distinction of being the most efficient of all the elementary
numeric data types.
Nonintegral Numeric Types
Nonintegral data types are those that represent numbers with both integer and fractional parts.
The nonintegral numeric data types are Decimal (128-bit fixed point), Single Data Type (Visual Basic) (32-bit floating point),
and Double Data Type (Visual Basic) (64-bit floating point). They are all signed types. If a variable can contain a fraction, declare
it as one of these types.
Decimal is not a floating-point data type. Decimal numbers have a binary integer value and an integer scaling factor that
specifies what portion of the value is a decimal fraction.
Floating-point (Single and Double) numbers have larger ranges than Decimal numbers but can be subject to rounding
errors. Floating-point types support fewer significant digits than Decimal but can represent values of greater magnitude.
Nonintegral number values can be expressed as mmmEeee, in which mmm is the mantissa (the significant digits) and eee is
the exponent (a power of 10). The highest positive values of the nonintegral types are
7.9228162514264337593543950335E+28 for Decimal, 3.4028235E+38 for Single, and 1.79769313486231570E+308 for
Double.
Performance
Double is the most efficient of the fractional data types, because the processors on current platforms perform floating-point
operations in double precision. However, operations with Double are not as fast as with the integral types such as Integer.
Small Magnitudes
For numbers with the smallest possible magnitude (closest to 0), Double variables can hold numbers as small as -
4.94065645841246544E-324 for negative values and 4.94065645841246544E-324 for positive values.
Small Fractional Numbers
If you do not need the full range of the Double data type, you can use the Single data type, which can hold floating-point
numbers from -3.4028235E+38 through 3.4028235E+38. The smallest magnitudes for Single variables are -1.401298E-45
for negative values and 1.401298E-45 for positive values. If you have a very large number of variables that hold small floating-
point numbers, the common language runtime can sometimes store your Single variables more efficiently and save memory
consumption.
See Also
Tasks
Troubleshooting Data Types
How to: Hold Integers in a Variable
How to: Hold Fractions in a Variable
How to: Hold the Largest Possible Number in a Variable
How to: Optimize Storage of Positive Integers With Unsigned Types
How to: Call a Windows Function that Takes Unsigned Types
How to: Hold the Most Significant Digits in a Variable
How to: Hold Money Values in a Variable
Concepts
Character Data Types
Miscellaneous Data Types
Other Resources
Elementary Data Types
Visual Basic Language Concepts

How to: Hold Integers in a Variable


Integers are whole numbers, including positive, zero, and negative. A variable holds integers if you declare it to be of type
Integer. The Integer Data Type (Visual Basic) can hold integers from -2,147,483,648 through 2,147,483,647.
You can also use the Long Data Type (Visual Basic), the Short Data Type (Visual Basic), or the SByte Data Type (Visual Basic) to
hold integers. For more information, see Numeric Data Types.
To hold integers in a variable
1. Declare the variable with a Dim Statement (Visual Basic).
2. Follow the variable name with an As clause.
3. Follow the As keyword with the Integer keyword.

Dim students As Integer

See Also
Reference
Data Type Summary (Visual Basic)
Concepts
Data Types in Visual Basic
Type Characters
Other Resources
Elementary Data Types
Visual Basic Language Concepts

How to: Hold the Largest Possible Number in a Variable


A variable holds the largest possible numbers with precision if you declare it to be of data type Decimal. The next largest
integer capacity is data type ULong. If you do not need the precision of integral data types, you can use floating-point types for
even greater magnitude.
Two Different Meanings for "Largest"
Largest Precise Value. If you need to hold large integers with complete precision down to the units digit, you can use the
Decimal Data Type (Visual Basic). The Decimal type can hold integers from -79,228,162,514,264,337,593,543,950,335 through
79,228,162,514,264,337,593,543,950,335 (7.9...E+28).
Greatest Magnitude. The fractional types Single and Double can hold numbers of greater magnitude, but not with exact
precision. The Single Data Type (Visual Basic) provides 8 digits of precision, and the Double Data Type (Visual Basic) provides
18 digits of precision.
To hold the largest possible integers in a variable
1. Declare the variable with a Dim Statement (Visual Basic).
2. Follow the variable name with an As clause, specifying the Decimal keyword.

Dim atomsInTheUniverse As Decimal

Efficient Data Types


The Decimal type has the slowest performance of all the elementary numeric data types. If your integer numbers do not attain
such large values and are always positive or zero, consider the ULong type.
A variable of the ULong Data Type (Visual Basic) can hold integers from 0 through 18,446,744,073,709,551,615 (1.8...E+19).
Operations with ULong numbers are much faster than with Decimal, although not quite as efficient as with UInteger.
To hold large nonnegative integers in a variable with efficient performance
1. Declare the variable with a Dim statement.
2. Follow the variable name with an As clause, specifying the ULong keyword.

Dim atomsInTheEarth As ULong

See Also
Reference
Data Type Summary (Visual Basic)
Integer Data Type (Visual Basic)
Long Data Type (Visual Basic)
Decimal Data Type (Visual Basic)
UInteger Data Type
ULong Data Type (Visual Basic)
Concepts
Type Characters
Other Resources
Elementary Data Types
Visual Basic Language Concepts

How to: Optimize Storage of Positive Integers With Unsigned


Types
If you have a variable that contains only positive values (or 0), and these values never exceed 4,294,967,295, you can declare
the variable as UInteger instead of Long.
The advantage of using UInteger is that the 32-bit integer types Integer and UInteger are the most efficient data types on
32-bit platforms, and they provide optimum performance for your application.
You can use an Integer variable if your positive values never exceed 2,147,483,647.
To declare an integer with only positive values
Declare the variable As UInteger. The following example illustrates this.

Public Function memoryRequired(ByVal m As UInteger) As UInteger


Static r As UInteger = 0
Try
r += m
Catch eo As System.OverflowException
r = 0
Catch ex As System.Exception
MsgBox("Incrementing required memory causes """ & ex.Message & """")
End Try
Return r
End Function

You can test the function memoryRequired with the following code:

Public Sub consumeMemoryRequired()


Dim m1 As UInteger = UInteger.MaxValue - 100
Dim m2 As UInteger = 100
MsgBox("Max = " & CStr(UInteger.MaxValue) & vbCrLf & _
CStr(m1) & " -> " & CStr(memoryRequired(m1)) & vbCrLf & _
"+ " & CStr(m2) & " -> " & CStr(memoryRequired(m2)) _
& vbCrLf & "+ 1 -> " & CStr(memoryRequired(1)))
End Sub

Caution
The UInteger data type is not part of the Common Language Specification (CLS), so CLS-compliant code cannot consu
me a component that uses it.

See Also
Tasks
How to: Call a Windows Function that Takes Unsigned Types
Reference
Data Type Summary (Visual Basic)
Integer Data Type (Visual Basic)
UInteger Data Type
Visual Basic Language Concepts

How to: Call a Windows Function that Takes Unsigned Types


If you are consuming a class, module, or structure that has members of unsigned integer types, you can access these members
with Visual Basic.
To call a Windows function that takes an unsigned type
1. Use a Declare Statement to tell Visual Basic which library holds the function, what its name is in that library, what its
calling sequence is, and how to convert strings when calling it.
2. In the Declare statement, use UInteger, ULong, UShort, or Byte as appropriate for each parameter with an unsigned
type.
3. Consult the documentation for the Windows function you are calling to find the names and values of the constants it
uses. Many of these are defined in the WinUser.h file.
4. Declare the necessary constants in your code. Many Windows constants are 32-bit unsigned values, and you should
declare these As UInteger.
5. Call the function in the normal way. The following example calls the Windows function MessageBox, which takes an
unsigned integer argument.

Public Class windowsMessage


Private Declare Auto Function mb Lib "user32.dll" Alias "MessageBox" _
(ByVal hWnd As Integer, _
ByVal lpText As String, _
ByVal lpCaption As String, _
ByVal uType As UInteger) As Integer
Private Const MB_OK As UInteger = 0
Private Const MB_ICONEXCLAMATION As UInteger = &H30
Private Const IDOK As UInteger = 1
Private Const IDCLOSE As UInteger = 8
Private Const c As UInteger = MB_OK Or MB_ICONEXCLAMATION
Public Function messageThroughWindows() As String
Dim r As Integer = mb(0, "Click OK if you see this!", _
"Windows API call", c)
Dim s As String = "Windows API MessageBox returned " _
& CStr(r)& vbCrLf & "(IDOK = " & CStr(IDOK) _
& ", IDCLOSE = " & CStr(IDCLOSE) & ")"
Return s
End Function
End Class

You can test the function messageThroughWindows with the following code.

Public Sub consumeWindowsMessage()


Dim w As New windowsMessage
w.messageThroughWindows()
End Sub

Caution
The UInteger, ULong, UShort, and SByte data types are not part of the Common Language Specification (CLS), so CL
S-compliant code cannot consume a component that uses them.

Security Note
Making a call to unmanaged code, such as the Windows application programming interface (API), exposes your code to
potential security risks.

Security Note
Calling the Windows API requires unmanaged code permission, which might affect its execution in partial-trust situatio
ns. For more information, see SecurityPermission and Code Access Permissions.

See Also
Tasks
How to: Optimize Storage of Positive Integers With Unsigned Types
Walkthrough: Calling Windows APIs
Reference
Data Type Summary (Visual Basic)
Integer Data Type (Visual Basic)
UInteger Data Type
Declare Statement
Visual Basic Language Concepts

How to: Hold Fractions in a Variable


A variable holds numbers with fractions if you declare it to be of type Double. The Double Data Type (Visual Basic) can hold
floating-point numbers from -1.79769313486231570E+308 through 1.79769313486231570E+308.
You can also use the Single Data Type (Visual Basic) or the Decimal Data Type (Visual Basic) to hold fractions. For more
information, see Numeric Data Types.
To hold fractions in a variable
1. Declare the variable with a Dim Statement (Visual Basic).
2. Follow the variable name with an As clause.
3. Follow the As keyword with the Double keyword.
See Also
Reference
Data Type Summary (Visual Basic)
Concepts
Type Characters
Numeric Data Types
Other Resources
Elementary Data Types
Visual Basic Language Concepts

How to: Hold the Most Significant Digits in a Variable


A variable holds numbers with fractions if you declare it to be of data type Decimal.
A variable of the Decimal Data Type (Visual Basic) can hold numbers with 29 significant digits, including as many as 28 decimal
places.
Performance. Decimal is the least efficient of the numeric data types. If you do not need the full precision of the Decimal
data type, you can use the Double data type, which can hold as many as 18 significant digits. Operations with Double are
faster than with Decimal, and Double variables take up less space in memory. For more information on Double, see
How to: Hold Fractions in a Variable.
You should weigh the importance of precision against performance before choosing a data type.
Larger Magnitude. If you need your variable to hold numbers of greater magnitude than the Decimal data type can hold,
you can use the Double or Single data type, each of which has a larger range. While Decimal variables can hold values up to
7.9228162514264337593543950335E+28, Single variables can hold up to 3.4028235E+38, and Double variables can hold
up to 1.79769313486231570E+308.
To hold the most significant digits in a variable
1. Declare the variable with a Dim Statement (Visual Basic).
2. Follow the variable name with an As clause.
3. Follow the As keyword with the Decimal keyword.
See Also
Reference
Data Type Summary (Visual Basic)
Decimal Data Type (Visual Basic)
Double Data Type (Visual Basic)
Concepts
Type Characters
Other Resources
Elementary Data Types
Visual Basic Language Concepts

How to: Hold Money Values in a Variable


A variable holds money values if you declare it to be of data type Decimal.
A variable of the Decimal Data Type (Visual Basic) can hold numbers with 29 significant digits, including as many as 28 decimal
places. For money values, you normally need only 2 or 3 decimal places. But for intermediate results during a transaction, such
as multiplying by an interest rate, you might want additional decimal places to retain accuracy.
The advantage of using Decimal variables for money values is the precision of the values. The Double data type is faster and
requires less memory, but it is subject to rounding errors. The Decimal data type retains complete accuracy to 28 places if
necessary.
Trailing 0 Characters. Visual Basic does not have any internal representation of trailing 0 characters in the floating-point data
types such as Double. It does not store trailing zeros in a Decimal literal, although a Decimal variable preserves any trailing
zeros acquired computationally. For more information and an example, see Decimal Data Type (Visual Basic).
Visual Basic often suppresses trailing 0 characters when displaying or printing. For example, a value of 4.2000 is often
rendered as 4.2. You can control the output format more closely if you call the System.Decimal.ToString or
System.Double.ToString method for the appropriate data type.
To hold money values in a variable
1. Declare the variable with a Dim Statement (Visual Basic).
2. Follow the variable name with an As clause.
3. Follow the As keyword with the Decimal keyword.
See Also
Reference
Data Type Summary (Visual Basic)
Single Data Type (Visual Basic)
Decimal Data Type (Visual Basic)
Double Data Type (Visual Basic)
Concepts
Data Types in Visual Basic
Type Characters
Other Resources
Elementary Data Types
Visual Basic Language Concepts

Character Data Types


Visual Basic provides character data types for dealing with printable and displayable characters. While they both deal with
Unicode characters, Char holds a single character while String contains an indefinite number of characters.
For a table showing a side-by-side comparison of the Visual Basic data types, see Data Type Summary (Visual Basic).
Char Type
The Char data type is a single two-byte (16-bit) Unicode character. If a variable always stores exactly one character, declare it
as Char.
For more information, see Char Data Type (Visual Basic).
String Type
The String data type is a sequence of zero or more two-byte (16-bit) Unicode characters. If a variable can contain an indefinite
number of characters, declare it as String.
For more information, see String Data Type (Visual Basic).
See Also
Tasks
Troubleshooting Data Types
How to: Hold Characters in a Variable
Concepts
Composite Data Types
Generic Types in Visual Basic
Typeless Programming in Visual Basic
Type Characters
Other Resources
Elementary Data Types
Data Type Implementation
Type Conversions in Visual Basic
Visual Basic Language Concepts

How to: Hold Characters in a Variable


A variable holds individual characters if you declare it to be of data type Char or String.
A variable of the Char Data Type (Visual Basic) can hold a single Unicode character. A variable of the
String Data Type (Visual Basic) can hold a sequence of zero or more Unicode characters.
Unicode Characters. Each possible value in a Char or String variable is a code point, or character code, in the Unicode
character set. Unicode characters include the basic ASCII character set, various other alphabet letters, accents, currency
symbols, fractions, diacritics, and mathematical and technical symbols.
If you never need to hold more than one character in a single variable, use the Char data type. The String data type requires
more memory and has slower performance.
Note
The Unicode character set reserves the code points D800 through DFFF (55296 through 55551 decimal) for surrogate pairs,
which require two 16-bit values to represent a single code point. A Char variable cannot hold a surrogate pair, and a String
uses two positions to hold such a pair.

To hold a single character in a variable


1. Declare the variable with a Dim Statement (Visual Basic).
2. Follow the variable name with an As clause.
3. Follow the As keyword with the Char keyword.
To hold a sequence of characters in a variable
1. Declare the variable with a Dim statement.
2. Follow the variable name with an As clause.
3. Follow the As keyword with the String keyword.
See Also
Reference
Data Type Summary (Visual Basic)
Single Data Type (Visual Basic)
Char Data Type (Visual Basic)
String Data Type (Visual Basic)
Concepts
Data Types in Visual Basic
Type Characters
Other Resources
Elementary Data Types
Visual Basic Language Concepts

Miscellaneous Data Types


Visual Basic supplies several data types that are not oriented toward numbers or characters. Instead, they deal with specialized
data such as yes/no values, date/time values, and object addresses.
For a table showing a side-by-side comparison of the Visual Basic data types, see Data Type Summary (Visual Basic).
Boolean Type
The Boolean Data Type (Visual Basic) is an unsigned value that is interpreted as either True or False. Its data width depends on
the implementing platform. If a variable can contain only two-state values such as true/false, yes/no, or on/off, declare it as
Boolean.
Date Type
The Date Data Type (Visual Basic) is a 64-bit value that holds both date and time information. Each increment represents 100
nanoseconds of elapsed time since the beginning (12:00 AM) of January 1 of the year 1 in the Gregorian calendar. If a variable
can contain a date value, a time value, or both, declare it as Date.
Object Type
The Object Data Type is a 32-bit address that points to an object instance within your application or in some other application.
An Object variable can refer to any object your application recognizes, or to data of any data type. If a variable stores a pointer
to an instance of a class that you do not know at compile time, or if it can point to data of various data types, declare it as
Object.
See Also
Tasks
Troubleshooting Data Types
How to: Hold True and False Values in a Variable
How to: Hold Date and Time Values in a Variable
How to: Hold Data of Unknown Type in a Variable
Concepts
Type Characters
Numeric Data Types
Character Data Types
Other Resources
Elementary Data Types
Visual Basic Language Concepts

How to: Hold True and False Values in a Variable


A variable holds true and false values if you declare it to be of data type Boolean.
A variable of the Boolean Data Type (Visual Basic) can hold two-state logical values such as true/false, on/off, and yes/no.
If you need to hold numeric values, use a numeric data type such as Integer or Double instead of Boolean. You should never
use Boolean values as numbers, and you should never rely on equivalent numeric values for them. For more information, see
Troubleshooting Data Types.
To hold true and false values in a variable
1. Declare the variable with a Dim Statement (Visual Basic).
2. Follow the variable name with an As clause.
3. Follow the As keyword with the Boolean keyword.
See Also
Tasks
Troubleshooting Data Types
Reference
Data Type Summary (Visual Basic)
Single Data Type (Visual Basic)
Boolean Data Type (Visual Basic)
Integer Data Type (Visual Basic)
Double Data Type (Visual Basic)
Concepts
Data Types in Visual Basic
Type Characters
Other Resources
Elementary Data Types
Visual Basic Language Concepts

How to: Hold Date and Time Values in a Variable


A variable holds date and time values if you declare it to be of data type Date.
A variable of the Date Data Type (Visual Basic) can hold date values ranging from January 1 of the year 0001 through
December 31 of the year 9999, and time values from 12:00:00 AM (midnight) through 11:59:59 PM.
The Date data type always holds both a date value and a time value. If you do not assign a time value to a Date variable, it
defaults to the start of the day, that is, midnight. If you do not assign a date value to a Date variable, it defaults to January 1,
0001.
To hold dates in a variable
1. Declare the variable with a Dim Statement (Visual Basic).
2. Follow the variable name with an As clause.
3. Follow the As keyword with the Date keyword.
See Also
Reference
Data Type Summary (Visual Basic)
Single Data Type (Visual Basic)
Date Data Type (Visual Basic)
Concepts
Data Types in Visual Basic
Type Characters
Other Resources
Elementary Data Types
Visual Basic Language Concepts

How to: Hold Data of Unknown Type in a Variable


A variable holds pointers to data if you declare it to be of data type Object.
A variable of the Object Data Type can hold a pointer to a value of any data type. This includes both value types, such as
Integer, Boolean, and structure instances, and reference types, which are instances of objects created from classes such as
String, Form, and array instances.
Performance. The advantage of the Object data type is that you can use it to point to data of any data type. The disadvantage
is that you incur extra operations that take more execution time and make your application perform slower. If you use an
Object variable for value types, you incur boxing and unboxing. If you use it for reference types, you incur late binding.
You should use the Object data type when your variable needs to hold different data types at different times, or when you do
not know at compile time what data type or types your variable might hold.
To hold data of unknown type in a variable
1. Declare the variable with a Dim Statement (Visual Basic).
2. Follow the variable name with an As clause.
3. Follow the As keyword with the Object keyword.

See Also
Reference
Data Type Summary (Visual Basic)
Single Data Type (Visual Basic)
Object Data Type
Concepts
Data Types in Visual Basic
Type Characters
Value Types and Reference Types
Other Resources
Elementary Data Types
Visual Basic Language Concepts

Composite Data Types


In addition to the elementary data types Visual Basic supplies, you can also assemble items of different types to create
composite data types such as structures, arrays, and classes. You can build composite data types from elementary types and
from other composite types. For example, you can define an array of structure elements, or a structure with array members.
Data Types
A composite type is different from the data type of any of its components. For example, an array of Integer elements is not of
the Integer data type.
An array data type is normally represented using the element type, parentheses, and commas as necessary. For example, a
one-dimensional array of String elements is represented as String(), and a two-dimensional array of Boolean elements is
represented as Boolean(,).
Structure Types
There is no single data type comprising all structures. Instead, each definition of a structure represents a unique data type, even
if two structures define identical elements in the same order. However, if you create two or more instances of the same
structure, Visual Basic considers them to be of the same data type.
Array Types
There is no single data type comprising all arrays. The data type of a particular instance of an array is determined by the
following:
The fact of being an array
The rank (number of dimensions) of the array
The element type of the array
In particular, the length of a given dimension is not part of the instance's data type. The following example illustrates this.

Dim arrayA( ) As Byte = New Byte(12) {}


Dim arrayB( ) As Byte = New Byte(100) {}
Dim arrayC( ) As Short = New Short(100) {}
Dim arrayD( , ) As Short
Dim arrayE( , ) As Short = New Short(4, 10) {}

In the preceding example, array variables arrayA and arrayB are considered to be of the same data type — Byte() — even
though they are initialized to different lengths. Variables arrayB and arrayC are not of the same type because their element
types are different. Variables arrayC and arrayD are not of the same type because their ranks are different. Variables arrayD
and arrayE have the same type — Short(,) — because their ranks and element types are the same, even though arrayD is not
yet initialized.
For more information on arrays, see Arrays in Visual Basic.
Class Types
There is no single data type comprising all classes. Although one class can inherit from another class, each is a separate data
type. Multiple instances of the same class are of the same data type. If you assign one class instance variable to another, not
only do they have the same data type, they point to the same class instance in memory.
For more information on classes, see Understanding Classes.
See Also
Tasks
Troubleshooting Data Types
How to: Hold More Than One Value in a Variable
Concepts
Data Types in Visual Basic
Generic Types in Visual Basic
Typeless Programming in Visual Basic
Data Types Are .NET Framework Types
Other Resources
Elementary Data Types
Data Type Implementation
Type Conversions in Visual Basic
Structures: Your Own Data Types
Visual Basic Language Concepts

How to: Hold More Than One Value in a Variable


A variable holds more than one value if you declare it to be of a composite data type.
Composite Data Types include structures, arrays, and classes. A variable of a composite data type can hold a combination of
elementary data types and other composite types. Structures and classes can hold code as well as data.
To hold more than one value in a variable
1. Determine what composite data type you want to use for your variable.
2. If the composite data type is not already defined, define it so that your variable can use it.
Define a structure with a Structure Statement.
Define an array with a Dim Statement (Visual Basic).
Define a class with a Class Statement (Visual Basic).
3. Declare your variable with a Dim statement.
4. Follow the variable name with an As clause.
5. Follow the As keyword with the name of the appropriate composite data type.
See Also
Reference
Data Type Summary (Visual Basic)
Concepts
Type Characters
Composite Data Types
Data Types Are .NET Framework Types
Other Resources
Structures: Your Own Data Types
Arrays in Visual Basic
Understanding Classes
Visual Basic Language Concepts

Generic Types in Visual Basic


A generic type is a single programming element that adapts to perform the same functionality for a variety of data types.
When you define a generic class or procedure, you do not have to define a separate version for each data type for which you
might want to perform that functionality.
An analogy is a screwdriver set with removable heads. You inspect the screw you need to turn and select the correct head for
that screw (slotted, crossed, starred). Once you insert the correct head in the screwdriver handle, you perform the exact same
function with the screwdriver, namely turning the screw.
Screwdriver set as a generic tool

When you define a generic type, you parameterize it with one or more data types. This allows the using code to tailor the data
types to its requirements. Your code can declare several different programming elements from the generic element, each one
acting on a different set of data types. But the declared elements all perform the identical logic, no matter what data types they
are using.
For example, you might want to create and use a queue class that operates on a specific data type such as String. You can
declare such a class from System.Collections.Generic.Queue, as the following example shows.
VB
Public stringQ As New System.Collections.Generic.Queue(Of String)

You can now use stringQ to work exclusively with String values. Because stringQ is specific for String instead of being
generalized for Object values, you do not have late binding or type conversion. This saves execution time and reduces run-
time errors.
For more information on using a generic type, see How to: Use a Generic Class.
Example of a Generic Class
The following example shows a skeleton definition of a generic class.
VB
Public Class classHolder(Of t)
Public Sub processNewItem(ByVal newItem As t)
Dim tempItem As t
' Insert code that processes an item of data type t.
End Sub
End Class

In the preceding skeleton, t is a type parameter, that is, a placeholder for a data type that you supply when you declare the
class. Elsewhere in your code, you can declare various versions of classHolder by supplying various data types for t. The
following example shows two such declarations.
VB
Public integerClass As New classHolder(Of Integer)
Friend stringClass As New classHolder(Of String)
The preceding statements declare constructed classes, in which a specific type replaces the type parameter. This replacement is
propagated throughout the code within the constructed class. The following example shows what the processNewItem
procedure looks like in integerClass.
VB
Public Sub processNewItem(ByVal newItem As Integer)
Dim tempItem As Integer
' Inserted code now processes an Integer item.
End Sub

For a more complete example, see How to: Define a Class That Can Provide Identical Functionality on Different Data Types.
Eligible Programming Elements
You can define and use generic classes, structures, interfaces, procedures, and delegates. Note that the .NET Framework defines
several generic classes, structures, and interfaces that represent commonly used generic elements. The
System.Collections.Generic namespace provides dictionaries, lists, queues, and stacks. Before defining your own generic
element, see if it is already available in System.Collections.Generic.
Procedures are not types, but you can define and use generic procedures. See Generic Procedures in Visual Basic.
Advantages of Generic Types
A generic type serves as a basis for declaring several different programming elements, each of which operates on a specific
data type. The alternatives to a generic type are:
1. A single type operating on the Object data type.
2. A set of type-specific versions of the type, each version individually coded and operating on one specific data type such
as String, Integer, or a user-defined type such as customer.
A generic type has the following advantages over these alternatives:
Type Safety. Generic types enforce compile-time type checking. Types based on Object accept any data type, and you
must write code to check whether an input data type is acceptable. With generic types, the compiler can catch type
mismatches before run time.
Performance. Generic types do not have to box and unbox data, because each one is specialized for one data type.
Operations based on Object must box input data types to convert them to Object and unbox data destined for output.
Boxing and unboxing reduce performance.
Types based on Object are also late-bound, which means that accessing their members requires extra code at run time.
This also reduces performance.
Code Consolidation. The code in a generic type has to be defined only once. A set of type-specific versions of a type
must replicate the same code in each version, with the only difference being the specific data type for that version. With
generic types, the type-specific versions are all generated from the original generic type.
Code Reuse. Code that does not depend on a particular data type can be reused with various data types if it is generic.
You can often reuse it even with a data type that you did not originally predict.
IDE Support. When you use a constructed type declared from a generic type, the integrated development environment
(IDE) can give you more support while you are developing your code. For example, IntelliSense™ can show you the type-
specific options for an argument to a constructor or method.
Generic Algorithms. Abstract algorithms that are type-independent are good candidates for generic types. For example,
a generic procedure that sorts items using the IComparable interface can be used with any data type that implements
IComparable.
Constraints
Although the code in a generic type definition should be as type-independent as possible, you might need to require a certain
capability of any data type supplied to your generic type. For example, if you want to compare two items for the purpose of
sorting or collating, their data type must implement the IComparable interface. You can enforce this requirement by adding a
constraint to the type parameter.
Example of a Constraint
The following example shows a skeleton definition of a class with a constraint that requires the type argument to implement
IComparable.
VB
Public Class itemManager(Of t As IComparable)
' Insert code that defines class members.
End Class

If subsequent code attempts to construct a class from itemManager supplying a type that does not implement IComparable,
the compiler signals an error.
Types of Constraints
Your constraint can specify the following requirements in any combination:
The type argument must implement one or more interfaces
The type argument must be of the type of, or inherit from, at most one class
The type argument must expose a parameterless constructor accessible to the code that creates objects from it
The type argument must be a reference type, or it must be a value type
If you need to impose more than one requirement, you use a comma-separated constraint list inside braces ({ }). To require an
accessible constructor, you include the New (Visual Basic) keyword in the list. To require a reference type, you include the
Class (Visual Basic) keyword; to require a value type, you include the Structure (Visual Basic) keyword.
For more information on constraints, see Type List.
Example of Multiple Constraints
The following example shows a skeleton definition of a generic class with a constraint list on the type parameter. In the code
that creates an instance of this class, the type argument must implement both the IComparable and IDisposable interfaces, be
a reference type, and expose an accessible parameterless constructor.
VB
Public Class thisClass(Of t As {IComparable, IDisposable, Class, New})
' Insert code that defines class members.
End Class

Important Terms
Generic types introduce and use the following terms:
Generic Type. A definition of a class, structure, interface, procedure, or delegate for which you supply at least one data
type when you declare it.
Type Parameter. In a generic type definition, a placeholder for a data type you supply when you declare the type.
Type Argument. A specific data type that replaces a type parameter when you declare a constructed type from a generic
type.
Constraint. A condition on a type parameter that restricts the type argument you can supply for it. A constraint can
require that the type argument must implement a particular interface, be or inherit from a particular class, have an
accessible parameterless constructor, or be a reference type or a value type. You can combine these constraints, but you
can specify at most one class.
Constructed Type. A class, structure, interface, procedure, or delegate declared from a generic type by supplying type
arguments for its type parameters.

See Also
Tasks
Troubleshooting Data Types
Reference
Data Type Summary (Visual Basic)
Of
As
Object Data Type
Concepts
Data Types in Visual Basic
Type Characters
Value Types and Reference Types
Other Resources
Data Type Implementation
Type Conversions in Visual Basic
Visual Basic Language Concepts

How to: Define a Class That Can Provide Identical Functionality


on Different Data Types
You can define a class from which you can create objects that provide identical functionality on different data types. To do this,
you specify one or more type parameters in the definition. The class can then serve as a template for objects that use various
data types. A class defined in this way is called a generic class.
The advantage of defining a generic class is that you define it just once, and your code can use it to create many objects that
use a wide variety of data types. This results in better performance than defining the class with the Object type.
In addition to classes, you can also define and use generic structures, interfaces, procedures, and delegates.
To define a class with a type parameter
1. Define the class in the normal way.
2. Add (Of typeparameter) immediately after the class name to specify a type parameter.
3. If you have more than one type parameter, make a comma-separated list inside the parentheses. Do not repeat the Of
keyword.
4. If your code performs operations on a type parameter other than simple assignment, follow that type parameter with an
As clause to add one or more constraints. A constraint guarantees that the type supplied for that type parameter satisfies
a requirement such as the following:
Supports an operation, such as >, that your code performs
Supports a member, such as a method, that your code accesses
Exposes a parameterless constructor
If you do not specify any constraints, the only operations and members your code can use are those supported by the
Object Data Type. For more information, see Type List.
5. Identify every class member that is to be declared with a supplied type, and declare it As typeparameter. This applies to
internal storage, procedure parameters, and return values.
6. Be sure your code uses only operations and methods that are supported by any data type it can supply to itemType.
The following example defines a class that manages a very simple list. It holds the list in the internal array items, and the
using code can declare the data type of the list elements. A parameterized constructor allows the using code to set the
upper bound of items, and the default constructor sets this to 9 (for a total of 10 items).
VB
Public Class simpleList(Of itemType)
Private items() As itemType
Private top As Integer
Private nextp As Integer
Public Sub New()
Me.New(9)
End Sub
Public Sub New(ByVal t As Integer)
MyBase.New()
items = New itemType(t) {}
top = t
nextp = 0
End Sub
Public Sub add(ByVal i As itemType)
insert(i, nextp)
End Sub
Public Sub insert(ByVal i As itemType, ByVal p As Integer)
If p > nextp OrElse p < 0 Then
Throw New System.ArgumentOutOfRangeException("p", _
" less than 0 or beyond next available list position")
ElseIf nextp > top Then
Throw New System.ArgumentException("No room to insert at ", _
"p")
ElseIf p < nextp Then
For j As Integer = nextp To p + 1 Step -1
items(j) = items(j - 1)
Next j
End If
items(p) = i
nextp += 1
End Sub
Public Sub remove(ByVal p As Integer)
If p >= nextp OrElse p < 0 Then
Throw New System.ArgumentOutOfRangeException("p", _
" less than 0 or beyond last list item")
ElseIf nextp = 0 Then
Throw New System.ArgumentException("List empty; cannot remove ", _
"p")
ElseIf p < nextp - 1 Then
For j As Integer = p To nextp - 2
items(j) = items(j + 1)
Next j
End If
nextp -= 1
End Sub
Public ReadOnly Property listLength() As Integer
Get
Return nextp
End Get
End Property
Public ReadOnly Property listItem(ByVal p As Integer) As itemType
Get
If p >= nextp OrElse p < 0 Then
Throw New System.ArgumentOutOfRangeException("p", _
" less than 0 or beyond last list item")
End If
Return items(p)
End Get
End Property
End Class

You can declare a class from simpleList to hold a list of Integer values, another class to hold a list of String values, and
another to hold Date values. Except for the data type of the list members, objects created from all these classes behave
identically.
The type argument that the using code supplies to itemType can be an intrinsic type such as Boolean or Double, a
structure, an enumeration, or any type of class, including one that your application defines.
You can test the class simpleList with the following code.
VB
Public Sub useSimpleList()
Dim iList As New simpleList(Of Integer)(2)
Dim sList As New simpleList(Of String)(3)
Dim dList As New simpleList(Of Date)(2)
iList.add(10)
iList.add(20)
iList.add(30)
sList.add("First")
sList.add("extra")
sList.add("Second")
sList.add("Third")
sList.remove(1)
dList.add(#1/1/2003#)
dList.add(#3/3/2003#)
dList.insert(#2/2/2003#, 1)
Dim s As String = _
"Simple list of 3 Integer items (reported length " _
& CStr(iList.listLength) & "):" _
& vbCrLf & CStr(iList.listItem(0)) _
& vbCrLf & CStr(iList.listItem(1)) _
& vbCrLf & CStr(iList.listItem(2)) _
& vbCrLf _
& "Simple list of 4 - 1 String items (reported length " _
& CStr(sList.listLength) & "):" _
& vbCrLf & CStr(sList.listItem(0)) _
& vbCrLf & CStr(sList.listItem(1)) _
& vbCrLf & CStr(sList.listItem(2)) _
& vbCrLf _
& "Simple list of 2 + 1 Date items (reported length " _
& CStr(dList.listLength) & "):" _
& vbCrLf & CStr(dList.listItem(0)) _
& vbCrLf & CStr(dList.listItem(1)) _
& vbCrLf & CStr(dList.listItem(2))
MsgBox(s)
End Sub

See Also
Tasks
How to: Use a Generic Class
Reference
Of
Type List
Object Data Type
Concepts
Data Types in Visual Basic
Generic Types in Visual Basic
Common Language Specification
Visual Basic Language Concepts

How to: Use a Generic Class


A class that takes type parameters is called a generic class. If you are using a generic class, you can generate a constructed class
from it by supplying a type argument for each of these parameters. You can then declare a variable of the constructed class
type, and you can create an instance of the constructed class and assign it to that variable.
In addition to classes, you can also define and use generic structures, interfaces, procedures, and delegates.
The following procedure takes a generic class defined in the .NET Framework and creates an instance from it.
To use a class that takes a type parameter
1. At the beginning of your source file, include an Imports Statement to import the System.Collections.Generic namespace.
This allows you to refer to the System.Collections.Generic.Queue class without having to fully qualify it to differentiate it
from other queue classes such as System.Collections.Queue.
2. Create the object in the normal way, but add (Of type) immediately after the class name.
The following example uses the same class (System.Collections.Generic.Queue) to create two queue objects that hold
items of different data types. It adds items to the end of each queue and then removes and displays items from the front
of each queue.
VB
Public Sub usequeue()
Dim queueDouble As New System.Collections.Generic.Queue(Of Double)
Dim queueString As New System.Collections.Generic.Queue(Of String)
queueDouble.Enqueue(1.1)
queueDouble.Enqueue(2.2)
queueDouble.Enqueue(3.3)
queueDouble.Enqueue(4.4)
queueString.Enqueue("First string of three")
queueString.Enqueue("Second string of three")
queueString.Enqueue("Third string of three")
Dim s As String = "Queue of Double items (reported length " _
& CStr(queueDouble.Count) & "):"
For i As Integer = 1 To queueDouble.Count
s &= vbCrLf & CStr(queueDouble.Dequeue())
Next i
s &= vbCrLf & "Queue of String items (reported length " _
& CStr(queueString.Count) & "):"
For i As Integer = 1 To queueString.Count
s &= vbCrLf & queueString.Dequeue()
Next i
MsgBox(s)
End Sub

See Also
Tasks
How to: Define a Class That Can Provide Identical Functionality on Different Data Types
Reference
Of
Imports Statement
Concepts
Data Types in Visual Basic
Generic Types in Visual Basic
Common Language Specification
Visual Basic Language Concepts

Generic Procedures in Visual Basic


A generic procedure, also called a generic method, is a procedure defined with at least one type parameter. This allows the
calling code to tailor the data types to its requirements each time it calls the procedure.
A procedure is not generic simply by virtue of being defined inside a generic class or a generic structure. To be generic, the
procedure must take at least one type parameter, in addition to any normal parameters it might take. A generic class or
structure can contain nongeneric procedures, and a nongeneric class, structure, or module can contain generic procedures.
A generic procedure can use its type parameters in its normal parameter list, in its return type if it has one, and in its procedure
code.
Type Inference
You can call a generic procedure without supplying any type arguments at all. If you call it this way, the compiler attempts to
determine the appropriate data types to pass to the procedure's type arguments. This is called type inference. The following
code shows a call in which the compiler infers that it should pass type String to the type parameter t.
VB
Public Sub testSub(Of t)(ByVal arg As t)
End Sub
Public Sub callTestSub()
testSub("Use this string")
End Sub

If the compiler cannot infer the type arguments from the context of your call, it reports an error. One possible cause of such an
error is an array rank mismatch. For example, suppose you define a normal parameter as an array of a type parameter. If you
call the generic procedure supplying an array of a different rank (number of dimensions), the mismatch causes type inference
to fail. The following code shows a call in which a two-dimensional array is passed to a procedure that expects a one-
dimensional array.
Public Sub demoSub(Of t)(ByVal arg() As t)
End Sub
Public Sub callDemoSub()
Dim twoDimensions(,) As Integer
demoSub(twoDimensions)
End Sub

You can invoke type inference only by omitting all the type arguments. If you supply one type argument, you must supply
them all.
Type inference is supported only for generic procedures. You cannot invoke type inference on generic classes, structures,
interfaces, or delegates.
Example
The following example defines a generic Function procedure to find a particular element in an array. It defines one type
parameter and uses it to construct the two parameters in the parameter list.
VB
Public Function findElement(Of T As IComparable) _
(ByVal searchArray As T(), ByVal searchValue As T) As Integer
If searchArray.GetLength(0) > 0 Then
For i As Integer = 0 To searchArray.GetUpperBound(0)
If searchArray(i).CompareTo(searchValue) = 0 Then Return i
Next i
End If
Return -1
End Function
The preceding example requires the ability to compare searchValue against each element of searchArray. To guarantee this
ability, it constrains the type parameter T to implement the IComparable interface. The code uses the CompareTo method
instead of the = operator, because there is no guarantee that a type argument supplied for T supports the = operator.
You can test the findElement procedure with the following code.
VB
Public Sub tryFindElement()
Dim stringArray() As String = {"abc", "def", "xyz"}
Dim stringSearch As String = "abc"
Dim integerArray() As Integer = {7, 8, 9}
Dim integerSearch As Integer = 8
Dim dateArray() As Date = {#4/17/1969#, #9/20/1998#, #5/31/2004#}
Dim dateSearch As Date = Microsoft.VisualBasic.DateAndTime.Today
MsgBox(CStr(findElement(Of String)(stringArray, stringSearch)))
MsgBox(CStr(findElement(Of Integer)(integerArray, integerSearch)))
MsgBox(CStr(findElement(Of Date)(dateArray, dateSearch)))
End Sub

The preceding calls to MsgBox display "0", "1", and "-1" respectively.
See Also
Tasks
How to: Define a Class That Can Provide Identical Functionality on Different Data Types
How to: Use a Generic Class
Reference
Type List
Parameter List
Concepts
Generic Types in Visual Basic
Procedures in Visual Basic
Procedure Parameters and Arguments
Visual Basic Language Concepts

Value Types that Might Not Have a Defined Value


Sometimes you work with a value type that does not have a defined value in certain circumstances. For example, a field in a
database might need to distinguish between having been assigned a meaningful value and never having been assigned a
value. Value types can be extended to take either their normal values or a null value. Such an extension is called a nullable type.
Each nullable type is constructed from the generic Nullable structure. Consider a database that tracks work-related activities.
The following example constructs a nullable Boolean type and declares a variable of that type.

Dim ridesBusToWork As Nullable(Of Boolean)

The variable ridesBusToWork can hold a value of True, a value of False, or no value at all. Its initial default value is no value at
all, which in this case could mean that the information has not yet been obtained for this person. In contrast, False could mean
that the information has been obtained and the person does not ride the bus to work.
You can declare variables and properties with nullable types, and you can declare an array with elements of a nullable type.
You can declare procedures with nullable types as parameters, and you can return a nullable type from a Function procedure.
You cannot construct a nullable type on a reference type such as an array, a String, or a class. The underlying type must be a
value type. For more information, see Value Types and Reference Types.
Using a Nullable Type Variable
The most important members of a nullable type are its HasValue and Value properties. For a variable of a nullable type,
HasValue tells you whether the variable contains a defined value. If HasValue is True, you can read the value from Value.
Note that both HasValue and Value are ReadOnly properties.
Default Values
When you declare a variable with a nullable type, its HasValue property has a default value of False. This means that the
variable itself defaults to having no defined value, rather than the default value of its underlying value type. In the following
example, the variable numberOfChildren initially has no defined value, even though the default value of the Integer type is 0.

Dim numberOfChildren As Nullable(Of Integer)

A null value is useful to indicate an undefined or unknown value. If numberOfChildren had been declared as Integer, there
would be no value that could indicate that the information is not currently available.
Storing Values
You store a value in a variable or property of a nullable type in the normal way. The following example assigns a value to the
variable numberOfChildren declared in the preceding example.

numberOfChildren = 2

If a variable or property of a nullable type contains a defined value, you can cause it to revert to its initial state of not having a
value assigned. You do this by setting the variable or property to Nothing, as the following example shows.

numberOfChildren = Nothing

Note
Although you can assign Nothing to a variable of a nullable type, you cannot test it for Nothing. You must test its HasValu
e property for False.

Retrieving Values
To retrieve the value of a variable of a nullable type, you should first test its HasValue property to confirm that it has a value. If
you attempt to read the value when HasValue is False, Visual Basic throws an InvalidOperationException exception. The
following example shows the recommended way to read the variable numberOfChildren of the preceding examples.
If numberOfChildren.HasValue Then
MsgBox("There are " & CStr(numberOfChildren) & " children.")
Else
MsgBox("It is not known how many children there are.")
End If

Using Nullable Types with Data


A database is one of the most important places to use nullable types. Not all database objects currently support nullable types,
but the designer-generated table adapters do. See "TableAdapter Support for Nullable Types" in TableAdapter Overview.
See Also
Tasks
Troubleshooting Data Types
Reference
InvalidOperationException
Concepts
Data Types in Visual Basic
Value Types and Reference Types
TableAdapter Overview
Other Resources
Data Type Implementation
Visual Basic Language Concepts

Data Type Implementation


The Visual Basic data types can be classified according to whether a variable of a particular type stores its own data or a pointer
to the data. If it stores its own data it is a value type; if it holds a pointer to data elsewhere in memory it is a reference type. This
classification affects the way a data type is implemented.
In This Section
Value Types and Reference Types
Explains the difference between value and reference types, and which data types are which.
Data Types Are .NET Framework Types
Describes how Visual Basic data types are implemented in the underlying .NET Framework.
Related Sections
Data Types in Visual Basic
Introduces the Visual Basic data types and describes how to use them.
Data Type Summary (Visual Basic)
Lists the elementary data types supplied by Visual Basic.
Visual Basic Language Concepts

Value Types and Reference Types


A data type is a value type if it holds the data within its own memory allocation. A reference type contains a pointer to another
memory location that holds the data.
Value Types
Value types include the following:
All numeric data types
Boolean, Char, and Date
All structures, even if their members are reference types
Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong
Reference Types
Reference types include the following:
String
All arrays, even if their elements are value types
Class types, such as Form
Delegates
Elements That Are Not Types
The following programming elements do not qualify as types, because you cannot specify any of them as a data type for a
declared element:
Namespaces
Modules
Events
Properties and procedures
Variables, constants, and fields
Working with the Object Data Type
You can assign either a reference type or a value type to a variable of the Object data type. An Object variable always holds a
pointer to the data, never the data itself. However, if you assign a value type to an Object variable, it behaves as if it holds its
own data. For more information, see Object Data Type.
You can find out whether an Object variable is acting as a reference type or a value type by passing it to the IsReference
method on the Information class in the Microsoft.VisualBasic namespace.
Microsoft.VisualBasic.Information.IsReference(System.Object) returns True if the content of the Object variable
represents a reference type.
See Also
Reference
Object Data Type
Concepts
Data Types Are .NET Framework Types
Efficient Use of Data Types
Other Resources
Type Conversions in Visual Basic
Structures: Your Own Data Types
Visual Basic Language Concepts

Data Types Are .NET Framework Types


Every elementary data type in Visual Basic is supported by a structure or a class in the System namespace. The compiler uses
each data type keyword as an alias for the underlying structure or class. For example, declaring a variable with the reserved
word Byte is the same as declaring it with the fully qualified structure name System.Byte.
Additional Classes and Structures Are Available in the .NET Framework
The common language runtime (CLR) also supports structures and classes that Visual Basic does not supply. For example, the
System.Guid structure provides a globally unique identifier (GUID), and the System.TimeZone class supports a time zone. You
can use these types to declare variables and constants, and you can access the methods the .NET Framework implements on
these types. However, Visual Basic does not support operations or type conversions involving types it does not supply.
Value Types and Reference Types
In the .NET Framework, a structure is a value type and a class is a reference type. For this reason, value types such as Char and
Integer are implemented by .NET Framework structures, while reference types such as Object and String are supported by
.NET Framework classes. Note that every array is a reference type, even if its members are value types, and that every structure
is a value type, even if it has reference type members.
Since every reference type represents an underlying .NET Framework class, you must use the New (Visual Basic) keyword
when you initialize it. The following statement initializes an array.

Dim totals() As Single = New Single(8) {}

You can also use the New keyword to initialize a value type. This is particularly useful if the type has a constructor that takes
parameters. An example of this is the Decimal constructor, which builds a new Decimal value from the supplied parts.
Data Types Have Members
Because they are supported by .NET Framework structures and classes, Visual Basic data types have members. These members
include constructors, methods, properties, and fields. You can access the members (except the constructors) on a variable the
same way you access methods and properties on an object.
The following example uses the Year, Month, and Day properties and the DaysInMonth method of the System.DateTime
structure to determine how many days are remaining in the current month.

Dim current As Date = Now


Dim daysRemaining As Integer
daysRemaining = Date.DaysInMonth(current.Year, current.Month) - current.Day

Note that you must qualify a reference to a data type member with either the name of the type (Date) or the name of a variable
declared to be of that type (current).
Examples of Data Type Members
The following code prototypes illustrate some of the useful methods, properties, and fields on the data types.
<Char>.IsDigit() ' Returns True if character is a numeric digit.
<Char>.IsLower() ' Returns True if character is a lowercase letter.
<Date>.IsLeapYear() ' Returns True if current year is a leap year.
<Date>.ToUniversalTime() ' Returns local date/time converted to UTC.
<Double>.IsInfinity() ' Returns True if contents represent infinity.
<Double>.IsNaN() ' Returns True if contents are not a number (0/0).
<Long>.MaxValue ' Constant representing largest positive Int64 value.
<Object>.GetType() ' Returns Type object representing type of <Object>.
<Object>.GetType().GetTypeCode() ' Returns type code of <Object>.
<String>.Chars(<index>) ' Character at position <index> of <String>.
<String>.Length ' Number of characters currently in <String>.
All numeric types, including Byte and Char, expose the MaxValue and MinValue public fields, which can be very useful when
dealing with these types.
Equivalence of Data Type Members Is Not Assured
The .NET Framework also supplies a number of methods on data types that might appear to be equivalent to Visual Basic
functions and keywords. However, Visual Basic does not always use the .NET Framework methods to accomplish conversion or
other operations, and the results are not always identical.
For example, the ToSingle method performs the same type of action as the CSng keyword does on a Decimal expression. But
CSng is not guaranteed to use System.<data type>.ToSingle, and therefore the results are not guaranteed to be the same
under marginal or boundary conditions.
In general, you should use the Visual Basic programming elements because they are easier to use and make your code more
readable. In some cases you might need some additional functionality provided by a .NET Framework method. For an example
of this, see "Mod Operator Does Not Return Accurate Result" in Troubleshooting Data Types.
See Also
Reference
Boolean
Byte
Char
DateTime
Decimal
Double
Guid
TimeZone
Concepts
Value Types and Reference Types
Structures and Classes
Visual Basic Language Concepts

Type Conversions in Visual Basic


The process of changing a value from one data type to another type is called conversion. Conversions are either widening or
narrowing, depending on the data capacities of the types involved. They are also implicit or explicit, depending on the syntax in
the source code.
In This Section
Widening and Narrowing Conversions
Explains conversions classified by whether the destination type can hold the data.
Implicit and Explicit Conversions
Discusses conversions classified by whether Visual Basic performs them automatically.
Value Changes During Conversions
Describes how converting to another data type can change the value or data representation.
Conversions Between Strings and Other Types
Illustrates converting between strings and numeric, Boolean, or date/time values.
How to: Convert an Object to Another Type in Visual Basic
Shows how to convert an Object variable to any other data type.
Array Conversions
Steps you through the process of converting between arrays of different data types.
Related Sections
Data Types in Visual Basic
Introduces the Visual Basic data types and describes how to use them.
Data Type Summary (Visual Basic)
Lists the elementary data types supplied by Visual Basic.
Troubleshooting Data Types
Discusses some common problems that can arise when working with data types.
Visual Basic Language Concepts

Widening and Narrowing Conversions


An important consideration with a type conversion is whether the result of the conversion is within the range of the destination
data type. A widening conversion changes a value to a data type that can accommodate any possible value of the original data.
A narrowing conversion changes a value to a data type that might not be able to hold some of the possible values.
Widening Conversions
The following table shows the standard widening conversions.
Data type Widens to data types 1
SByte SByte, Short, Integer, Long, Decimal, Single, Double

Byte Byte, Short, UShort, Integer, UInteger, Long, ULong, Decimal, Single, Double

Short Short, Integer, Long, Decimal, Single, Double

UShort UShort, Integer, UInteger, Long, ULong, Decimal, Single, Double

Integer Integer, Long, Decimal, Single, Double2

UInteger UInteger, Long, ULong, Decimal, Single, Double 2

Long Long, Decimal, Single, Double 2

ULong ULong, Decimal, Single, Double 2

Decimal Decimal, Single, Double 2

Single Single, Double

Double Double

Any enumerated type (Enum) Its underlying integral type and any type to which the underlying type widens

Char Char, String

Char array Char array, String

Any type Object

Any derived type Any base type from which it is derived 3

Any type Any interface it implements

Nothing Any data type or object type

1 By definition, every data type widens to itself.

2 Conversions from Integer, UInteger, Long, ULong, or Decimal to Single or Double might result in loss of precision, but
never in loss of magnitude. In this sense they do not incur information loss.
3 It might seem surprising that a conversion from a derived type to one of its base types is widening. The justification is that
the derived type contains all the members of the base type, so it qualifies as an instance of the base type. In the opposite
direction, the base type does not contain any new members defined by the derived type.
Widening conversions always succeed at run time and never incur data loss. You can always perform them implicitly, whether
the Option Strict Statement sets the type checking switch to On or to Off.
Narrowing Conversions
The standard narrowing conversions include the following:
The reverse directions of the widening conversions in the preceding table (except that every type widens to itself)
Conversions in either direction between Boolean and any numeric type
Conversions from any numeric type to any enumerated type (Enum)
Conversions in either direction between String and any numeric type, Boolean, or Date
Conversions from a data type or object type to a type derived from it
Narrowing conversions do not always succeed at run time, and can fail or incur data loss. An error occurs if the destination
data type cannot receive the value being converted. For example, a numeric conversion can result in an overflow. The compiler
does not allow you to perform narrowing conversions implicitly unless the Option Strict Statement sets the type checking
switch to Off.
When to Use Narrowing Conversions
You use a narrowing conversion when you know the source value can be converted to the destination data type without error
or data loss. For example, if you have a String that you know contains either "True" or "False", you can use the CBool keyword
to convert it to Boolean.
Exceptions During Conversion
Because widening conversions always succeed, they do not throw exceptions. Narrowing conversions, when they fail, most
commonly throw the following exceptions:
InvalidCastException — if no conversion is defined between the two types
OverflowException — (integral types only) if the converted value is too large for the target type
If a class or structure defines a CType Function to serve as a conversion operator to or from that class or structure, that CType
can throw any exception it deems appropriate. In addition, that CType might call Visual Basic functions or .NET Framework
methods, which in turn could throw a variety of exceptions.
See Also
Tasks
How to: Convert an Object to Another Type in Visual Basic
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Concepts
Data Types in Visual Basic
Implicit and Explicit Conversions
Value Changes During Conversions
Conversions Between Strings and Other Types
Array Conversions
Typeless Programming in Visual Basic
Other Resources
Type Conversions in Visual Basic
Visual Basic Language Concepts

Implicit and Explicit Conversions


An implicit conversion does not require any special syntax in the source code. In the following example, Visual Basic implicitly
converts the value of k to a single-precision floating-point value before assigning it to q.

Dim k As Integer
Dim q As Double
' Integer widens to Double, so you can do this with Option Strict On.
k = 432
q = K

An explicit conversion uses a type conversion keyword. Visual Basic provides several such keywords, which coerce an
expression in parentheses to the desired data type. These keywords act like functions, but the compiler generates the code
inline, so execution is slightly faster than with a function call.
In the following extension of the preceding example, the CInt keyword converts the value of q back to an integer before
assigning it to k.

' q had been assigned the value 432 from k.


q = Math.Sqrt(q)
k = CInt(q)
' k now has the value 21 (rounded square root of 432).

Conversion Keywords
The following table shows the available conversion keywords.
Type conversi Converts an expression to da Allowable data types of expression to be converted
on keyword ta type
CBool Boolean Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), String, Ob
ject

CByte Byte Data Type (Visual Basic) Any numeric type (including SByte and enumerated types), Boolean, String,
Object

CChar Char Data Type (Visual Basic) String, Object

CDate Date Data Type (Visual Basic) String, Object

CDbl Double Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object

CDec Decimal Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object

CInt Integer Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object

CLng Long Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object

CObj Object Data Type Any type

CSByte SByte Data Type (Visual Basic) Any numeric type (including Byte and enumerated types), Boolean, String,
Object
CShort Short Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object

CSng Single Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object

CStr String Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
Char, Char array, Date, Object

CType Type specified following the co When converting to an elementary data type (including an array of an eleme
mma (,) ntary type), the same types as allowed for the corresponding conversion key
word
When converting to a composite data type, the interfaces it implements and t
he classes from which it inherits
When converting to a class or structure on which you have overloaded CTyp
e, that class or structure

CUInt UInteger Data Type Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object

CULng ULong Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object

CUShort UShort Data Type (Visual Basic) Any numeric type (including Byte, SByte, and enumerated types), Boolean,
String, Object

The CType Function


The CType Function operates on two arguments. The first is the expression to be converted, and the second is the destination
data type or object class. Note that the first argument must be an expression, not a type.
CType is an inline function, meaning the compiled code makes the conversion, often without generating a function call. This
improves performance.
For a comparison of CType with the other type conversion keywords, see DirectCast and TryCast.
Elementary Types
The following example demonstrates the use of CType.

k = CType(q, Integer)
' The following statement coerces w to the specific object class Label.
f = CType(w, Label)

Composite Types
You can use CType to convert values to composite data types as well as to elementary types. You can also use it to coerce an
object class to the type of one of its interfaces, as in the following example.

' Assume class cZone implements interface iZone.


Dim h As Object
' The first argument to CType must be an expression, not a type.
Dim cZ As cZone
' The following statement coerces a cZone object to its interface iZone.
h = CType(cZ, iZone)

Array Types
CType can also convert array data types, as in the following example.
Dim v() As classV
Dim obArray() As Object
' Assume some object array has been assigned to obArray.
' Check for run-time type compatibility.
If TypeOf obArray Is classV()
' obArray can be converted to classV.
v = CType(obArray, classV())
End If

For more information and an example, see Array Conversions.


Types Defining CType
You can define CType on a class or structure you have defined. This allows you to convert values to and from the type of your
class or structure. For more information and an example, see How to: Define a Conversion Operator.
Note
Values used with a conversion keyword must be valid for the destination data type, or an error occurs. For example, if you att
empt to convert a Long to an Integer, the value of the Long must be within the valid range for the Integer data type.

Caution
Specifying CType to convert from one class type to another fails at run time if the source type does not derive from the desti
nation type. Such a failure throws an InvalidCastException exception.

However, if one of the types is a structure or class you have defined, and if you have defined CType on that structure or class, a
conversion can succeed if it satisfies the requirements of your CType. See How to: Define a Conversion Operator.
Performing an explicit conversion is also known as casting an expression to a given data type or object class.
See Also
Tasks
How to: Convert an Object to Another Type in Visual Basic
Troubleshooting Data Types
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Concepts
Value Changes During Conversions
Conversions Between Strings and Other Types
Typeless Programming in Visual Basic
Other Resources
Type Conversions in Visual Basic
Structures: Your Own Data Types
Visual Basic Language Concepts

Value Changes During Conversions


A conversion from a value type stores a copy of the source value in the destination of the conversion. However, this copy is not
an exact image of the source value. The destination data type stores values differently, and even the value being represented
might change, depending on the kind of conversion being performed.
Changes During Widening and Narrowing Conversions
Narrowing conversions change the destination copy of the source value, with potential information loss. For example, a
fractional value is rounded when converted to an integral type, and a numeric type being converted to Boolean is reduced to
either True or False.
Widening conversions preserve the source value but can change its representation. This happens if you convert from an
integral type to Decimal, or from Char to String.
The original source value is not changed as a result of a conversion.
Changes During Reference Type Conversions
A conversion from a reference type copies only the pointer to the value. The value itself is neither copied nor changed in any
way. The only thing that can change is the data type of the variable holding the pointer. In the following example, the data type
is converted from the derived class to its base class, but the object that both variables now point to is unchanged.

' Assume class cSquare inherits from class cShape.


Dim shape As cShape
Dim square As cSquare = New cSquare
' The following statement performs a widening
' conversion from a derived class to its base class.
shape = square

See Also
Tasks
How to: Convert an Object to Another Type in Visual Basic
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Concepts
Widening and Narrowing Conversions
Implicit and Explicit Conversions
Conversions Between Strings and Other Types
Array Conversions
Typeless Programming in Visual Basic
Other Resources
Type Conversions in Visual Basic
Structures: Your Own Data Types
Visual Basic Language Concepts

Conversions Between Strings and Other Types


You can convert a numeric, Boolean, or date/time value to a String. You can also convert in the reverse direction — from a
string value to numeric, Boolean, or Date — provided the contents of the string can be interpreted as a valid value of the
destination data type. If they cannot, a run-time error occurs.
The conversions for all these assignments, in either direction, are narrowing conversions. You should use the type conversion
keywords (CBool, CByte, CDate, CDbl, CDec, CInt, CLng, CSByte, CShort, CSng, CStr, CUInt, CULng, CUShort, and CType).
The Format Function and Val Function give you additional control over conversions between strings and numbers.
If you have defined a class or structure, you can define type conversion operators between String and the type of your class or
structure. For more information, see How to: Define a Conversion Operator.
Conversion of Numbers to Strings
You can use the Format function to convert a number to a formatted string, which can include not only the appropriate digits
but also formatting symbols such as a currency sign (such as $), thousands separators or digit grouping symbols (such as ,),
and a decimal separator (such as .). Format automatically uses the appropriate symbols according to the Regional Options
settings specified in the Windows Control Panel.
Note that the concatenation (&) operator can convert a number to a string implicitly, as the following example shows.

' The following statement converts count to a String value.


Str = "The total count is " & count

Conversion of Strings to Numbers


You can use the Val function to explicitly convert the digits in a string to a number. Val reads the string until it encounters a
character other than a digit, space, tab, line feed, or period. The sequences "&O" and "&H" alter the base of the number system
and terminate the scanning. Until it stops reading, Val converts all appropriate characters to a numeric value. For example, the
following statement returns the value 141.825.
Val(" 14 1.825 miles")

When Visual Basic converts a string to a numeric value, it uses the Regional Options settings specified in the Windows
Control Panel to interpret the thousands separator, decimal separator, and currency symbol. This means that a conversion
might succeed under one setting but not another. For example, "$14.20" is acceptable in the English (United States) locale but
not in any French locale.
See Also
Tasks
How to: Convert an Object to Another Type in Visual Basic
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Concepts
Widening and Narrowing Conversions
Implicit and Explicit Conversions
Value Changes During Conversions
Array Conversions
Introduction to International Applications Based on the .NET Framework
Other Resources
Type Conversions in Visual Basic
Visual Basic Language Concepts

How to: Convert an Object to Another Type in Visual Basic


You convert an Object variable to another data type by using a conversion keyword such as CType Function.
Example
The following example converts an Object variable to an Integer and a String.

Public Sub objectConversion(ByVal anObject As Object)


Dim anInteger As Integer
Dim aString As String
anInteger = CType(anObject, Integer)
aString = CType(anObject, String)
End Sub

If you know that the contents of an Object variable are of a particular data type, it is better to convert the variable to that data
type. If you continue to use the Object variable, you incur either boxing and unboxing (for a value type) or late binding (for a
reference type). These operations all take extra execution time and make your performance slower.
Compiling the Code
This example requires:
A reference to the System namespace.
See Also
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Object
Concepts
Widening and Narrowing Conversions
Implicit and Explicit Conversions
Value Changes During Conversions
Conversions Between Strings and Other Types
Array Conversions
Typeless Programming in Visual Basic
Other Resources
Type Conversions in Visual Basic
Structures: Your Own Data Types
Visual Basic Language Concepts

Array Conversions
You can convert an array type to a different array type provided you meet the following conditions:
Equal Rank. The ranks of the two arrays must be the same, that is, they must have the same number of dimensions.
However, the lengths of the respective dimensions do not need to be the same.
Element Data Type. The data types of the elements of both arrays must be reference types. You cannot convert an
Integer array to a Long array, or even to an Object array, because at least one value type is involved. For more
information, see Value Types and Reference Types.
Convertibility. A conversion, either widening or narrowing, must be possible between the element types of the two
arrays. An example that fails this requirement is an attempted conversion between a String array and an array of a class
derived from System.Attribute. These two types have nothing in common, and no conversion of any kind exists between
them.
A conversion of one array type to another is widening or narrowing depending on whether the conversion of the respective
elements is widening or narrowing. For more information, see Widening and Narrowing Conversions.
Conversion to an Object Array
When you declare an Object array without initializing it, its element type is Object as long as it remains uninitialized. When
you set it to an array of a specific class, it takes on the type of that class. However, its underlying type is still Object, and you
can subsequently set it to another array of an unrelated class. Since all classes derive from Object, you can change the array's
element type from any class to any other class.
In the following example, no conversion exists between types student and String, but both derive from Object, so all
assignments are valid.

' Assume student has already been defined as a class.


Dim testArray() As Object
' testArray is still an Object array at this point.
Dim names() As String = New String(3) {"Name0", "Name1", "Name2", "Name3"}
testArray = New student(3) {}
' testArray is now of type student().
testArray = names
' testArray is now a String array.

Underlying Type of an Array


If you originally declare an array with a specific class, its underlying element type is that class. If you subsequently set it to an
array of another class, there must be a conversion between the two classes.
In the following example, students is a student array. Since no conversion exists between String and student, the last
statement fails.

Dim students() As student


Dim names() As String = New String(3) {"Name0", "Name1", "Name2", "Name3"}
students = New Student(3) {}
' The following statement fails at compile time.
students = names

See Also
Tasks
How to: Convert an Object to Another Type in Visual Basic
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Concepts
Data Types in Visual Basic
Implicit and Explicit Conversions
Value Changes During Conversions
Conversions Between Strings and Other Types
Typeless Programming in Visual Basic
Other Resources
Type Conversions in Visual Basic
Arrays in Visual Basic
Visual Basic Language Concepts

Structures: Your Own Data Types


A structure is a generalization of the user-defined type (UDT) supported by previous versions of Visual Basic. In addition to
fields, structures can expose properties, methods, and events. A structure can implement one or more interfaces, and you can
declare individual access levels for each field.
You can combine data items of different types to create a structure. A structure associates one or more elements with each
other and with the structure itself. When you declare a structure, it becomes a composite data type, and you can declare
variables of that type.
Structures are useful when you want a single variable to hold several related pieces of information. For example, you might
want to keep an employee's name, telephone extension, and salary together. You could use several variables for this
information, or you could define a structure and use it for a single employee variable. The advantage of the structure becomes
apparent when you have many employees and therefore many instances of the variable.
In This Section
How to: Declare a Structure
Shows how to declare a structure and its elements.
Structure Variables
Covers assigning a structure to a variable and accessing its elements.
Structures and Other Programming Elements
Summarizes how structures interact with arrays, objects, procedures, and each other.
Structures and Classes
Describes the similarities and differences between structures and classes.
Related Sections
Data Types in Visual Basic
Introduces the Visual Basic data types and describes how to use them.
Data Type Summary (Visual Basic)
Lists the elementary data types supplied by Visual Basic.
Visual Basic Language Concepts

How to: Declare a Structure


You begin a structure declaration with the Structure Statement, and you end it with the End Structure statement. Between
these two statements you must declare at least one element. The elements can be of any data type, but at least one must be
either a nonshared variable or a nonshared, noncustom event.
You cannot initialize any of the structure elements in the structure declaration. When you declare a variable to be of a structure
type, you assign values to the elements by accessing them through the variable.
For a discussion of the differences between structures and classes, see Structures and Classes.
For demonstration purposes, consider a situation where you want to keep track of an employee's name, telephone extension,
and salary. A structure allows you to do this in a single variable.
To declare a structure
1. Create the beginning and ending statements for the structure.
You can specify the access level of a structure using the Public (Visual Basic), Protected (Visual Basic),
Friend (Visual Basic), or Private (Visual Basic) keyword, or you can let it default to Public.

Private Structure employee


End Structure

2. Add elements to the body of the structure.


A structure must have at least one element. You must declare every element and specify an access level for it. If you use
the Dim Statement (Visual Basic) without any keywords, the accessibility defaults to Public.

Private Structure employee


Public givenName As String
Public familyName As String
Public phoneExtension As Long
Private salary As Decimal
Public Sub giveRaise(raise As Double)
salary *= raise
End Sub
Public Event salaryReviewTime()
End Structure

The salary field in the preceding example is Private, which means it is inaccessible outside the structure, even from the
containing class. However, the giveRaise procedure is Public, so it can be called from outside the structure. Similarly,
you can raise the salaryReviewTime event from outside the structure.
In addition to variables, Sub procedures, and events, you can also define constants, Function procedures, and properties
in a structure. You can designate at most one property as the default property, provided it takes at least one argument.
You can handle an event with a Shared (Visual Basic) Sub procedure. For more information, see
How to: Declare and Call a Default Property in Visual Basic.
See Also
Tasks
Troubleshooting Data Types
Reference
User-Defined Data Type
Concepts
Data Types in Visual Basic
Composite Data Types
Structure Variables
Structures and Other Programming Elements
Structures and Classes
Other Resources
Elementary Data Types
Data Type Implementation
Structures: Your Own Data Types
Visual Basic Language Concepts

Structure Variables
Once you have created a structure, you can declare procedure-level and module-level variables as that type. For example, you
can create a structure that records information about a computer system. The following example demonstrates this.

Public Structure systemInfo


Public cPU As String
Public memory As Long
Public purchaseDate As Date
End Structure

You can now declare variables of that type. The following declaration illustrates this.

Dim mySystem, yourSystem As systemInfo

Note
In classes and modules, structures declared using the Dim Statement (Visual Basic) default to public access. If you intend a str
ucture to be private, make sure you declare it using the Private (Visual Basic) keyword.

Access to Structure Values


To assign and retrieve values from the elements of a structure variable, you use the same syntax as you use to set and get
properties on an object. You place the member access operator (.) between the structure variable name and the element name.
The following example accesses elements of the variables previously declared as type systemInfo.

mySystem.cPU = "486"
Dim tooOld As Boolean
If yourSystem.purchaseDate < #1/1/1992# Then tooOld = True

Assigning Structure Variables


You can also assign one variable to another if both are of the same structure type. This copies all the elements of one structure
to the corresponding elements in the other. The following declaration illustrates this.

yourSystem = mySystem

If a structure element is a reference type, such as a String, Object, or array, the pointer to the data is copied. In the previous
example, if systemInfo had included an object variable, then the preceding example would have copied the pointer from
mySystem to yourSystem, and a change to the object's data through one structure would be in effect when accessed through the
other structure.
See Also
Tasks
Troubleshooting Data Types
How to: Declare a Structure
Reference
Structure Statement
Concepts
Data Types in Visual Basic
Composite Data Types
Structures and Other Programming Elements
Structures and Classes
Other Resources
Elementary Data Types
Data Type Implementation
Structures: Your Own Data Types
Visual Basic Language Concepts

Structures and Other Programming Elements


You can use structures in conjunction with arrays, objects, and procedures, as well as with each other. The interactions use the
same syntax as these elements use individually.
Note
You cannot initialize any of the structure elements in the structure declaration. You can assign values only to elements of a va
riable that has been declared to be of a structure type.

Structures and Arrays


A structure can contain an array as one or more of its elements. The following example illustrates this.

Public Structure systemInfo


Public cPU As String
Public memory As Long
Public diskDrives() As String
Public purchaseDate As Date
End Structure

You access the values of an array within a structure the same way you access a property on an object. The following example
illustrates this.

Dim mySystem As systemInfo


ReDim mySystem.diskDrives(3)
mySystem.diskDrives(0) = "1.44 MB"

You can also declare an array of structures. The following example illustrates this.

Dim allSystems(100) As systemInfo

You follow the same rules to access the components of this data architecture. The following example illustrates this.

ReDim allSystems(5).diskDrives(3)
allSystems(5).CPU = "386SX"
allSystems(5).diskDrives(2) = "100M SCSI"

Structures and Objects


A structure can contain an object as one or more of its elements. The following example illustrates this.

Protected Structure userInput


Public userName As String
Public inputForm As System.Windows.Forms.Form
Public userFileNumber As Integer
End Structure

You should use a specific object class in such a declaration, rather than Object.
Structures and Procedures
You can pass a structure as a procedure argument. The following example illustrates this.

Public currentCPUName As String = "700MHz Pentium compatible"


Public currentMemorySize As Long = 256
Public Sub fillSystem(ByRef someSystem As systemInfo)
someSystem.cPU = currentCPUName
someSystem.memory = currentMemorySize
someSystem.purchaseDate = Now
End Sub

The preceding example passes the structure by reference, which allows the procedure to modify its elements so that the
changes take effect in the calling code. If you want to protect a structure against such modification, pass it by value.
You can also return a structure from a Function procedure. The following example illustrates this.

Dim allSystems(100) As systemInfo


Function findByDate(ByVal searchDate As Date) As systemInfo
Dim i As Integer
For i = 1 To 100
If allSystems(i).purchaseDate = searchDate Then Return allSystems(i)
Next i
' Process error: system with desired purchase date not found.
End Function

Structures Within Structures


Structures can contain other structures. The following example illustrates this.

Public Structure driveInfo


Public type As String
Public size As Long
End Structure
Public Structure systemInfo
Public cPU As String
Public memory As Long
Public diskDrives() As driveInfo
Public purchaseDate As Date
End Structure
Dim allSystems(100) As systemInfo
ReDim allSystems(1).diskDrives(3)
allSystems(1).diskDrives(0).type = "Floppy"

You can also use this technique to encapsulate a structure defined in one module within a structure defined in a different
module.
Structures can contain other structures to an arbitrary depth.
See Also
Tasks
Troubleshooting Data Types
How to: Declare a Structure
Reference
Structure Statement
Concepts
Data Types in Visual Basic
Composite Data Types
Structure Variables
Structures and Classes
Other Resources
Elementary Data Types
Data Type Implementation
Structures: Your Own Data Types
Visual Basic Language Concepts

Structures and Classes


Visual Basic unifies the syntax for structures and classes, with the result that both entities support most of the same features.
However, there are also important differences between structures and classes.
Classes have the advantage of being reference types — passing a reference is more efficient than passing a structure variable
with all its data. On the other hand, structures do not require allocation of memory on the global heap.
Because you cannot inherit from a structure, structures should be used only for objects that do not need to be extended. Use
structures when the object you wish to create has a small instance size, and take into account the performance characteristics
of classes versus structures.
Similarities
Structures and classes are similar in the following respects:
Both are container types, meaning that they contain other types as members.
Both have members, which can include constructors, methods, properties, fields, constants, enumerations, events, and
event handlers. However, do not confuse these members with the declared elements of a structure.
Members of both can have individualized access levels. For example, one member can be declared Public and another
Private.
Both can implement interfaces.
Both can have shared constructors, with or without parameters.
Both can expose a default property, provided that property takes at least one parameter.
Both can declare and raise events, and both can declare delegates.
Differences
Structures and classes differ in the following particulars:
Structures are value types; classes are reference types. A variable of a structure type contains the structure's data, rather
than containing a reference to the data as a class type does.
Structures use stack allocation; classes use heap allocation.
All structure elements are Public by default; class variables and constants are Private by default, while other class
members are Public by default. This behavior for class members provides compatibility with the Visual Basic 6.0 system
of defaults.
A structure must have at least one nonshared variable or nonshared, noncustom event element; a class can be
completely empty.
Structure elements cannot be declared as Protected; class members can.
A structure procedure can handle events only if it is a Shared (Visual Basic) Sub procedure, and only by means of the
AddHandler Statement; any class procedure can handle events, using either the Handles keyword or the AddHandler
statement. For more information, see Events and Event Handlers.
Structure variable declarations cannot specify initializers or initial sizes for arrays; class variable declarations can.
Structures implicitly inherit from the System.ValueType class and cannot inherit from any other type; classes can inherit
from any class or classes other than System.ValueType.
Structures are not inheritable; classes are.
Structures are never terminated, so the common language runtime (CLR) never calls the Finalize method on any
structure; classes are terminated by the garbage collector (GC), which calls Finalize on a class when it detects there are
no active references remaining.
A structure does not require a constructor; a class does.
Structures can have nonshared constructors only if they take parameters; classes can have them with or without
parameters.
Every structure has an implicit public constructor without parameters. This constructor initializes all the structure's data
elements to their default values. You cannot redefine this behavior.
Instances and Variables
Because structures are value types, each structure variable is permanently bound to an individual structure instance. But
classes are reference types, and an object variable can refer to various class instances at different times. This distinction affects
your usage of structures and classes in the following ways:
Initialization. A structure variable implicitly includes an initialization of the elements using the structure's parameterless
constructor. Therefore, Dim s As struct1 is equivalent to Dim s As struct1 = New struct1().
Assigning Variables. When you assign one structure variable to another, or pass a structure instance to a procedure
argument, the current values of all the variable elements are copied to the new structure. When you assign one object
variable to another, or pass an object variable to a procedure, only the reference pointer is copied.
Assigning Nothing. You can assign the value Nothing (Visual Basic) to a structure variable, but the instance continues
to be associated with the variable. You can still call its methods and access its data elements, although variable elements
are reinitialized by the assignment.
In contrast, if you set an object variable to Nothing, you dissociate it from any class instance, and you cannot access any
members through the variable until you assign another instance to it.
Multiple Instances. An object variable can have different class instances assigned to it at different times, and several
object variables can refer to the same class instance at the same time. Changes you make to the values of class members
affect those members when accessed through another variable pointing to the same instance.
Structure elements, however, are isolated within their own instance. Changes to their values are not reflected in any other
structure variables, even in other instances of the same Structure declaration.
Equality. Equality testing of two structures must be performed with an element-by-element test. Two object variables
can be compared using the Equals method. Equals indicates whether the two variables point to the same instance.

See Also
Tasks
Troubleshooting Data Types
Concepts
Data Types in Visual Basic
Composite Data Types
Structures and Other Programming Elements
Value Types and Reference Types
Other Resources
Data Type Implementation
Structures: Your Own Data Types
Understanding Classes
Visual Basic Language Concepts

Typeless Programming in Visual Basic


The Visual Basic compiler is capable of enforcing two rules that affect your source code:
Every local variable must appear in a declaration statement before being used in any other kind of statement. This rule is
enforced by default.
Every narrowing type conversion must be specified with a type conversion keyword. This rule is not enforced by default.
Compiler Options that Change the Rules
You can change either or both of these rules by resetting corresponding compiler options. If you relax the type-conversion rule,
the compiler operates under permissive type semantics, which allows you to make narrowing conversions without conversion
keywords. For more information, see Type Checking in Visual Basic.
If you relax the variable-declaration rule, you can then use typeless programming, which permits you to refer to variables
without first declaring them. For more information, see Implicit and Explicit Declaration.
Typeless programming is not usually recommended, because it can lead to subtle execution errors involving data types.
However, you might find it useful in some circumstances, such as porting an old application that did not declare variables.
See Also
Tasks
Troubleshooting Data Types
Reference
Option Explicit Statement (Visual Basic)
Option Strict Statement
Concepts
Data Types in Visual Basic
Type Characters
Composite Data Types
Object as the Universal Data Type
Efficient Use of Data Types
Other Resources
Elementary Data Types
Type Conversions in Visual Basic
Visual Basic Language Concepts

Implicit and Explicit Declaration


By default, the Visual Basic compiler enforces explicit declaration, which requires that you declare every variable before you
use it. You can remove this requirement and permit implicit declaration.
Visual Basic provides a switch that controls explicit declaration. By default, this switch is set to On, and the compiler enforces
explicit declaration. If you turn this switch Off, you can use variables without declaring them.
Explicit Declaration Switch. You can set the explicit declaration switch On or Off in any of the following ways:
Set the appropriate project property in the integrated development environment (IDE). Choose <Projectname>
Properties from the Project menu, then choose the Compile tab. You can set the default values for Option explicit,
Option strict, and Option compare.
Specify the /optionexplicit command-line compiler option.
Include the Option Explicit Statement (Visual Basic) at the beginning of your code.
If you use the Option Explicit statement, that setting overrides both the project property and compiler option settings, but
only for the source code file in which it appears.
Performance Advantage. Setting Option Explicit to On has the advantage of forcing type inference to be made at compile
time instead of run time. This improves performance.
Implicit Declaration
If you set Option Explicit to Off, you can implicitly declare a variable by simply using it in your code. The compiler assigns the
Object Data Type to all implicitly declared variables. However, your application is more efficient if you declare all your variables
explicitly and with a specific data type. This reduces the incidence of naming-conflict errors and spelling mistakes. It also allows
the compiler to detect potential run-time errors such as assigning an Integer to a Short.
Potential Errors
Unintended New Variables
You can write a procedure in which you do not declare a local variable. The following example illustrates this.

Function safeSqrt(num)
' Make sure num is positive for square root.
tempVal = Math.Abs(num)
Return Math.Sqrt(tempVal)
End Function

Visual Basic automatically creates tempVal as a local variable, which you can use as if you had declared it explicitly. While this is
convenient, it can lead to subtle errors in your code if you misspell a variable name. Suppose you had written the procedure in
the preceding example as follows:

Function safeSqrt(num)
' Make sure num is positive for square root.
tempVal = Math.Abs(num)
Return Math.Sqrt(temVal)
End Function

At first glance, this code looks the same. But because the tempVal variable is misspelled as the argument to Sqrt, the compiler
creates an additional local variable called temVal, which is never assigned a value, and your function always returns zero.
Unintended Existing Element Reference
When Visual Basic encounters a new name, it cannot determine whether you meant to declare a new variable implicitly, or
whether you misspelled an existing variable name. Therefore it attempts to create a new variable with that name. There might
be a variable or other programming element already defined with that name, and your code would use that definition
unintentionally.
You can avoid problems with misnamed variables by using explicit declaration.
Explicit Declaration
Had explicit declaration been in effect for the source file containing the safeSqrt procedure in the preceding example, Visual
Basic would have recognized tempVal and temVal as undeclared variables and generated errors for both of them. As a result,
you would then explicitly declare tempVal. The following example illustrates this.

Function safeSqrt(ByVal num As Double) As Double


' Make sure num is positive for square root.
Dim tempVal As Double = Math.Abs(num)
Return Math.Sqrt(temVal)
End Function

With this revised code, you would understand the problem immediately because Visual Basic would display an error message
for the incorrectly spelled temVal. Because explicit declaration helps you catch these kinds of errors, it is recommended that
you use it with all your code.
Note
The Option Explicit statement operates on a file-by-file basis. It must be at the beginning of every source code file in which
you want to control the enforcement of explicit variable declaration.

See Also
Tasks
How to: Modify Project Properties and Configuration Settings
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Concepts
Typeless Programming in Visual Basic
Type Checking in Visual Basic
Object as the Universal Data Type
Efficient Use of Data Types
Variables in Visual Basic
Visual Basic Naming Conventions
Visual Basic Language Concepts

Type Checking in Visual Basic


When converting between data types, the Visual Basic compiler can operate under strict or permissive type semantics. If strict
type semantics are in effect, only widening conversions are permitted implicitly, and narrowing conversions must be explicit.
Under permissive type semantics, you can attempt all widening and narrowing conversions implicitly. Type semantics apply to
conversions between all data types, including object types.
Ways to Set the Type Checking Option
Visual Basic provides a switch that controls type checking. By default, this switch is Off, and the compiler allows implicit
narrowing conversions. If you turn the switch On, the compiler enforces strict type semantics.
Type Checking Switch
You can set the type checking switch On or Off in any of the following ways:
Set the appropriate project property in the Properties window of the integrated development environment (IDE)
Specify the /optionstrict command-line compiler option
Include the Option Strict statement at the beginning of your code
If you use the Option Strict statement, that setting overrides both the project property and compiler option settings, but only
for the source code file in which it appears. For more information, see Option Strict Statement.
Performance Advantage
Setting Option Strict to On has the advantage of forcing early binding. This improves performance.
See Also
Tasks
How to: Modify Project Properties and Configuration Settings
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Concepts
Data Types in Visual Basic
Typeless Programming in Visual Basic
Implicit and Explicit Declaration
Object as the Universal Data Type
Efficient Use of Data Types
Widening and Narrowing Conversions
Implicit and Explicit Conversions
Visual Basic Language Concepts

Object as the Universal Data Type


The Object Data Type is the root type in the .NET Framework and in Visual Basic. This means that all other data types and object
types are derived from it, either directly or ultimately. It also means that any other data type, whether elementary or composite,
can be converted to Object.
Loose Typing
You can use Object as the universal data type. This is called loose typing. The following example illustrates this flexibility.

Dim v As Object
v = "17"
' v contains the 2-character String value "17".
v = v - 15
' v now contains the Integer value 2.
v = "H" & v
' v now contains the 2-character String value "H2".

While you can perform such operations on Object variables without much concern for the kind of data they contain, you must
avoid the following traps:
If you perform arithmetic operations or functions on an Object, it must hold numerical data or a run-time error occurs.
If you are concatenating strings, use the & operator instead of the + operator. There are complex rules governing when
the + operator adds its operands and when it concatenates them. The + operator also must perform type checking and
conversion in some cases, which reduces performance.
Changing an Object Variable's Data Type
Although an Object variable can accept data of any type, you cannot change the variable itself to a different data type.
However, you can redimension an Object variable to an array of Object variables. The following example illustrates both valid
and invalid uses of the ReDim Statement (Visual Basic).

' The following statement declares a single Object.


Dim someObj As Object
' The following reallocation is valid only for Object.
ReDim someObj(8)
' The following statement attempts an INVALID change of data type.
ReDim someObj(8) As Double

The first ReDim statement changes someObj to an array of type Object. This is valid only with the Object data type. The
second ReDim statement is invalid because it involves a different data type. You can achieve the desired effect by using a
separate array. The following example illustrates this.

' First allocate a separate array.


Dim someArray(8) As Double
' Then assign the new array to the Object variable.
someObj = someArray

Object as an Alternative to a Structure


Because the Object data type can store many different types of data, you can use an Object array in many situations where
you might expect to use a structure. An Object array is somewhat more flexible than a structure, because you can change the
type of data you store in each element at any time, and you can make the array dynamic so you can change its size as
necessary. However, an Object array uses more memory than an equivalent structure, and its performance is slower.
See Also
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Concepts
Typeless Programming in Visual Basic
Implicit and Explicit Declaration
Type Checking in Visual Basic
Efficient Use of Data Types
Object Variable Declaration
Object Variable Assignment
Object Variable Values
Other Resources
Type Conversions in Visual Basic
Visual Basic Language Concepts

Efficient Use of Data Types


Undeclared variables and variables declared without a data type are assigned the Object data type. This makes it easy to write
programs quickly, but it can cause them to execute more slowly.
Strong Typing
Specifying data types for all your variables is known as strong typing. Using strong typing has several advantages:
It enables IntelliSense® support for your variables. This allows you to see their properties and other members as you
type in the code.
It takes advantage of compiler type checking. This catches statements that can fail at run time due to errors such as
overflow. It also catches calls to methods on objects that do not support them.
It results in faster execution of your code.
Most Efficient Data Types
For variables that never contain fractions, the integral data types are more efficient than the nonintegral types. In Visual Basic,
Integer and UInteger are the most efficient numeric types.
For fractional numbers, Double is the most efficient data type, because the processors on current platforms perform floating-
point operations in double precision. However, operations with Double are not as fast as with the integral types such as
Integer.
Specifying Data Type
Use the Dim Statement (Visual Basic) to declare a variable of a specific type. You can simultaneously specify its access level by
using the Public (Visual Basic), Protected (Visual Basic), Friend (Visual Basic), or Private (Visual Basic) keyword, as in the
following example.

Private x As Double
Protected s As String

Character Conversion
The AscW and ChrW functions operate in Unicode. You should use them in preference to Asc and Chr, which must translate
into and out of Unicode.
See Also
Reference
Asc, AscW Functions
Chr, ChrW Functions
Concepts
Data Types in Visual Basic
Typeless Programming in Visual Basic
Implicit and Explicit Declaration
Type Checking in Visual Basic
Object as the Universal Data Type
Numeric Data Types
Variable Declaration in Visual Basic
Other Resources
Using IntelliSense
Visual Basic Language Reference

Troubleshooting Data Types


This page lists some common problems that can occur when performing operations on intrinsic data types.
Floating-Point Expressions Do Not Compare as Equal
When you work with floating-point numbers (Single Data Type (Visual Basic) and Double Data Type (Visual Basic)), keep in
mind that they are stored as binary fractions. This means they cannot hold an exact representation of any quantity that is not a
binary fraction (of the form k / (2 ^ n) where k and n are integers). For example, 0.5 (= 1/2) and 0.3125 (= 5/16) can be held as
precise values, while 0.2 (= 1/5) and 0.3 (= 3/10) can be only approximations.
Because of this imprecision, you cannot rely on exact results when you operate on floating-point values. In particular, two
values that are theoretically equal might have slightly different representations.
To compare floating-point quantities
1. Calculate the absolute value of their difference, using the Abs method of the Math class in the System namespace.
2. Determine an acceptable maximum difference, such that you can consider the two quantities to be equal for practical
purposes if their difference is no greater.
3. Compare the absolute value of the difference to the acceptable difference.
The following example demonstrates both improper and proper comparison of two Double values.
VB
Dim oneThird As Double = 1.0 / 3.0
Dim pointThrees As Double = 0.333333333333333

' The following comparison does not indicate equality.


Dim exactlyEqual As Boolean = (oneThird = pointThrees)

' The following comparison indicates equality.


Dim closeEnough As Double = 0.000000000000001
Dim absoluteDifference As Double = Math.Abs(oneThird - pointThrees)
Dim practicallyEqual As Boolean = (absoluteDifference < closeEnough)

MsgBox("1.0 / 3.0 is represented as " & oneThird.ToString("G17") _


& vbCrLf & "0.333333333333333 is represented as " _
& pointThrees.ToString("G17") _
& vbCrLf & "Exact comparison generates " & CStr(exactlyEqual) _
& vbCrLf & "Acceptable difference comparison generates " _
& CStr(practicallyEqual))

The preceding example uses the ToString method of the Double structure so that it can specify greater precision than the CStr
keyword uses. The default is 15 digits, but the "G17" format extends it to 17 digits.
Mod Operator Does Not Return Accurate Result
Because of the imprecision of floating-point storage, the Mod Operator (Visual Basic) can return an unexpected result when at
least one of the operands is floating-point.
The Decimal Data Type (Visual Basic) does not use floating-point representation. Many numbers that are inexact in Single and
Double are exact in Decimal (for example 0.2 and 0.3). Although arithmetic is slower in Decimal than in floating-point, it
might be worth the performance decrease to achieve greater precision.
To find the integer remainder of floating-point quantities
1. Declare variables as Decimal.
2. Use the literal type character D to force literals to Decimal, in case their values are too large for the Long data type.
The following example demonstrates the potential imprecision of floating-point operands.
VB
Dim two As Double = 2.0
Dim zeroPointTwo As Double = 0.2
Dim quotient As Double = two / zeroPointTwo
Dim doubleRemainder As Double = two Mod zeroPointTwo
MsgBox("2.0 is represented as " & two.ToString("G17") _
& vbCrLf & "0.2 is represented as " & zeroPointTwo.ToString("G17") _
& vbCrLf & "2.0 / 0.2 generates " & quotient.ToString("G17") _
& vbCrLf & "2.0 Mod 0.2 generates " _
& doubleRemainder.ToString("G17"))

Dim decimalRemainder As Decimal = 2D Mod 0.2D


MsgBox("2.0D Mod 0.2D generates " & CStr(decimalRemainder))

The preceding example uses the ToString method of the Double structure so that it can specify greater precision than the
CStr keyword uses. The default is 15 digits, but the "G17" format extends it to 17 digits.
Because zeroPointTwo is Double, its value for 0.2 is an infinitely repeating binary fraction with a stored value of
0.20000000000000001. Dividing 2.0 by this quantity yields 9.9999999999999995 with a remainder of
0.19999999999999991.
In the expression for decimalRemainder, the literal type character D forces both operands to Decimal, and 0.2 has a precise
representation. Therefore the Mod operator yields the expected remainder of 0.0.
Note that it is not sufficient to declare decimalRemainder as Decimal. You must also force the literals to Decimal, or they
default to Double and decimalRemainder receives the same inaccurate value as doubleRemainder.
Boolean Type Does Not Convert to Numeric Type Accurately
Boolean Data Type (Visual Basic) values are not stored as numbers, and the stored values are not intended to be equivalent to
numbers. For compatibility with previous versions, Visual Basic provides conversion keywords (CType Function, CBool, CInt,
and so on) to convert between Boolean and numeric types. However, other languages sometimes perform these conversions
differently, as do the .NET Framework methods.
You should never write code that relies on equivalent numeric values for True and False. Whenever possible, you should
restrict usage of Boolean variables to the logical values for which they are designed. If it is necessary to mix Boolean and
numeric values, be sure that you understand the conversion method you choose.
Conversion in Visual Basic
When you use the CType or CBool conversion keywords to convert numeric data types to Boolean, 0 becomes False and all
other values become True. When you convert Boolean values to numeric types using the conversion keywords, False
becomes 0 and True becomes -1.
Conversion in the Framework
The ToInt32 method of the Convert class in the System namespace converts True to +1.
If you need to convert a Boolean value to a numeric data type, take care which conversion method you use.
Character Literal Generates Compiler Error
In the absence of any type characters, Visual Basic assumes default data types for literals. The default type for a character literal
— enclosed within double quotes (" ") — is String.
The String data type does not widen to the Char Data Type (Visual Basic). This means that if you want to assign a literal to a
Char variable, you must either make a narrowing conversion or force the literal to the Char type.
To create a Char literal to assign to a variable or constant
1. Declare the variable or constant as Char.
2. Enclose the character value within double quotation marks (" ").
3. Follow the closing double quotation mark with the literal type character C to force the literal to Char. This is necessary if
the type checking switch (Option Strict Statement) is On, and it is desirable in any case.
The following example demonstrates both unsuccessful and successful assignments of a literal to a Char variable.
VB
Option Strict On

VB
Dim charVar As Char
' The following statement attempts to convert a String literal to Char.
' Because Option Strict is On, it generates a compiler error.
charVar = "Z"
' The following statement succeeds because it specifies a Char literal.
charVar = "Z"c
' The following statement succeeds because it converts String to Char.
charVar = CChar("Z")

There is always a risk in using narrowing conversions, because they can fail at run time. For example, a conversion from String
to Char can fail if the String value contains more than one character. Therefore, it is better programming to use the C type
character.
String Conversion Fails at Run Time
The String Data Type (Visual Basic) participates in very few widening conversions. String widens only to itself and Object, and
only Char and Char() (a Char array) widen to String. This is because String variables and constants can contain values that
other data types cannot accommodate.
When the type checking switch (Option Strict Statement) is On, the compiler disallows all implicit narrowing conversions,
including those involving String. Your code can still use conversion keywords such as CStr and CType Function, which direct
the .NET Framework to attempt the conversion.
Narrowing Conversion Protection
The disadvantage of narrowing conversions is that they can fail at run time. For example, if a String variable contains anything
other than "True" or "False", it cannot be converted to Boolean. If it contains punctuation characters, conversion to any
numeric type fails. Unless you know that your String variable always holds values that the destination type can accept, you
should not attempt a conversion.
If you need to convert from String to another data type, the safest procedure is to enclose the attempted conversion in the
Try...Catch...Finally Statement (Visual Basic). This allows you to deal with a run-time failure.
Character Arrays
A single Char and an array of Char elements both widen to String. However, String does not widen to Char(). To convert a
String value to a Char array, you can use the ToCharArray method of the System.String class.
Meaningless Values
In general, String values are not meaningful in other data types, and conversion is highly artificial and dangerous. Whenever
possible, you should restrict usage of String variables to the character sequences for which they are designed. You should
never write code that relies on equivalent values in other types.
See Also
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Concepts
Data Types in Visual Basic
Type Characters
Typeless Programming in Visual Basic
Data Types Are .NET Framework Types
Efficient Use of Data Types
Other Resources
Data Type Implementation
Type Conversions in Visual Basic
Visual Basic Language Concepts

Variables in Visual Basic


You often need to store values when performing calculations with Visual Basic. For example, you might want to calculate
several values, compare them, and perform different operations on them, depending on the result of the comparison. You need
to retain the values if you want to compare them.
Usage
Visual Basic, like most programming languages, uses variables for storing values. A variable has a name (the word that you
use to refer to the value the variable contains) and a data type (which determines the kind of data that the variable can store). A
variable can represent an array if it needs to store an indexed set of closely related data items.
Assigning Values
You use assignment statements to perform calculations and assign the result to a variable, as the following example shows.
VB
' The following statement assigns the value 10 to the variable.
applesSold = 10
' The following statement increments the variable.
applesSold = applesSold + 1
' The variable now holds the value 11.

Note
The equal sign (=) in this example is an assignment operator, not an equality operator. The value is being assigned to the vari
able applesSold.

For more information, see How to: Move Data Into and Out of a Variable.
Variables and Properties
Like a variable, a property represents a value you can access. However, it is more complex than a variable. A property uses code
blocks that control how to set and retrieve its value. For more information, see
Differences Between Properties and Variables in Visual Basic.
See Also
Tasks
Troubleshooting Variables in Visual Basic
How to: Move Data Into and Out of a Variable
Concepts
Variable Declaration in Visual Basic
Object Variables in Visual Basic
Differences Between Properties and Variables in Visual Basic
Visual Basic Language Concepts

Variable Declaration in Visual Basic


You declare a variable to specify its name and characteristics. The declaration statement for variables is the
Dim Statement (Visual Basic). Its location and contents determine the variable's characteristics.
For variable naming rules and considerations, see Declared Element Names.
Declaration Levels
Local and Member Variables
A local variable is one that is declared within a procedure. A member variable is a member of a Visual Basic type; it is declared
at module level, inside a class, structure, or module, but not within any procedure internal to that class, structure, or module.
Shared and Instance Variables
In a class or structure, the category of a member variable depends on whether or not it is shared. If it is declared with the
Shared keyword, it is a shared variable, and it exists in a single copy shared among all instances of the class or structure.
Otherwise it is an instance variable, and a separate copy of it is created for each instance of the class or structure. A given copy
of an instance variable is available only to the instance for which it was created. It is independent of a copy in any other
instance.
Declaring Data Type
The As clause in the declaration statement allows you to define the data type or object type of the variable you are declaring.
You can specify any of the following types for a variable:
An elementary data type, such as Boolean, Long, or Decimal
A composite data type, such as an array or structure
An object type, or class, defined either in your application or in another application
A .NET Framework class, such as Label or TextBox
An interface type, such as IComparable or IDisposable
You can declare several variables in one statement without having to repeat the data type. In the following statements, the
variables i, j, and k are declared as type Integer, l and m as Long, and x and y as Single:

Dim i, j, k As Integer
' All three variables in the preceding statement are declared as Integer.
Dim l, m As Long, x, y As Single
' In the preceding statement, l and m are Long, x and y are Single.

For more information on data types, see Data Types in Visual Basic. For more information on objects, see
Object-Oriented Programming in Visual Basic and Programming with Components.
Declaring Characteristics
The lifetime of a variable is the period of time during which it is available for use. In general, a variable exists as long as the
element that declares it (such as a procedure or class) continues to exist. In some cases it is possible to extend a variable's
lifetime. For more information, see Lifetime in Visual Basic.
The scope of a variable is the set of all code that can refer to it without qualifying its name. A variable's scope is determined by
where it is declared. Code located in a given region can use the variables defined in that region without having to qualify their
names. For more information, see Scope in Visual Basic.
A variable's access level is the extent of code that has permission to access it. This is determined by the access modifier (such as
Public (Visual Basic) or Private (Visual Basic)) that you use in the Dim statement. For more information, see
Access Levels in Visual Basic.
See Also
Tasks
How to: Create a New Variable
How to: Create a Variable that Does Not Change in Value
How to: Move Data Into and Out of a Variable
Reference
Data Type Summary (Visual Basic)
Protected (Visual Basic)
Friend (Visual Basic)
Static (Visual Basic)
Concepts
Deciding What Type of Variable to Define
Declared Element Characteristics
Visual Basic Language Concepts

How to: Create a New Variable


You create a variable with a Dim Statement (Visual Basic).
To create a new variable
1. Declare the variable in a Dim statement.

Dim newCustomer

2. Include specifications for the variable's characteristics, such as Private (Visual Basic), Static (Visual Basic), Shadows, or
WithEvents. For more information, see Declared Element Characteristics.

Public Static newCustomer

You do not need the Dim keyword if you use other keywords in the declaration.
3. Follow the specifications with the variable's name, which must follow Visual Basic rules and conventions. For more
information, see Declared Element Names.

Public Static newCustomer

4. Follow the name with the As clause to specify the variable's data type.

Public Static newCustomer As Customer

If you do not specify the data type, it defaults to Object.


5. Follow the As clause with an equal sign (=) and follow the equal sign with the variable's initial value.
Visual Basic assigns the specified value to the variable every time it runs the Dim statement. If you do not specify an
initial value, Visual Basic assigns the default initial value for the variable's data type when it first enters the code
containing the Dim statement.
If the variable is a reference type, you can create an instance of its class by including the New (Visual Basic) keyword in
the As clause. If you do not use New, the initial value of the variable is Nothing (Visual Basic).

Public Static newCustomer As New Customer

See Also
Concepts
Variables in Visual Basic
Variable Declaration in Visual Basic
Declared Element Names
Declared Element Characteristics
Value Types and Reference Types
Declaration Statements in Visual Basic
Visual Basic Language Concepts

Deciding What Type of Variable to Define


When you define a variable, you must decide the following characteristics:
Its data type — what kind of data it should hold
Its lifetime — how long it should continue to exist
Its scope — what code should be able to refer to it without qualifying its name
Its access level — what code should have permission to read and write to it
Data Type
In the Dim Statement (Visual Basic) that declares the variable, include an As clause specifying the appropriate data type (such
as Integer or String). The following pages can help you choose a variable's data type.
How to: Hold Integers in a Variable
How to: Hold the Largest Possible Number in a Variable
How to: Optimize Storage of Positive Integers With Unsigned Types
How to: Hold Fractions in a Variable
How to: Hold the Most Significant Digits in a Variable
How to: Hold Money Values in a Variable
How to: Hold Characters in a Variable
How to: Hold True and False Values in a Variable
How to: Hold Date and Time Values in a Variable
How to: Hold Data of Unknown Type in a Variable
How to: Declare a Structure
Creating and Using Objects
For more information, see Data Type Summary (Visual Basic).
Lifetime
The important decision in lifetime is whether it is acceptable for the variable to cease to exist when the module, class, or
procedure that declares it ceases to exist.
If the variable does not need to continue existing beyond the lifetime of its containing element, you do not need to do anything
else. If the variable needs to continue to exist longer than its containing element, you can include the Static or Shared
keyword in its Dim statement. Follow the steps described in How to: Lengthen a Variable's Lifetime.
For more information, see Lifetime in Visual Basic.
Scope
A variable's scope is normally the same as its declaration space, that is, the containing element in which it is declared. You must
decide how extensive the variable's scope should be.
Be sure the Dim statement appears at the appropriate level, such as block, procedure, or module level. Follow the steps
described in How to: Control the Scope of a Variable.
For more information, see Scope in Visual Basic.
Access Level
Every variable has a default access level that depends where it is declared, that is, in what type of containing element.
If you need to specify an access level other than the default, you can include an access modifier (such as Protected or Private)
in its Dim statement. You can do this only for member variables (namely, variables declared outside a procedure). Follow the
steps described in How to: Control the Availability of a Variable.
For more information, see Access Levels in Visual Basic.
See Also
Tasks
How to: Lengthen a Variable's Lifetime
How to: Control the Scope of a Variable
Reference
As (Visual Basic)
Concepts
Variable Declaration in Visual Basic
Declared Element Characteristics
Scope in Visual Basic
Access Levels in Visual Basic
Visual Basic Language Concepts

How to: Create a Variable that Does Not Change in Value


The notion of a variable that does not change its value might appear to be contradictory. But there are situations when a
constant is not feasible and it is useful to have a variable with a fixed value. In such a case you can define a member variable
with the ReadOnly (Visual Basic) keyword.
You cannot use the Const Statement (Visual Basic) to declare and assign a constant value in the following circumstances:
The Const statement does not accept the data type you want to use
You do not know the value at compile time
You are unable to compute the constant value at compile time
To create a variable that does not change in value
1. At module level, declare a member variable with the Dim Statement (Visual Basic), and include the
ReadOnly (Visual Basic) keyword.

Dim ReadOnly timeStarted

You can specify ReadOnly only on a member variable. This means you must define the variable at module level, outside
of any procedure.
2. If you can compute the value in a single statement at compile time, use an initialization clause in the Dim statement.
Follow the As clause with an equal sign (=), followed by an expression. Be sure the compiler can evaluate this expression
to a constant value.

Dim ReadOnly timeStarted As Date = Now

You can assign a value to a ReadOnly variable only once. Once you do so, no code can ever change its value.
If you do not know the value at compile time, or cannot compute it at compile time in a single statement, you can still
assign it at run time in a constructor. To do this, you must declare the ReadOnly variable at class or structure level. In the
constructor for that class or structure, compute the variable's fixed value, and assign it to the variable before returning
from the constructor.

See Also
Reference
WriteOnly
Const Statement (Visual Basic)
Visual Basic Language Concepts

How to: Move Data Into and Out of a Variable


You store a value in a variable by putting the variable name on the left side of an assignment statement.
Putting Data in a Variable
To store a value in a variable
Use the variable name on the left side of an assignment statement.
The following example sets the value of the variable alpha.

alpha = (beta * 6.27) / (gamma + 2.1)

The value generated on the right side of the assignment statement is stored in the variable.
Getting Data from a Variable
You retrieve a variable's value by including the variable name in an expression.
To retrieve a value from a variable
Use the variable name in an expression. You can use a variable anywhere you can use a constant or a literal, except in an
expression that defines the value of a constant.
-or-
Use the variable name following the equal (=) sign in an assignment statement.
The following example reads the value of the variable startValue and then uses the value of the variable counter in an
expression.

counter = startValue
cellValue = (counter + 5) ^ 2

The value of the variable participates in the expression just as a constant would, and then it is stored in the variable or
property on the left side of the assignment statement.
See Also
Concepts
Variables in Visual Basic
Variable Declaration in Visual Basic
Object Variables in Visual Basic
Visual Basic Language Concepts

Object Variables in Visual Basic


In addition to storing values directly, a variable can refer to an object. You assign an object to a variable for the same reasons
you assign any value to a variable:
A variable name is often shorter and easier to remember than the full path of methods and properties necessary to
access the object itself.
Using a variable that refers to an object is more efficient than repeatedly accessing the object itself through the necessary
methods or properties.
You can change a variable to refer to other objects while your code is running.
Making Code Shorter
You can use object variables to shorten the code you have to type. The following example uses the full path of methods and
properties to access a Control object.

' Assume Me is a valid Form, or replace Me with a valid Form.


Me.ActiveForm.ActiveControl.Text = "Test"
Me.ActiveForm.ActiveControl.Location = New Point(100, 100)
Me.ActiveForm.ActiveControl.Show()

You can shorten this code, and speed up execution, if you use an object variable for the control. You should declare the object
variable with the specific class that you intend to assign to it (Control in this case). Once you assign an object to the variable,
you can treat it exactly the same as you treat the object to which it refers. You can set or retrieve the properties of the object or
use any of its methods. The following example uses an object variable to simplify the code in the preceding example.

Dim ctrlActv As System.Windows.Forms.Control = Me.ActiveForm.ActiveControl


ctrlActv.Text = "Test"
ctrlActv.Location = New Point(100, 100)
ctrlActv.Show()

See Also
Tasks
How to: Speed Up Access to an Object with a Long Qualification Path
Concepts
Variable Declaration in Visual Basic
Object Variable Declaration
Object Variable Assignment
Object Variable Values
Visual Basic Language Concepts

How to: Speed Up Access to an Object with a Long


Qualification Path
If you frequently access an object that requires a qualification path of several methods and properties, you can speed up your
code by not repeating the qualification path.
There are two ways you can avoid repeating the qualification path. You can assign the object to a variable, or you can use it in a
With...End With block.
To speed up access to a heavily qualified object by assigning it to a variable
1. Declare a variable of the type of the object that you are accessing frequently. Specify the qualification path in the
initialization part of the declaration.

Dim ctrlActv As Control = someForm.ActiveForm.ActiveControl

2. Use the variable to access the object's members.

ctrlActv.Text = "Test"
ctrlActv.Location = New Point(100, 100)
ctrlActv.Show()

To speed up access to a heavily qualified object by using a With...End With block


1. Put the qualification path in a With statement.

With someForm.ActiveForm.ActiveControl

2. Access the object's members inside the With block, before the End With statement.

.Text = "Test"
.Location = New Point(100, 100)
.Show()
End With

See Also
Reference
With...End With Statement (Visual Basic)
Concepts
Object Variables in Visual Basic
Visual Basic Language Concepts

Object Variable Declaration


You use a normal declaration statement to declare an object variable. For the data type, you specify either Object (that is, the
Object Data Type) or a more specific class from which the object is to be created.
Declaring a variable as Object is the same as declaring it as System.Object.
When you declare a variable with a specific object class, it can access all the methods and properties exposed by that class and
the classes from which it inherits. If you declare the variable with Object, it can access only the members of the Object class,
unless you turn Option Strict Off to allow late binding.
Declaration Syntax
Use the following syntax to declare an object variable:

Dim variablename As [New] { objectclass | Object }

You can also specify Public (Visual Basic), Protected (Visual Basic), Friend (Visual Basic), Protected Friend,
Private (Visual Basic), Shared (Visual Basic), or Static (Visual Basic) in the declaration. The following example declarations are
valid:

Private objA As Object


Static objB As System.Windows.Forms.Label
Dim objC As System.OperatingSystem

Late Binding and Early Binding


Sometimes the specific class is not known until your code runs. In this case, you must declare the object variable with the
Object data type. This creates a general reference to any type of object, and the specific class is assigned at run time. This is
called late binding. Late binding requires additional execution time. It also limits your code to the methods and properties of
the class you have most recently assigned to it. This can cause run-time errors if your code attempts to access members of a
different class.
When you know the specific class at compile time, you should declare the object variable to be of that class. This is called early
binding. Early binding improves performance and guarantees your code access to all the methods and properties of the
specific class. In the preceding example declarations, if variable objA uses only objects of class System.Windows.Forms.Label,
you should specify As System.Windows.Forms.Label in its declaration.
Advantages of Early Binding
Declaring an object variable as a specific class gives you several advantages:
Automatic type checking
Guaranteed access to all members of the specific class
Microsoft IntelliSense support in the Code Editor
Improved readability of your code
Fewer errors in your code
Errors caught at compile time rather than run time
Faster code execution
Access to Object Variable Members
When Option Strict is turned On, an object variable can access only the methods and properties of the class with which you
declare it. The following example illustrates this.

' Option statements must precede all other source file lines.
Option Strict On
' Imports statement must precede all declarations in the source file.
Imports System.Windows.Forms
Public Sub accessMembers()
Dim p As Object
Dim q As System.Windows.Forms.Label
p = New System.Windows.Forms.Label
q = New System.Windows.Forms.Label
Dim j, k As Integer
' The following statement generates a compiler ERROR.
j = p.Left
' The following statement retrieves the left edge of the label in pixels.
k = q.Left
End Sub

In this example, p can use only the members of the Object class itself, which do not include the Left property. On the other
hand, q was declared to be of type Label, so it can use all the methods and properties of the Label class in the
System.Windows.Forms namespace.
Flexibility of Object Variables
When working with objects in an inheritance hierarchy, you have a choice of which class to use for declaring your object
variables. In making this choice, you must balance flexibility of object assignment against access to a class's members. For
example, consider the inheritance hierarchy that leads to the System.Windows.Forms.Form class:
Object
Component
Control
ScrollableControl
ContainerControl
Form
Suppose your application defines a form class called specialForm, which inherits from class Form. You can declare an object
variable that refers specifically to specialForm, as the following example shows.

Public Class specialForm


Inherits System.Windows.Forms.Form
' Insert code defining methods and properties of specialForm.
End Class
Dim nextForm As New specialForm

The declaration in the preceding example limits the variable nextForm to objects of class specialForm, but it also makes all the
methods and properties of specialForm available to nextForm, as well as all the members of all the classes from which
specialForm inherits.

You can make an object variable more general by declaring it to be of type Form, as the following example shows.

Dim anyForm As System.Windows.Forms.Form

The declaration in the preceding example allows you to assign any form in your application to anyForm. However, although
anyForm can access all the members of class Form, it cannot use any of the additional methods or properties defined for
specific forms such as specialForm.
All the members of a base class are available to derived classes, but the additional members of a derived class are not available
to the base class.
See Also
Tasks
How to: Declare an Object Variable and Assign an Object to It in Visual Basic
How to: Access Members of an Object
Reference
New (Visual Basic)
Option Strict Statement
Concepts
Object Variables in Visual Basic
Object Variable Assignment
Object Variable Values
Typeless Programming in Visual Basic
Visual Basic Language Concepts

How to: Access Members of an Object


When you have an object variable that refers to an object, you often want to work with the members of that object, such as its
methods, properties, fields, and events. For example, once you have created a new Form object, you might want to set its Text
property or call its Focus method.
Accessing Members
You access an object's members through the variable that refers to it.
To access members of an object
Use the member-access operator (.) between the object variable name and the member name.

currentText = newForm.Text

If the member is Shared (Visual Basic), you do not need a variable to access it. For more information, see
How to: Access Shared and Nonshared Members of an Object.

Accessing Members of an Object of Known Type


If you know the type of an object at compile time, you can use early binding for a variable that refers to it.
To access members of an object for which you know the type at compile time
1. Declare the object variable to be of the type of the object you intend to assign to the variable.

Dim extraForm As System.Windows.Forms.Form

With Option Strict On, you can assign only Form objects (or objects of a type derived from Form) to extraForm. If you
have defined a class or structure with a widening CType conversion to Form, you can also assign that class or structure
to extraForm.
2. Use the member-access operator (.) between the object variable name and the member name.

extraForm.Show()

You can access all of the methods and properties specific to the Form class, no matter what the Option Strict setting is.
Accessing Members of an Object of Unknown Type
If you do not know the type of an object at compile time, you must use late binding for any variable that refers to it.
To access members of an object for which you do not know the type at compile time
1. Declare the object variable to be of the Object Data Type. (Declaring a variable as Object is the same as declaring it as
System.Object.)

Dim someControl As Object

With Option Strict On, you can access only the members that are defined on the Object class.
2. Use the member-access operator (.) between the object variable name and the member name.

someControl.GetType()

To be able to access the members of any object you assign to the object variable, you must set Option Strict Off. When
you do this, the compiler cannot guarantee that a given member is exposed by the object you assign to the variable. If the
object does not expose a member you attempt to access, a MemberAccessException exception occurs.
See Also
Reference
Object Data Type
Option Strict Statement
Object
Form
MemberAccessException
Concepts
Object Variables in Visual Basic
Object Variable Declaration
Visual Basic Language Concepts

Object Variable Assignment


You use a normal assignment statement to assign an object to an object variable. You can assign an object expression or the
Nothing keyword, as the following example illustrates.

Dim thisObject As Object


' The following statement assigns an object reference.
thisObject = Form1
' The following statement discontinues association with any object.
thisObject = Nothing

Nothing means there is no object currently assigned to the variable.


Initialization
When your code begins running, your object variables are initialized to Nothing. Those whose declarations include
initialization are reinitialized to the values you specify when the declaration statements are executed.
You can include initialization in your declaration by using the New keyword. The following declaration statements declare
object variables testUri and ver and assign specific objects to them. Each uses one of the overloaded constructors of the
appropriate class to initialize the object.

Dim testUri As New System.Uri("http://www.microsoft.com")


Dim ver As New System.Version(6, 1, 0)

Disassociation
Setting an object variable to Nothing discontinues the association of the variable with any specific object. This prevents you
from accidentally changing the object by changing the variable. It also allows you to test whether the object variable points to a
valid object, as the following example shows.

If otherObject IsNot Nothing Then


' otherObject refers to a valid object, so your code can use it.
End If

If the object your variable refers to is in another application, this test cannot determine whether that application has terminated
or just invalidated the object.
An object variable with a value of Nothing is also called a null reference.
Current Instance
The current instance of an object is the one in which the code is currently executing. Since all code executes inside a procedure,
the current instance is the one in which the procedure was invoked.
The Me keyword acts as an object variable referring to the current instance. If a procedure is not Shared (Visual Basic), it can
use the Me keyword to obtain a pointer to the current instance. Shared procedures cannot be associated with a specific
instance of a class.
Using Me is particularly useful for passing the current instance to a procedure in another module. For example, suppose you
have a number of XML documents and wish to add some standard text to all of them. The following example defines a
procedure to do this.

Sub addStandardText(XmlDoc As System.Xml.XmlDocument)


XmlDoc.CreateTextNode("This text goes into every XML document.")
End Sub

Every XML document object could then call the procedure and pass its current instance as an argument. The following example
demonstrates this.

addStandardText(Me)
See Also
Tasks
How to: Declare an Object Variable and Assign an Object to It in Visual Basic
How to: Make an Object Variable Not Refer to Any Instance
Concepts
Object Variables in Visual Basic
Object Variable Declaration
Object Variable Values
Visual Basic Language Concepts

How to: Declare an Object Variable and Assign an Object to It


in Visual Basic
You declare a variable of the Object Data Type by specifying As Object in a Dim Statement (Visual Basic). You assign an object
to such a variable by placing the object after the equal sign (=) in an assignment statement or initialization clause.
Example
The following example declares an Object variable and assigns the current instance to it.

Dim thisObject As Object


thisObject = Me

You can combine the declaration and assignment by initializing the variable as part of its declaration. The following example is
equivalent to the preceding example.

Dim thisObject As Object = Me

Compiling the Code


This example requires:
A reference to the System namespace.
A class, structure, or module in which to put the Dim statement.
A procedure in which to put the assignment statement.
See Also
Reference
Object Data Type
Me
Dim Statement (Visual Basic)
Concepts
Variable Declaration in Visual Basic
Object Variables in Visual Basic
Object Variable Declaration
Visual Basic Language Concepts

How to: Make an Object Variable Not Refer to Any Instance


You can disassociate an object variable from any object instance by setting it to Nothing (Visual Basic).
To disassociate an object variable from any object instance
Set the variable to Nothing in an assignment statement.

' Assume account is a defined class


Dim currentAccount As account
currentAccount = Nothing

Robust Programming
If your code tries to access a member of an object variable that has been set to Nothing, a NullReferenceException occurs. If
you set an object variable to Nothing frequently, or if it is possible the variable is not initialized, it is a good idea to enclose
member accesses in a Try...Catch...Finally block.
Security
If you use an object variable for objects that contain confidential or sensitive data, you can set the variable to Nothing when
you are not actively dealing with one of those objects. This reduces the chance of malicious code gaining access to the data.
See Also
Reference
Nothing (Visual Basic)
Try...Catch...Finally Statement (Visual Basic)
Troubleshooting Exceptions: System.NullReferenceException
NullReferenceException
Concepts
Object Variables in Visual Basic
Object Variable Assignment
Visual Basic Language Concepts

Object Variable Values


A variable of the Object Data Type can refer to data of any type. The value you store in an Object variable is kept elsewhere in
memory, while the variable itself holds a pointer to the data.
Object Classifier Functions
Visual Basic supplies functions that return information about what an Object variable refers to, as shown in the following
table.
Function Returns True if the Object variable refers to
IsArray Function (Visual Basic) An array of values, rather than a single value

IsDate Function (Visual Basic) A Date Data Type (Visual Basic) value, or a string that can be interpreted as a date and time v
alue

IsDBNull Function An object of type DBNull, which represents missing or nonexistent data

IsError Function An exception object, which derives from Exception

IsNothing Function Nothing (Visual Basic), that is, no object is currently assigned to the variable

IsNumeric Function (Visual Basic) A number, or a string that can be interpreted as a number

IsReference Function A reference type (such as a string, array, delegate, or class type)

You can use these functions to avoid submitting an invalid value to an operation or a procedure.
TypeOf Operator
You can also use the TypeOf Operator (Visual Basic) to determine whether an object variable currently refers to a specific data
type. The TypeOf...Is expression evaluates to True if the run-time type of the operand is derived from or implements the
specified type.
The following example uses TypeOf on object variables referring to value and reference types.

' The following statement puts a value type (Integer) in an Object variable.
Dim num As Object = 10
' The following statement puts a reference type (Form) in an Object variable.
Dim frm As Object = New Form()
If TypeOf num Is Long Then Debug.WriteLine("num is Long")
If TypeOf num Is Integer Then Debug.WriteLine("num is Integer")
If TypeOf num Is Short Then Debug.WriteLine("num is Short")
If TypeOf num Is Object Then Debug.WriteLine("num is Object")
If TypeOf frm Is Form Then Debug.WriteLine("frm is Form")
If TypeOf frm Is Label Then Debug.WriteLine("frm is Label")
If TypeOf frm Is Object Then Debug.WriteLine("frm is Object")

The preceding example writes the following lines to the Debug window:
num is Integer
num is Object
frm is Form
frm is Object

The object variable num refers to data of type Integer, and frm refers to an object of class Form.
Object Arrays
You can declare and use an array of Object variables. This is useful when you need to handle a variety of data types and object
classes. All the elements in an array must have the same declared data type. Declaring this data type as Object allows you to
store objects and class instances alongside other data types in the array.
See Also
Tasks
How to: Refer to the Current Instance of an Object
How to: Determine What Type an Object Variable Refers To
How to: Determine Whether Two Objects Are Related
How to: Determine Whether Two Objects Are Identical
Reference
Is (Visual Basic)
Concepts
Object Variables in Visual Basic
Object Variable Declaration
Object Variable Assignment
Data Types in Visual Basic
Visual Basic Language Concepts

How to: Refer to the Current Instance of an Object


The current instance of an object is the instance in which the code is currently executing.
You use the Me keyword to refer to the current instance.
To refer to the current instance
Use the Me keyword where you would normally use the name of an object variable.

Me.ForeColor = System.Drawing.Color.Crimson
Me.Close()

Although Me behaves like an object variable, you cannot declare it or assign anything to it. Me always refers to the
current instance.
See Also
Reference
Me
Concepts
Object Variables in Visual Basic
Object Variable Assignment
Visual Basic Language Concepts

How to: Determine What Type an Object Variable Refers To


An object variable contains a pointer to data that is stored elsewhere. The type of that data can change during run time. At any
moment, you can use the GetTypeCode method to determine the current run-time type, or the TypeOf Operator (Visual Basic)
to find out if the current run-time type is compatible with a specified type.
To determine the exact type an object variable currently refers to
1. On the object variable, call the GetType method to retrieve a System.Type object.

Dim myObject As Object


myObject.GetType()

2. On the System.Type class, call the shared method GetTypeCode to retrieve the TypeCode enumeration value for the
object's type.

Dim myObject As Object


Dim datTyp As Integer = Type.GetTypeCode(myObject.GetType())
MsgBox("myObject currently has type code " & CStr(datTyp))

You can test the TypeCode enumeration value against whichever enumeration members are of interest, such as Double.
To determine whether an object variable's type is compatible with a specified type
Use the TypeOf operator in combination with the Is Operator (Visual Basic) to test the object with a TypeOf...Is
expression.

If TypeOf objA Is System.Windows.Forms.Control Then


MsgBox("objA is compatible with the Control class")
End If

The TypeOf...Is expression returns True if the object's run-time type is compatible with the specified type.
The criterion for compatibility depends on whether the specified type is a class, structure, or interface. In general, the
types are compatible if the object is of the same type as, inherits from, or implements the specified type. For more
information, see TypeOf Operator (Visual Basic).
Compiling the Code
Note that the specified type cannot be a variable or expression. It must be the name of a defined type, such as a class, structure,
or interface. This includes intrinsic types such as Integer and String.
See Also
Reference
Object Data Type
GetType
System.Type
GetTypeCode
TypeCode
Concepts
Object Variables in Visual Basic
Object Variable Values
Visual Basic Language Concepts

How to: Determine Whether Two Objects Are Related


You can compare two objects to determine the relationship, if any, between the classes from which they are created. The
IsInstanceOfType method of the System.Type class returns True if the specified class inherits from the current class, or if the
current type is an interface supported by the specified class.
To determine if one object inherits from another object's class or interface
1. On the object you think might be of the base type, invoke the GetType method.
2. On the System.Type object returned by GetType, invoke the IsInstanceOfType method.
3. In the argument list for IsInstanceOfType, specify the object you think might be of the derived type.
IsInstanceOfType returns True if its argument type inherits from the System.Type object type.

Example
The following example determines whether one object represents a class derived from another object's class.

Public Class baseClass


End Class
Public Class derivedClass : Inherits baseClass
End Class
Public Class testTheseClasses
Public Sub seeIfRelated()
Dim baseObj As Object = New baseClass()
Dim derivedObj As Object = New derivedClass()
Dim related As Boolean
related = baseObj.GetType().IsInstanceOfType(derivedObj)
MsgBox(CStr(related))
End Sub
End Class

Note the unexpected placement of the two object variables in the call to IsInstanceOfType. The supposed base type is used to
generate the System.Type class, and the supposed derived type is passed as an argument to the IsInstanceOfType method.
See Also
Tasks
How to: Determine Whether Two Objects Are Identical
Reference
Object Data Type
GetType
System.Type
IsInstanceOfType
Concepts
Object Variables in Visual Basic
Object Variable Values
Visual Basic Language Concepts

How to: Determine Whether Two Objects Are Identical


Visual Basic considers two objects to be identical if their pointers are the same, that is, if both variables point to the same class
instance in memory. You might want to make this comparison, for example, to determine whether the current instance (Me) is
the same as a particular instance such as Form2.
Visual Basic provides two operators to compare pointers. The Is Operator (Visual Basic) returns True if the objects are identical,
and the IsNot Operator returns True if they are not.
Determining if Two Objects Are Identical
To determine if two objects are identical
1. Set up a Boolean expression to test the two objects.
2. In your testing expression, use the Is operator with the two objects as operands.
Is returns True if the objects point to the same class instance.

Determining if Two Objects Are Not Identical


Sometimes you want to perform an action if the two objects are not identical, and it can be awkward to combine Not and Is,
for example If Not obj1 Is obj2. In such a case you can use the IsNot operator.
To determine if two objects are not identical
1. Set up a Boolean expression to test the two objects.
2. In your testing expression, use the IsNot operator with the two objects as operands.
IsNot returns True if the objects do not point to the same class instance.
Example
The following example tests pairs of Object variables to see if they point to the same class instance.

Dim objA, objB, objC as Object


objA = Me
objB = New System.Windows.Forms.Form()
objC = Me
MsgBox("objA different from objB? " & CStr(objA IsNot objB))
MsgBox("objA identical to objC? " & CStr(objA Is objC))

The preceding example displays the following output.


objA different from objB? True
objA identical to objC? True

See Also
Tasks
How to: Determine Whether Two Objects Are Related
Reference
Object Data Type
Is Operator (Visual Basic)
IsNot Operator
Concepts
Object Variables in Visual Basic
Object Variable Values
Visual Basic Language Concepts

Troubleshooting Variables in Visual Basic


This page lists some common problems that can occur when working with variables in Visual Basic.
Unable to Access Members of an Object
If your code attempts to access a property or method on an object, there are two possible error outcomes:
The compiler can generate an error message if you declare the object variable to be of a specific type and then refer to a
member not defined by that type.
A run-time MemberAccessException occurs when the object assigned to an object variable does not expose the member
your code is trying to access. In the case of a variable of Object Data Type, you can also get this exception if the member
is not Public. This is because late binding allows access only to Public members.
When the Option Strict Statement sets type checking On, an object variable can access only the methods and properties of the
class with which you declare it. The following example illustrates this.
VB
Option Strict On

VB
Dim p As Object = New System.Windows.Forms.Label
Dim q As System.Windows.Forms.Label = New System.Windows.Forms.Label
Dim j, k As Integer
' The following statement generates a compiler error.
j = p.Left
' The following statement retrieves the left edge of the label
' in pixels.
k = q.Left

In this example, p can use only the members of the Object class itself, which do not include the Left property. On the other
hand, q was declared to be of type Label, so it can use all the methods and properties of the Label class in the
System.Windows.Forms namespace.
Correct Approach
To be able to access all the members of an object of a particular class, declare the object variable to be of the type of that class
when possible. If you cannot do this, for example if you do not know the object type at compile time, you must set Option
Strict to Off and declare the variable to be of the Object Data Type. This allows objects of any type to be assigned to the
variable, and you should take steps to ensure that the currently assigned object is of an acceptable type. You can use the
TypeOf Operator (Visual Basic) to make this determination.
Other Components Cannot Access Your Variable
Visual Basic names are case-insensitive. If two names differ in alphabetic case only, the compiler interprets them as the same
name. For example, it considers ABC and abc to refer to the same declared element.
However, the common language runtime (CLR) uses case-sensitive binding. Therefore, when you produce an assembly or a
DLL and make it available to other assemblies, your names are no longer case-insensitive. For example, if you define a class
with an element called ABC, and other assemblies make use of your class through the common language runtime, they must
refer to the element as ABC. If you subsequently recompile your class and change the element's name to abc, the other
assemblies using your class can no longer access that element. Therefore, when you release an updated version of an
assembly, you should not change the alphabetic case of any public elements.
For more information, see Common Language Runtime.
Correct Approach
To allow other components to access your variables, treat their names as if they were case-sensitive. When you are testing
your class or module, make sure other assemblies are binding to the variables you expect them to. Once you have published a
component, do not make any modifications to existing variable names, including changing their cases.
Wrong Variable Being Used
When you have more than one variable with the same name, the Visual Basic compiler attempts to resolve each reference to
that name. If the variables have different scope, the compiler resolves a reference to the declaration with the narrowest scope.
If they have the same scope, the resolution fails and the compiler signals an error. For more information, see
Resolving a Reference When Multiple Variables Have the Same Name.
Correct Approach
Avoid using variables with the same name but different scope. If you are using other assemblies or projects, avoid using any
names defined in those external components as much as possible. If you have more than one variable with the same name, be
sure you qualify every reference to it. For more information, see
How to: Distinguish Between Two Elements with the Same Name.
See Also
Tasks
How to: Access Members of an Object
How to: Determine What Type an Object Variable Refers To
Concepts
Variables in Visual Basic
Variable Declaration in Visual Basic
Object Variables in Visual Basic
Object Variable Declaration
Object Variable Values
Resolving a Reference When Multiple Variables Have the Same Name
Declared Element Names
Visual Basic Language Concepts

Arrays in Visual Basic


When you use arrays, you can refer to multiple values by the same name, using a number called an index or subscript to
distinguish them from one another. Arrays can shorten and simplify your code, allowing you to create loops that deal
efficiently with any number of elements.
In This Section
Overview of Arrays in Visual Basic
Defines the relevant terms and exhibits sample arrays.
Array Dimensions in Visual Basic
Explains rank and dimensions in arrays.
Multidimensional Arrays in Visual Basic
Discusses arrays that have more than one dimension.
Jagged Arrays in Visual Basic
Describes arrays of arrays, also known as jagged arrays.
Array Data Types in Visual Basic
Discusses the factors that determine the data type of an array.
Array Size in Visual Basic
Discusses considerations relating to the size of an array and each of its dimensions.
Working with Arrays and Array Elements
Discusses sorting of arrays, getting or putting an array value, and so on.
Collections as an Alternative to Arrays
Compares on storing items in a collection to storing them in an array.
Troubleshooting Arrays
Discusses some common problems that arise when working with arrays.
Related Sections
Language Changes for Visual Basic 6.0 Users
Provides an overview of the new features in Visual Basic 2005.
Object-Oriented Programming in Visual Basic
Covers object-oriented programming basics.
Visual Basic Language Concepts

Overview of Arrays in Visual Basic


An array is a set of values that are logically related to each other, such as the number of students in each grade in a grammar
school.
An array allows you to refer to these related values by the same name and to use a number, called an index or subscript, to tell
them apart. The individual values are called the elements of the array. They are contiguous from index 0 through the highest
index value.
Example
The following example declares an array variable to hold the number of students in each grade in a grammar school.

Dim students(6) As Integer

The array students in the preceding example contains 7 elements. The indexes of the elements range from 0 through 6. Having
this array is simpler than declaring 7 different variables.
The following illustration shows the array students. For each element of the array:
The index of the element represents the grade (index 0 represents kindergarten).
The value contained in the element represents the number of students in that grade.
Elements of the "students" array

The following example shows how to refer to the first, second, and last element of the array students.

Dim kindergarten As Integer = students(0)


Dim firstGrade As Integer = students(1)
Dim sixthGrade As Integer = students(6)
MsgBox("Students in kindergarten = " & CStr(kindergarten))
MsgBox("Students in first grade = " & CStr(firstGrade))
MsgBox("Students in sixth grade = " & CStr(sixthGrade))

You can refer to the array as a whole by using just the array variable name without indexes.
Array Types and Other Types
Data Types
Every array has a data type, but it is not the same as the data type of its elements. For example, the array students in the
preceding example is of type Integer(), while each of its elements is of type Integer. The notation Integer() means an array of
Integer elements. For more information, see Array Data Types in Visual Basic.
Every array inherits from the System.Array class, and you can declare a variable to be of type Array, but you cannot create an
array of type Array. Also, the ReDim Statement (Visual Basic) cannot operate on a variable declared as type Array. For these
reasons, and for type safety, it is advisable to declare every array as a specific type, such as Integer in the preceding example.
Array Dimensions
The array students in the preceding example uses one index and is said to be one-dimensional. An array that uses more than
one index or subscript is called multidimensional.
Another kind of array is one which holds other arrays as elements. This is known as an array of arrays or a jagged array. A
jagged array can be either one-dimensional or multidimensional, and so can its elements.
Contrasting Types
In contrast to an array, a variable containing a single value is called a scalar variable.
An array is not the same as a collection. For more information, see Collections as an Alternative to Arrays.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
Troubleshooting Arrays
Concepts
Array Dimensions in Visual Basic
Multidimensional Arrays in Visual Basic
Jagged Arrays in Visual Basic
Array Data Types in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Declare an Array Variable


You declare an array variable the same way as any other variable, using the Dim statement. You follow the variable name with
one or more pairs of parentheses to indicate that it is to hold an array rather than a scalar (a variable containing a single value).
Declaring Array Variables
To declare a one-dimensional array variable
In your declaration, add one pair of parentheses after the variable name. The following example declares a variable to
hold a one-dimensional array with elements of the Double Data Type (Visual Basic).

Dim cargoWeights() As Double

The preceding example declares an array variable but does not assign an array to it. You still must create a one-
dimensional array, initialize it, and assign it to cargoWeights.

To declare a multidimensional array variable


In your declaration, add one pair of parentheses after the variable name and place commas inside the parentheses to
separate the dimensions. The following example declares a variable to hold a four-dimensional array with elements of
the Short Data Type (Visual Basic).

Dim atmospherePressures(,,,) As Short

The preceding example declares an array variable but does not assign an array to it. You still must create a four-
dimensional array, initialize it, and assign it to atmospherePressures.

To declare a jagged array variable


In your declaration, add as many pairs of parentheses after the variable name as there are levels of nested arrays. The
following example declares a variable to hold an array of arrays of arrays (an array, each element of which is an array,
each element of which is an array), with the innermost array having elements of the Byte Data Type (Visual Basic).

Dim inquiriesByYearMonthDay()()() As Byte

The preceding example declares an array variable but does not assign an array to it. You still must create an array of
arrays of arrays, initialize it, and assign it to inquiriesByYearMonthDay.

See Also
Tasks
How to: Create an Array
How to: Create an Array with More Than One Dimension
How to: Create an Array of Arrays
How to: Initialize an Array Variable
Troubleshooting Arrays
Concepts
Overview of Arrays in Visual Basic
Multidimensional Arrays in Visual Basic
Jagged Arrays in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Create an Array


An array is an object, so you create it with a New (Visual Basic) clause and assign it to the array variable. You can do this as part
of the array declaration, or in a subsequent assignment statement.
To create an array in the array declaration statement
In your declaration, add a New clause after the variable name and its parentheses. The following example declares a
variable to hold an array with elements of the Date Data Type (Visual Basic), creates the array, and assigns it to the
variable.

Dim validDates() As Date = New Date() {}

Following the execution of this statement, the array in variable validDates has length 0.
Note
The New clause must specify the type name, followed by parentheses, followed by braces, {}. The parentheses do not r
epresent a call to an array constructor. Instead, they indicate that the object type is an array type. The braces supply initi
alization values. The compiler requires the braces even if you are not supplying any values. Therefore, the New clause
must include both the parentheses and the braces, even if they are empty.

To create an array in a separate assignment statement


Use a subsequent assignment statement with a New clause. The following example declares a variable to hold an array
with elements of the Integer Data Type (Visual Basic), and it creates the array and assigns it to the variable in another
statement.

Dim scores() As Integer


scores = New Integer() {}

Following the execution of these statements, the array in variable scores has length 0.
-or-
Use the ReDim Statement (Visual Basic) to not only create an array but initialize its length.

ReDim scores(4)

Following the execution of this statement, the array in variable scores has length 5, with all the elements holding default
values.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array with More Than One Dimension
How to: Create an Array of Arrays
How to: Create an Array with Mixed Element Types
How to: Create an Array with No Elements
How to: Initialize an Array Variable
Troubleshooting Arrays
Concepts
Overview of Arrays in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Create an Array with Mixed Element Types


You declare only one data type for an array, and all its elements must be of that data type. Normally this limitation is desirable,
since all the elements are closely related to each other and have similar types of values. However, sometimes the elements are
not closely related or do not have similar values. In this case, you can declare the array elements to be of the Object Data Type,
and the individual elements can point to different kinds of data, such as numbers, characters, strings, objects, and other arrays.
To create an array with elements of different data types
Declare the array as Object. The following example declares a variable to hold an array of Object elements, creates the
array, and assigns it to the variable.

Dim mixedTypes As Object() = New Object() {}

When you use the Object data type, keep in mind that the performance is not as efficient as when you use a more
specific data type. This is because the runtime has to convert the data between its natural data type and Object, using
operations called boxing and unboxing. This additional processing can hurt your performance if you do it often.

To access elements of different data types in an array


Read or write the elements in the normal way. You can store and retrieve an element of any data type in an Object array.
The following example demonstrates putting information of different data types in an Object array. It stores employee
information in the array in variable employeeData.

Dim employeeData(3) As Object


employeeData(0) = "Alex Hankin"
employeeData(1) = "4242 Maple Street"
employeeData(2) = 48
employeeData(3) = #8/23/1956#

To retrieve information of different data types from an Object array, you can convert an element to the appropriate data
type, as the following example illustrates.

Dim age As Integer = CInt(employeeData(2))


Dim birthDate as Date = CDate(employeeData(3))

In a situation where the elements are not similar or related to each other, another possibility is to put them in a collection
instead of an Object array. For more information, see Collections as an Alternative to Arrays.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Create an Array with More Than One Dimension
How to: Create an Array of Arrays
How to: Create an Array with No Elements
How to: Initialize an Array Variable
Troubleshooting Arrays
Concepts
Overview of Arrays in Visual Basic
Collections as an Alternative to Arrays
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Create an Array with No Elements


An array with no elements is also called a zero-length array. A variable holding a zero-length array does not have the value
Nothing.
You might need to create a zero-length array under the following circumstances:
Your code needs to access members of the Array class, such as Length or Rank, or call a Visual Basic function such as
UBound Function (Visual Basic), without risking a NullReferenceException exception.
You want to keep the consuming code simpler by not having to check for Nothing as a special case.
Your code interacts with an application programming interface (API) that requires you to pass a zero-length array to one
or more procedures, or that returns a zero-length array from one or more procedures.

To create an array with no elements


Declare one of the array's dimensions to be -1. The following example declares a variable to hold an array with elements
of the String Data Type (Visual Basic), but initially sets it to be empty.

Dim twoDimensionalStrings(-1, 3) As String

Following the execution of this statement, the array in variable twoDimensionalStrings is two-dimensional with length 0.
It is empty, but it nonetheless exists. Therefore, a variable pointing to the array is not equal to Nothing. Subsequently,
you can create a nonempty array and assign it to twoDimensionalStrings.
In contrast, the following example declares an array variable that does not initially point to any array.

Dim twoDimStrings( , ) As String

Unlike twoDimensionalStrings in the earlier example, the variable twoDimStrings has the value Nothing.

See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Create an Array with More Than One Dimension
How to: Create an Array of Arrays
How to: Create an Array with Mixed Element Types
How to: Initialize an Array Variable
Troubleshooting Arrays
Concepts
Overview of Arrays in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Initialize an Array Variable


You can initialize an array at the same time you create it, as part of the New (Visual Basic) clause. You can also initialize it in
subsequent assignment statements.
The aspects of an array that you can initialize are the following:
The index upper bounds, which specify the lengths of the array's dimensions
The values of some or all of the array's elements
You can initialize either of these without initializing the other. However, if you supply element values but not upper bounds, the
number of values you supply determines the upper bounds.
To initialize an array in the New clause at creation time
In the New clause, specify the index upper bound inside the parentheses, and supply the element values inside the
braces ({}). The following example declares, creates, and initializes a variable to hold an array with elements of the
Char Data Type (Visual Basic), specifying the upper bound and the values.

Dim testChars As Char() = New Char(2) {"%"c, "&"c, "@"c}

Following the execution of this statement, the array in variable testChars has length 3, with elements at index 0 through
index 2 holding initialized values. If you supply both the upper bound and the values, you must include a value for every
element from index 0 through the upper bound.
Note the literal type character c, which forces a character literal to the Char data type. Without any type character, a
literal enclosed within double quotes (" ") defaults to String.
You do not need to specify the index upper bound if you supply element values in the New clause. The following
example declares, creates, and initializes a variable to hold an array with elements of the
Boolean Data Type (Visual Basic), specifying only the element values.

Dim answers As Boolean() = New Boolean() {True, True, False, True}

Following the execution of this statement, the array in variable answers has length 4, with elements at indexes 0 through
3 holding initialized values.
You can initialize the index upper bound without initializing any elements. If you create an array in this way, you must use a
subsequent assignment statement to initialize each element value.
To initialize an array in subsequent assignment statements
1. Specify the index upper bound in the array variable declaration.
2. Use one or more assignment statements, each of which assigns a value to one of the array's elements. The following
example declares and creates a variable to hold an array with elements of the String Data Type (Visual Basic), and
supplies two element values in subsequent statements.

Dim comments(30) As String


comments(0) = "This is the first comment."
comments(5) = "This is the sixth comment."

Following the execution of these statements, the array in variable comments has length 31, with elements at indexes 0 and
5 holding initialized values, and the other 29 elements holding default values. If you initialize an array in this way, you
can initialize some elements and skip over others.
-or-
Use the ReDim Statement (Visual Basic) to initialize the array's length.
ReDim comments(5)

Following the execution of this statement, the array in variable comments has length 6, with all the elements holding
default values.
Note
You can initialize the index upper bound in only one place. If you specify an upper bound in the parentheses following t
he array variable name, you cannot use a New clause. If you specify the upper bound in the parentheses in the New cl
ause, you must leave the parentheses following the variable name empty.

See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize a Multidimensional Array
How to: Initialize a Jagged Array
Troubleshooting Arrays
Concepts
Overview of Arrays in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

Array Dimensions in Visual Basic


A dimension is a direction in which you can vary the specification of an array's elements. An array that holds the sales total for
each day of the month has one dimension (the day of the month). An array that holds the sales total by department for each
day of the month has two dimensions (the department number and the day of the month). The number of dimensions an array
has is called its rank.
Working with Dimensions
You specify an element of an array by supplying an index or subscript for each of its dimensions. The elements are contiguous
along each dimension from index 0 through the highest index for that dimension.
The following illustrations show the conceptual structure of arrays with different ranks. Each element in the illustrations shows
the index values that access it. For example, you can access the first element of the second row of the two-dimensional array by
specifying indexes (1, 0).
One-dimensional array

Two-dimensional array

Three-dimensional array

One Dimension
Many arrays have only one dimension, such as the number of people of each age. The only requirement to specify an element
is the age for which that element holds the count. Therefore, such an array uses only one index. The following example declares
a variable to hold a one-dimensional array of age counts for ages 0 through 120.

Dim ageCounts(120) As UInteger

Two Dimensions
Some arrays have two dimensions, such as the number of offices on each floor of each building on a campus. The specification
of an element requires both the building number and the floor, and each element holds the count for that combination of
building and floor. Therefore, such an array uses two indexes. The following example declares a variable to hold a two-
dimensional array of office counts, for buildings 0 through 40 and floors 0 through 5.

Dim officeCounts(40, 5) As Byte

A two-dimensional array is also called a rectangular array.


Three Dimensions
A few arrays have three dimensions, such as values in three-dimensional space. Such an array uses three indexes, which in this
case represent the x, y, and z coordinates of physical space. The following example declares a variable to hold a three-
dimensional array of air temperatures at various points in a three-dimensional volume.

Dim airTemperatures(99, 99, 24) As Single

More than Three Dimensions


Although an array can have as many as 32 dimensions, it is rare to have more than three.
Note
When you add dimensions to an array, the total storage needed by the array increases considerably, so use multidimensional
arrays with care.

Using Different Dimensions


Suppose you want to track sales amounts for every day of the present month. You might declare a one-dimensional array with
31 elements, one for each day of the month, as the following example shows.

Dim salesAmounts(30) As Double

Now suppose you want to track the same information not only for every day of a month but also for every month of the year.
You might declare a two-dimensional array with 12 rows (for the months) and 31 columns (for the days), as the following
example shows.

Dim salesAmounts(11, 30) As Double

Now suppose you decide to have your array hold information for more than one year. If you want to track sales amounts for 5
years, you could declare a three-dimensional array with 5 layers, 12 rows, and 31 columns, as the following example shows.

Dim salesAmounts(4, 11, 30) As Double

Note that, because each index varies from 0 to its maximum, each dimension of salesAmounts is declared as one less than the
required length for that dimension. Note also that the size of the array increases with each new dimension. The three sizes in
the preceding examples are 31, 372, and 1,860 elements respectively.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
Troubleshooting Arrays
Concepts
Overview of Arrays in Visual Basic
Multidimensional Arrays in Visual Basic
Jagged Arrays in Visual Basic
Array Data Types in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Specify a Zero Lower Bound on an Array


If you are declaring an array, you can specify the lower bound of each dimension using the zero character (0) with the To
keyword. This does not change the required lower bound, but it can make your code easier to read.
To explicitly specify the zero lower bound on an array
1. Declare the array in the normal way.
2. Inside the parentheses, add 0 To in front of the upper bound for each dimension.

Public Sub declarelowerbounds()


Dim monthtotal(0 To 11) As Double
Dim cell(0 To 39, 0 To 19) As Integer
MsgBox("Total number of elements:" _
& vbCrLf & "monthtotal (0 To 11) length " & CStr(monthtotal.Length) _
& vbCrLf & "cell (0 To 39, 0 To 19) length " & CStr(cell.Length))
End Sub

The lower bound must always be 0, but your code can be more readable when you explicitly declare it. Specifying both bounds
also reminds the reader that the lower bound is 0.
Alternative Array Creation. You can create an array without using the Dim Statement (Visual Basic) or the New (Visual Basic)
clause. For example, you can call the CreateInstance method, or another component can pass your code an array created in this
manner. Such an array can have lower bounds other than 0. You can always test for the lower bound of a dimension with the
GetLowerBound method or the LBound Function (Visual Basic).
See Also
Tasks
Troubleshooting Arrays
Concepts
Array Dimensions in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Determine the Number of Dimensions in an Array


The Rank property of an array returns its rank (the number of dimensions).
To determine the rank of an array
Read the array's Rank property. Do not follow the array name with parentheses.

Dim thisThreeDimArray(,,) As Byte = New Byte(4, 4, 4) {}


MsgBox("Rank of thisThreeDimArray is " & CStr(thisThreeDimArray.Rank))

The MsgBox call displays "Rank of thisThreeDimArray is 3."


An array's rank is part of its data type. Because of this, you cannot change the rank, even with a ReDim statement.
See Also
Tasks
How to: Specify a Zero Lower Bound on an Array
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
Troubleshooting Arrays
Concepts
Array Dimensions in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

Multidimensional Arrays in Visual Basic


An array can have one dimension or more than one. If it has more than one, it is called a multidimensional array. Note that
having multiple dimensions is not the same thing as a jagged array, which has other arrays as its elements.
Dimensions and Size
The dimensionality or rank of an array corresponds to the number of indexes used to identify an individual element. You can
specify up to 32 dimensions, although more than three is rare. The following example declares a two-dimensional array
variable and a three-dimensional array variable.

Dim populations(200, 3) As Long


Dim matrix(5, 15, 10) As Single

The total number of elements is the product of the lengths of all the dimensions. In the preceding example, populations has a
total of 804 elements (201 x 4), and matrix has 1056 elements (6 x 16 x 11). Each index ranges from 0 through the length
specified for its dimension.
A two-dimensional array is also called a rectangular array.
Note
When you add dimensions to an array, the total storage needed by the array increases considerably, so use multidimensional
arrays with care.

Array Class Members


All arrays inherit from the Array class in the System namespace, and you can access the methods and properties of Array on
any array. The following members of Array can be useful:
The Rank property returns the array's rank (number of dimensions).
The GetLength method returns the length along the specified dimension.
The GetUpperBound method returns the highest index value for the specified dimension. The lowest index value for each
dimension is always 0.
The Length property returns the total number of elements in the array.
The System.Array.Sort method sorts the elements of a one-dimensional array.
Note that GetLength and GetUpperBound take a 0-based argument for the dimension you are specifying.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array with More Than One Dimension
How to: Initialize a Multidimensional Array
How to: Initialize a Jagged Array
How to: Initialize a Multidimensional Array
Troubleshooting Arrays
Concepts
Overview of Arrays in Visual Basic
Array Dimensions in Visual Basic
Jagged Arrays in Visual Basic
Array Size in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Create an Array with More Than One Dimension


An array that uses more than one index is called a multidimensional array. As with a one-dimensional array, you create it with
a New (Visual Basic) clause and assign it to the array variable. You can do this as part of the array declaration or in a
subsequent assignment statement.
To create a multidimensional array
1. Place the appropriate number of commas inside the parentheses following the variable name. You should have one
comma fewer than the number of dimensions.
2. Place the same number of commas inside the parentheses in the New clause. You do not need commas inside the braces
({}) if you are not supplying any element values.
The following example declares a variable to hold a two-dimensional array with elements of the
Double Data Type (Visual Basic), creates the array, and assigns it to the variable.

Dim weights(,) As Double = New Double(,) {}

Following the execution of this statement, the array in variable weights has length 0.
Note
When you add dimensions to an array, the total storage needed by the array increases considerably, so use multidimen
sional arrays with care.

To work efficiently with a multidimensional array


Enclose it in a nested For loop.
The following example initializes every element in matrix to a value between 0 and 99, based on its location in the array.

Dim matrix(9, 9) As Double


Dim maxDim0 As Integer = UBound(matrix, 1)
Dim maxDim1 As Integer = UBound(matrix, 2)
For i As Integer = 0 To maxDim0
For j As Integer = 0 To maxDim1
matrix(i, j) = (i * 10) + j
Next j
Next i

A multidimensional array is not the same as a jagged array. For more information, see How to: Create an Array of Arrays.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Create an Array with Mixed Element Types
How to: Create an Array with No Elements
How to: Initialize a Multidimensional Array
Troubleshooting Arrays
Reference
For...Next Statement (Visual Basic)
Concepts
Multidimensional Arrays in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Initialize a Multidimensional Array


You can initialize a multidimensional array variable the same ways you can initialize a one-dimensional array, except that you
must account for every dimension.
To initialize a multidimensional array variable
In the array variable declaration, specify each index upper bound inside the parentheses, separated by commas. The
following example declares and creates a variable to hold a two-dimensional array with elements of the
Short Data Type (Visual Basic), specifying only the upper bounds.

Dim sizes(1, 1) As Short

Following the execution of this statement, the array in variable sizes has a total of four elements, at indexes (0, 0), (0, 1),
(1, 0), and (1, 1), holding default values. If you create an array in this way, you must use a subsequent assignment
statement to assign each element value.
-or-
Follow the declaration with an equal sign (=) and a New (Visual Basic) clause. In the New clause, repeat the element data
type, specify the index upper bounds inside parentheses, and supply empty braces ({}). The following example declares
and creates a variable to hold a three-dimensional array with elements of the Short data type, specifying only the upper
bounds.

Dim replyCounts(,,) As Short = New Short(2, 1, 2) {}

Following the execution of this statement, the array in variable replyCounts has 18 elements holding default values. If
you create an array in this way, you must use a subsequent assignment statement to assign each element value.
Note
You can initialize the index upper bounds in only one place. If you specify upper bounds in the parentheses following th
e array variable name, you cannot use a New clause. If you specify upper bounds in the parentheses in the New clause,
you must leave the parentheses following the variable name empty.

-or-
In the New clause, specify each index upper bound inside the parentheses, and supply the element values inside the
braces ({}). The following example declares, creates, and initializes a variable to hold a two-dimensional array with
elements of the Short data type, specifying the upper bounds and the values. Note the two levels of braces in the New
clause.

Dim startingScores(,) As Short = New Short(1, 1) {{10, 10}, {10, 10}}

Following the execution of this statement, the array in variable startingScores holds four initialized elements. If you
supply both the upper bounds and the values, you must include a value for every element from index 0 through the
upper bound in every dimension.
-or-
In the New clause, leave the parentheses empty except for commas for the appropriate number of dimensions, and
supply the element values inside the braces ({}). The following example declares, creates, and initializes a variable to hold
a two-dimensional array with elements of the Single Data Type (Visual Basic), specifying only the element values. Note
the two levels of braces in the New clause.

Dim diagonal(,) As Single = New Single(,) {{1, 0}, {0, 1}}


Following the execution of this statement, the array in variable diagonal holds four initialized elements.

See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array with More Than One Dimension
How to: Initialize an Array Variable
How to: Initialize a Jagged Array
Troubleshooting Arrays
Concepts
Multidimensional Arrays in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

Jagged Arrays in Visual Basic


An array of which each element is itself an array is called an array of arrays, or a jagged array. Note that having arrays as
elements is not the same thing as a multidimensional array, which has more than one index on a single array.
Meaning of Jagged
Sometimes the data structure in your application is two-dimensional but not rectangular. For example, you might have an
array of months, each element of which is an array of days. Since different months have different numbers of days, the
elements do not form a rectangular two-dimensional array. In such a case, you can use a jagged array instead of a
multidimensional array.
Example
The following example declares an array variable to hold an array of arrays with elements of the
Double Data Type (Visual Basic). Each element of the array sales is itself an array that represents a month. Each month array
holds values for each day in that month.

Dim sales()() As Double = New Double(11)() {}


Dim month As Integer
Dim days As Integer
For month = 0 To 11
days = DateTime.DaysInMonth(Year(Now), month + 1)
sales(month) = New Double(days - 1) {}
Next month

The New clause in the declaration of sales sets the array variable to a 12-element array, each element of which is of type
Double(), an array of Double elements. The For loop then determines how many days are in each month this year
(Year(Now)), and sets the corresponding element of sales to a Double array of the appropriate size.
In the preceding example, the jagged array saves seven elements (six in a leap year) compared to a two-dimensional array. In a
more extreme case the memory savings could be significant.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array of Arrays
How to: Initialize a Jagged Array
Troubleshooting Arrays
Concepts
Overview of Arrays in Visual Basic
Array Dimensions in Visual Basic
Multidimensional Arrays in Visual Basic
Array Data Types in Visual Basic
Writing CLS-Compliant Code
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Create an Array of Arrays


An array with arrays for elements is called an array of arrays, or a jagged array. As with a one-dimensional array, you create it
with a New (Visual Basic) clause and assign it to the array variable. You can do this as part of the array declaration, or in a
subsequent assignment statement.
To create a jagged array
1. Add as many pairs of parentheses after the variable name as there are levels of nested arrays.
2. Add the same number of pairs of parentheses to the New clause. You do not need more than one pair of braces ({}) if
you are not supplying any element values. The following example declares a variable to hold an array of arrays with
elements of the Byte Data Type (Visual Basic), creates the array, and assigns it to the variable.

Dim ratings As Byte()() = New Byte()() {}

Following the execution of this statement, the array in variable ratings has length 0.

See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Create an Array with More Than One Dimension
How to: Create an Array with Mixed Element Types
How to: Create an Array with No Elements
How to: Initialize a Jagged Array
Troubleshooting Arrays
Concepts
Jagged Arrays in Visual Basic
Writing CLS-Compliant Code
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Initialize a Jagged Array


When you initialize a jagged array variable, you can specify the dimension lengths only for the top-level array. There are
several ways you can do this:
To initialize a jagged array variable
In the array variable declaration, specify the top-level index upper bound inside the first pair of parentheses, separated by
commas. The following example declares and creates a variable to hold a jagged array of Byte elements, specifying only
the top-level upper bound.

Dim rainfall(11)() As Byte

Following the execution of this statement, the array in variable rainfall holds 12 elements, each of which is an empty
array of Byte elements.
-or-
In the New clause, specify the top-level index upper bound inside the first pair of parentheses, and supply empty braces
({}). The following example declares and creates a variable to hold a jagged array of Short elements, specifying only the
top-level upper bound.

Dim snowfall()() As Short = New Short(11)() {}

Following the execution of this statement, the array in variable snowfall holds 12 elements, each of which is an empty
array of Short elements.
Note
You can initialize the top-level index upper bound in only one place. If you specify an upper bound in the parentheses f
ollowing the array variable name, you cannot use a New clause. If you specify the upper bound in the parentheses in th
e New clause, you must leave the parentheses following the variable name empty.

-or-
In the New clause, specify the top-level index upper bound inside the parentheses, and supply the element values inside
the braces ({}). The following example declares, creates, and initializes a variable to hold a jagged array of Char elements,
specifying the top-level upper bound and the values. Note the nested New clauses to initialize the bottom-level arrays.

Dim decodeValues()() As Char = New Char(1)() {New Char() {"a"c, "b"c}, New Char() {"p"
c, "q"c}}

Following the execution of this statement, the array in variable decodeValues holds two elements, each of which is a Char
array of length 1 with the element at index 0 holding an initialized value. If you supply both the top-level upper bound
and the values, you must include a value for every top-level element from index 0 through the upper bound.
-or-
In the New clause, omit the top-level parentheses and supply the element values inside the braces ({}). The following
example declares, creates, and initializes a variable to hold a jagged array of Byte elements, specifying only the element
values. Note the two levels of braces in the New clause.

Dim firstValues()() As Byte = {New Byte() {2, 1}, New Byte() {3, 0}}

Following the execution of this statement, the array in variable firstValues has length 2, with elements firstValues(0)
and firstValues(1). Each of the elements is initialized to a two-element Byte array, the first with element values 2 and 1
and the second with element values 3 and 0.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array of Arrays
How to: Initialize an Array Variable
How to: Initialize a Multidimensional Array
Troubleshooting Arrays
Reference
New (Visual Basic)
Concepts
Jagged Arrays in Visual Basic
Writing CLS-Compliant Code
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

Array Data Types in Visual Basic


There is no single data type for all arrays. Instead, the data type of an array is determined by the following factors:
The fact of being an array
The rank (number of dimensions)
The data type of the array's elements
Therefore, two array variables are considered to be of the same data type only when they have the same rank and their
elements have the same data type.
Note that the lengths of the dimensions do not influence the array data type.
Array Examples
The following example declares four array variables, which have various data types.

Dim firstArray(12, 8) As UInteger


Dim secondArray(12, 8, 3) As UInteger
Dim thirdArray(12, 8) As String
Dim fourthArray(5, 20) As UInteger

Following the execution of the preceding statements, the following data type relationships apply to the array variables:
Variables firstArray and secondArray are not of the same data type because they have different ranks.
Variables firstArray and thirdArray are not of the same data type because they have different element data types.
Variables firstArray and fourthArray are of the same data type, and you can assign one to the other.
Jagged Array Data Types
Arrays of arrays, that is, arrays that contain other arrays as elements, are also known as jagged arrays because the lengths of
the element arrays are not necessarily equal. The following example declares two jagged array variables, which have different
data types.

Dim twoDimOfOneDim(,)() As Integer


Dim oneDimOfTwoDim()(,) As Integer

The array in twoDimOfOneDim is two-dimensional, and its element data type is Integer(), or one-dimensional Integer arrays.
The array in oneDimOfTwoDim is one-dimensional, and its element data type is Integer(,), or two-dimensional Integer arrays.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Determine the Data Type of an Array
Troubleshooting Arrays
Concepts
Overview of Arrays in Visual Basic
Array Dimensions in Visual Basic
Multidimensional Arrays in Visual Basic
Jagged Arrays in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Determine the Data Type of an Array


Keep in mind that an array's data type is never the same as that of its elements. You can find out the data type of either an
array or its elements in several ways.
You can call the System.Object.GetType method on the variable to obtain a Type object for the run-time type of the
variable. The Type object holds extensive information in its properties and methods.
You can pass the variable to the TypeName Function (Visual Basic) to obtain a String containing the name of run-time
type.
You can pass the variable to the VarType Function (Visual Basic) to obtain a VariantType value representing the type
classification of the variable.
To determine the data type of an array
Call TypeName on the array name. Do not follow the array name with parentheses, because you are requesting the type
of the array itself.

Dim thisTwoDimArray(,) As Integer = New Integer(9, 9) {}


MsgBox("Type of thisTwoDimArray is " & TypeName(thisTwoDimArray))

The MsgBox call displays "Type of thisTwoDimArray is Integer(,)", which shows you both the element type and the
number of dimensions. It does not display the current lengths of the dimensions, because they are not part of an array's
data type.
To determine the data type of an array element
Select an existing element and call TypeName on that element.

Dim thisTwoDimArray(,) As Integer = New Integer(9, 9) {}


MsgBox("Type of thisTwoDimArray(0, 0) is " & TypeName(thisTwoDimArray(0, 0)))

The MsgBox call displays "Type of thisTwoDimArray(0, 0) is Integer".


The element data type is part of the array's data type. Because of this, you cannot change the data type, even with an
assignment statement or a ReDim statement.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
Troubleshooting Arrays
Reference
TypeName Function (Visual Basic)
VarType Function (Visual Basic)
VariantType Enumeration
Concepts
Array Data Types in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

Array Size in Visual Basic


The size of an array is the product of the lengths of all its dimensions. It represents the total number of elements currently
contained in the array.
The following example declares a three-dimensional array.

Dim prices(3, 4, 5) As Long

The overall size of the array in variable prices is (3 + 1) x (4 + 1) x (5 + 1) = 120.


Array Size Considerations
There are several things to keep in mind when dealing with the size of an array.
Dimension Length
The index of each dimension is 0-based, which means it ranges from 0 through its upper bound. Therefore, the length of a
given dimension is greater by 1 than the declared upper bound for that dimension.
Length Limits
The length of every dimension of an array is limited to the maximum value of the Integer data type, which is (2 ^ 31) - 1.
However, the total size of an array is also limited by the memory available on your system. If you attempt to initialize an array
that exceeds the amount of available RAM, the common language runtime throws an OutOfMemoryException exception.
Size and Element Size
An array's size is independent of the data type of its elements. The size always represents the total number of elements, not the
number of bytes that they consume in storage.
Memory Consumption
It is not safe to make any assumptions regarding how an array is stored in memory. Storage varies on platforms of different
data widths, so the same array can consume more memory on a 64-bit system than on a 32-bit system. Depending on system
configuration when you initialize an array, the common language runtime (CLR) can assign storage either to pack elements as
close together as possible, or to align them all on natural hardware boundaries. Also, an array requires a storage overhead for
its control information, and this overhead increases with each added dimension.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Determine the Size of an Array
How to: Change the Size of an Array
How to: Determine the Length of One Dimension of an Array
Troubleshooting Arrays
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Determine the Size of an Array


The overall size of an array is the product of the lengths of all its dimensions. The array's Length property returns this overall
size, which represents the total number of elements currently contained in the array, not the number of bytes they consume in
storage.
To determine the total size of an array
Read the array's Length property. Do not follow the array name with parentheses.

Dim thisDoubleArray(,) As Char = New Char(4, 9) {}


MsgBox("Total length of thisDoubleArray is " & CStr(thisDoubleArray.Length))

The MsgBox call displays "Total length of thisDoubleArray is 50".


You can find the length of each dimension from the array's GetLength method.
You can change the length of an individual dimension, which changes the overall size. However, you cannot change the rank
(the number of dimensions).
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Change the Size of an Array
How to: Determine the Length of One Dimension of an Array
Troubleshooting Arrays
Reference
Length
Concepts
Array Size in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Change the Size of an Array


You resize an array variable by assigning a new array object to it. You can use either a standard assignment statement or the
ReDim Statement (Visual Basic). In either case, the original array is replaced with a completely new one, and the array variable
points to the new array.
Resizing an array helps you manage memory efficiently. For example, you can start with a small array and then increase its size
if you need more elements. Alternatively, you can start with a large array and then reduce its size when you no longer need all
of it. This technique takes up the additional memory only when you need it.
To resize an array variable using a standard assignment statement
1. Create the new array object, specifying the new dimension lengths.
2. Assign the new array object to the array variable.

Dim thisArrayVariable() As Integer = New Integer(99) {}


thisArrayVariable = New Integer(49) {}

To resize an array variable using the ReDim statement


Specify the new dimension lengths for the array variable in the ReDim statement.

Dim thisArrayVariable() As Integer = New Integer(99) {}


ReDim thisArrayVariable(9)

When you ReDim an array, the existing values of its elements are normally lost. However, you can retain them by including the
Preserve keyword in the ReDim statement.
To resize an array variable preserving existing element values
1. Specify the new dimension lengths for the array variable in the ReDim statement.
2. Add the Preserve keyword in the ReDim statement. The following example creates a new array, initializes its elements
from the corresponding elements of the existing array in arrayToIncrease, and assigns the new array to the array
variable arrayToIncrease.

Dim arrayToIncrease(9, 49)


ReDim Preserve arrayToIncrease(9, 199)

If you use Preserve on a multidimensional array, you can change only the last dimension length. If you attempt to change any
of the other dimensions, an ArrayTypeMismatchException exception occurs.
If you resize a large array using the Preserve keyword, keep in mind that Visual Basic must copy all the existing elements into
the new array. This can make your performance slower.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Determine the Size of an Array
How to: Determine the Length of One Dimension of an Array
How to: Assign One Array to Another Array
How to: Change an Array to a Different Array
Troubleshooting Arrays
Concepts
Array Size in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Determine the Length of One Dimension of an Array


The GetLength method of an array returns the length along the dimension you specify.
To determine the length of one dimension of an array
Call GetLength on the array name. Supply the dimension for which you want the length as the argument to GetLength.
Note that the dimension argument is 0-based.

Dim sampleTripleArray(,,) As Short = New Short(2, 3, 4) {}


MsgBox("Dimension lengths of sampleTripleArray are " & CStr(sampleTripleArray.GetLengt
h(0)) _
& ", " & CStr(sampleTripleArray.GetLength(1)) & ", " & CStr(sampleTripleArray.GetL
ength(2)))

The MsgBox call displays "Dimension lengths of sampleTripleArray are 3, 4, 5".


The lowest index value for each dimension is always 0, and the GetUpperBound method returns a dimension's highest index
value. For each dimension, GetLength returns a value higher by 1 than that returned by GetUpperBound. As with
GetLength, the dimension you specify for GetUpperBound is 0-based.
You can find the total length of an array from its Length property.
You can change the overall size by changing the length of an individual dimension. However, you cannot change the rank (the
number of dimensions).
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Determine the Size of an Array
How to: Change the Size of an Array
Troubleshooting Arrays
Concepts
Array Size in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

Working with Arrays and Array Elements


This section discusses the sorting of arrays, putting or getting an array value, and other actions on arrays and array elements.
In This Section
How to: Put a Value into an Array
Shows how to store values in array elements.
How to: Get a Value from an Array
Discusses how to retrieve values from array elements.
How to: Locate an Element in an Array in Visual Basic
Explains how to find a particular element in an array.
How to: Reverse the Contents of An Array in Visual Basic
Describes how to reverse the order of the elements of an array.
How to: Sort An Array in Visual Basic
Shows how to sort the elements of an array alphabetically.
How to: Assign One Array to Another Array
Describes the rules and steps for assigning an array to another array variable.
How to: Change an Array to a Different Array
Discusses what changes are possible and how to accomplish them.
How to: Pass an Array to a Procedure or Property
Explains how to pass an array as an argument to a procedure or property.
How to: Return an Array from a Procedure or Property
Describes how to return an array to the code that calls a procedure or property.
Reference
Dim Statement (Visual Basic)
Declares and allocates storage space for one or more variables.
System.Array
Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the base class for all arrays in
the common language runtime.
Related Sections
Troubleshooting Arrays
Discusses some common problems that arise when working with arrays.
Arrays in Visual Basic
Discusses making your code more compact and powerful by declaring and using arrays.
Visual Basic Language Concepts

How to: Put a Value into an Array


You can store one of an array's values by using the array name and the appropriate indexes to specify the individual element.
To put a value into an array element
1. At the left of the equal sign (=), specify the array name followed by parentheses.
2. Inside the parentheses, include an expression for each index corresponding to the element you want to store. You need
one index for each array dimension. The following example shows some statements that store values in arrays.
Dim numbers() As Integer

Dim matrix(,) As Double

numbers(i + 1) = 0

matrix(3, j * 2) = j

For each array dimension, the GetUpperBound method returns the highest value the index can have. The lowest index
value is always 0.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Get a Value from an Array
How to: Locate an Element in an Array in Visual Basic
How to: Reverse the Contents of An Array in Visual Basic
How to: Sort An Array in Visual Basic
Troubleshooting Arrays
Concepts
Array Dimensions in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Get a Value from an Array


You can get one of an array's values by using the array name and the appropriate indexes to specify the individual element.
To get a value from an array element
1. Inside an expression, specify the array name followed by parentheses.
2. Inside the parentheses, include an expression for each index corresponding to the element you want to get. You need one
index for each array dimension. The following example shows some statements that get values from arrays.

Dim sortedValues(), rawValues(), estimates(,,) As Double


lowestValue = sortedValues(0)
wTotal += (rawValues(v) ^ 2)
firstGuess = estimates(i, j, k)

For each array dimension, the GetUpperBound method returns the highest value the index can have. The lowest index value is
always 0.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Put a Value into an Array
How to: Locate an Element in an Array in Visual Basic
How to: Reverse the Contents of An Array in Visual Basic
How to: Sort An Array in Visual Basic
Troubleshooting Arrays
Concepts
Array Dimensions in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Locate an Element in an Array in Visual Basic


This example declares an array of String objects named zooAnimals, populates it, and then finds the element "turtle" and
displays its location.
Example
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).

Public Sub findAnimal()


Dim zooAnimals(2) As String
zooAnimals(0) = "lion"
zooAnimals(1) = "turtle"
zooAnimals(2) = "ostrich"
Dim turtleIndex As Integer
turtleIndex = (Array.IndexOf(zooAnimals,"turtle"))
MsgBox("The turtle is element " & turtleIndex)
End Sub

Compiling the Code


This example requires:
Access to Mscorlib.dll and the System namespace.
Robust Programming
The following conditions may cause an exception:
Array is empty (ArgumentNullException class)
Array is multidimensional (RankException class)
One or more elements of the array do not implement the IComparable interface (InvalidOperationException class)
See Also
Tasks
How to: Put a Value into an Array
How to: Get a Value from an Array
How to: Reverse the Contents of An Array in Visual Basic
How to: Sort An Array in Visual Basic
Troubleshooting Arrays
Reference
System.Array.IndexOf
Concepts
Overview of Arrays in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Reverse the Contents of An Array in Visual Basic


This example declares an array of String objects named zooAnimals, populates it, and then reverses its contents.
Example
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).

Public Sub reverseAnimals()


Dim zooAnimals(2) As String
zooAnimals(0) = "lion"
zooAnimals(1) = "turtle"
zooAnimals(2) = "ostrich"
Array.Reverse(zooAnimals)
End Sub

Compiling the Code


This example requires:
Access to Mscorlib.dll and the System namespace.
Robust Programming
The following conditions may cause an exception:
Array is empty (ArgumentNullException class)
Array is multidimensional (RankException class)
One or more elements of the array do not implement the IComparable interface (InvalidOperationException class)
See Also
Tasks
How to: Put a Value into an Array
How to: Get a Value from an Array
How to: Locate an Element in an Array in Visual Basic
How to: Sort An Array in Visual Basic
Troubleshooting Arrays
Reference
System.Array.Reverse
Concepts
Overview of Arrays in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Sort An Array in Visual Basic


This example declares an array of String objects named zooAnimals, populates it, and then sorts it alphabetically.
Example
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).

Private Sub sortAnimals()


Dim zooAnimals(2) As String
zooAnimals(0) = "lion"
zooAnimals(1) = "turtle"
zooAnimals(2) = "ostrich"
Array.Sort(zooAnimals)
End Sub

Compiling the Code


This example requires:
Access to Mscorlib.dll and the System namespace.
Robust Programming
The following conditions may cause an exception:
Array is empty (ArgumentNullException class)
Array is multidimensional (RankException class)
One or more elements of the array do not implement the IComparable interface (InvalidOperationException class)
See Also
Tasks
How to: Put a Value into an Array
How to: Get a Value from an Array
How to: Locate an Element in an Array in Visual Basic
How to: Reverse the Contents of An Array in Visual Basic
Troubleshooting Arrays
Reference
System.Array.Sort
Concepts
Overview of Arrays in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Assign One Array to Another Array


Because arrays are objects, you can use them in assignment statements like other object types. An array variable holds a
pointer to the data constituting the array elements and the rank and length information, and an assignment copies only this
pointer.
To assign one array to another array
1. Ensure that the two arrays have the same rank (number of dimensions) and compatible element data types.
2. Use a standard assignment statement to assign the source array to the destination array. Do not follow either array name
with parentheses.

Dim formArray() As System.Windows.Forms.Form


Dim controlArray() As System.Windows.Forms.Control
controlArray = formArray

When you assign one array to another, the following rules apply:
Equal Ranks. The rank (number of dimensions) of the destination array must be the same as that of the source array.
Provided the ranks of the two arrays are equal, the dimensions do not need to be equal. The number of elements in a
given dimension can change during assignment.
Element Types. Either both arrays must have reference type elements or both arrays must have value type elements.
For more information, see Value Types and Reference Types.
If both arrays have value type elements, the element data types must be exactly the same. The only exception to
this is that you can assign an array of Enum elements to an array of the base type of that Enum.
If both arrays have reference type elements, the source element type must derive from the destination element
type. When this is the case, the two arrays have the same inheritance relationship as their elements. This is called
array covariance.
The compiler reports an error if the above rules are violated, for example if the data types are not compatible or the ranks are
unequal. You can add error handling to your code to make sure that the arrays are compatible before attempting an
assignment. You can also use the TryCast keyword if you want to avoid throwing an exception.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Change the Size of an Array
How to: Change an Array to a Different Array
How to: Pass an Array to a Procedure or Property
How to: Return an Array from a Procedure or Property
Troubleshooting Arrays
Reference
Enum Statement (Visual Basic)
Concepts
Array Conversions
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Change an Array to a Different Array


It is important to distinguish between an array object and an array variable. An array variable holds a pointer to an array
object, which holds the array elements and the rank and length information.
Once you create an array object, you cannot change its rank (number of dimensions), its dimension lengths, or the data
type of its elements. You can change only the contents of its elements.
Once you declare an array variable, you cannot change its rank or its element data type. However, you can assign a
succession of different array objects to the variable during its lifetime. These array objects can have different dimension
lengths.
To change an array variable to point to a different array object
Use a standard assignment statement to assign the source array to the destination array.

Dim array1(4), array2(19) As String


array2 = array1

You can change an array variable to point to an array object with different dimension lengths, but you cannot change it to
point to an array object of a different data type. This means that the rank and the element data type must remain the same,
because they are inherently part of the array variable's data type.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Assign One Array to Another Array
How to: Pass an Array to a Procedure or Property
How to: Return an Array from a Procedure or Property
How to: Change the Size of an Array
Troubleshooting Arrays
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Pass an Array to a Procedure or Property


You pass an array the same way you pass any other variable. You supply the array variable name in the appropriate argument
when you call the procedure or access the property.
To pass an array to a procedure
1. Ensure that one of the procedure parameters specifies an array with the same rank (number of dimensions) and element
data type.
2. Supply the array variable at the corresponding place in the argument list. Do not follow the array name with parentheses.

Public Function findLargest(ByVal numbers() As Double) As Double


' Insert code to calculate and return largest number.
End Function
Dim testNumbers() As Double = New Double() {5.0, 3.7, 1.2, 7.6}
Dim largestNumber As Double = findLargest(testNumbers)

To pass an array to a property


1. Ensure that one of the property parameters specifies an array with the same rank (number of dimensions) and element
data type.
2. Supply the array variable at the corresponding place in the argument list. Do not follow the array name with parentheses.

Public Property bestMatch(ByVal formattedStrings() As String) As Double


' Insert Get and Set procedures for number best matching strings.
End Property
Dim testStrings() As String = New String() {}
Dim formattedNumber As Double = bestMatch(testStrings)

See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Assign One Array to Another Array
How to: Change an Array to a Different Array
How to: Return an Array from a Procedure or Property
Troubleshooting Arrays
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Return an Array from a Procedure or Property


You return an array the same way you return any other data type. You supply the array type as the return type of the
procedure or property.
To return an array from a Function procedure
1. Specify the array type (rank and element data type) as the return type in the Function Statement (Visual Basic).
2. Within the procedure, declare a local array variable with the same rank and element data type.
3. Include this local array variable in the Return Statement (Visual Basic). Do not follow the array name with parentheses.

Public Function splitNumber(ByVal number As Double) As Char()


Dim characters() As Char
' Insert code to split number into characters.
Return characters
End Function
Dim piCharacters() As Char = splitNumber(3.14159265)

To return an array from a property


1. Specify the array type (rank and element data type) as the property type in the Property Statement.
2. Within the property's Get procedure, or in a place available to the Get procedure, declare a local array variable with the
same rank and element data type.
3. Include this local array variable in the Return statement. Do not follow the array name with parentheses.

Private nameList() As String


Public Property stationNames As String()
Get
Return nameList
End Get
Set(ByVal Value As String())
' Insert code to store nameList values.
End Set
End Property
Dim listOfNames() As String = stationNames

See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
How to: Assign One Array to Another Array
How to: Change an Array to a Different Array
How to: Pass an Array to a Procedure or Property
Troubleshooting Arrays
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

Collections as an Alternative to Arrays


Although collections are most often used for working with the Object Data Type, you can use a collection to work with any data
type. In some circumstances, it can be more efficient to store items in a collection than in an array.
If you need to change the size of an array, you must use the ReDim Statement (Visual Basic). When you do this, Visual Basic
creates a new array and releases the previous array for disposal. This takes execution time. Therefore, if the number of items
you are working with changes frequently, or you cannot predict the maximum number of items you need, you might obtain
better performance using a collection.
A collection, which does not have to create a new object or copy existing elements, can handle resizing in less execution time
than an array, which has to use ReDim. But if the size does not change, or changes only rarely, an array is likely to be more
efficient. As always, performance is highly dependent on the individual application. It is often worth your time to try both an
array and a collection.
Specialized Collections
The .NET Framework also provides a variety of classes, interfaces, and structures for general and special collections. The
System.Collections and System.Collections.Specialized namespaces contain definitions and implementations that include
dictionaries, lists, queues, and stacks. The System.Collections.Generic namespace provides many of these in generic versions,
which take one or more type arguments.
If your collection is to hold elements of only one specific data type, a generic collection has the advantage of enforcing type
safety. For more information on generics, see Generic Types in Visual Basic.
Example
The following example uses the .NET Framework generic class System.Collections.Generic.List to create a list collection of
customer structures.

' Define the structure for a customer.


Public Structure customer
Public name As String
' Insert code for other members of customer structure.
End Structure
' Create a module-level collection that can hold 200 elements.
Public custFile As New List(Of customer)(200)
' Add a specified customer to the collection.
Private Sub addNewCustomer(ByVal newCust As customer)
' Insert code to perform validity check on newCust.
custFile.Add(newCust)
End Sub
' Display the list of customers in the Debug window.
Private Sub printCustomers()
For Each cust As customer In custFile
Debug.WriteLine(cust)
Next cust
End Sub

The declaration of the custFile collection specifies that it can contain elements only of type customer. It also provides for an
initial capacity of 200 elements. The procedure addNewCustomer checks the new element for validity and then adds it to the
collection. The procedure printCustomers uses a For Each loop to traverse the collection and display its elements.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Initialize an Array Variable
Troubleshooting Arrays
Reference
ReDim Statement (Visual Basic)
Concepts
Collections in Visual Basic
Generic Types in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

Troubleshooting Arrays
This page lists some common problems that can occur when working with arrays.
Compilation Errors Declaring and Initializing an Array
Compilation errors can arise from misunderstanding of the rules for declaring, creating, and initializing arrays. The most
common causes of errors are the following:
Supplying a New (Visual Basic) clause after specifying dimension lengths in the array variable declaration. The following
code lines show invalid declarations of this type.
Dim INVALIDsingleDimByteArray(2) As Byte = New Byte()

Dim INVALIDtwoDimShortArray(1, 1) As Short = New Short(,)

Dim INVALIDjaggedByteArray(1)() As Byte = New Byte()()

Specifying dimension lengths for more than the top-level array of a jagged array. The following code line shows an
invalid declaration of this type.
Dim INVALIDjaggedByteArray(1)(1) As Byte

Omitting the New keyword when specifying the element values. The following code line shows an invalid declaration of
this type.
Dim INVALIDoneDimShortArray() As Short = Short() {0, 1, 2, 3}

Supplying a New clause without braces ({}). The following code lines show invalid declarations of this type.
Dim INVALIDsingleDimByteArray() As Byte = New Byte()

Dim INVALIDsingleDimByteArray() As Byte = New Byte(2)

Dim INVALIDtwoDimShortArray(,) As Short = New Short(,)

Dim INVALIDtwoDimShortArray(,) As Short = New Short(1, 1)

Accessing an Array Out of Bounds


The process of initializing an array assigns an upper bound and a lower bound to each dimension. Every access to an element
of the array must specify a valid index, or subscript, for every dimension. If any index is below its lower bound or above its
upper bound, an IndexOutOfRangeException exception results. The compiler cannot detect such an error, so an error occurs at
run time.
Determining Bounds
If another component passes an array to your code, for example as a procedure argument, you do not know the size of that
array or the lengths of its dimensions. You should always determine the upper bound for every dimension of an array before
you attempt to access any elements. If the array has been created by some means other than a Visual Basic New clause, the
lower bound might be something other than 0, and it is safest to determine that lower bound as well.
Specifying the Dimension
When determining the bounds of a multidimensional array, take care how you specify the dimension. The dimension
parameters of the GetLowerBound and GetUpperBound methods are 0-based, while the Rank parameters of the Visual
Basic LBound Function (Visual Basic) and UBound Function (Visual Basic) are 1-based.
See Also
Tasks
How to: Declare an Array Variable
How to: Create an Array
How to: Create an Array with More Than One Dimension
How to: Create an Array of Arrays
How to: Create an Array with Mixed Element Types
How to: Create an Array with No Elements
How to: Initialize an Array Variable
How to: Initialize a Multidimensional Array
How to: Initialize a Jagged Array
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

Objects in Visual Basic


When you create an application in Visual Basic, you constantly work with objects. You can use objects provided by Visual Basic,
such as controls, forms, and data access objects. You can also use objects from other applications within your Visual Basic
application. You can even create your own objects and define additional properties and methods for them. Objects act like
prefabricated building blocks for programs — they let you write a piece of code once and reuse it over and over.
The following topics discuss objects in more detail.
In This Section
Objects and Classes
Provides an overview of objects and classes.
How to: Create an Object
Explains how to create an object so you can use its members.
How to: Reuse a Working Component
Describes how to use functionality that has already been written and debugged.
How to: Define a Class That Uses Members of an Existing Class
Shows how to use properties and methods of a base class in your derived class.
Relationships Among Objects
Discusses object hierarchies, containers, and collections.
Object Members
Summarizes the fields, properties, methods, and events exposed by objects.
How to: Access Shared and Nonshared Members of an Object
Explains how to read, write, or call a member of an object that you have created.
Related Sections
Introduction to Objects in Visual Basic
Provides an overview of how objects are used in Visual Basic.
Creating and Using Objects
Shows how to create and use instances of classes.
Visual Basic Language Concepts

Objects and Classes


An object is a combination of code and data that can be treated as a unit. An object can be a piece of an application, like a
control or a form. An entire application can also be an object.
Reusing Code
Objects let you declare variables and procedures once and then reuse them whenever needed. For example, if you want to add
a spelling checker to an application you could define all the variables and support functions to provide spell-checking
functionality. If you create your spelling checker as a class, you can then reuse it in other applications by adding a reference to
the compiled assembly. Better yet, you may be able to save yourself some work by using a spelling checker class that someone
else has already developed.
Classes
Each object in Visual Basic is defined by a class. A class describes the variables, properties, procedures, and events of an object.
Objects are instances of classes; you can create as many objects you need once you have defined a class.
To understand the relationship between an object and its class, think of cookie cutters and cookies. The cookie cutter is the
class. It defines the characteristics of each cookie, for example size and shape. The class is used to create objects. The objects
are the cookies.
Two examples in Visual Basic might help illustrate the relationship between classes and objects.
The controls on the Toolbox in Visual Basic represent classes. When you drag a control from the Toolbox onto a form,
you are creating an object — an instance of a class.
The form you work with at design time is a class. At run time, Visual Basic creates an instance of the form's class — that
is, an object.
Multiple Instances
Objects newly created from a class are often identical to each other. Once they exist as individual objects, however, their
variables and properties can be changed independently of the other instances. For example, if you add three check boxes to a
form, each check box object is an instance of the CheckBox class. The individual CheckBox objects share a common set of
characteristics and capabilities (properties, variables, procedures, and events) defined by the class. However, each has its own
name, can be separately enabled and disabled, and can be placed in a different location on the form.
See Also
Concepts
Relationships Among Objects
Introduction to Objects in Visual Basic
Other Resources
Creating and Using Objects
Understanding Classes
Visual Basic Language Concepts

How to: Create an Object


An object is an instance of a class. To make use of the class's members you must first create an object from that class.
To create an object from a class
1. Determine from which class you want to create an object.
2. Write a Dim Statement (Visual Basic) to create a variable to which you can assign a class instance. The variable should be
of the type of the desired class.

Dim nextCustomer As customer

3. Add the New (Visual Basic) keyword to initialize the variable to a new instance of the class.

Dim nextCustomer As New customer

4. You can now access the members of the class through the object variable.

nextCustomer.accountNumber = lastAccountNumber + 1

Robust Programming
Whenever possible, you should declare the variable to be of the class type you intend to assign to it. This is called early
binding. If you do not know the class type at compile time, you can invoke late binding by declaring the variable to be of the
Object Data Type. However, late binding can make performance slower and limit access to the run-time object's members. For
more information, see Object Variable Declaration.
See Also
Tasks
How to: Reuse a Working Component
How to: Define a Class That Uses Members of an Existing Class
How to: Access Shared and Nonshared Members of an Object
Concepts
Objects and Classes
Visual Basic Language Concepts

How to: Reuse a Working Component


If a component already exists and is debugged and working, it is to your advantage to use it in your code instead of developing
another component with the same functionality. Such a component is usually exposed as a class. To reuse it, you create an
object from that class.
Example
The .NET Framework provides many examples of components that are available for use. One such component is the TimeZone
class in the System namespace. TimeZone provides members that allow you to retrieve information about the time zone of
the current computer system.

Public Sub examineTimeZone()


Dim tz As System.TimeZone = System.TimeZone.CurrentTimeZone
Dim s As String = "Current time zone is "
s &= CStr(tz.GetUtcOffset(Now).Hours) & " hours and "
s &= CStr(tz.GetUtcOffset(Now).Minutes) & " minutes "
s &= "different from UTC (coordinated universal time)"
s &= vbCrLf & "and is currently "
If tz.IsDaylightSavingTime(Now) = False Then s &= "not "
s &= "on ""summer time""."
MsgBox(s)
End Sub

The first Dim Statement (Visual Basic) declares an object variable of type TimeZone and assigns to it a TimeZone object
returned by the CurrentTimeZone property.
See Also
Tasks
How to: Create an Object
How to: Define a Class That Uses Members of an Existing Class
How to: Access Shared and Nonshared Members of an Object
Concepts
Objects and Classes
Visual Basic Language Concepts

How to: Define a Class That Uses Members of an Existing Class


You can use members of an existing class in another class that derives from it.
In the following example, suppose you want to define a special kind of Button that acts like a normal Button but also exposes a
method that reverses the foreground and background colors.
To define a class that uses the members of an already existing class
1. Use a Class Statement (Visual Basic) to define a class from which to create the object you need.
Public Class reversibleButton

Be sure an End Class statement follows the last line of code in your class. By default, the integrated development
environment (IDE) automatically generates an End Class when you enter a Class statement.
2. Follow the Class statement immediately with an Inherits Statement. Specify the class from which your new class derives.
Inherits System.Windows.Forms.Button

Your new class inherits all the members defined by the base class.
3. Add the code for the additional members your derived class exposes. For example, you might add a reverseColors
method, and your derived class might look as follows:

Public Class reversibleButton


Inherits System.Windows.Forms.Button
Public Sub reverseColors()
Dim saveColor As System.Drawing.Color = Me.BackColor
Me.BackColor = Me.ForeColor
Me.ForeColor = saveColor
End Sub
End Class

If you create an object from the reversibleButton class, it can access all the members of the Button class, as well as the
reverseColors method and any other new members you define on reversibleButton.

Compiling the Code


Be sure the compiler can access the class from which you intend to derive your new class. This might mean fully qualifying its
name, as in the preceding example, or identifying its namespace in an Imports Statement. If the class is in a different project,
you might need to add a reference to that project. For more information, see Referencing Namespaces and Components.
See Also
Tasks
How to: Create an Object
How to: Reuse a Working Component
How to: Access Shared and Nonshared Members of an Object
How to: Create Derived Classes
Concepts
Objects and Classes
Inheritance Basics
Visual Basic Language Concepts

Relationships Among Objects


Objects can be related to each other in several ways. The principal kinds of relationship are hierarchical and containment.
Hierarchical Relationship
When classes are derived from more fundamental classes, they are said to have a hierarchical relationship. Class hierarchies
are useful when describing items that are a subtype of a more general class. For example, in the System.Windows.Forms
namespace, the Label and TextBox classes both derive from the Control class. Derived classes inherit members from the class
they are based on, allowing you to add complexity as you progress in a class hierarchy.
Containment Relationship
Another way that objects can be related is a containment relationship. Container objects logically encapsulate other objects.
For example, the OperatingSystem object logically contains a Version object, which it returns through its Version property.
Note that the container object does not physically contain any other object.
Collections
One particular type of object containment is represented by collections. Collections are groups of similar objects that can be
enumerated. Visual Basic supports a specific syntax in the For Each...Next Statement (Visual Basic) that allows you to iterate
through the items of a collection. Additionally, collections often allow you to use an Item Property (Collection Object) to
retrieve elements by their index or by associating them with a unique string. Collections can be easier to use than arrays
because they allow you to add or remove items without using indexes. Because of their ease of use, collections are often used
to store forms and controls.
See Also
Concepts
Object Members
Collections in Visual Basic
Objects from Visual Basic and Other Sources
Other Resources
Designing an Inheritance Hierarchy
Creating and Using Objects
Visual Basic Language Concepts

Object Members
Objects are the basic units of object-oriented programming. An object is an element of an application, representing an instance
of a class. Fields, properties, methods, and events are the building blocks of objects and constitute their members.
Objects
An object represents an instance of a class, such as Form or Label. You must create an object before you can access its
nonshared members. To do this, you use the New keyword to specify the class from which to create the object, and then assign
the new object to an object variable.

Dim warningLabel As New System.Windows.Forms.Label

For more information, see How to: Create an Object.


Member Access
You access a member of an object by specifying, in order, the name of the object variable, a period (.), and the name of the
member. The following example sets the Text property of a Label object.

warningLabel.Text = "Data not saved"

Fields and Properties


Fields and properties represent information stored in an object. You retrieve and set their values with assignment statements
the same way you retrieve and set local variables in a procedure. The following example retrieves the Width property and sets
the ForeColor property of a Label object.

Dim warningWidth As Integer = warningLabel.Width


warningLabel.ForeColor = System.Drawing.Color.Red

Note that a field is also called a member variable.


For more information, see Property Procedures vs. Fields.
Methods
A method is an action that an object can perform. For example, Add is a method of the ComboBox object that adds a new entry
to a combo box.
The following example demonstrates the Start method of a Timer object.

Dim safetyTimer As New System.Windows.Forms.Timer


safetyTimer.Start()

Note that a method is simply a procedure that is exposed by an object.


For more information, see How to: Perform Actions with Methods.
Events
An event is an action recognized by an object, such as clicking the mouse or pressing a key, and for which you can write code
to respond. Events can occur as a result of a user action or program code, or they can be caused by the system. Code that
signals an event is said to raise the event, and code that responds to it is said to handle it.
You can also develop your own custom events to be raised by your objects and handled by other objects. For more
information, see Events and Event Handlers.
Instance Members and Shared Members
When you create an object from a class, the result is an instance of that class. Members that are not declared with the
Shared (Visual Basic) keyword are instance members, which belong strictly to that particular instance. An instance member in
one instance is independent of the same member in another instance of the same class. An instance member variable, for
example, can have different values in different instances.
Members declared with the Shared keyword are shared members, which belong to the class as a whole and not to any
particular instance. A shared member exists only once, no matter how many instances of its class you create, or even if you
create no instances. A shared member variable, for example, has only one value, which is available to all code that can access
the class.
IntelliSense Listing of Members
IntelliSense lists members of a class when you invoke its List Members option, for example when you type a period (.) as a
member-access operator. If you type the period following the name of a variable declared as an instance of that class,
IntelliSense lists all the instance members and none of the shared members. If you type the period following the class name
itself, IntelliSense lists all the shared members and none of the instance members. For more information, see
Using IntelliSense.
See Also
Concepts
Relationships Among Objects
Other Resources
Objects in Visual Basic
Visual Basic Language Concepts

How to: Access Shared and Nonshared Members of an Object


Once an object is created, you can access its fields, properties, methods, and events through the object's variable. If the
member is Shared (Visual Basic), you do not need to create an object to access it.
Accessing Nonshared Members
To access a nonshared member of an object
1. Make sure the object has been created from its class and assigned to an object variable.

Dim secondForm As New System.Windows.Forms.Form

2. In the statement that accesses the member, follow the object variable name with the member-access operator (.) and
then the member name.

secondForm.Show()

Accessing Shared Members


To access a shared member of an object
Follow the class name with the member-access operator (.) and then the member name. You should always access a
Shared member of the object directly through the class name.

MsgBox("This computer is called " & Environment.MachineName)

If you have already created an object from the class, you can alternatively access a Shared member through the object's
variable.
See Also
Tasks
How to: Create an Object
How to: Reuse a Working Component
How to: Define a Class That Uses Members of an Existing Class
How to: Access Members of an Object
Concepts
Object Members
Visual Basic Language Concepts

Strings in Visual Basic


This section describes the basic concepts behind using strings in Visual Basic.
In This Section
Introduction to Strings in Visual Basic
Lists topics that describe the basic concepts behind using strings in Visual Basic.
Building Strings in Visual Basic
Lists topics that discuss how to create new strings.
Converting Between Strings and Other Data Types in Visual Basic
Lists topics that describe how to convert strings into other data types.
Walkthroughs For Strings in Visual Basic
Lists walkthroughs involving string manipulation.
Validating Strings in Visual Basic
Lists topics that discuss how to validate strings.
Search and Replace for Strings in Visual Basic
Lists topics that discuss how to use search and replace for strings.
Parsing Strings in Visual Basic
Lists topics that discuss how to parse strings.
Troubleshooting Strings in Visual Basic
Lists topics that provide advice on how to troubleshoot string manipulation.
See Also
Other Resources
Visual Basic Language Features
Visual Basic Language Concepts

Introduction to Strings in Visual Basic


This section describes the basic concepts behind using strings in Visual Basic.
In This Section
String Basics in Visual Basic
Introduces the basic concepts behind using strings and string variables.
Types of String Manipulation Methods in Visual Basic
Introduces several different ways to analyze and manipulate strings.
Nothing and Strings in Visual Basic
Describes how the Visual Basic runtime and the .NET Framework evaluate Nothing differently when it comes to strings.
How Culture Affects Strings in Visual Basic
Discusses how Visual Basic uses culture information to perform string conversions and comparisons.
Zero-based vs. One-based String Access in Visual Basic
Compares how Visual Basic and the .NET Framework provide access to the characters in a string.
See Also
Other Resources
Strings in Visual Basic
Building Strings in Visual Basic
Visual Basic Language Concepts

String Basics in Visual Basic


The String data type represents a series of characters (each representing in turn an instance of the Char data type). This topic
introduces the basic concepts of strings in Visual Basic.
String Variables
An instance of a string can be assigned a literal value that represents a series of characters. For example:
VB
Dim MyString As String
MyString = "This is an example of the String data type"

A String variable can also accept any expression that evaluates to a string. Examples are shown below:
VB
Dim OneString As String
Dim TwoString As String
OneString = "one, two, three, four, five"
' Evaluates to "two".
TwoString = OneString.Substring(5, 3)
OneString = "1"
' Evaluates to "11".
TwoString = OneString & "1"

Any literal that is assigned to a String variable must be enclosed in quotation marks (""). This means that a quotation mark
within a string cannot be represented by a quotation mark. For example, the following code causes a compiler error:
VB
Dim myString As String

' This line would cause an error.


' myString = "He said, "Look at this example!""

This code causes an error because the compiler terminates the string after the second quotation mark, and the remainder of
the string is interpreted as code. To solve this problem, Visual Basic interprets two quotation marks in a string literal as one
quotation mark in the string. The following example demonstrates the correct way to include a quotation mark in a string:
VB
' The value of myString is: He said, "Look at this example!"
myString = "He said, ""Look at this example!"""

In the preceding example, the two quotation marks preceding the word Look become one quotation mark in the string. The
three quotation marks at the end of the line represent one quotation mark in the string and the string termination character.
Characters in Strings
A string can be thought of as a series of Char values, and the String type has built-in functions that allow you to perform
many manipulations on a string that resemble the manipulations allowed by arrays. Like all array in .NET Framework, these are
zero-based arrays. You may refer to a specific character in a string through the Chars property, which provides a way to access
a character by the position in which it appears in the string. For example:
VB
Dim myString As String = "ABCDE"
Dim myChar As Char
' The value of myChar is "C".
myChar = myString.Chars(3)

In the above example, the Chars property of the string returns the fourth character in the string, which is D, and assigns it to
myChar. You can also get the length of a particular string through the Length property. If you need to perform multiple array-
type manipulations on a string, you can convert it to an array of Char instances using the ToCharArray function of the string.
For example:
VB
Dim myString As String = "abcdefghijklmnop"
Dim myArray As Char() = myString.ToCharArray

The variable myArray now contains an array of Char values, each representing a character from myString.
The Immutability of Strings
A string is immutable, which means its value cannot be changed once it has been created. However, this does not prevent you
from assigning more than one value to a string variable. Consider the following example:
VB
Dim myString As String = "This string is immutable"
myString = "Or is it?"

Here, a string variable is created, given a value, and then its value is changed.
More specifically, in the first line, an instance of type String is created and given the value This string is immutable. In the
second line of the example, a new instance is created and given the value Or is it?, and the string variable discards its
reference to the first instance and stores a reference to the new instance.
Unlike other intrinsic data types, String is a reference type. When a variable of reference type is passed as an argument to a
function or subroutine, a reference to the memory address where the data is stored is passed instead of the actual value of the
string. So in the previous example, the name of the variable remains the same, but it points to a new and different instance of
the String class, which holds the new value.
See Also
Reference
String Data Type (Visual Basic)
Char Data Type (Visual Basic)
Other Resources
Introduction to Strings in Visual Basic
Basic String Operations
Visual Basic Language Concepts

Types of String Manipulation Methods in Visual Basic


There are several different ways to analyze and manipulate your strings. Some of the methods are a part of the Visual Basic
language, and others are inherent in the String class.
Visual Basic Language and the .NET Framework
Visual Basic methods are used as inherent functions of the language. They may be used without qualification in your code. The
following example shows typical use of a Visual Basic string-manipulation command:
VB
Dim aString As String = "SomeString"
Dim bString As String
bString = Mid(aString, 3, 3)

In this example, the Mid function performs a direct operation on aString and assigns the value to bString.
Shared Methods and Instance Methods
You can also manipulate strings with the methods of the String class. There are two types of methods in String: shared
methods and instance methods.
Shared Methods
A shared method is a method that stems from the String class itself and does not require an instance of that class to work.
These methods can be qualified with the name of the class (String) rather than with an instance of the String class. For
example:
VB
Dim aString As String = String.Copy("A literal string")

In the preceding example, the System.String.Copy(System.String) method is a static method, which acts upon an expression it
is given and assigns the resulting value to bString.
Instance Methods
Instance methods, by contrast, stem from a particular instance of String and must be qualified with the instance name. For
example:
VB
Dim aString As String = "A String"
Dim bString As String
' Assign "String" to bString.
bString = aString.Substring(2, 6)

In this example, the System.String.Substring(System.Int32) method is a method of the instance of String (that is, aString). It
performs an operation on aString and assigns that value to bString.
See Also
Other Resources
Introduction to Strings in Visual Basic
Visual Basic Language Concepts

Nothing and Strings in Visual Basic


The Visual Basic runtime and the .NET Framework evaluate Nothing differently when it comes to strings.
Visual Basic Runtime and the .NET Framework
Consider the following example:
VB
Dim MyString As String = "This is my string"
Dim stringLength As Integer
' Explicitly set the string to Nothing.
MyString = Nothing
' stringLength = 0
stringLength = Len(MyString)
' This line, however, causes an exception to be thrown.
stringLength = MyString.Length

The Visual Basic runtime usually evaluates Nothing as an empty string (""). The .NET Framework does not, however, and
throws an exception whenever an attempt is made to perform a string operation on Nothing.
See Also
Other Resources
Introduction to Strings in Visual Basic
Visual Basic Language Concepts

How Culture Affects Strings in Visual Basic


This Help page discusses how Visual Basic uses culture information to perform string conversions and comparisons.
When to Use Culture-Specific Strings
Typically, you should use culture-specific strings for all data presented to and read from users, and use culture-invariant strings
for your application's internal data.
For example, if your application asks users to enter a date as a string, it should expect users to format the strings according to
their culture, and the application should convert the string appropriately. If your application then presents that date in its user
interface, it should present it in the user's culture.
However, if the application uploads the date to a central server, it should format the string according to one specific culture, to
prevent confusion between potentially different date formats.
Culture-Sensitive Functions
All of the Visual Basic string-conversion functions (except for the Str and Val functions) use the application's culture
information to make sure that the conversions and comparisons are appropriate for the culture of the application's user.
The key to successfully using string-conversion functions in applications that run on computers with different culture settings
is to understand which functions use a specific culture setting, and which use the current culture setting. Notice that the
application's culture settings are, by default, inherited from the culture settings of the operating system. For more information,
see Asc, AscW Functions, Chr, ChrW Functions, Format Function, Hex Function (Visual Basic), Oct Function, and
Type Conversion Functions.
The Str (converts numbers to strings) and Val (converts strings to numbers) functions do not use the application's culture
information when converting between strings and numbers. Instead, they recognize only the period (.) as a valid decimal
separator. The culturally-aware analogues of these functions are:
Conversions that use the current culture. The CStr and Format functions convert a number to a string, and the CDbl
and CInt functions convert a string to a number.
Conversions that use a specific culture. Each number object has a ToString(IFormatProvider) method that converts
a number to a string, and a Parse(String, IFormatProvider) method that converts a string to a number. For example,
the Double type provides the ToString and Parse methods.
For more information, see Str Function and Val Function.
Using a Specific Culture
Imagine that you are developing an application that sends a date (formatted as a string) to a Web service. In this case, your
application must use a specific culture for the string conversion. To illustrate why, consider the result of using the date's
ToString method: If your application uses that method to format the date July 4, 2005, it returns "7/4/2005 12:00:00 AM" when
run with the United States English (en-US) culture, but it returns "04.07.2005 00:00:00" when run with the German (de-DE)
culture.
When you need to perform a string conversion in a specific culture format, you should use the CultureInfo class that is built
into the .NET Framework. You can create a new CultureInfo object for a specific culture by passing the culture's name to the
CultureInfo constructor. The supported culture names are listed in the CultureInfo class Help page.
Alternatively, you can get an instance of the invariant culture from the System.Globalization.CultureInfo.InvariantCulture
property. The invariant culture is based on the English culture, but there are some differences. For example, the invariant
culture specifies a 24-hour clock instead of a 12-hour clock.
To convert a date to the culture's string, pass the CultureInfo object to the date object's ToString method. For example, the
following code displays "07/04/2005 00:00:00", regardless of the application's culture settings.

Dim d As Date = #7/4/2005#


MsgBox(d.ToString(System.Globalization.CultureInfo.InvariantCulture))

Note
Date literals are always interpreted according to the English culture.

Comparing Strings
There are two important situations where string comparisons are needed:
Sorting data for display to the user. Use operations based on the current culture so the strings sort appropriately.
Determining if two application-internal strings exactly match (typically for security purposes). Use operations
that disregard the current culture.
You can perform both types of comparisons with the Visual Basic StrComp function. Specify the optional Compare argument
to control the type of comparison: Text for most input and output, Binary for determining exact matches.
The StrComp function returns an integer that indicates the relationship between the two compared strings based on the
sorting order. A positive value for the result indicates that the first string is greater than the second string. A negative result
indicates the first string is smaller, and zero indicates equality between the strings.
VB
' Defines variables.
Dim TestStr1 As String = "ABCD"
Dim TestStr2 As String = "abcd"
Dim TestComp As Integer
' The two strings sort equally. Returns 0.
TestComp = StrComp(TestStr1, TestStr2, CompareMethod.Text)
' TestStr1 sorts after TestStr2. Returns -1.
TestComp = StrComp(TestStr1, TestStr2, CompareMethod.Binary)
' TestStr2 sorts before TestStr1. Returns 1.
TestComp = StrComp(TestStr2, TestStr1)

You can also use the .NET Framework partner of the StrComp function, the
System.String.Compare(System.String,System.String) method. This is a static, overloaded method of the base string class. The
following example illustrates how this method is used:
VB
Dim myString As String = "Alphabetical"
Dim secondString As String = "Order"
Dim result As Integer
result = String.Compare(myString, secondString)

For finer control over how the comparisons are performed, you can use additional overloads of the Compare method. With
the System.String.Compare(System.String,System.String,System.StringComparison) method, you can use the comparisonType
argument to specify which type of comparison to use.
Value for comparisonTyp Type of comparison When to use
e argument
Ordinal Comparison based on strings' component bytes. Use this value when comparing: case-sensitive
identifiers, security-related settings, or other n
on-linguistic identifiers where the bytes must
match exactly.

OrdinalIgnoreCase Comparison based on strings' component bytes. Use this value when comparing: case-insensiti
ve identifiers, security-related settings, and dat
OrdinalIgnoreCase uses the invariant culture info a stored in Windows.
rmation to determine when two characters differ o
nly in capitalization.
CurrentCulture or Comparison based on the strings' interpretation in Use these values when comparing: data that is
CurrentCultureIgnoreCase the current culture. displayed to the user, most user input, and oth
er data that requires linguistic interpretation.

InvariantCulture or Comparison based on the strings' interpretation in Use these values only when comparing persisti
InvariantCultureIgnoreCase the invariant culture. ng data or displaying linguistically-relevant dat
a that requires a fixed sort order.
This is different than the Ordinal and OrdinalIgn
oreCase, because the invariant culture treats chara
cters outside its accepted range as equivalent invar
iant characters.
Security Considerations
If your application makes security decisions based on the result of a comparison or case-change operation, then the operation
should use the System.String.Compare(System.String,System.String,System.StringComparison) method, and pass
Ordinal or OrdinalIgnoreCase for the comparisonType argument.
See Also
Reference
Type Conversion Functions
CultureInfo
Other Resources
Introduction to Strings in Visual Basic
Visual Basic Language Concepts

Zero-based vs. One-based String Access in Visual Basic


This topic compares how Visual Basic and the .NET Framework provide access to the characters in a string. The .NET
Framework always provides zero-based access to the characters in a string, whereas Visual Basic provides zero-based and one-
based access, depending on the function.
One-Based
For an example of a one-based Visual Basic function, consider the Mid function. It takes an argument that indicates the
character position at which the substring will start, starting with position 1. The .NET
Framework System.String.Substring(System.Int32) method takes an index of the character in the string at which the substring
is to start, starting with position 0. Thus, if you have a string "ABCDE", the individual characters are numbered 1,2,3,4,5 for use
with the Mid function, but 0,1,2,3,4 for use with the System.String.Substring(System.Int32) method.
Zero-Based
For an example of a zero-based Visual Basic function, consider the Split function. It splits a string and returns an array
containing the substrings. The .NET Framework System.String.Split(System.Char[]) method also splits a string and returns an
array containing the substrings. Because the Split function and Split method return .NET Framework arrays, they must be
zero-based.
See Also
Tasks
Troubleshooting Collections
Reference
Mid Function (Visual Basic)
Split Function (Visual Basic)
Substring
Split
Other Resources
Introduction to Strings in Visual Basic
Visual Basic Language Concepts

Building Strings in Visual Basic


This section discusses how to build strings in Visual Basic.
In This Section
How to: Create Strings Using a StringBuilder in Visual Basic
Constructs a long string from many smaller strings using the StringBuilder class.
How to: Generate Multiline String Literals (Visual Basic)
Constructs a string literal that is three lines long.
See Also
Concepts
Using the StringBuilder Class
Visual Basic Language Concepts

How to: Create Strings Using a StringBuilder in Visual Basic


This example constructs a long string from many smaller strings using the StringBuilder class. The StringBuilder class is more
efficient than the &= operator for concatenating many strings.
Example
The following example creates an instance of the StringBuilder class, appends 1,000 strings to that instance, and then returns
its string representation.
VB
Private Function StringBuilderTest() As String
Dim builder As New System.Text.StringBuilder
For i As Integer = 1 To 1000
builder.Append("Step " & i & vbCrLf)
Next
Return builder.ToString
End Function

See Also
Reference
&= Operator (Visual Basic)
Concepts
Using the StringBuilder Class
Creating New Strings
Strings Sample
Other Resources
Strings in Visual Basic
Manipulating Strings
Building Strings in Visual Basic
Visual Basic Language Concepts

How to: Generate Multiline String Literals (Visual Basic)


This example constructs a string literal that is three lines long.
Example
VB
Dim MyString As String
MyString = "This is the first line of my string." & VbCrLf & _
"This is the second line of my string." & VbCrLf & _
"This is the third line of my string."

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Data Types -
defined by Visual Basic. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
An Imports statement specifying the System namespace. For more information, see Imports Statement.
See Also
Concepts
Converting Strings to .NET Framework Data Types
Creating New Strings
Strings Sample
Other Resources
Strings in Visual Basic
Parsing Strings
Manipulating Strings
Building Strings in Visual Basic
Visual Basic Language Concepts

Converting Between Strings and Other Data Types in Visual


Basic
This section describes how to convert strings into other data types.
In This Section
How to: Convert an Array of Bytes into a String in Visual Basic
How to convert the bytes from a byte array into a string.
How to: Convert Strings into an Array of Bytes in Visual Basic
How to convert a string into an array of bytes.
How to: Create a String from An Array of Char Values (Visual Basic)
How to create the string "abcd" from individual characters.
How to: Convert Hexadecimal Strings to Numbers
How to convert a hexadecimal string into an integer.
Visual Basic Language Concepts

How to: Convert an Array of Bytes into a String in Visual Basic


This topic shows how to convert the bytes from a byte array into a string.
Example
This example uses the GetString method of the System.Text.Encoding.Unicode encoding class to convert all the bytes from a
byte array into a string.
VB
Private Function UnicodeBytesToString( _
ByVal bytes() As Byte) _
As String

Return System.Text.Encoding.Unicode.GetString(bytes)
End Function

You can choose from several encoding options to convert a byte array into a string:
System.Text.Encoding.ASCII: Gets an encoding for the ASCII (7-bit) character set.
System.Text.Encoding.BigEndianUnicode: Gets an encoding for the UTF-16 format using the big-endian byte order.
System.Text.Encoding.Default: Gets an encoding for the system's current ANSI code page.
System.Text.Encoding.Unicode: Gets an encoding for the UTF-16 format using the little-endian byte order.
System.Text.Encoding.UTF32: Gets an encoding for the UTF-32 format using the little-endian byte order.
System.Text.Encoding.UTF7: Gets an encoding for the UTF-7 format.
System.Text.Encoding.UTF8: Gets an encoding for the UTF-8 format.
See Also
Tasks
How to: Convert Strings into an Array of Bytes in Visual Basic
Reference
System.Text.Encoding
GetString
Visual Basic Language Concepts

How to: Convert Strings into an Array of Bytes in Visual Basic


This topic shows how to convert a string into an array of bytes.
Example
This example uses the GetBytes method of the System.Text.Encoding.Unicode encoding class to convert a string into an array of
bytes.
VB
Private Function UnicodeStringToBytes( _
ByVal str As String) _
As Byte()

Return System.Text.Encoding.Unicode.GetBytes(str)
End Function

You can choose from several encoding options to convert a string into a byte array:
System.Text.Encoding.ASCII: Gets an encoding for the ASCII (7-bit) character set.
System.Text.Encoding.BigEndianUnicode: Gets an encoding for the UTF-16 format using the big-endian byte order.
System.Text.Encoding.Default: Gets an encoding for the system's current ANSI code page.
System.Text.Encoding.Unicode: Gets an encoding for the UTF-16 format using the little-endian byte order.
System.Text.Encoding.UTF32: Gets an encoding for the UTF-32 format using the little-endian byte order.
System.Text.Encoding.UTF7: Gets an encoding for the UTF-7 format.
System.Text.Encoding.UTF8: Gets an encoding for the UTF-8 format.
See Also
Tasks
How to: Convert an Array of Bytes into a String in Visual Basic
Reference
System.Text.Encoding
GetBytes
Visual Basic Language Concepts

How to: Create a String from An Array of Char Values (Visual


Basic)
This example creates the string "abcd" from individual characters.
Example
VB
Private Sub MakeStringFromCharacters()
Dim characters() As Char = {"a"c, "b"c, "c"c, "d"c}
Dim alphabet As New String(characters)
End Sub

Compiling the Code


This method has no special requirements.
The syntax "a"c, where a single c follows a single character in quotation marks, is used to create a character literal.
Robust Programming
Null characters (equivalent to Chr(0)) in the string lead to unexpected results when using the string. The null character will be
included with the string, but characters following the null character will not be displayed in some situations.
See Also
Reference
Char Data Type (Visual Basic)
String
Concepts
Data Types in Visual Basic
Visual Basic Language Concepts

How to: Convert Hexadecimal Strings to Numbers


This example converts a hexadecimal string to an integer using the ToInt32 method.
To convert a hexadecimal string to a number
Use the ToInt32 method to convert the number expressed in base-16 to an integer.
The first argument of the ToInt32 method is the string to convert. The second argument describes what base the number
is expressed in; hexadecimal is base 16.
VB
' Assign the value 49153 to i.
Dim i As Integer = Convert.ToInt32("c001", 16)

See Also
Reference
Hex Function (Visual Basic)
ToInt32
Visual Basic Language Concepts

How to: Convert a String to an Array of Characters in Visual


Basic
Sometimes it is useful to have data about the characters in your string and the positions of those characters within your string,
such as when you are parsing a string. This example shows how you can get an array of the characters in a string by calling the
string's ToCharArray method.
Example
This example demonstrates how to split a string into a Char array, and how to split a string into a String array of its Unicode
text characters. The reason for this distinction is that Unicode text characters can be composed of two or more Char characters
(such as a surrogate pair or a combining character sequence). For more information, see TextElementEnumerator and "The
Unicode Standard" at http://www.unicode.org.
VB
Dim testString1 As String = "ABC"
' Create an array containing "A", "B", and "C".
Dim charArray() As Char = testString1.ToCharArray

It is more difficult to split a string into its Unicode text characters, but this is necessary if you need information about the visual
representation of a string. This example uses the SubstringByTextElements method to get information about the Unicode text
characters that make up a string.
VB
' This string is made up of a surrogate pair (high surrogate
' U+D800 and low surrogate U+DC00) and a combining character
' sequence (the letter "a" with the combining grave accent).
Dim testString2 As String = ChrW(&HD800) & ChrW(&HDC00) & "a" & ChrW(&H300)

' Create and initialize a StringInfo object for the string.


Dim si As New System.Globalization.StringInfo(testString2)

' Create and populate the array.


Dim unicodeTestArray(si.LengthInTextElements) As String
For i As Integer = 0 To si.LengthInTextElements - 1
unicodeTestArray(i) = si.SubstringByTextElements(i, 1)
Next

See Also
Tasks
How to: Access Characters in Strings in Visual Basic
Reference
Chars
System.Globalization.StringInfo
Other Resources
Converting Between Strings and Other Data Types in Visual Basic
Strings in Visual Basic
Visual Basic Language Concepts

How to: Access Characters in Strings in Visual Basic


This example demonstrates how to use the Chars property to access the character at the specified location in a string.
Example
Sometimes it is useful to have data about the characters in your string and the positions of those characters within your string.
You can think of a string as an array of characters (Char instances); you can retrieve a particular character by referencing the
index of that character through the Chars property.
VB
Dim myString As String = "ABCDE"
Dim myChar As Char
' Assign "D" to myChar.
myChar = myString.Chars(3)

The index parameter of the Chars property is zero-based.


Robust Programming
The Chars property returns the character at the specified position. However, some Unicode characters can be represented by
more than one character. For more information on how to work with Unicode characters, see
How to: Convert a String to an Array of Characters in Visual Basic.
The Chars property throws an IndexOutOfRangeException exception if the index parameter is greater than or equal to the
length of the string, or if it is less than zero
See Also
Tasks
How to: Convert a String to an Array of Characters in Visual Basic
Reference
Chars
Other Resources
Converting Between Strings and Other Data Types in Visual Basic
Strings in Visual Basic
Visual Basic Language Concepts

Walkthroughs For Strings in Visual Basic


This section contains a walkthrough involving string manipulation.
In This Section
Walkthrough: Encrypting and Decrypting Strings in Visual Basic
Demonstrates how to encrypt and decrypt strings using the Data Encryption Standard algorithm.
See Also
Other Resources
Strings in Visual Basic
Visual Basic Language Concepts

Walkthrough: Encrypting and Decrypting Strings in Visual


Basic
This walkthrough shows you how to use the DESCryptoServiceProvider class to encrypt and decrypt strings using the
cryptographic service provider (CSP) version of the Triple Data Encryption Standard (TripleDES) algorithm. The first step is to
create a simple wrapper class that encapsulates the 3DES algorithm and stores the encrypted data as a base-64 encoded string.
Then, that wrapper is used to securely store private user data in a publicly accessible text file.
You can use encryption to protect user secrets (for example, passwords) and to make credentials unreadable by unauthorized
users. This can protect an authorized user's identity from being stolen, which protects the user's assets and provides non-
repudiation. Encryption can also protect a user's data from being accessed by unauthorized users.
For more information, see Cryptography Overview.
Security Note
The Rijndael (now referred to as Advanced Encryption Standard [AES]) and Triple Data Encryption Standard (3DES) algorithm
s provide greater security than DES because they are more computationally intensive. For more information, see DES and
Rijndael.

To create the encryption wrapper


1. Add an import of the cryptography namespace to the beginning of the file.
VB
Imports System.Security.Cryptography

2. Create a class to encapsulate the encryption and decryption methods.


VB
Public NotInheritable Class Simple3Des
End Class

3. Add a private field to store the 3DES cryptographic service provider.


VB
Private TripleDes As New TripleDESCryptoServiceProvider

4. Add a private method that creates a byte array of a specified length from the hash of the specified key.
VB
Private Function TruncateHash( _
ByVal key As String, _
ByVal length As Integer) _
As Byte()

Dim sha1 As New SHA1CryptoServiceProvider

' Hash the key.


Dim keyBytes() As Byte = _
System.Text.Encoding.Unicode.GetBytes(key)
Dim hash() As Byte = sha1.ComputeHash(keyBytes)
' Truncate or pad the hash.
ReDim Preserve hash(length - 1)
Return hash
End Function

5. Add a constructor to initialize the 3DES cryptographic service provider.


The key parameter controls the EncryptData and DecryptData methods.
VB
Sub New(ByVal key As String)
' Initialize the crypto provider.
TripleDes.Key = TruncateHash(key, TripleDes.KeySize \ 8)
TripleDes.IV = TruncateHash("", TripleDes.BlockSize \ 8)
End Sub

6. Add a public method that encrypts a string.


VB
Public Function EncryptData( _
ByVal plaintext As String) _
As String

' Convert the plaintext string to a byte array.


Dim plaintextBytes() As Byte = _
System.Text.Encoding.Unicode.GetBytes(plaintext)

' Create the stream.


Dim ms As New System.IO.MemoryStream
' Create the encoder to write to the stream.
Dim encStream As New CryptoStream(ms, _
TripleDes.CreateEncryptor(), _
System.Security.Cryptography.CryptoStreamMode.Write)

' Use the crypto stream to write the byte array to the stream.
encStream.Write(plaintextBytes, 0, plaintextBytes.Length)
encStream.FlushFinalBlock()

' Convert the encrypted stream to a printable string.


Return Convert.ToBase64String(ms.ToArray)
End Function

7. Add a public method that decrypts a string.


VB
Public Function DecryptData( _
ByVal encryptedtext As String) _
As String

' Convert the encrypted text string to a byte array.


Dim encryptedBytes() As Byte = Convert.FromBase64String(encryptedtext)

' Create the stream.


Dim ms As New System.IO.MemoryStream
' Create the decoder to write to the stream.
Dim decStream As New CryptoStream(ms, _
TripleDes.CreateDecryptor(), _
System.Security.Cryptography.CryptoStreamMode.Write)

' Use the crypto stream to write the byte array to the stream.
decStream.Write(encryptedBytes, 0, encryptedBytes.Length)
decStream.FlushFinalBlock()

' Convert the plaintext stream to a string.


Return System.Text.Encoding.Unicode.GetString(ms.ToArray)
End Function

The wrapper class can now be used to protect user assets. In this example, it is used to securely store private user data in
a publicly accessible text file.
To test the encryption wrapper
1. In a separate class, add a method that uses the wrapper's EncryptData method to encrypt a string and write it to the
user's My Documents folder.
VB
Sub TestEncoding()
Dim plainText As String = InputBox("Enter the plain text:")
Dim password As String = InputBox("Enter the password:")

Dim wrapper As New Simple3Des(password)


Dim cipherText As String = wrapper.EncryptData(plainText)

MsgBox("The cipher text is: " & cipherText)


My.Computer.FileSystem.WriteAllText( _
My.Computer.FileSystem.SpecialDirectories.MyDocuments & _
"\cipherText.txt", cipherText, False)
End Sub

2. Add a method that reads the encrypted string from the user's My Documents folder and decrypts the string with the
wrapper's DecryptData method.
VB
Sub TestDecoding()
Dim cipherText As String = My.Computer.FileSystem.ReadAllText( _
My.Computer.FileSystem.SpecialDirectories.MyDocuments & _
"\cipherText.txt")
Dim password As String = InputBox("Enter the password:")
Dim wrapper As New Simple3Des(password)

' DecryptData throws if the wrong password is used.


Try
Dim plainText As String = wrapper.DecryptData(cipherText)
MsgBox("The plain text is: " & plainText)
Catch ex As System.Security.Cryptography.CryptographicException
MsgBox("The data could not be decrypted with the password.")
End Try
End Sub

3. Add user interface code to call the TestEncoding and TestDecoding methods.
4. Run the application.
When you test the application, notice that it will not decrypt the data if you provide the wrong password.
See Also
Reference
System.Security.Cryptography
DESCryptoServiceProvider
DES
TripleDES
Rijndael
Concepts
Cryptography Overview
Other Resources
Walkthroughs For Strings in Visual Basic
Visual Basic Language Concepts

Validating Strings in Visual Basic


This section discusses how to validate strings in Visual Basic.
In This Section
Constructing a Validation Function in Visual Basic
Discusses the properties of validation functions, and describes how to create and use validation functions.
How to: Validate File Names and Paths in Visual Basic
How to determine whether a string represents a file name or path.
How to: Validate Strings That Represent Dates or Times (Visual Basic)
How to determine whether a string represents a valid date.
How to: Validate Strings That Represent E-Mail Addresses (Visual Basic)
How to determine whether a string represents a valid e-mail address.
How to: Validate Text for Display in a Web Browser in Visual Basic
Demonstrates how to ensure that a browser will correctly display text.
Using Regular Expressions with the MaskedTextBox Control in Visual Basic
Demonstrates how to convert simple regular expressions to work with the MaskedTextBox control.
Regular Expressions vs. the Like Operator
Compares and contrasts the Like operator and regular expressions.
Walkthrough: Validate That Passwords Are Complex (Visual Basic)
How to determine whether a string has the characteristics of a strong password.
See Also
Other Resources
Strings in Visual Basic
Parsing Strings in Visual Basic
Search and Replace for Strings in Visual Basic
MaskedTextBox Control (Windows Forms)
Visual Basic Language Concepts

Constructing a Validation Function in Visual Basic


A validation function determines whether or not a string meets certain requirements. This topic discusses the properties of
validation functions, and describes how to create and use validation functions.
Types of Validation Functions
A string that you are attempting to validate falls into one of three categories:
1. Provably valid.
2. Provably not valid.
3. Not provably valid or not valid.
It is clear what a validation function should do with strings in the first two categories; the third category is more troublesome.
Validation functions can be grouped into two categories, depending on how they treat strings in the third category:
Conservative validation functions. These functions validate only strings that can be proven to be valid.
You must use conservative validation functions when your application relies on the string for security. For example, do
not create a filter that attempts to filter out only unacceptable elements—it is difficult to anticipate every possible bad
input. Instead, if you do create a filter, create one that has a defined list of acceptable input.
Permissive validation functions. These functions validate all strings unless they are provably not valid.
In most situations that are not security-related, such as storing a user's profile, you can use permissive validation
functions, which are more flexible and user-friendly than conservative validation functions.
Regular Expressions in Validation Functions
You can use the .NET Framework Regex regular-expression class to determine if a string matches a certain pattern or contains
a certain pattern.
When validating a string, the regular expression must start with the ^ character. This instructs the regular-expression engine to
start matching the specified pattern at the start of the string.
See Also
Tasks
How to: Verify That Strings are in Valid E-Mail Format
Other Resources
Validating Strings in Visual Basic
.NET Framework Regular Expressions
Visual Basic Language Concepts

How to: Validate File Names and Paths in Visual Basic


This example returns a Boolean value that indicates whether a string represents a file name or path. The validation checks if
the name contains characters that are not allowed by the file system.
Example
VB
Function IsValidFileNameOrPath(ByVal name As String) As Boolean
' Determines if the name is Nothing.
If name Is Nothing Then
Return False
End If

' Determines if there are bad characters in the name.


For Each badChar As Char In System.IO.Path.GetInvalidPathChars
If InStr(name, badChar) > 0 Then
Return False
End If
Next

' The name passes basic validation.


Return True
End Function

This example does not check if the name has incorrectly placed colons, or directories with no name, or if the length of the name
exceeds the system-defined maximum length. It also does not check if the application has permission to access the file-system
resource with the specified name.
See Also
Reference
GetInvalidPathChars
Other Resources
Validating Strings in Visual Basic
Visual Basic Language Concepts

How to: Validate Strings That Represent Dates or Times (Visual


Basic)
The following code example sets a Boolean value that indicates whether a string represents a valid date or time.
Example
VB
Dim isValidDate As Boolean = IsDate("01/01/03")
Dim isValidTime As Boolean = IsDate("9:30 PM")

Compiling the Code


Replace ("01/01/03") and "9:30 PM" with the date and time you want to validate. You can replace the string with another
hard-coded string, with a String variable, or with a method that returns a string, such as InputBox.
Robust Programming
Use this method to validate the string before trying to convert the String to a DateTime variable. By checking the date or time
first, you can avoid generating an exception at run time.
See Also
Reference
IsDate Function (Visual Basic)
InputBox Function (Visual Basic)
Other Resources
Validating Strings in Visual Basic
Visual Basic Language Concepts

How to: Validate Strings That Represent E-Mail Addresses


(Visual Basic)
The following code example sets a Boolean variable that indicates whether a string represents a valid e-mail address.
Example
VB
Function ValidateEmail(ByVal email As String) As Boolean
Dim emailRegex As _
New System.Text.RegularExpressions.Regex( _
"^(?<user>[^@]+)@(?<host>.+)$")
Dim emailMatch As _
System.Text.RegularExpressions.Match = emailRegex.Match(email)
Return emailMatch.Success
End Function

Compiling the Code


Call this method by passing the string that contains an e-mail address.
Robust Programming
This method validates that e-mail addresses have the form "someone@microsoft.com".
Use this code to validate the string before trying to use it as an e-mail address. This could prevent other errors at run time.
See Also
Reference
Regex
Visual Basic Language Concepts

How to: Validate Text for Display in a Web Browser in Visual


Basic
This example demonstrates how to use the HtmlEncode method to ensure that a browser correctly displays text. Characters in
a string such as <, >, and & are rendered incorrectly unless they are escaped as &lt;, &gt;, and &amp;.
Example
The following code example encodes a string to be displayed in a browser. It encodes the string named TestString, which
contains the text This is a <Test String>, and copies it into the string named EncodedString as This is a &lt;Test
String&gt;.

Dim TestString As String = "This is a <Test String>"


Dim EncodedString As String = Server.HtmlEncode(TestString)

This example requires a reference to System.Web.dll.


See Also
Reference
HtmlEncode
Other Resources
Validating Strings in Visual Basic
Visual Basic Language Concepts

Using Regular Expressions with the MaskedTextBox Control in


Visual Basic
This example demonstrates how to convert simple regular expressions to work with the MaskedTextBox control.
Description of the Masking Language
The standard MaskedTextBox masking language is based on the one used by the Masked Edit control in Visual Basic 6.0 and
should be familiar to users migrating from that platform.
The Mask property of the MaskedTextBox control specifies what input mask to use. The mask must be a string composed of
one or more of the masking elements from the following table.
Masking el Description Regular expression
ement element
0 Any single digit between 0 and 9. Entry required. \d

9 Digit or space. Entry optional. [ \d]?

# Digit or space. Entry optional. If this position is left blank in the mask, it will be rendered as [ \d+-]?
a space. Plus (+) and minus (-) signs are allowed.

L ASCII letter. Entry required. [a-zA-Z]

? ASCII letter. Entry optional. [a-zA-Z]?

& Character. Entry required. [\p{Ll}\p{Lu}\p{Lt}\p{


Lm}\p{Lo}]

C Character. Entry optional. [\p{Ll}\p{Lu}\p{Lt}\p{


Lm}\p{Lo}]?

A Alphanumeric. Entry optional. \W

. Culture-appropriate decimal placeholder. Not available.

, Culture-appropriate thousands placeholder. Not available.

: Culture-appropriate time separator. Not available.

/ Culture-appropriate date separator. Not available.

$ Culture-appropriate currency symbol. Not available.

< Converts all characters that follow to lowercase. Not available.

> Converts all characters that follow to uppercase. Not available.

| Undoes a previous shift up or shift down. Not available.

\ Escapes a mask character, turning it into a literal. “\\” is the escape sequence for a backslash \
.
All other cha Literals. All non-mask elements will appear as themselves within MaskedTextBox. All other characters.
racters.

The decimal (.), thousandths (,), time (:), date (/), and currency ($) symbols default to displaying those symbols as defined by the
application's culture. You can force them to display symbols for another culture by using the FormatProvider property.
Regular Expressions and Masks
Although you can use regular expressions and masks to validate user input, they are not completely equivalent. Regular
expressions can express more complex patterns than masks, but masks can express the same information more succinctly and
in a culturally relevant format.
The following table compares four regular expressions and the equivalent mask for each.
Regular Exp Mask Notes
ression
\d{2}/\d{2} 00/00/ The / character in the mask is a logical date separator, and it will appear to the user as the date separator
/\d{4} 0000
appropriate to the application's current culture.

\d{2}-[A-Z] 00->L< A date (day, month abbreviation, and year) in United States format in which the three-letter month abbre
[a-z]{2}-\d LL-000
{4} 0 viation is displayed with an initial uppercase letter followed by two lowercase letters.

(\(\d{3}\)- (999)- United States phone number, area code optional. If the user does not wish to enter the optional character
)?\d{3}-d{4 000-00
} 00 s, she can either enter spaces or place the mouse pointer directly at the position in the mask represented
by the first 0.

$\d{6}.00 $999,9 A currency value in the range of 0 to 999999. The currency, thousandth, and decimal characters will be r
99.00
eplaced at run-time with their culture-specific equivalents.

See Also
Reference
Mask
MaskedTextBox
Other Resources
Validating Strings in Visual Basic
MaskedTextBox Control (Windows Forms)
Visual Basic Language Concepts

Regular Expressions vs. the Like Operator


This topic compares and contrasts the Visual Basic Like operator and regular expressions in the .NET Framework.
Comparison of Syntax
The following table compares the pattern-specification language syntax for the Like operator with the syntax for regular
expressions.
Like operator syntax Regular expression syntax
The behavior of the Like operator depends on the Regular expressions work the same regardless of Opti
Option Compare Statement. The default string comparison method for on Compare.
each source file is Option Compare Binary.

To match any single character in charlist, use [charlist]. To match any single character in charlist, use [charlist].

To match any single character not in charlist, use [!charlist]. To match any single character not in charlist, use [^ch
arlist].

To match any single digit (0–9), use #. To match any single digit (0–9), use the character class
for decimal digits, \d.

To match any single character, use ?. To match any single character, specify mutually exclusi
ve character classes for the charlist in [charlist]. For ex
ample, [\s\S].

To match zero or more characters, use *. To match zero or more characters, specify mutually exc
lusive character classes for the charlist in [charlist]*. Fo
r example, [\s\S]*.

To match a special character char, enclose it in brackets: [char]. To match a special character char, precede it with a bac
kslash: \char.

To match any character in a range, use a hyphen (–) to separate the lo To match any character in a range, use a hyphen (–) to
wer and upper bounds of the range in a charlist. separate the lower and upper bounds of the range in a
charlist.

See Also
Reference
Like Operator
Other Resources
Validating Strings in Visual Basic
.NET Framework Regular Expressions
Visual Basic Language Concepts

Walkthrough: Validate That Passwords Are Complex (Visual


Basic)
This method checks for some strong-password characteristics and updates a string parameter with information about which
checks the password fails.
Passwords can be used in a secure system to authorize a user. However, the passwords must be difficult for unauthorized
users to guess. Attackers can use a dictionary attack program, which iterates through all of the words in a dictionary (or
multiple dictionaries in different languages) and tests whether any of the words work as a user's password. Weak passwords
such as "Yankees" or "Mustang" can be guessed quickly. Stronger passwords, such as "?You'L1N3vaFiNdMeyeP@sSWerd!",
are much less likely to be guessed. A password-protected system should ensure that users choose strong passwords.
A strong password is complex (containing a mixture of uppercase, lowercase, numeric, and special characters) and is not a
word. This example demonstrates how to verify complexity.
Example
VB
''' <summary>Determines if a password is sufficiently complex.</summary>
''' <param name="pwd">Password to validate</param>
''' <param name="minLength">Minimum number of password characters.</param>
''' <param name="numUpper">Minimum number of uppercase characters.</param>
''' <param name="numLower">Minimum number of lowercase characters.</param>
''' <param name="numNumbers">Minimum number of numeric characters.</param>
''' <param name="numSpecial">Minimum number of special characters.</param>
''' <returns>True if the password is sufficiently complex.</returns>
Function ValidatePassword(ByVal pwd As String, _
Optional ByVal minLength As Integer = 8, _
Optional ByVal numUpper As Integer = 2, _
Optional ByVal numLower As Integer = 2, _
Optional ByVal numNumbers As Integer = 2, _
Optional ByVal numSpecial As Integer = 2) _
As Boolean

' Replace [A-Z] with \p{Lu}, to allow for Unicode uppercase letters.
Dim upper As New System.Text.RegularExpressions.Regex("[A-Z]")
Dim lower As New System.Text.RegularExpressions.Regex("[a-z]")
Dim number As New System.Text.RegularExpressions.Regex("[0-9]")
' Special is "none of the above".
Dim special As New System.Text.RegularExpressions.Regex("[^a-zA-Z0-9]")
' Check the length.
If Len(pwd) < minLength Then Return False
' Check for minimum number of occurrences.
If upper.Matches(pwd).Count < numUpper Then Return False
If lower.Matches(pwd).Count < numLower Then Return False
If number.Matches(pwd).Count < numNumbers Then Return False
If special.Matches(pwd).Count < numSpecial Then Return False
' Passed all checks.
Return True
End Function
Sub TestValidatePassword()
Dim password As String = "Password"
' Demonstrate that "Password" is not complex.
MsgBox(password & " is complex: " & ValidatePassword(password))
password = "Z9f%a>2kQ"
' Demonstrate that "Z9f%a>2kQ" is not complex.
MsgBox(password & " is complex: " & ValidatePassword(password))
End Sub
Compiling the Code
Call this method by passing the string that contains that password.
This example requires:
Access to the members of the System.Text.RegularExpressions namespace. Add an Imports statement if you are not fully
qualifying member names in your code. For more information, see Imports Statement.
Security
If you are moving the password across a network, you need to use a secure method for transferring data. For more
information, see ASP.NET Web Application Security.
You can improve the accuracy of the ValidatePassword function by adding additional complexity checks:
Compare the password and its substrings against the user's name, user identifier, and an application-defined dictionary.
In addition, treat visually similar characters as equivalent when performing the comparisons. For example, treat the
letters "l" and "e" as equivalent to the numerals "1" and "3".
If there is only one uppercase character, make sure it is not the password's first character.
Make sure that the last two characters of the password are letter characters.
Do not allow passwords in which all the symbols are entered from the keyboard's top row.
See Also
Reference
Regex
Other Resources
ASP.NET Web Application Security
Walkthroughs For Strings in Visual Basic
Visual Basic Language Concepts

Search and Replace for Strings in Visual Basic


This section discusses how to use search and replace for strings in Visual Basic.
In This Section
How to: Remove Parts of a String (Visual Basic)
Removes all occurrences of one string from another string.
How to: Search for a String in an Array of Strings (Visual Basic)
Reports the index of the first string in the array with the specified substring, and the index of the substring in the string.
How to: Search Within a String (Visual Basic)
Reports the index of the first occurrence of a substring in a string.
See Also
Concepts
Types of String Manipulation Methods in Visual Basic
Other Resources
Strings in Visual Basic
Visual Basic Language Concepts

How to: Search for a String in an Array of Strings (Visual Basic)


This example loops over each string in an array of strings to determine which ones contain the specified substring. For each
match, the example displays the index of the substring in the string.
Example
The following example uses the Contains and IndexOf methods of the String object.
The Contains method indicates whether the string contains the specified substring.
The IndexOf method reports the location of the first character of the first occurrence of the substring. The index is 0-based,
which means the first character of a string has an index of 0. If IndexOf does not find the substring, it returns -1.
VB
Dim StrArray() As String = {"ABCDEFG", "HIJKLMNOP"}
Dim FindThisString As String = "JKL"
For Each Str As String In StrArray
If Str.Contains(FindThisString) Then
MsgBox("Found " & FindThisString & " at index " & _
Str.IndexOf(FindThisString))
End If
Next

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Data Types -
defined by Visual Basic. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
An Imports statement specifying the System namespace. For more information, see Imports Statement.
Robust Programming
The IndexOf method is case-sensitive and uses the current culture.
For optimal error control, you might want to enclose the string search in the Try block of a
Try...Catch...Finally Statement (Visual Basic) construction.
See Also
Tasks
How to: Search Within a String (Visual Basic)
Reference
Try...Catch...Finally Statement (Visual Basic)
IndexOf
Other Resources
Introduction to Strings in Visual Basic
Visual Basic Language Concepts

How to: Search Within a String (Visual Basic)


This example calls the IndexOf method on a String object to report the index of the first occurrence of a substring.
Example
VB
Dim SearchWithinThis As String = "ABCDEFGHIJKLMNOP"
Dim SearchForThis As String = "DEF"
Dim FirstCharacter As Integer = SearchWithinThis.IndexOf(SearchForThis)

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Data Types -
defined by Visual Basic. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
An Imports statement specifying the System namespace. For more information, see Imports Statement.
Robust Programming
The IndexOf method reports the location of the first character of the first occurrence of the substring. The index is 0-based,
which means the first character of a string has an index of 0.
If IndexOf does not find the substring, it returns -1.
The IndexOf method is case-sensitive and uses the current culture.
For optimal error control, you might want to enclose the string search in the Try block of a
Try...Catch...Finally Statement (Visual Basic) construction.
See Also
Reference
Try...Catch...Finally Statement (Visual Basic)
IndexOf
Other Resources
Introduction to Strings in Visual Basic
Search and Replace for Strings in Visual Basic
Visual Basic Language Concepts

How to: Remove Parts of a String (Visual Basic)


The following code example removes all occurrences of one string from another string.
Example
This example uses the Replace function to replace each occurrence of the substring with an empty string. The result is a new
string with the substrings removed.
The example assigns the return value of the Replace function to the string variable withoutParts. The original string, stored in
withParts, is not changed.

VB
Dim withParts As String = "Books and Chapters and Pages"
Dim withoutParts As String = Replace(withParts, "and ", "")

Compiling the Code


Replace "Books and Chapters and Pages" with the string you want to manipulate.

See Also
Reference
Replace Function (Visual Basic)
String Data Type (Visual Basic)
Visual Basic Language Concepts

Parsing Strings in Visual Basic


This section discusses how to parse strings in Visual Basic.
In This Section
How to: Parse URIs in Visual Basic
Demonstrates how to use the System.Uri class to parse a uniform resource identifier (URI).
How to: Parse E-mail Addresses in Visual Basic
Demonstrates a simple regular expression for parsing an e-mail address.
How to: Identify URIs in a String in Visual Basic
Demonstrates how to use a simple regular expression to identify a URI in a string.
How to: Identify Text in an HTML String in Visual Basic
Demonstrates how to use a simple regular expression to remove tags from an HTML document.
How to: Identify Hyperlinks in an HTML String in Visual Basic
Demonstrates a simple regular expression for identifying hyperlinks in an HTML document.
See Also
Other Resources
Strings in Visual Basic
Introduction to Strings in Visual Basic
Visual Basic Language Concepts

How to: Parse URIs in Visual Basic


This example demonstrates how to use the System.Uri class to parse a URI.
Example
This example uses several methods of a Uri object to get information about a URI.

Dim uriString As String = "http://www.contoso.com/index.htm?date=today"


Dim uriObject As New Uri(uriString)
' Display "Scheme: http"
MsgBox("Scheme: " & uriObject.Scheme)
' Display "Host: www.contoso.com"
MsgBox("Host: " & uriObject.Host)
' Display "Local path: /index.htm"
MsgBox("Local path: " & uriObject.LocalPath)
' Display "Query: ?date=today"
MsgBox("Query: " & uriObject.Query)

See Also
Reference
Uri
Other Resources
Parsing Strings in Visual Basic
Visual Basic Language Concepts

How to: Parse E-mail Addresses in Visual Basic


This example demonstrates a simple regular expression for parsing an e-mail address.
Example
This example uses the regular expression (\S+)@([^\.\s]+)(?:\.([^\.\s]+))+, which means:
1. Set of one or more non-space characters (captured), followed by
2. The character "@", followed by
3. Set of one or more non-space and non-period characters (captured), followed by
4. One or more of the following:
a. The character ".", followed by
b. Set of one or more non-space and non-period characters (captured).
The regular expression's Match method returns a Match object that contains information about what part of the input string
the regular expression matches.

''' <summary>
''' Parses an e-mail address into its parts.
''' </summary>
''' <param name="emailString">E-mail address to parse.</param>
''' <remarks> For example, this method displays the following
''' text when called with "someone@mail.contoso.com":
''' User name: someone
''' Address part: mail
''' Address part: contoso
''' Address part: com
''' </remarks>
Sub ParseEmailAddress(ByVal emailString As String)
Dim emailRegEx As New Regex("(\S+)@([^\.\s]+)(?:\.([^\.\s]+))+")
Dim m As Match = emailRegEx.Match(emailString)
If m.Success Then
Dim output As String = ""
output &= "User name: " & m.Groups(1).Value & vbCrLf
For i As Integer = 2 To m.Groups.Count - 1
Dim g As Group = m.Groups(i)
For Each c As Capture In g.Captures
output &= "Address part: " & c.Value & vbCrLf
Next
Next
MsgBox(output)
Else
MsgBox("The e-mail address cannot be parsed.")
End If
End Sub

This example requires that you use the Imports statement to import the System.Text.RegularExpressions namespace. For more
information, see Imports Statement.
See Also
Tasks
How to: Verify That Strings are in Valid E-Mail Format
Other Resources
Parsing Strings in Visual Basic
Visual Basic Language Concepts

How to: Identify URIs in a String in Visual Basic


This example demonstrates how to use a simple regular expression to identify a uniform resource identifier (URI) in a string. To
reduce the number of false positives (text mistakenly identified as a URI), a specific URI format is assumed. This means there
will be some false negatives, where valid URIs are not identified.
Example
A specific form of URI can be matched with the regular expression ([^=":\s]+:)?//[^\s"]+, which means:
1. Optional appearance of:
a. Set of one or more characters that are not =, ", :, or a space character, followed by
b. The : character, followed by
2. The string //, followed by
3. Set of one or more characters that are not quotation marks or space characters.
The Regex object is initialized with the regular expression.
The Regex object's Matches method returns a MatchCollection object that contains information about all the parts of the input
string that the regular expression matches.

''' <summary>Identifies URIs in text.</summary>


''' <param name="text">Text to parse.</param>
''' <remarks>Displays each URI in the input text.</remarks>
Sub IdentifyURIs(ByVal text As String)
Dim uriRegex As New Regex("([^="":\s]+:)?//[^\s""]+")
Dim output As String = ""
For Each m As Match In uriRegex.Matches(text)
output &= m.Value & vbCrLf
Next
MsgBox(output)
End Sub

This example requires that you use the Imports statement to import the System.Text.RegularExpressions namespace. For more
information, see Imports Statement.
See Also
Tasks
How to: Identify Hyperlinks in an HTML String in Visual Basic
How to: Strip Invalid Characters from a String
Other Resources
Parsing Strings in Visual Basic
Visual Basic Language Concepts

How to: Identify Text in an HTML String in Visual Basic


This example demonstrates how to use a simple regular expression to remove tags from an HTML document.
Example
HTML tags can be matched with the regular expression \<[^\>]+\>, which means:
1. The character "<", followed by
2. A set of one or more characters, not including the ">" character, followed by
3. The character ">".
This example uses the shared System.Text.RegularExpressions.Regex.Replace(System.String,System.String,System.String)
method to replace all matches of the tag regular expression with the empty string.

''' <summary>Removes the tags from an HTML document.</summary>


''' <param name="htmlText">HTML text to parse.</param>
''' <returns>The text of an HTML document without tags.</returns>
''' <remarks></remarks>
Function GetTextFromHtml(ByVal htmlText As String) As String
Dim output As String = Regex.Replace(htmlText, "\<[^\>]+\>", "")
Return output
End Function

This example requires that you use the Imports statement to import the System.Text.RegularExpressions namespace. For more
information, see Imports Statement.
See Also
Tasks
How to: Identify Hyperlinks in an HTML String in Visual Basic
How to: Strip Invalid Characters from a String
Other Resources
Parsing Strings in Visual Basic
Visual Basic Language Concepts

How to: Identify Hyperlinks in an HTML String in Visual Basic


This example demonstrates a simple regular expression for identifying hyperlinks in an HTML document.
Example
This example uses the regular expression <A[^>]*?HREF\s*=\s*"([^"]+)"[^>]*?>([\s\S]*?)<\/A>, which means:
1. The string "<A", followed by
2. The smallest set of zero or more characters that does not include the character ">", followed by
3. The string "HREF", followed by
4. Zero or more space characters, followed by
5. The character "=", followed by
6. Zero or more space characters, followed by
7. The quotation-mark character, followed by
8. The set of characters that does not include the quotation-mark character (captured), followed by
9. The quotation-mark character, followed by
10. The smallest set of zero or more characters that does not include the character ">", followed by
11. The character ">", followed by
12. The smallest set of zero or more characters (captured), followed by
13. The string "</A>".
The Regex object is initialized with the regular expression, and specified to be case-insensitive.
The Regex object's Matches method returns a MatchCollection object that contains information about all the parts of the input
string that the regular expression matches.

''' <summary>Identifies hyperlinks in HTML text.</summary>


''' <param name="htmlText">HTML text to parse.</param>
''' <remarks>This method displays the label and destination for
''' each link in the input text.</remarks>
Sub IdentifyLinks(ByVal htmlText As String)
Dim hrefRegex As New Regex( _
"<A[^>]*?HREF\s*=\s*""([^""]+)""[^>]*?>([\s\S]*?)<\/A>", _
RegexOptions.IgnoreCase)
Dim output As String = ""
For Each m As Match In hrefRegex.Matches(htmlText)
output &= "Link label: " & m.Groups(2).Value & vbCrLf
output &= "Link destination: " & m.Groups(1).Value & vbCrLf
Next
MsgBox(output)
End Sub

This example requires that you use the Imports statement to import the System.Text.RegularExpressions namespace. For more
information, see Imports Statement.
See Also
Concepts
Example: Scanning for HREFs
Other Resources
Parsing Strings in Visual Basic
Visual Basic Language Concepts

Troubleshooting Strings in Visual Basic


This section provides advice on how to troubleshoot string manipulation in Visual Basic.
In This Section
Troubleshooting Regular Expressions in Visual Basic
Lists topics that describe the basic concepts behind using strings in Visual Basic.
Related Sections
Nothing and Strings in Visual Basic
Describes how the Visual Basic runtime and the .NET Framework evaluate Nothing differently when it comes to strings.
How Culture Affects Strings in Visual Basic
Discusses how Visual Basic uses culture information to perform string conversions and comparisons.
Zero-based vs. One-based String Access in Visual Basic
Compares how Visual Basic and the .NET Framework provide access to the characters in a string.
See Also
Other Resources
Strings in Visual Basic
Walkthroughs For Strings in Visual Basic
Introduction to Strings in Visual Basic
Visual Basic Language Concepts

Troubleshooting Regular Expressions in Visual Basic


This topic discusses some common problems that can occur when working with regular expressions, provides some tips for
solving these problems, and provides a procedure for accessing captured strings.
Not Matching the Intended Pattern
Listed below are some common tasks you can perform with regular expressions, along with troubleshooting tips if you do not
get the results you expect:
Validating strings. A string-validation regular expression must start with the ^ character. This instructs the regular-
expression engine to start matching the specified pattern at the start of the string. For more information, see
Constructing a Validation Function in Visual Basic. and Atomic Zero-Width Assertions.
Matching with quantifiers. The regular-expression quantifiers (*, +, ?, {}) are greedy, meaning they match the longest
possible string. However, for some patterns, you may want to use lazy matching to get the shortest possible string. The
lazy regular-expression quantifiers are *?, +?, ??, and {}?. For more information, see Quantifiers.
Matching with nested quantifiers. When you use nested quantifiers, make sure all the quantifiers are either greedy or
lazy. Otherwise, the results of the match will be hard to predict.
Accessing the Captured Stings
Once a regular expression is finding your intended strings, you may want to capture those strings and then access what you
have captured. You can use grouping constructs to capture the strings that match groups of subexpressions in your regular
expression. For more information, see Grouping Constructs.
There are several steps involved in accessing the strings captured with nested groups.
To access captured text
1. Create a Regex object for a regular expression.
2. Call the Match method to get the Match object.
The Match object contains information about how the regular expression matches the string.
3. Iterate over the Group objects stored in the Match object's Groups collection.
The Group objects contain information about the results from a single capturing group.
4. Iterate over the Capture objects stored in each Group object's Captures collection.
Each Capture object contains information about a single captured subexpression, including the matched substring and
location.
For example, the following code demonstrates how to access the strings captured with a regular expression containing three
capturing groups:

''' <summary>
''' Parses an e-mail address into its parts.
''' </summary>
''' <param name="emailString">E-mail address to parse.</param>
''' <remarks> For example, this method displays the following
''' text when called with "someone@mail.contoso.com":
''' User name: someone
''' Address part: mail
''' Address part: contoso
''' Address part: com
''' </remarks>
Sub ParseEmailAddress(ByVal emailString As String)
Dim emailRegEx As New Regex("(\S+)@([^\.\s]+)(?:\.([^\.\s]+))+")
Dim m As Match = emailRegEx.Match(emailString)
If m.Success Then
Dim output As String = ""
output &= "User name: " & m.Groups(1).Value & vbCrLf
For i As Integer = 2 To m.Groups.Count - 1
Dim g As Group = m.Groups(i)
For Each c As Capture In g.Captures
output &= "Address part: " & c.Value & vbCrLf
Next
Next
MsgBox(output)
Else
MsgBox("The e-mail address cannot be parsed.")
End If
End Sub

See Also
Tasks
Troubleshooting Strings in Visual Basic
Concepts
Constructing a Validation Function in Visual Basic
Visual Basic Language Concepts

Constants and Enumerations in Visual Basic


Constants are a way to use meaningful names in place of a value that does not change. Constants store values that, as the
name implies, remain constant throughout the execution of an application. You can use constants to provide meaningful
names, instead of numbers, making your code more readable.
Enumerations provide a convenient way to work with sets of related constants, and to associate constant values with names.
For example, you can declare an enumeration for a set of integer constants associated with the days of the week, and then use
the names of the days rather than their integer values in your code.
In This Section
Constants in Visual Basic
Topics in this section describe constants and their uses.
Enumerations Overview
Topics in this section describe enumerations and their uses.
Intrinsic Constants and Enumerations
Discusses the constants and enumerations that Visual Basic 2005 provides.
Related Sections
Const Statement (Visual Basic)
Provides syntax and usage rules for the Const statement, which is used to declare constants.
Enum Statement (Visual Basic)
Provides syntax and usage rules for the Enum statement, which is used to create enumerations.
Option Explicit Statement (Visual Basic)
Provides syntax and usage rules for the Option Explicit statement, which is used at module level to force explicit declaration
of all variables in that module.
Option Strict Statement
Provides syntax and usage rules for the Option Strict statement, which restricts implicit data type conversions to widening
conversions only.
Visual Basic Language Concepts

Constants in Visual Basic


Constants store values that, as the name implies, remain constant throughout the execution of an application. Use constants in
your code for values that are used repeatedly or to make code more readable.
In This Section
Constants Overview
Defines constants, and discusses when and where to use them.
Constants Declared by Visual Basic
Lists the constants predefined by Visual Basic.
How to: Declare A Constant
Explains how to use the Const statement to declare a constant and set its value; by declaring a constant, you assign a
meaningful name to the value.
User-Defined Constants
Describes how to create your own constants, including information on scoping and how to avoid circular references.
Constant and Literal Data Types
Provides information on how the Visual Basic compiler initializes constants when Option Explicit is turned off.
How to: Group Related Constant Values Together
Demonstrates how to group constant values that are related.
Reference
Const Statement (Visual Basic)
Describes the Const statement and its use.
Option Strict Statement
Describes the Option Strict statement and its use.
Related Sections
Enumerations Overview
Discusses enumerations and their use, including common tasks involving enumerations.
Print and Display Constants
Lists print and display constants pre-defined by Visual Basic.
Intrinsic Constants and Enumerations
Discusses the constants and enumerations that Visual Basic provides.
Constants and Enumerations in Visual Basic
What has changed for constants and enumerations in the latest version of Visual Basic.
Visual Basic Language Concepts

Constants Overview
A constant is a meaningful name that takes the place of a number or string that does not change. Constants store values that,
as the name implies, remain the same throughout the execution of an application. You can greatly improve the readability of
your code and make it easier to maintain by using constants. Use them in code that contains values that reappear or that
depends on certain numbers that are difficult to remember or have no obvious meaning.
How to Create and Use Constants
Visual Basic contains a number of predefined constants, mainly using for printing and displaying. You can also create your own
constants with the Const statement, using the same guidelines you would for creating a variable name. If Option Strict is On,
you must explicitly declare the constant type.
A constant's scope, which is the set of all code that can refer to it without qualifying its name, is the same as that of a variable
declared in the same location. To create a constant that exists within the scope of a particular procedure, declare it inside that
procedure. To create a constant that is available throughout an application, declare it using the Public keyword in the
declarations section of the class.
Note
Although constants somewhat resemble variables, you cannot modify them or assign new values to them as you can to varia
bles.

The constants you use in your code can be defined by the object model for controls or components you work with, or they can
be user-defined (that is, those you create yourself).
Compile-time and Run-time Constants
A compile-time constant is computed at the time the code is compiled, while a run-time constant can only be computed while
the application is running. A compile-time constant will have the same value each time an application runs, while a run-time
constant may change each time. Compile-time constants are required for cases such as array bounds, case expressions, or
enumerator initializers.
See Also
Tasks
How to: Declare A Constant
Reference
Const Statement (Visual Basic)
Public (Visual Basic)
Concepts
Constant and Literal Data Types
Constants Declared by Visual Basic
Other Resources
Constants and Enumerations (Visual Basic)
Constants in Visual Basic
Visual Basic Language Concepts

Constants Declared by Visual Basic


Visual Basic provides a number of predefined constants for developers for use in conditional compilation as well as in printing
and displaying data.
Conditional Compilation Constants
The following table lists the predefined constants available for conditional compilation.
Co Description
nst
an
t
CO A string that corresponds to the current setting of the Active Solution Configuration box in the Configuration Manag
NF er.
IG

DE A Boolean value that can be set in the Project Properties dialog box. By default, the Debug configuration for a project de
BU fines DEBUG. When DEBUG is defined, Debug class methods generate output to the Output window. When it is not defin
G ed, Debug class methods are not compiled and no Debug output is generated.

TA A string representing the output type for the project or the setting of the command-line /target option. The possible value
RG s of TARGET are:
ET
"winexe" for a Windows application.
"exe" for a console application.
"library" for a class library.
"module" for a module.
The /target option may be set in the Visual Studio integrated development environment. For more information, see
/target (Visual Basic).

TR A Boolean value that can be set in the Project Properties dialog box. By default, all configurations for a project define TR
AC ACE. When TRACE is defined, Trace class methods generate output to the Output window. When it is not defined, Trace c
E lass methods are not compiled and no Trace output is generated.

VB A number representing the Visual Basic version, in major.minor format. The version number for Visual Basic 2005 is 8.0.
C_
VE
R

Print and Display Constants


When you call print and display functions, you can use the following constants in your code in place of the actual values.
Constant Description
vbCrLf Carriage return/linefeed character combination.

vbCr Carriage return character.

vbLf Linefeed character.

vbNewLine Newline character.

vbNullChar Character having a value of 0.


vbNullString Not the same as a zero-length string (""); used for calling external procedures.

vbObjectError Error number. User-defined error numbers should be greater than this value. For example:
Err.Raise(Number) = vbObjectError + 1000

vbTab Tab character.

vbBack Backspace character.

vbFormFeed Not used in Microsoft Windows.

vbVerticalTab Not useful in Microsoft Windows.

See Also
Tasks
How to: Declare A Constant
Concepts
Enumerations Declared by Visual Basic
Constants Overview
User-Defined Constants
Constant and Literal Data Types
Visual Basic Language Concepts

How to: Declare A Constant


You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to
a value. Once a constant is declared, it cannot be modified or assigned a new value.
You declare a constant within a procedure or in the declarations section of a module, class, or structure. Class or structure-level
constants are Private by default, but may also be declared as Public, Friend, Protected, or Protected Friend for the
appropriate level of code access.
The constant must have a valid symbolic name (the rules are the same as those for creating variable names) and an expression
composed of numeric or string constants and operators (but no function calls).
Note
The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is d
escribed in Help depending on your active settings or edition. This Help page was written with General Development Setti
ngs in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To declare a constant
Write a declaration that includes an access specifier, the Const keyword, and an expression, as in the following examples:
VB
Public Const DaysInYear = 365
Private Const WorkDays = 250

When Option Strict is On, you must declare a constant explicitly by specifying a data type (Boolean, Byte, Char,
DateTime, Decimal, Double, Integer, Long, Short, Single, or String). When Option Strict is Off, the constant is
assigned a data type by the compiler. For more information, see Constant and Literal Data Types.
To declare a constant with Option Strict On
With Option Strict On, write a declaration that includes the As keyword and an explicit data type, as in the following
examples:
VB
Public Const MyInteger As Integer = 42
Private Const DaysInWeek As Short = 7
Protected Friend Const Funday As String = "Sunday"

You can declare multiple constants on a single line, although your code is more readable if you declare only a single
constant per line. If you declare multiple constants on a single line, they must all have the same access level (Public,
Private, Friend, Protected, or Protected Friend).
To declare multiple constants on a single line
Separate the declarations with a comma and a space, as in the following example:

Public Const Four As Integer = 4, Five As Integer = 5, Six As Integer = 44

See Also
Tasks
How to: Declare Enumerations
Reference
Const Statement (Visual Basic)
Option Strict Statement
Concepts
Constant and Literal Data Types
Enumerations Overview
Constants Overview
Enumerations and Name Qualification
Intrinsic Constants and Enumerations
Other Resources
Constants and Enumerations in Visual Basic
Visual Basic Language Concepts

User-Defined Constants
A constant is a meaningful name that takes the place of a number or string that does not change. Constants store values that,
as the name implies, remain constant throughout the execution of an application. You can use constants that are defined by the
controls or components you work with, or you can create your own. Constants you create yourself are described as user-
defined.
You declare a constant with the Const statement, using the same guidelines you would for creating a variable name. If Option
Strict is On, you must explicitly declare the constant type.
Const Statement Usage
A Const statement can represent a mathematical or date/time quantity:
VB
Const conPi = 3.14159265358979
Public Const conMaxPlanets As Integer = 9
Const conReleaseDate = #1/1/1995#

It also can define String constants:


VB
Public Const conVersion = "07.10.A"
Const conCodeName = "Enigma"

The expression on the right side of the equal sign ( = ) is often a number or literal string, but it also can be an expression that
results in a number or string (although that expression cannot contain calls to functions). You can even define constants in
terms of previously defined constants:
VB
Const conPi2 = conPi * 2

Scope of User-Defined Constants


A Const statement's scope is the same as that of a variable declared in the same location. You can specify scope in any of the
following ways:
To create a constant that exists only within a procedure, declare it within that procedure.
To create a constant available to all procedures within a class, but not to any code outside that module, declare it in the
declarations section of the class.
To create a constant that is available to all members of an assembly, but not to outside clients of the assembly, declare it
using the Friend keyword in the declarations section of the class.
To create a constant available throughout the application, declare it using the Public keyword in the declarations section
the class.
For more information, see How to: Declare A Constant.
Avoiding Circular References
Because constants can be defined in terms of other constants, it is possible to inadvertently create a cycle, or circular reference,
between two or more constants. A cycle occurs when you have two or more public constants, each of which is defined in terms
of the other, as in the following example:
VB
Public Const conA = conB * 2
... Public Const conB = conA / 2
If a cycle occurs, Visual Basic generates a compiler error.
See Also
Tasks
How to: Declare Enumerations
Reference
Const Statement (Visual Basic)
Option Strict Statement
Concepts
Constant and Literal Data Types
Enumerations Overview
Constants Overview
Enumerations and Name Qualification
Intrinsic Constants and Enumerations
Constants Overview
Other Resources
Constants and Enumerations in Visual Basic
Visual Basic Language Concepts

Constant and Literal Data Types


A literal is a value that is expressed as itself rather than as a variable's value or the result of an expression, such as the number
3 or the string "Hello". A constant is a meaningful name that takes the place of a literal and retains this same value throughout
the program, as opposed to a variable, whose value may change.
When Option Strict is On, you must declare all constants explicitly with a data type. In the following example, the data type of
MyByte is explicitly declared as data type Byte:

Option Strict On
Public Const MyByte As Byte = 2

Explicitly declaring data types is unambiguous, and typed code is easier to read and maintain than untyped code. When
Option Strict is Off, however, the compiler uses the type of the expression used to initialize the constant. A numeric integer
literal is cast by default to the Integer data type. The default data type for floating-point numbers is Double, and the keywords
True and False specify a Boolean constant.
Literals and Type Coercion
In some cases, you might want to force a literal to a particular data type; for example, when assigning a particularly large
integral literal value to a variable of type Decimal. The following example produces an error:

Dim myDecimal as Decimal


myDecimal = 100000000000000000000 ' This causes a compiler error.

The error results from the representation of the literal. The Decimal data type can hold a value this large, but the literal is
implicitly represented as a Long, which cannot.
You can coerce a literal to a particular data type in two ways: by appending a type character to it, or by placing it within
enclosing characters. A type character or enclosing characters must immediately precede and/or follow the literal, with no
intervening space or characters of any kind.
To make the previous example work, you can append the D type character to the literal, which causes it to be represented as a
Decimal:

MyDecimal = 100000000000000000000D

The following example demonstrates correct usage of type characters and enclosing characters:

Option Strict Off


Public Const DefaultInteger = 100 ' Default is Integer.
Public Const DefaultDouble = 54.3345612 ' Default is Double.
Public Const MyCharacter = "a"C ' Forces constant to be a Char type.
Public Const MyDate = #01/15/01# ' Demonstrates DateTime constants.
Public Const MyTime = #1:15:59 AM#
Public Const MyLong = 45L ' Forces data type to be a Long.
Public Const MySingle = 45.55! ' Forces data type to be a Single.

The following table shows the enclosing characters and type characters available in Visual Basic.
Data type Enclosing character Appended type character
Boolean (none) (none)

Byte (none) (none)

Char " C

Date # (none)
Decimal (none) D or @

Double (none) R or #

Integer (none) I or %

Long (none) L or &

Short (none) S

Single (none) F or !

String " (none)

See Also
Tasks
How to: Declare A Constant
How to: Declare Enumerations
Reference
Option Strict Statement
Option Explicit Statement (Visual Basic)
Data Type Summary (Visual Basic)
Concepts
User-Defined Constants
Constants Overview
Enumerations Overview
Enumerations and Name Qualification
Intrinsic Constants and Enumerations
Visual Basic Language Concepts

How to: Group Related Constant Values Together


An enumeration is the best way to group related constants together. You create an enumeration with the Enum statement in
the declarations section of a class or a module. For more information, see How to: Declare Enumerations.
To group related constant values
1. Write a declaration that includes a code access level, the Enum keyword, and a valid name. This example creates the
Private enumeration, temperatureValues.
VB
Private Enum temperatureValues

2. Define the constants in the enumeration. This example creates the Public enumeration temperatureValues and assigns
its values.
VB
Public Enum temperatureValues
Scorching
Hot
Lukewarm
Cool
Cold
End Enum

See Also
Tasks
How to: Refer to an Enumeration Member
Concepts
Enumerations and Name Qualification
When to Use an Enumeration
Intrinsic Constants and Enumerations
Constants Overview
Constant and Literal Data Types
Visual Basic Language Concepts

Enumerations Overview
Enumerations provide a convenient way to work with sets of related constants and to associate constant values with names.
For example, you can declare an enumeration for a set of integer constants associated with the days of the week, and then use
the names of the days rather than their integer values in your code.
Tasks involving Enumerations
The following table lists common tasks involving enumerations.
To do this See
Find a pre-defined enumeration Enumerations Declared by Visual Basic

Declare an enumeration How to: Declare Enumerations

Fully qualify an enumeration's name Enumerations and Name Qualification

Refer to an enumeration member How to: Refer to an Enumeration Member

Iterate through an enumeration How to: Iterate Through An Enumeration in Visual Basic

Determine the string associated with an enumeration How to: Determine the String Associated with an Enumeration Value

Decide when to use an enumeration When to Use an Enumeration

See Also
Tasks
How to: Declare A Constant
Reference
Enum Statement (Visual Basic)
Concepts
Constants Overview
User-Defined Constants
Constant and Literal Data Types
Intrinsic Constants and Enumerations
Visual Basic Language Concepts

Enumerations Declared by Visual Basic


Enumerations provide a convenient way to work with sets of related constants and to associate constant values with names.
Visual Basic provides a number of useful enumerations.
Predefined Enumerations
The following table lists and describes the enumerations provided by Visual Basic.
Enumeration Description
AppWinStyle Enumeration Indicates the window style to use for the invoked program when calling the Shell functio
n.

AudioPlayMode Enumeration Indicates how to play sounds when calling audio methods.

BuiltInRole Enumeration Indicates the type of role to check when calling the My.User.IsInRole Method.

CallType Enumeration Indicates the type of the type of procedure being invoked when calling the CallByName f
unction.

CompareMethod Enumeration Indicates how to compare strings when calling comparison functions.

DateFormat Enumeration Indicates how to display dates when calling the FormatDateTime function.

DateInterval Enumeration Indicates how to determine and format date intervals when calling date-related functions.

DeleteDirectoryOption Enumeration Specifies what should be done when a directory that is to be deleted contains files or dire
ctories.

DueDate Enumeration Indicates when payments are due when calling financial methods.

FieldType Enumeration Indicates whether text fields are delimited or fixed-width.

FileAttribute Enumeration Indicates the file attributes to use when calling file-access functions.

FirstDayOfWeek Enumeration Indicates the first day of the week to use when calling date-related functions.

FirstWeekOfYear Enumeration Indicates the first week of the year to use when calling date-related functions.

MsgBoxResult Enumeration Indicates which button was pressed on a message box, returned by the MsgBox function.

MsgBoxStyle Enumeration Indicates which buttons to display when calling the MsgBox function.

OpenAccess Enumeration Indicates type of access when calling file-access functions.

OpenMode Enumeration Indicates mode that should be used when calling file-access functions.

OpenShare Enumeration Indicates whether a file can be used by other processes when calling file-access functions.

RecycleOption Enumeration Specifies whether a file should be deleted permanently or placed in the Recycle Bin.

SearchOption Enumeration Specifies whether to search all or only top level directories.
TriState Enumeration Indicates either a Boolean value or that the default should be used when calling number-
formatting functions.

UICancelOption Enumeration Specifies what should be done if the user clicks Cancel during an operation.
UIOption Enumeration Specifies whether or not to show a progress dialog box when copying, deleting, or movin
g files or directories.

VariantType Enumeration Indicates the type of a variant object, returned by the VarType function.

VbStrConv Enumeration Indicates which type of conversion to perform when calling the StrConv function.

DueDate Enumeration Indicates when payments are due when calling financial methods.

See Also
Tasks
How to: Declare Enumerations
How to: Refer to an Enumeration Member
How to: Iterate Through An Enumeration in Visual Basic
How to: Determine the String Associated with an Enumeration Value
Concepts
Enumerations and Name Qualification
When to Use an Enumeration
Visual Basic Language Concepts

How to: Declare Enumerations


You create an enumeration with the Enum statement in the declarations section of a class or module. You cannot declare an
enumeration within a method. To specify the appropriate level of access, use Private, Protected, Friend, or Public.
An Enum type has a name, an underlying type, and a set of fields, each representing a constant. The name must be a valid
Visual Basic 2005 qualifier. The underlying type must be one of the integer types—Byte, Short, Long or Integer. Integer is
the default. Enumerations are always strongly typed and are not interchangeable with integer number types.
Enumerations cannot have floating-point values. If an enumeration is assigned a floating-point value with Option Strict On, a
compiler error results. If Option Strict is Off, the value is automatically converted to the Enum type.
For information on names, and how to use the Imports statement to make name qualification unnecessary, see
Enumerations and Name Qualification.
To declare an enumeration
1. Write a declaration that includes a code access level, the Enum keyword, and a valid name, as in the following examples,
each of which declares a different Enum.
VB
Private Enum SampleEnum
SampleMember
End Enum
Public Enum SampleEnum2
SampleMember
End Enum
Protected Enum SampleEnum3
SampleMember
End Enum
Friend Enum SampleEnum4
SampleMember
End Enum
Protected Friend Enum SampleEnum5
SampleMember
End Enum

2. Define the constants in the enumeration. By default, the first constant in an enumeration is initialized to 0, and
subsequent constants are initialized to a value of one more than the previous constant. For example, the following
enumeration, Days, contains a constant named Sunday with the value 0, a constant named Monday with the value 1, a
constant named Tuesday with the value of 2, and so on.
VB
Public Enum Days
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
End Enum

3. You can explicitly assign values to constants in an enumeration by using an assignment statement. You can assign any
integer value, including negative numbers. For example, you may want constants with values less than zero to represent
error conditions. In the following enumeration, the constant Invalid is explicitly assigned the value –1, and the constant
Sunday is assigned the value 0. Because it is the first constant in the enumeration, Saturday is also initialized to the value
0. The value of Monday is 1 (one more than the value of Sunday); the value of Tuesday is 2, and so on.

VB
Public Enum WorkDays
Saturday
Sunday = 0
Monday
Tuesday
Wednesday
Thursday
Friday
Invalid = -1
End Enum

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
To declare an enumeration explicitly
Write a declaration using the following syntax.
VB
Public Enum MyEnum As Byte
Zero
One
Two
End Enum

See Also
Tasks
How to: Refer to an Enumeration Member
How to: Iterate Through An Enumeration in Visual Basic
How to: Determine the String Associated with an Enumeration Value
Concepts
Enumerations and Name Qualification
When to Use an Enumeration
Intrinsic Constants and Enumerations
Constant and Literal Data Types
Other Resources
Constants in Visual Basic
Visual Basic Language Concepts

How to: Refer to an Enumeration Member


Enumerations provide a convenient way to work with sets of related constants and to associate constant values with names.
For example, you can declare an enumeration for a set of integer constants associated with the days of the week, and then use
the names of the days rather than their integer values in your code.
You can avoid using fully qualified names with the Imports statement. For more information, see
Enumerations and Name Qualification.
To refer to an enumeration member
Qualify the member name with the enumeration. For example, the following example assigns the Saturday member of
the FirstDayOfWeek enumeration to the variable DayValue.
VB
DayValue = FirstDayOfWeek.Saturday

See Also
Tasks
How to: Declare Enumerations
How to: Iterate Through An Enumeration in Visual Basic
How to: Determine the String Associated with an Enumeration Value
Concepts
Enumerations Declared by Visual Basic
Enumerations and Name Qualification
When to Use an Enumeration
Visual Basic Language Concepts

Enumerations and Name Qualification


Normally, when referring to a member of an enumeration, you must qualify the member name with the enumeration name.
For example, to refer to the Sunday member of your Days enumeration, you would use the following syntax:
VB
X = Days.Sunday

Using the Imports Statement


You can avoid using fully qualified names by adding an Imports statement to the namespace declarations section of your
code, as in the following example:
VB
Imports WindowsApplication1.Form1.Days
Imports WindowsApplication1.Form1.WorkDays

An Imports statement imports namespace names from referenced projects and assemblies and from within the same project
as the module in which the statement appears. Once this statement is added, you can refer to your enumeration members
without qualification, as in the following example:
VB
X = Sunday

By organizing sets of related constants in enumerations, you can use the same constant names in different contexts. For
example, you can use the same names for the weekday constants in the Days and WorkDays enumerations. If you use the
Imports statement with your enumerations, you must be careful to avoid ambiguous references. Consider the following
example:
VB
Imports WindowsApplication1.Form1.Days
Imports WindowsApplication1.Form1.WorkDays

VB
Public Sub New()
' Insert code to implement constructor.
X = Monday
End Sub

Assuming that Monday is a member of both the Days enumeration and the Workdays enumeration, this code generates a
compiler error. To avoid ambiguous references when referring to an individual constant, qualify the constant name with its
enumeration. The following code refers to the Saturday constants in the Days and WorkDays enumerations.
VB
X = Days.Saturday
Y = WorkDays.Saturday

See Also
Tasks
How to: Declare Enumerations
How to: Refer to an Enumeration Member
How to: Iterate Through An Enumeration in Visual Basic
How to: Determine the String Associated with an Enumeration Value
Reference
Enum Statement (Visual Basic)
Imports Statement
Data Type Summary (Visual Basic)
Concepts
Enumerations Declared by Visual Basic
When to Use an Enumeration
Constant and Literal Data Types
Visual Basic Language Concepts

How to: Iterate Through An Enumeration in Visual Basic


Enumerations provide a convenient way to work with sets of related constants, and to associate constant values with names. To
iterate through an enumeration, you can move it into an array using the GetValues method. You could also iterate through an
enumeration using a For...Each statement, using the GetNames or GetValues method to extract the string or numeric value.
To iterate through an enumeration
Declare an array and convert the enumeration to it with the GetValues method before passing the array as you would
any other variable. The following example displays each member of the enumeration MyEnum as it iterates through the
enumeration.
VB
Dim items As Array
items = System.Enum.GetValues(GetType(FirstDayOfWeek))
Dim item As String
For Each item In items
MsgBox(item)
Next

See Also
Tasks
How to: Declare Enumerations
How to: Determine the String Associated with an Enumeration Value
How to: Refer to an Enumeration Member
How to: Pass an Array to a Procedure or Property
Concepts
Enumerations Overview
When to Use an Enumeration
Enumerations and Name Qualification
Enumerations Declared by Visual Basic
Overview of Arrays in Visual Basic
Visual Basic Language Concepts

How to: Determine the String Associated with an Enumeration


Value
The GetValues and GetNames methods allow you to determine the strings and values associated with enumeration members.
To determine the string associated with an enumeration
Use the GetNames method to retrieve the strings associated with the enumeration members. This example declares an
enumeration, flavorEnum, then uses the GetNames method to display the strings associated with each member.
VB
Public Enum flavorEnum
salty
sweet
sour
bitter
End Enum

Private Sub TestMethod()


MsgBox("The strings in the flavorEnum are:")
Dim i As String
For Each i In [Enum].GetNames(GetType(flavorEnum))
MsgBox(i)
Next
End Sub

See Also
Tasks
How to: Declare Enumerations
How to: Refer to an Enumeration Member
How to: Iterate Through An Enumeration in Visual Basic
Reference
Enum Statement (Visual Basic)
GetValues
GetNames
Enum
Concepts
Enumerations Declared by Visual Basic
Enumerations and Name Qualification
When to Use an Enumeration
Visual Basic Language Concepts

When to Use an Enumeration


Enumerations offer an easy way to work with sets of related constants. An enumeration, or Enum, is a symbolic name for a set
of values. Enumerations are treated as data types, and you can use them to create sets of constants for use with variables and
properties.
When to Use an Enumeration
Whenever a procedure accepts a limited set of variables, consider using an enumeration. Enumerations make for clearer and
more readable code, particularly when meaningful names are used.
The benefits of using enumerations include:
Reduces errors caused by transposing or mistyping numbers.
Makes it easy to change values in the future.
Makes code easier to read, which means it is less likely that errors will creep into it.
Ensures forward compatibility. With enumerations, your code is less likely to fail if in the future someone changes the
values corresponding to the member names.
Naming Enumerations
Use a naming convention for enumeration members. When Visual Basic encounters an enumeration member name, an
exception may be thrown if other referenced type libraries contain the same name. Use a unique prefix that identifies the
values from your application or component.
When referring to a member of an enumeration, you must qualify the member name with the enumeration name or else use
the Imports statement. For more information, see Enumerations and Name Qualification.
Predefined Enumerations
Visual Basic provides a number of predefined enumerations, such as FirstDayOfWeek and MsgBoxResult, to facilitate your
code. For a list of these see Enumerations Declared by Visual Basic.
See Also
Tasks
How to: Declare Enumerations
How to: Refer to an Enumeration Member
How to: Iterate Through An Enumeration in Visual Basic
How to: Determine the String Associated with an Enumeration Value
Reference
Enum Statement (Visual Basic)
Concepts
Enumerations and Name Qualification
Intrinsic Constants and Enumerations
Visual Basic Language Concepts

Intrinsic Constants and Enumerations


Visual Basic provides a number of intrinsic constants and enumerations to facilitate your programming.
Remarks
Constants store values that remain constant throughout the execution of an application. They are meaningful names that take
the place of a number or string and make code more readable. Enumerations offer an easy way to work with sets of related
constants. An enumeration, or Enum, is a symbolic name for a set of values.
You can create your own constants and enumerations, as discussed in User-Defined Constants, or you can use the intrinsic
constants and enumerations Visual Basic provides, which are listed in the Object Browser.
The following table lists and describes the intrinsic enumerations available in Visual Basic.
Enumeration Description
AppWinStyle Enumeration Indicates the window style to use for the invoked program when calling the Shell functio
n.

AudioPlayMode Enumeration Indicates how to play sounds when calling audio methods.

BuiltInRole Enumeration Indicates the type of role to check when calling the My.User.IsInRole Method.

CallType Enumeration Indicates the type of procedure being invoked when calling the CallByName function.

CompareMethod Enumeration Indicates how to compare strings when calling comparison functions.

DateFormat Enumeration Indicates how to display dates when calling the FormatDateTime function.

DateInterval Enumeration Indicates how to determine and format date intervals when calling date-related functions.

DeleteDirectoryOption Enumeration Specifies what should be done when a directory that is to be deleted contains files or dire
ctories.

DueDate Enumeration Indicates when payments are due when calling financial methods.

FieldType Enumeration Indicates whether text fields are delimited or fixed-width.

FileAttribute Enumeration Indicates the file attributes to use when calling file-access functions.

FirstDayOfWeek Enumeration Indicates the first day of the week to use when calling date-related functions.

FirstWeekOfYear Enumeration Indicates the first week of the year to use when calling date-related functions.

MsgBoxResult Enumeration Indicates which button was pressed on a message box, returned by the MsgBox function.

MsgBoxStyle Enumeration Indicates which buttons to display when calling the MsgBox function.

OpenAccess Enumeration Identifies whether a file can be read from, written to, or both.

OpenMode Enumeration Indicates what access mode should be used when accessing a file.

OpenShare Enumeration Specifies whether other processes can access an open file.

RecycleOption Enumeration Specifies whether a file should be deleted permanently or placed in the Recycle Bin.
SearchOption Enumeration Specifies whether to search all or only top-level directories.

TriState Enumeration Indicates a Boolean value or if the default should be used when calling number-formattin
g functions.

UICancelOption Enumeration Specifies what should be done if the user clicks Cancel during an operation.

UIOption Enumeration Specifies whether or not to show a progress dialog box when copying, deleting, or movin
g files or directories.

VariantType Enumeration Indicates the type of a variant object, returned by the VarType function.

VbStrConv Enumeration Indicates which type of conversion to perform when calling the StrConv function.

See Also
Tasks
How to: Declare A Constant
Reference
Enum Statement (Visual Basic)
Object Browser
Concepts
Constants Overview
Constant and Literal Data Types
Enumerations Overview
User-Defined Constants
Other Resources
Constants and Enumerations (Visual Basic)
Visual Basic Language Concepts

Operators and Expressions in Visual Basic


An operator is a code element that performs an operation on one or more code elements that hold values. Value elements
include variables, constants, literals, properties, returns from Function and Operator procedures, and expressions.
An expression is a series of value elements combined with operators, which yields a new value. The operators act on the value
elements by performing calculations, comparisons, or other operations.
Types of Operators
Visual Basic provides the following types of operators:
Arithmetic Operators perform familiar calculations on numeric values, including shifting their bit patterns.
Comparison Operators compare two expressions and return a Boolean value representing the result of the comparison.
Concatenation Operators join multiple strings into a single string.
Logical and Bitwise Operators in Visual Basic combine Boolean or numeric values and return a result of the same data
type as the values.
The value elements that are combined with an operator are called operands of that operator. Operators combined with value
elements form expressions, except for the assignment operator, which forms a statement. For more information, see
Assignment Statements.
Evaluation of Expressions
The end result of an expression represents a value, which is typically of a familiar data type such as Boolean, String, or a
numeric type.
The following are examples of expressions.
5 + 4
' The preceding expression evaluates to 9.
15 * System.Math.Sqrt(9) + x
' The preceding expression evaluates to 45 plus the value of x.
"Concat" & "ena" & "tion"
' The preceding expression evaluates to "Concatenation".
763 < 23
' The preceding expression evaluates to False.

Several operators can perform actions in a single expression or statement, as the following example illustrates.
VB
x = 45 + y * z ^ 2

In the preceding example, Visual Basic performs the operations in the expression on the right side of the assignment operator
(=), then assigns the resulting value to the variable x on the left. There is no practical limit to the number of operators that can
be combined into an expression, but an understanding of Operator Precedence in Visual Basic is necessary to ensure that you
get the results you expect.
See Also
Concepts
Efficient Combination of Operators
Other Resources
Operators (Visual Basic)
Statements in Visual Basic
Visual Basic Language Concepts

Common Tasks Performed with Visual Basic Operators


Operators perform many common tasks involving one or more expressions called operands.
Arithmetic and Bit-shift Tasks
The following table summarizes the available arithmetic and bit-shift operations.
To See
Add one numeric value to another + Operator (Visual Basic)

Subtract one numeric value from another - Operator (Visual Basic)

Reverse the sign of a numeric value - Operator (Visual Basic)

Multiply one numeric value by another * Operator (Visual Basic)

Divide one numeric value into another / Operator (Visual Basic)

Find the quotient of one numeric value divided by another (without the remainder) \ Operator

Find the remainder of one numeric value divided by another (without the quotient) Mod Operator (Visual Basic)

Raise one numeric value to the power of another ^ Operator (Visual Basic)

Shift the bit pattern of a numeric value to the left << Operator (Visual Basic)

Shift the bit pattern of a numeric value to the right >> Operator (Visual Basic)

Comparison Tasks
The following table summarizes the available comparison operations.
To See
Determine whether two values are equal = Operator (Comparison Operators in Visual Basic)

Determine whether two values are unequal <> Operator (Comparison Operators in Visual Basic
)

Determine whether one value is less than another < Operator (Comparison Operators in Visual Basic)

Determine whether one value is greater than another > Operator (Comparison Operators in Visual Basic)

Determine whether one value is less than or equal to another <= Operator (Comparison Operators in Visual Basic
)

Determine whether one value is greater than or equal to another >= Operator (Comparison Operators in Visual Basic
)

Determine whether two object variables refer to the same object instance Is Operator (Visual Basic)

Determine whether two object variables refer to different object instance IsNot Operator
s
Determine whether an object is of a specific type TypeOf Operator (Visual Basic)

Concatenation Tasks
The following table summarizes the available concatenation operations.
To See
Join multiple strings into a single string & Operator (Concatenation Operators in Visual Basic)

Join numeric values with string values + Operator (Concatenation Operators in Visual Basic)

Logical and Bitwise Tasks


The following table summarizes the available logical and bitwise operations.
To See
Perform logical negation on a Boolean value Not Operator (Visual Basic)

Perform logical conjunction on two Boolean values And Operator (Visual Basic)

Perform inclusive logical disjunction on two Boolean values Or Operator (Visual Basic)

Perform exclusive logical disjunction on two Boolean values Xor Operator (Visual Basic)

Perform short-circuited logical conjunction on two Boolean values AndAlso Operator

Perform short-circuited inclusive logical disjunction on two Boolean values OrElse Operator

Perform bit-by-bit logical conjunction on two integral values And Operator (Visual Basic)

Perform bit-by-bit inclusive logical disjunction on two integral values Or Operator (Visual Basic)

Perform bit-by-bit exclusive logical disjunction on two integral values Xor Operator (Visual Basic)

Perform bit-by-bit logical negation on an integral value Not Operator (Visual Basic)

See Also
Reference
Operators Listed by Functionality
Concepts
Operators and Expressions in Visual Basic
Visual Basic Language Concepts

Arithmetic Operators in Visual Basic


Arithmetic operators are used to perform many of the familiar arithmetic operations that involve the calculation of numeric
values represented by literals, variables, other expressions, function and property calls, and constants. Also classified with
arithmetic operators are the bit-shift operators, which act at the level of the individual bits of the operands and shift their bit
patterns to the left or right.
Arithmetic Operations
You can add two values in an expression together with the + Operator (Visual Basic), or subtract one from another with the
- Operator (Visual Basic), as the following example demonstrates.
VB
Dim x As Integer
x = 67 + 34
x = 32 - 12

Negation also uses the - Operator (Visual Basic), but with only one operand, as the following example demonstrates.
VB
Dim x As Integer = 65
Dim y As Integer
y = -x

Multiplication and division use the * Operator (Visual Basic) and / Operator (Visual Basic), respectively, as the following
example demonstrates.
VB
Dim y As Double
y = 45 * 55.23
y = 32 / 23

Exponentiation uses the ^ Operator (Visual Basic), as the following example demonstrates.
VB
Dim z As Double
z = 23 ^ 3
' The preceding statement sets z to 12167 (the cube of 23).

Integer division is carried out using the \ Operator. Integer division returns the quotient, that is, the integer that represents the
number of times the divisor can divide into the dividend without consideration of any remainder. Both the divisor and the
dividend must be integral types (SByte, Byte, Short, UShort, Integer, UInteger, Long, and ULong) for this operator. All other
types must be converted to an integral type first. The following example demonstrates integer division.
VB
Dim k As Integer
k = 23 \ 5
' The preceding statement sets k to 4.

Modulus arithmetic is performed using the Mod Operator (Visual Basic). This operator returns the remainder after dividing the
divisor into the dividend an integral number of times. If both divisor and dividend are integral types, the returned value is
integral. If divisor and dividend are floating-point types, the returned value is also floating-point. The following example
demonstrates this behavior.
VB
Dim x As Integer = 100
Dim y As Integer = 6
Dim z As Integer
z = x Mod y
' The preceding statement sets z to 4.

VB
Dim a As Double = 100.3
Dim b As Double = 4.13
Dim c As Double
c = a Mod b
' The preceding statement sets c to 1.18.

Attempted Division by Zero


Division by zero has different results depending on the data types involved. In integral divisions (SByte, Byte, Short, UShort,
Integer, UInteger, Long, ULong), the .NET Framework throws a DivideByZeroException exception. In division operations on
the Decimal or Single data type, the .NET Framework also throws a DivideByZeroException exception.
In floating-point divisions involving the Double data type, no exception is thrown, and the result is the class member
representing NaN, PositiveInfinity, or NegativeInfinity, depending on the dividend. The following table summarizes the various
results of attempting to divide a Double value by zero.
Dividend data type Divisor data type Dividend value Result
Double Double 0 NaN (not a mathematically defined number)

Double Double >0 PositiveInfinity

Double Double <0 NegativeInfinity

When you catch a DivideByZeroException exception, you can use its members to help you handle it. For example, the
Message property holds the message text for the exception. For more information, see
Structured Exception Handling Overview for Visual Basic.
Bit-Shift Operations
A bit-shift operation performs an arithmetic shift on a bit pattern. The pattern is contained in the operand on the left, while the
operand on the right specifies the number of positions to shift the pattern. You can shift the pattern to the right with the
>> Operator (Visual Basic) or to the left with the << Operator (Visual Basic).
The data type of the pattern operand must be SByte, Byte, Short, UShort, Integer, UInteger, Long, or ULong. The data type
of the shift amount operand must be Integer or must widen to Integer.
Arithmetic shifts are not circular, which means the bits shifted off one end of the result are not reintroduced at the other end.
The bit positions vacated by a shift are set as follows:
0 for an arithmetic left shift
0 for an arithmetic right shift of a positive number
0 for an arithmetic right shift of an unsigned data type (Byte, UShort, UInteger, ULong)
1 for an arithmetic right shift of a negative number (SByte, Short, Integer, or Long)
The following example shifts an Integer value both left and right.
VB
Dim lResult, rResult As Integer
Dim pattern As Integer = 12
' The low-order bits of pattern are 0000 1100.
lResult = pattern << 3
' A left shift of 3 bits produces a value of 96.
rResult = pattern >> 2
' A right shift of 2 bits produces value of 3.

Arithmetic shifts never generate overflow exceptions.


Bitwise Operations
In addition to being logical operators, Not, Or, And, and Xor also perform bitwise arithmetic when used on numeric values.
For more information, see "Bitwise Operations" in Logical and Bitwise Operators in Visual Basic.
Type Safety
Operands should normally be of the same type. For example, if you are doing addition with an Integer variable, you should
add it to another Integer variable, and you should assign the result to a variable of type Integer as well.
One way to ensure good type-safe coding practice is to use the Option Strict Statement. If you set Option Strict On, Visual
Basic automatically performs type-safe conversions. For example, if you try to add an Integer variable to a Double variable
and assign the value to a Double variable, the operation proceeds normally, because an Integer value can be converted to
Double without loss of data. Type-unsafe conversions, on the other hand, cause a compiler error with Option Strict On. For
example, if you try to add an Integer variable to a Double variable and assign the value to an Integer variable, a compiler
error results, because a Double variable cannot be implicitly converted to type Integer.
If you set Option Strict Off, however, Visual Basic allows implicit narrowing conversions to take place, although they can
result in the unexpected loss of data or precision. For this reason, we recommend that you use Option Strict On when writing
production code. For more information, see Widening and Narrowing Conversions.
See Also
Reference
Arithmetic Operators (Visual Basic)
Bit Shift Operators
Concepts
Comparison Operators in Visual Basic
Concatenation Operators in Visual Basic
Logical and Bitwise Operators in Visual Basic
Efficient Combination of Operators
Visual Basic Language Concepts

Comparison Operators in Visual Basic


Comparison operators compare two expressions and return a Boolean value that represents the relationship of their values.
There are operators for comparing numeric values, operators for comparing strings, and operators for comparing objects. All
three types of operators are discussed herein.
Comparing Numeric Values
Visual Basic compares numeric values using six numeric comparison operators. Each operator takes as operands two
expressions that evaluate to numeric values. The following table lists the operators and shows examples of each.
Operator Condition tested Examples
= (Equality) Is the value of the first expression equal to the value of the second? 23 = 33 ' False
23 = 23 ' True
23 = 12 ' False

<> (Inequality) Is the value of the first expression unequal to the value of the second? 23 <> 33 ' True
23 <> 23 ' Fals
e
23 <> 12 ' True

< (Less than) Is the value of the first expression less than the value of the second? 23 < 33 ' True
23 < 23 ' False
23 < 12 ' False

> (Greater than) Is the value of the first expression greater than the value of the second? 23 > 33 ' False
23 > 23 ' False
23 > 12 ' True

<= (Less than or equal to) Is the value of the first expression less than or equal to the value of the second? 23 <= 33 ' True
23 <= 23 ' True
23 <= 12 ' Fals
e

>= (Greater than or equal t Is the value of the first expression greater than or equal to the value of the seco 23 >= 33 ' Fals
e
o) nd?
23 >= 23 ' True
23 >= 12 ' True

Comparing Strings
Visual Basic compares strings using the Like Operator as well as the numeric comparison operators. The Like operator allows
you to specify a pattern. The string is then compared against the pattern, and if it matches, the result is True. Otherwise, the
result is False. The numeric operators allow you to compare String values based on their sort order, as the following example
shows.
"73" < "9"
' The result of the preceding comparison is True.

The result in the preceding example is True because the first character in the first string sorts before the first character in the
second string. If the first characters were equal, the comparison would continue to the next character in both strings, and so on.
You can also test equality of strings using the equality operator, as the following example shows.
"734" = "734"
' The result of the preceding comparison is True.

If one string is a prefix of another, such as "aa" and "aaa", the longer string is considered to be greater than the shorter string.
The following example illustrates this.
"aaa" > "aa"
' The result of the preceding comparison is True.

The sort order is based on either a binary comparison or a textual comparison depending on the setting of Option Compare.
For more information see Option Compare Statement.
Comparing Objects
Visual Basic compares two object reference variables with the Is Operator (Visual Basic) and the IsNot Operator. You can use
either of these operators to determine if two reference variables refer to the same object instance. The following example
illustrates this.
VB
Dim x As testClass
Dim y As New testClass()
x = y
If x Is y Then
' Insert code to run if x and y point to the same instance.
End If

In the preceding example, x Is y evaluates to True, because both variables refer to the same instance. Contrast this result with
the following example.
VB
Dim x As New customer()
Dim y As New customer()
If x Is y Then
' Insert code to run if x and y point to the same instance.
End If

In the preceding example, x Is y evaluates to False, because although the variables refer to objects of the same type, they
refer to different instances of that type.
When you want to test for two objects not pointing to the same instance, the IsNot operator lets you avoid a grammatically
clumsy combination of Not and Is. The following example illustrates this.
VB
Dim a As New classA()
Dim b As New classB()
If a IsNot b Then
' Insert code to run if a and b point to different instances.
End If

In the preceding example, If a IsNot b is equivalent to If Not a Is b.


Comparing Object Type
You can test whether an object is of a particular type with the TypeOf...Is expression. The syntax is as follows:
TypeOf <objectexpression> Is <typename>

When typename specifies an interface type, then the TypeOf...Is expression returns True if the object implements the interface
type. When typename is a class type, then the expression returns True if the object is an instance of the specified class or of a
class that derives from the specified class. The following example illustrates this.
VB
Dim x As System.Windows.Forms.Button
x = New System.Windows.Forms.Button()
If TypeOf x Is System.Windows.Forms.Control Then
' Insert code to run if x is of type System.Windows.Forms.Control.
End If
In the preceding example, the TypeOf x Is Control expression evaluates to True because the type of x is Button, which
inherits from Control.
For more information, see TypeOf Operator (Visual Basic).
See Also
Reference
Comparison Operators (Visual Basic)
Concepts
Value Comparisons
Arithmetic Operators in Visual Basic
Concatenation Operators in Visual Basic
Logical and Bitwise Operators in Visual Basic
Other Resources
Operators (Visual Basic)
Visual Basic Language Concepts

How to: Test Whether Two Objects Are the Same


If you have two variables that refer to objects, you can use either the Is or IsNot operator, or both, to determine whether they
refer to the same instance.
To test whether two objects are the same
Use the Is Operator (Visual Basic) or the IsNot Operator with the two variables as operands.
VB
Public Sub processControl(ByVal f As System.Windows.Forms.Form, _
ByVal c As System.Windows.Forms.Control)
Dim active As System.Windows.Forms.Control = f.ActiveControl
If (active IsNot Nothing) And (c Is active) Then
' Insert code to process control c
End If
Return
End Sub

You might want to take a certain action depending on whether two objects refer to the same instance. The preceding example
compares control c against the active control on form f. If there is no active control, or if there is one but it is not the same
control instance as c, then the If statement fails and the procedure returns without further processing.
Whether you use Is or IsNot is a matter of personal convenience to you. One might be easier to read than the other in a given
expression.
See Also
Concepts
Comparison Operators in Visual Basic
Visual Basic Language Concepts

How to: Match a String against a Pattern


If you want to find out if an expression of the String Data Type (Visual Basic) satisfies a pattern, then you can use the
Like Operator.
Like takes two operands. The left operand is a string expression, and the right operand is a string containing the pattern to be
used for matching. Like returns a Boolean value indicating whether the string expression satisfies the pattern.
You can match each character in the string expression against a specific character, a wildcard character, a character list, or a
character range. The positions of the specifications in the pattern string correspond to the positions of the characters to be
matched in the string expression.
To match a character in the string expression against a specific character
Put the specific character directly in the pattern string. Certain special characters must be enclosed in brackets ([ ]). For
more information, see Like Operator.
The following example tests whether myString consists exactly of the single character H.
VB
Dim sMatch As Boolean = myString Like "H"

To match a character in the string expression against a wildcard character


Put a question mark (?) in the pattern string. Any valid character in this position makes a successful match.
The following example tests whether myString consists of the single character W followed by exactly two characters of
any values.
VB
Dim sMatch As Boolean = myString Like "W??"

To match a character in the string expression against a list of characters


Put brackets ([ ]) in the pattern string, and inside the brackets put the list of characters. Do not separate the characters
with commas or any other separator. Any single character in the list makes a successful match.
The following example tests whether myString consists of any valid character followed by exactly one of the characters A,
C, or E.

VB
Dim sMatch As Boolean = myString Like "?[ACE]"

Note that this match is case-sensitive.


To match a character in the string expression against a range of characters
Put brackets ([ ]) in the pattern string, and inside the brackets put the lowest and highest characters in the range,
separated by a hyphen (–). Any single character within the range makes a successful match.
The following example tests whether myString consists of the characters num followed by exactly one of the characters i,
j, k, l, m, or n.

VB
Dim sMatch As Boolean = myString Like "num[i-m]"
Note that this match is case-sensitive.
Matching Empty Strings
Like treats the sequence [] as a zero-length string (""). You can use [] to test whether the entire string expression is empty,
but you cannot use it to test if a particular position in the string expression is empty. If an empty position is one of the options
you need to test for, you can use Like more than once.
To match a character in the string expression against a list of characters or no character
1. Call the Like operator twice on the same string expression, and connect the two calls with either the
Or Operator (Visual Basic) or the OrElse Operator.
2. In the pattern string for the first Like clause, include the character list, enclosed in brackets ([ ]).
3. In the pattern string for the second Like clause, do not put any character at the position in question.
The following example tests the seven-digit telephone number phoneNum for exactly three numeric digits, followed by a
space, a hyphen (–), a period (.), or no character at all, followed by exactly four numeric digits.
VB
Dim sMatch As Boolean = _
(phoneNum Like "###[ -.]####") OrElse (phoneNum Like "#######")

See Also
Reference
Comparison Operators (Visual Basic)
Like Operator
String Data Type (Visual Basic)
Concepts
Operators and Expressions in Visual Basic
Visual Basic Language Concepts

Concatenation Operators in Visual Basic


Concatenation operators join multiple strings into a single string. There are two concatenation operators, + and &. Both carry
out the basic concatenation operation, as the following example shows.
VB
Dim x As String = "Con" & "caten" & "ation"
Dim y As String = "Con" + "caten" + "ation"
' The preceding statements set both x and y to "Concatenation".

These operators can also concatenate String variables, as the following example shows.
VB
Dim a As String = "abc"
Dim d As String = "def"
Dim z As String = a & d
Dim w As String = a + d
' The preceding statements set both z and w to "abcdef".

Differences Between the Two Concatenation Operators


The + Operator (Visual Basic) has the primary purpose of adding two numbers. However, it can also concatenate numeric
operands with string operands. The + operator has a complex set of rules that determine whether to add, concatenate, signal a
compiler error, or throw a run-time InvalidCastException exception.
The & Operator (Visual Basic) is defined only for String operands, and it always widens its operands to String, regardless of
the setting of Option Strict. The & operator is recommended for string concatenation because it is defined exclusively for
strings and reduces your chances of generating an unintended conversion.
Performance: String and StringBuilder
If you do a significant number of manipulations on a string, such as concatenations, deletions, and replacements, your
performance might profit from the StringBuilder class in the System.Text namespace. It takes an extra instruction to create and
initialize a StringBuilder object, and another instruction to convert its final value to a String, but you might recover this time
because StringBuilder can perform faster.
See Also
Reference
Option Strict Statement
Concepts
Types of String Manipulation Methods in Visual Basic
Arithmetic Operators in Visual Basic
Comparison Operators in Visual Basic
Logical and Bitwise Operators in Visual Basic
Visual Basic Language Concepts

Logical and Bitwise Operators in Visual Basic


Logical operators compare Boolean expressions and return a Boolean result. The And, Or, AndAlso, OrElse, and Xor
operators are binary because they take two operands, while the Not operator is unary because it takes a single operand. Some
of these operators can also perform bitwise logical operations on integral values.
Unary Logical Operator
The Not Operator (Visual Basic) performs logical negation on a Boolean expression. It yields the logical opposite of its
operand. If the expression evaluates to True, then Not returns False; if the expression evaluates to False, then Not returns
True. The following example illustrates this.
VB
Dim x, y As Boolean
x = Not 23 > 14
y = Not 23 > 67
' The preceding statements set x to False and y to True.

Binary Logical Operators


The And Operator (Visual Basic) performs logical conjunction on two Boolean expressions. If both expressions evaluate to
True, then And returns True. If at least one of the expressions evaluates to False, then And returns False.
The Or Operator (Visual Basic) performs logical disjunction or inclusion on two Boolean expressions. If either expression
evaluates to True, or both evaluate to True, then Or returns True. If neither expression evaluates to True, Or returns False.
The Xor Operator (Visual Basic) performs logical exclusion on two Boolean expressions. If exactly one expression evaluates to
True, but not both, Xor returns True. If both expressions evaluate to True or both evaluate to False, Xor returns False.
The following example illustrates the And, Or, and Xor operators.
VB
Dim a, b, c, d, e, f, g As Boolean

a = 23 > 14 And 11 > 8


b = 14 > 23 And 11 > 8
' The preceding statements set a to True and b to False.

c = 23 > 14 Or 8 > 11
d = 23 > 67 Or 8 > 11
' The preceding statements set c to True and d to False.
e = 23 > 67 Xor 11 > 8
f = 23 > 14 Xor 11 > 8
g = 14 > 23 Xor 8 > 11
' The preceding statements set e to True, f to False, and g to False.

Short-Circuiting Logical Operations


The AndAlso Operator is very similar to the And operator, in that it also performs logical conjunction on two Boolean
expressions. The key difference between the two is that AndAlso exhibits short-circuiting behavior. If the first expression in an
AndAlso expression evaluates to False, then the second expression is not evaluated because it cannot alter the final result, and
AndAlso returns False.
Similarly, the OrElse Operator performs short-circuiting logical disjunction on two Boolean expressions. If the first expression
in an OrElse expression evaluates to True, then the second expression is not evaluated because it cannot alter the final result,
and OrElse returns True.
Short-Circuiting Trade-Offs
Short-circuiting can improve performance by not evaluating an expression that cannot alter the result of the logical operation.
However, if that expression performs additional actions, short-circuiting skips those actions. For example, if the expression
includes a call to a Function procedure, that procedure is not called if the expression is short-circuited, and any additional code
contained in the Function does not run. If your program logic depends on any of that additional code, you should probably
avoid short-circuiting operators.
The following example illustrates the difference between And, Or, and their short-circuiting counterparts.
VB
Dim amount As Integer = 12
Dim highestAllowed As Integer = 45
Dim grandTotal As Integer

VB
If amount > highestAllowed And checkIfValid(amount) Then
' The preceding statement calls checkIfValid().
End If
If amount > highestAllowed AndAlso checkIfValid(amount) Then
' The preceding statement does not call checkIfValid().
End If
If amount < highestAllowed Or checkIfValid(amount) Then
' The preceding statement calls checkIfValid().
End If
If amount < highestAllowed OrElse checkIfValid(amount) Then
' The preceding statement does not call checkIfValid().
End If

VB
Function checkIfValid(ByVal checkValue As Integer) As Boolean
If checkValue > 15 Then
MsgBox(CStr(checkValue) & " is not a valid value.")
' The MsgBox warning is not displayed if the call to
' checkIfValid() is part of a short-circuited expression.
Return False
Else
grandTotal += checkValue
' The grandTotal value is not updated if the call to
' checkIfValid() is part of a short-circuited expression.
Return True
End If
End Function

In the preceding example, note that some important code inside checkIfValid() does not run when the call is short-circuited.
The first If statement calls checkIfValid() even though 12 > 45 returns False, because And does not short-circuit. The second
If statement does not call checkIfValid(), because when 12 > 45 returns False, AndAlso short-circuits the second
expression. The third If statement calls checkIfValid() even though 12 < 45 returns True, because Or does not short-circuit.
The fourth If statement does not call checkIfValid(), because when 12 < 45 returns True, OrElse short-circuits the second
expression.
Bitwise Operations
Bitwise operations evaluate two integral values in binary (base 2) form. They compare the bits at corresponding positions and
then assign values based on the comparison. The following example illustrates the And operator.

Dim x As Integer
x = 3 And 5

The preceding example sets the value of x to 1. This happens for the following reasons:
The values are treated as binary:
3 in binary form = 011
5 in binary form = 101
The And operator compares the binary representations, one binary position (bit) at a time. If both bits at a given position
are 1, then a 1 is placed in that position in the result. If either bit is 0, then a 0 is placed in that position in the result. In the
preceding example this works out as follows:
011 (3 in binary form)
101 (5 in binary form)
001 (The result, in binary form)
The result is treated as decimal. The value 001 is the binary representation of 1, so x = 1.
The bitwise Or operation is similar, except that a 1 is assigned to the result bit if either or both of the compared bits is 1. Xor
assigns a 1 to the result bit if exactly one of the compared bits (not both) is 1. Not takes a single operand and inverts all the
bits, including the sign bit, and assigns that value to the result. This means that for signed positive numbers, Not always
returns a negative value, and for negative numbers, Not always returns a positive or zero value.
The AndAlso and OrElse operators do not support bitwise operations.
Note
Bitwise operations can be performed on integral types only. Floating-point values must be converted to integral types before
bitwise operation can proceed.

See Also
Reference
Logical/Bitwise Operators
Concepts
Boolean Expressions
Arithmetic Operators in Visual Basic
Comparison Operators in Visual Basic
Concatenation Operators in Visual Basic
Efficient Combination of Operators
Visual Basic Language Concepts

Efficient Combination of Operators


Complex expressions can contain many different operators. The following example illustrates this.
x = (45 * (y + z)) ^ (2 / 85) * 5 + z

Creating complex expressions such as the one in the preceding example requires a thorough understanding of the rules of
operator precedence. For more information, see Operator Precedence in Visual Basic.
Parenthetical Expressions
Often you want operations to proceed in a different order from that determined by operator precedence. Consider the
following example.
x = z * y + 4

The preceding example multiplies z by y, then adds the result to 4. But if you want to add y and 4 before multiplying the result
by z, you can override normal operator precedence by using parentheses. By enclosing an expression in parentheses, you force
that expression to be evaluated first, regardless of operator precedence. To force the preceding example to do the addition first,
you could rewrite it as in the following example.
x = z * (y + 4)

The preceding example adds y and 4, then multiplies that sum by z.


Nested Parenthetical Expressions
You can nest expressions in multiple levels of parentheses to override precedence even further. The expressions most deeply
nested in parentheses are evaluated first, followed by the next most deeply nested, and so on to the least deeply nested, and
finally the expressions outside parentheses. The following example illustrates this.
x = (z * 4) ^ (y * (z + 2))

In the preceding example, z + 2 is evaluated first, then the other parenthetical expressions. Exponentiation, which normally has
higher precedence than addition or multiplication, is evaluated last in this example because the other expressions are enclosed
in parentheses.
See Also
Tasks
How to: Calculate Numeric Values
Reference
Logical/Bitwise Operators
Operator Precedence in Visual Basic
Concepts
Arithmetic Operators in Visual Basic
Comparison Operators in Visual Basic
Logical and Bitwise Operators in Visual Basic
Boolean Expressions
Value Comparisons
Visual Basic Language Concepts

How to: Calculate Numeric Values


You can calculate numeric values through the use of numeric expressions. A numeric expression is an expression that contains
literals, constants, and variables representing numeric values, and operators that act on those values.
Calculating Numeric Values
To calculate a numeric value
Combine one or more numeric literals, constants, and variables into a numeric expression. The following example shows
some valid numeric expressions.
93.217

System.Math.PI

counter

4 * (67 + i)

The first three lines show a literal, a constant, and a variable. Each one forms a valid numeric expression by itself. The final
line shows a combination of a variable with two literals.
Note that a numeric expression does not form a complete Visual Basic statement by itself. You must use the expression
as part of a complete statement.
To store a numeric value
You can use an assignment statement to assign the value represented by a numeric expression to a variable, as the
following example demonstrates.
VB
Dim i As Integer = 2
Dim j As Integer
j = 4 * (67 + i)

In the preceding example, the value of the expression on the right side of the equal operator (=) is assigned to the
variable j on the left side of the operator, so j evaluates to 276.
For more information, see Assignment Statements.
Multiple Operators
If the numeric expression contains more than one operator, the order in which they are evaluated is determined by the rules of
operator precedence. To override the rules of operator precedence, you enclose expressions in parentheses, as in the above
example; the enclosed expressions are evaluated first.
To override normal operator precedence
Use parentheses to enclose the operations you want to be performed first. The following example shows two different
results with the same operands and operators.
VB
Dim i As Integer = 2
Dim j, k As Integer
j = 4 * (67 + i)
k = 4 * 67 + i

In the preceding example, the calculation for j performs the addition operator (+) first because the parentheses around
(67 + i) override normal precedence, and the value assigned to j is 276 (4 times 69). The calculation for k performs the
operators in their normal precedence (* before +), and the value assigned to k is 270 (268 plus 2).
For more information, see Operator Precedence in Visual Basic.
See Also
Reference
Operator Precedence in Visual Basic
Arithmetic Operators (Visual Basic)
Concepts
Operators and Expressions in Visual Basic
Value Comparisons
Assignment Statements
Efficient Combination of Operators
Visual Basic Language Concepts

Value Comparisons
Comparison operators can be used to construct expressions that compare the values of numeric variables. These expressions
return a Boolean value based on whether the comparison is true or false. Examples of such an expression are as follows.
45 > 26
26 > 45

The first expression evaluates to True, because 45 is greater than 26. The second example evaluates to False, because 26 is not
greater than 45.
You can also compare numeric expressions in this fashion. The expressions you compare can themselves be complex
expressions, as in the following example.
x / 45 * (y +17) >= System.Math.Sqrt(z) / (p - (x * 16))

The preceding complex expression includes literals, variables, and function calls. The expressions on both sides of the
comparison operator are evaluated, and the resulting values are then compared using the >= comparison operator. If the
value of the expression on the left side is greater than or equal to the value of the expression on the right, the entire expression
evaluates to True; otherwise, it evaluates to False.
Expressions that compare values are most commonly used in If...Then constructions, as in the following example.
VB
If x > 50 Then
' Insert code to run if x is greater than 50.
Else
' Insert code to run if x is less than or equal to 50.
End If

The = sign is a comparison operator as well as an assignment operator. When used as a comparison operator, it evaluates
whether the value on the left is equal to the value on the right, as shown in the following example.
VB
If x = 50 Then
' Insert code to continue program.
End If

You can also use a comparison expression anywhere a Boolean value is needed, such as in an If, While, Loop, or ElseIf
statement, or when assigning to or passing a value to a Boolean variable. In the following example, the value returned by the
comparison expression is assigned to a Boolean variable.
VB
Dim x As Boolean
x = 50 < 30
' The preceding statement assigns False to x.

See Also
Tasks
How to: Calculate Numeric Values
Reference
Operator Precedence in Visual Basic
Concepts
Boolean Expressions
Operators and Expressions in Visual Basic
Comparison Operators in Visual Basic
Visual Basic Language Concepts

Boolean Expressions
A Boolean expression is an expression that evaluates to a value of the Boolean Data Type. Boolean expressions can take
several forms. The simplest is the direct comparison of the value of a Boolean variable to a Boolean literal, as shown in the
following example.
VB
If newCustomer = True Then
' Insert code to execute if newCustomer = True.
Else
' Insert code to execute if newCustomer = False.
End If

Two Meanings of the = Operator


Notice that the assignment statement newCustomer = True looks the same as the expression in the preceding example, but it
performs a different function and is used differently. In the preceding example, the expression newCustomer = True represents
a Boolean value, and the = sign is interpreted as a comparison operator. In a stand-alone statement, the = sign is interpreted as
an assignment operator and assigns the value on the right to the variable on the left. The following example illustrates this.
VB
If newCustomer = True Then
newCustomer = False
End If

For further information, see Value Comparisons and Assignment Statements.


Comparison Operators
Comparison operators such as =, <, >, <>, <=, and >= produce Boolean expressions by comparing the expression on the left
side of the operator to the expression on the right side of the operator and evaluating the result as True or False. The
following example illustrates this.
42 < 81

Because 42 is less than 81, the Boolean expression in the preceding example evaluates to True. For more information on this
kind of expression, see Value Comparisons.
Comparison Operators Combined with Logical Operators
Comparison expressions can be combined using logical operators to produce more complex Boolean expressions. The
following example demonstrates the use of comparison operators in conjunction with a logical operator.
x > y And x < 1000

In the preceding example, the value of the overall expression depends on the values of the expressions on each side of the And
operator. If both expressions are True, then the overall expression evaluates to True. If either expression is False, then the
entire expression evaluates to False.
Short-Circuiting Operators
The logical operators AndAlso and OrElse exhibit behavior known as short-circuiting. A short-circuiting operator evaluates the
left operand first. If the left operand determines the value of the entire expression, then program execution proceeds without
evaluating the right expression. The following example illustrates this.
VB
If 45 < 12 AndAlso testFunction(3) = 81 Then
' Add code to continue execution.
End If
In the preceding example, the operator evaluates the left expression, 45 < 12. Because the left expression evaluates to False,
the entire logical expression must evaluate to False. Program execution thus skips execution of the code within the If block
without evaluating the right expression, testFunction(3). This example does not call testFunction() because the left
expression falsifies the entire expression.
Similarly, if the left expression in a logical expression using OrElse evaluates to True, execution proceeds to the next line of
code without evaluating the right expression, because the left expression has already validated the entire expression.
Comparison with Non-Short-Circuiting Operators
By contrast, both sides of the logical operator are evaluated when the logical operators And and Or are used. The following
example illustrates this.
VB
If 45 < 12 And testFunction(3) = 81 Then
' Add code to continue execution.
End If

The preceding example calls testFunction() even though the left expression evaluates to False.
Parenthetical Expressions
You can use parentheses to control the order of evaluation of Boolean expressions. Expressions enclosed by parentheses
evaluate first. For multiple levels of nesting, precedence is granted to the most deeply-nested expressions. Within parentheses,
evaluation proceeds according to the rules of operator precedence. For more information, see
Operator Precedence in Visual Basic.
See Also
Reference
Comparison Operators (Visual Basic)
Operator Precedence in Visual Basic
Boolean Data Type (Visual Basic)
Concepts
Logical and Bitwise Operators in Visual Basic
Value Comparisons
Assignment Statements
Efficient Combination of Operators
Visual Basic Language Concepts

Statements in Visual Basic


A statement in Visual Basic is a complete instruction that can contain keywords, operators, variables, constants, and
expressions. All statements fall into one of two categories: declaration statements, which name a variable, constant, or
procedure and can also specify a data type; or executable statements, which initiate actions.
In This Section
Statements Overview
Provides a high-level look at statements, including how to have multiple statements on one line, continue a statement over
multiple lines, add comments, and check compilation errors.
Assignment Statements
Describes statements that carry out assignment operations, which assign the value on the right side of the operator to the
variable on the left side.
Declaration Statements in Visual Basic
Describes statements that name and define procedures, variables, arrays, and constants.
Executable Statements
Describes statements that initiate action by executing a method. Executable statements can loop or branch through blocks of
code, and often contain mathematical or conditional operators.
Related Sections
Assignment Operators
Provides links to language reference pages covering assignment operators such as =, *=, and &=.
Operators and Expressions in Visual Basic
Shows how to combine elements with operators to yield new values.
Visual Basic Language Concepts

Statements Overview
A statement in Visual Basic is a complete instruction. It can contain keywords, operators, variables, constants, and expressions.
Each statement belongs to one of the following categories:
Declaration Statements, which name a variable, constant, or procedure, and can also specify a data type.
Executable Statements, which initiate actions. These statements can call a method or function, and they can loop or
branch through blocks of code. Executable statements include Assignment Statements, which assign a value or
expression to a variable or constant.
Putting Multiple Statements on One Line
You can have multiple statements on a single line separated by the colon (:) character. The following example illustrates this.
VB
Dim sampleString As String = "Hello World" : MsgBox(sampleString)

Though occasionally convenient, this form of syntax makes your code hard to read and maintain. Thus, it is recommended that
you keep one statement to a line.
Continuing a Statement over Multiple Lines
A statement usually fits on one line, but when it is too long, you can continue it onto the next line using a line-continuation
sequence, which consists of a space followed by an underscore character (_) followed by a carriage return. In the following
example, the MsgBox executable statement is continued over two lines.
VB
Public Sub demoBox()
Dim nameVar As String
nameVar = "John"
MsgBox("Hello " & nameVar & _
". How are you?")
End Sub

Adding Comments
Source code is not always self-explanatory, even to the programmer who wrote it. To help document their code, therefore,
most programmers make liberal use of embedded comments. Comments in code can explain a procedure or a particular
instruction to anyone reading or working with it later. Visual Basic ignores comments during compilation, and they do not
affect the compiled code.
Comment lines begin with an apostrophe (') or REM followed by a space. They can be added anywhere in code, except within a
string. To append a comment to a statement, insert an apostrophe or REM after the statement, followed by the comment.
Comments can also go on their own separate line. The following example demonstrates these possibilities.
VB
' This is a comment on a separate code line.
REM This is another comment on a separate code line.
x += a(i) * b(i) ' Add this amount to total.
MsgBox(statusMessage) REM Inform operator of status.

Checking Compilation Errors


If, after you type a line of code, the line is displayed with a wavy blue underline (an error message may appear as well), there is
a syntax error in the statement. You must find out what is wrong with the statement (by looking in the task list, or hovering
over the error with the mouse pointer and reading the error message) and correct it. Until you have fixed all syntax errors in
your code, your program will fail to compile correctly.
See Also
Tasks
How to: Break and Combine Statements in Code
How to: Label Statements
Concepts
Assignment Statements
Declaration Statements in Visual Basic
Executable Statements
Visual Basic Language Concepts

Assignment Statements
Assignment statements carry out assignment operations, which consist of taking the value on the right side of the assignment
operator (=) and storing it in the element on the left, as in the following example.
VB
v = 42

In the preceding example, the assignment statement stores the literal value 42 in the variable v.
Eligible Programming Elements
The programming element on the left side of the assignment operator must be able to accept and store a value. This means it
must be a variable or property that is not ReadOnly (Visual Basic), or it must be an array element. In the context of an
assignment statement, such an element is sometimes called an lvalue, for "left value."
The value on the right side of the assignment operator is generated by an expression, which can consist of any combination of
literals, constants, variables, properties, array elements, other expressions, or function calls. The following example illustrates
this.
VB
x = y + z + findResult(3)

The preceding example adds the value held in variable y to the value held in variable z, and then adds the value returned by the
call to function findResult. The total value of this expression is then stored in variable x.
Data Types in Assignment Statements
In addition to numeric values, the assignment operator can also assign String values, as the following example illustrates.
VB
Dim a, b As String
a = "String variable assignment"
b = "Con" & "cat" & "enation"
' The preceding statement assigns the value "Concatenation" to b.

You can also assign Boolean values, using either a Boolean literal or a Boolean expression, as the following example
illustrates.
VB
Dim r, s, t As Boolean
r = True
s = 45 > 1003
t = 45 > 1003 Or 45 > 17
' The preceding statements assign False to s and True to t.

Similarly, you can assign appropriate values to programming elements of the Char, Date, or Object data type. You can also
assign an object instance to an element declared to be of the class from which that instance is created.
Compound Assignment Statements
Compound assignment statements first perform an operation on an expression before assigning it to a programming element.
The following example illustrates one of these operators, +=, which increments the value of the variable on the left side of the
operator by the value of the expression on the right.
VB
n += 1

The preceding example adds 1 to the value of n, and then stores that new value in n. It is a shorthand equivalent of the
following statement:
VB
n = n + 1

A variety of compound assignment operations can be performed using operators of this type. For a list of these operators and
more information about them, see Assignment Operators.
The concatenation assignment operator (&=) is useful for adding a string to the end of already existing strings, as the
following example illustrates.
VB
Dim q As String = "Sample "
q &= "String"
' q now contains "Sample String".

Type Conversions in Assignment Statements


The value you assign to a variable, property, or array element must be of a data type appropriate to that destination element. In
general, you should try to generate a value of the same data type as that of the destination element. However, some types can
be converted to other types during assignment.
For information on converting between data types, see Type Conversions in Visual Basic. In brief, Visual Basic automatically
converts a value of a given type to any other type to which it widens. A widening conversion is one in that always succeeds at
run time and does not lose any data. For example, Visual Basic converts an Integer value to Double when appropriate,
because Integer widens to Double. For more information, see Widening and Narrowing Conversions.
Narrowing conversions (those that are not widening) carry a risk of failure at run time, or of data loss. You can perform a
narrowing conversion explicitly by using a type conversion function, or you can direct the compiler to perform all conversions
implicitly by setting Option Strict Off. For more information, see Implicit and Explicit Conversions.
See Also
Reference
Assignment Operators
Concepts
Statements Overview
Declaration Statements in Visual Basic
Executable Statements
Widening and Narrowing Conversions
Visual Basic Language Concepts

Declaration Statements in Visual Basic


You use declaration statements to name and define procedures, variables, properties, arrays, and constants. When you declare
a programming element, you can also define its data type, access level, and scope. For more information, see
Declared Element Characteristics.
The following example contains three declarations.
VB
Public Sub applyFormat()
Const limit As Integer = 33
Dim thisWidget As New widget
' Insert code to implement the procedure.
End Sub

The first declaration is the Sub statement. Together with its matching End Sub statement, it declares a procedure named
applyFormat. It also specifies that applyFormat is Public, which means that any code that can refer to it can call it.

The second declaration is the Const statement, which declares the constant limit, specifying the Integer data type and a value
of 33.
The third declaration is the Dim statement, which declares the variable thisWidget. The data type is a specific object, namely
an object created from the Widget class. You can declare a variable to be of any elementary data type or of any object type that
is exposed in the application you are using.
Initial Values
When the code containing a declaration statement runs, Visual Basic reserves the memory required for the declared element. If
the element holds a value, Visual Basic initializes it to the default value for its data type. For more information, see "Behavior" in
Dim Statement (Visual Basic).
You can assign an initial value to a variable as part of its declaration, as the following example illustrates.
VB
Dim m As Integer = 45
' The preceding declaration creates m and assigns the value 45 to it.

If a variable is an object variable, you can explicitly create an instance of its class when you declare it by using the
New (Visual Basic) keyword, as the following example illustrates.
VB
Dim f As New System.Windows.Forms.Form()

Note that the initial value you specify in a declaration statement is not assigned to a variable until execution reaches its
declaration statement. Until that time, the variable contains the default value for its data type.
See Also
Tasks
How to: Declare A Constant
Concepts
Statements Overview
Assignment Statements
Executable Statements
Visual Basic Language Concepts

Executable Statements
An executable statement performs an action. It can call a procedure, branch to another place in the code, loop through several
statements, or evaluate an expression. An assignment statement is a special case of an executable statement.
The following example uses an If...Then...Else control structure to run different blocks of code based on the value of a variable.
Within each block of code, a For...Next loop runs a specified number of times.
VB
Public Sub startWidget(ByVal aWidget As widget, _
ByVal clockwise As Boolean, ByVal revolutions As Integer)
Dim counter As Integer
If clockwise = True Then
For counter = 1 To revolutions
aWidget.spinClockwise()
Next counter
Else
For counter = 1 To revolutions
aWidget.spinCounterClockwise()
Next counter
End If
End Sub

The If statement in the preceding example checks the value of the parameter clockwise. If the value is True, it calls the
spinClockwise method of aWidget. If the value is False, it calls the spinCounterClockwise method of aWidget. The
If...Then...Else control structure ends with End If.
The For...Next loop within each block calls the appropriate method a number of times equal to the value of the revolutions
parameter.
See Also
Concepts
Statements Overview
Assignment Statements
Declaration Statements in Visual Basic
Visual Basic Language Concepts

Procedures in Visual Basic


A procedure is a block of Visual Basic statements enclosed by a declaration statement (Function, Sub, Operator, Get, Set) and
a matching End declaration. All executable statements in Visual Basic must be within some procedure.
Calling a Procedure
You invoke a procedure from some other place in the code. This is known as a procedure call. When the procedure is finished
running, it returns control to the code that invoked it, which is known as the calling code. The calling code is a statement, or an
expression within a statement, that specifies the procedure by name and transfers control to it.
Returning from a Procedure
A procedure returns control to the calling code when it has finished running. To do this, it can use a
Return Statement (Visual Basic), the appropriate Exit Statement (Visual Basic) statement for the procedure, or the procedure's
End (Visual Basic) statement. Control then passes to the calling code following the point of the procedure call.
With a Return statement, control returns immediately to the calling code. Statements following the Return statement do
not run. You can have more than one Return statement in the same procedure.
With an Exit Sub or Exit Function statement, control returns immediately to the calling code. Statements following the
Exit statement do not run. You can have more than one Exit statement in the same procedure, and you can mix Return
and Exit statements in the same procedure.
If a procedure has no Return or Exit statements, it concludes with an End Sub or End Function, End Get, or End Set
statement following the last statement of the procedure body. The End statement returns control immediately to the
calling code. You can have only one End statement in a procedure.
Parameters and Arguments
In most cases, a procedure needs to operate on different data each time you call it. You can pass this information to the
procedure as part of the procedure call. The procedure defines zero or more parameters, each of which represents a value it
expects you to pass to it. Corresponding to each parameter in the procedure definition is an argument in the procedure call. An
argument represents the value you pass to the corresponding parameter in a given procedure call.
Types of Procedures
Visual Basic uses several types of procedures:
Sub Procedures perform actions but do not return a value to the calling code.
Event-handling procedures are Sub procedures that execute in response to an event raised by user action or by an
occurrence in a program.
Function Procedures return a value to the calling code. They can perform other actions before returning.
Property Procedures return and assign values of properties on objects or modules.
Operator Procedures define the behavior of a standard operator when one or both of the operands is a newly-defined
class or structure.
Generic Procedures in Visual Basic define one or more type parameters in addition to their normal parameters, so the
calling code can pass specific data types each time it makes a call.
Procedures and Structured Code
Every line of executable code in your application must be inside some procedure, such as Main, calculate, or Button1_Click. If
you subdivide large procedures into smaller ones, your application is more readable.
Procedures are useful for performing repeated or shared tasks, such as frequently used calculations, text and control
manipulation, and database operations. You can call a procedure from many different places in your code, so you can use
procedures as building blocks for your application.
Structuring your code with procedures gives you the following benefits:
Procedures allow you to break your programs into discrete logical units. You can debug separate units more easily than
you can debug an entire program without procedures.
After you develop procedures for use in one program, you can use them in other programs, often with little or no
modification. This helps you avoid code duplication.
See Also
Tasks
How to: Create a Procedure
Concepts
Sub Procedures
Function Procedures
Property Procedures
Operator Procedures
Procedure Parameters and Arguments
Recursive Procedures
Procedure Overloading
Generic Procedures in Visual Basic
Other Resources
Object-Oriented Programming in Visual Basic
Visual Basic Language Concepts

How to: Break Large Pieces of Code into Smaller Pieces


All executable statements in Visual Basic must be inside some procedure, such as Main, Form1_Load, or calculateTotal. It is
possible to write your entire application as a single large procedure, but if you divide it into smaller ones, your code is more
readable.
Structured programming is an approach that emphasizes program modularity and a hierarchical structure within an
application. In Visual Basic, the most straightforward way to achieve structured programming is through judicious use of
procedures to break your application into discrete logical units. You can debug each individual unit more easily than the entire
program. You can also use a procedure developed for one program in other programs, often with little or no modification.
Breaking Up a Large Procedure
To break a large procedure into self-contained pieces
1. Identify one or more self-contained sections of your code.
2. For each self-contained section, move the source code outside the large procedure and surround it with the Sub and End
Sub statements.
3. At the place in your large procedure from which you removed the code section, add a statement that calls the Sub
procedure.
Returning a Value to the Large Procedure
If it is useful for the new procedure to return a value to the large procedure, you can define a Function procedure.
To break out a section that returns a value
1. Surround the removed source code with Function and End Function statements instead of Sub and End Sub.
2. At the place where the Function procedure has the value ready to return to the calling code, add a Return statement.
3. At the place in your large procedure from which you removed the code section, make sure the calling statement does
something with the returned value. You can store it in a variable or use it in an expression.
See Also
Tasks
How to: Create a Procedure
Concepts
Procedures in Visual Basic
Sub Procedures
Function Procedures
Property Procedures
Operator Procedures
Procedure Parameters and Arguments
Recursive Procedures
Procedure Overloading
Other Resources
Object-Oriented Programming in Visual Basic
Visual Basic Language Concepts

How to: Create a Procedure


You enclose a procedure between a starting declaration statement (Sub or Function) and an ending declaration statement
(End Sub or End Function). All the procedure's code lies between these statements.
A procedure cannot contain another procedure, so its starting and ending statements must be outside any other procedure.
If you have code that performs the same task in different places, you can write the task once as a procedure and then call it
from different places in your code.
To create a procedure that does not return a value
1. Outside any other procedure, use a Sub statement, followed by an End Sub statement.
2. In the Sub statement, follow the Sub keyword with the name of the procedure, then the parameter list in parentheses.
3. Place the procedure's code statements between the Sub and End Sub statements.
To create a procedure that returns a value
1. Outside any other procedure, use a Function statement, followed by an End Function statement.
2. In the Function statement, follow the Function keyword with the name of the procedure, then the parameter list in
parentheses, and then an As clause specifying the data type of the return value.
3. Place the procedure's code statements between the Function and End Function statements.
4. Use a Return statement to return the value to the calling code.
To connect your new procedure with the old, repetitive blocks of code
1. Make sure you define the new procedure in a place where the old code has access to it.
2. In your old, repetitive code block, replace the statements that perform the repetitive task with a single statement that calls
the Sub or Function procedure.
3. If your procedure is a Function that returns a value, ensure that your calling statement performs an action with the
returned value, such as storing it in a variable, or else the value will be lost.
Example
The following Function procedure calculates the longest side, or hypotenuse, of a right triangle, given the values for the other
two sides.
VB
Function hypotenuse(ByVal side1 As Single, ByVal side2 As Single) As Single
Return Math.Sqrt((side1 ^ 2) + (side2 ^ 2))
End Function

See Also
Tasks
How to: Break Large Pieces of Code into Smaller Pieces
Concepts
Procedures in Visual Basic
Sub Procedures
Function Procedures
Property Procedures
Operator Procedures
Procedure Parameters and Arguments
Recursive Procedures
Procedure Overloading
Other Resources
Object-Oriented Programming in Visual Basic
Visual Basic Language Concepts

Sub Procedures
A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End Sub statements. The Sub procedure
performs a task and then returns control to the calling code, but it does not return a value to the calling code.
Each time the procedure is called, its statements are executed, starting with the first executable statement after the Sub
statement and ending with the first End Sub, Exit Sub, or Return statement encountered.
You can define a Sub procedure in modules, classes, and structures. It is Public by default, which means you can call it from
anywhere in your application that has access to the module, class, or structure in which you defined it. The term, method,
describes a Sub or Function procedure that is accessed from outside its defining module, class, or structure. For more
information, see Class Methods.
A Sub procedure can take arguments, such as constants, variables, or expressions, which are passed to it by the calling code.
Declaration Syntax
The syntax for declaring a Sub procedure is as follows:
[ modifiers ] Sub subname [( parameterlist )]
' Statements of the Sub procedure.
End Sub

The modifiers can specify access level and information regarding overloading, overriding, sharing, and shadowing. For more
information, see Sub Statement (Visual Basic).
Parameter Declaration
You declare each procedure parameter similarly to how you declare a variable, specifying the parameter name and data type.
You can also specify the passing mechanism, and whether the parameter is optional or a parameter array.
The syntax for each parameter in the parameter list is as follows:
[Optional] [ByVal | ByRef] [ParamArray] parametername As datatype
If the parameter is optional, you must also supply a default value as part of its declaration. The syntax for specifying a default
value is as follows:
Optional [ByVal | ByRef] parametername As datatype = defaultvalue
Parameters as Local Variables
When control passes to the procedure, each parameter is treated as a local variable. This means that its lifetime is the same as
that of the procedure, and its scope is the entire procedure.
Calling Syntax
You invoke a Sub procedure explicitly with a stand-alone calling statement. You cannot call it by using its name within an
expression. You must provide values for all arguments that are not optional, and you must enclose the argument list in
parentheses. If no arguments are supplied, you can optionally omit the parentheses. The use of the Call keyword is optional
but not recommended.
The syntax for a call to a Sub procedure is as follows:
[Call] subname [( argumentlist )]
You can call a Sub method from outside the class that defines it. First, you need to use the New keyword to create an instance
of the class, or call a method that returns an instance of the class. For more information, see How to: Use the New Keyword.
Then, you can use the following syntax to call the Sub method on the instance object:
Object.methodname[(argumentlist)]
For more information, see How to: Perform Actions with Methods.
Illustration of Declaration and Call
The following Sub procedure tells the computer operator which task the application is about to perform, and also displays a
time stamp. Instead of duplicating this code at the beginning of every task, the application simply calls tellOperator from
various places. Each call passes a string in the task argument that identifies the task being started.
VB
Sub tellOperator(ByVal task As String)
Dim stamp As Date
stamp = TimeOfDay()
MsgBox("Starting " & task & " at " & CStr(stamp))
End Sub

The following example shows a typical call to tellOperator.

VB
Call tellOperator("file update")

See Also
Tasks
How to: Call a Procedure that Does Not Return a Value
How to: Call an Event Handler in Visual Basic
Reference
Sub Statement (Visual Basic)
Concepts
Procedures in Visual Basic
Function Procedures
Property Procedures
Operator Procedures
Procedure Parameters and Arguments
Visual Basic Language Concepts

How to: Call a Procedure that Does Not Return a Value


A Sub procedure does not return a value to the calling code. You call it explicitly with a stand-alone calling statement. You
cannot call it by simply using its name within an expression.
The calling statement can optionally use the Call keyword. This is recommended, because it improves the readability of your
code.
To call a Sub procedure
1. Use a Call statement, following the Call keyword with the name of the Sub procedure.
2. Follow the procedure name with parentheses to enclose the argument list. If there are no arguments, you can optionally
omit the parentheses. However, using the parentheses makes your code easier to read.
3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the
arguments in the same order that the Sub procedure defines the corresponding parameters.
The following example calls the Visual Basic AppActivate function to activate an application window. AppActivate takes
the window title as its sole argument. It does not return a value to the calling code. If a Notepad process is not running,
the example throws an ArgumentException. The Shell procedure assumes the applications are in the paths specified.
VB
Dim notepadID As Integer
' Activate a running Notepad process.
AppActivate("Untitled - Notepad")
' AppActivate can also use the return value of the Shell function.
' Shell runs a new instance of Notepad.
notepadID = Shell("C:\WINNT\NOTEPAD.EXE", AppWinStyle.NormalFocus)
' Activate the new instance of Notepad.
AppActivate(notepadID)

See Also
Tasks
How to: Create a Procedure
How to: Call a Procedure that Returns a Value
How to: Call an Event Handler in Visual Basic
Reference
Sub Statement (Visual Basic)
Shell Function
ArgumentException
Concepts
Procedures in Visual Basic
Sub Procedures
Procedure Parameters and Arguments
Visual Basic Language Concepts

How to: Call an Event Handler in Visual Basic


An event is an action or occurrence — such as a mouse click or a credit limit exceeded — that is recognized by some program
component, and for which you can write code to respond. An event handler is the code you write to respond to an event.
An event handler in Visual Basic is a Sub procedure. However, you do not normally call it the same way as other Sub
procedures. Instead, you identify the procedure as a handler for the event. You can do this either with a Handles clause and a
WithEvents variable, or with an AddHandler Statement. Using a Handles clause is the default way to declare an event handler
in Visual Basic. This is the way the event handlers are written by the designers when you program in the integrated
development environment (IDE). The AddHandler statement is suitable for raising events dynamically at run time.
When the event occurs, Visual Basic automatically calls the event handler procedure. Any code that has access to the event can
cause it to occur by executing a RaiseEvent Statement.
You can associate more than one event handler with the same event. In some cases you can dissociate a handler from an event.
For more information, see Events in Visual Basic.
To call an event handler using Handles and WithEvents
1. Make sure the event is declared with an Event Statement.
2. Declare an object variable at module or class level, using the WithEvents keyword. The As clause for this variable must
specify the class that raises the event.
3. In the declaration of the event-handling Sub procedure, add a Handles clause that specifies the WithEvents variable and
the event name.
4. When the event occurs, Visual Basic automatically calls the Sub procedure. Your code can use a RaiseEvent statement to
make the event occur.
The following example defines an event and a WithEvents variable that refers to the class that raises the event. The
event-handling Sub procedure uses a Handles clause to specify the class and event it handles.
VB
Public Class raisesEvent
Public Event somethingHappened()
Dim WithEvents happenObj As New raisesEvent
Public Sub processHappen() Handles happenObj.somethingHappened
' Insert code to handle somethingHappened event.
End Sub
End Class

To call an event handler using AddHandler


1. Make sure the event is declared with an Event statement.
2. Execute an AddHandler Statement to dynamically connect the event-handling Sub procedure with the event.
3. When the event occurs, Visual Basic automatically calls the Sub procedure. Your code can use a RaiseEvent statement to
make the event occur.
The following example defines a Sub procedure to handle the Closing event of a form. It then uses the
AddHandler Statement to associate the catchClose procedure as an event handler for Closing.
VB
' Place these procedures inside a Form class definition.
Private Sub catchClose(ByVal sender As Object, ByVal e As System.ComponentModel.Cancel
EventArgs)
' Insert code to deal with impending closure of this form.
End Sub
Public Sub formOpened()
AddHandler Me.Closing, AddressOf catchClose
End Sub

You can dissociate an event handler from an event by executing the RemoveHandler Statement.
See Also
Tasks
How to: Create a Procedure
How to: Call a Procedure that Does Not Return a Value
Reference
Sub Statement (Visual Basic)
AddressOf Operator
Concepts
Procedures in Visual Basic
Sub Procedures
Visual Basic Language Concepts

Function Procedures
A Function procedure is a series of Visual Basic statements enclosed by the Function and End Function statements. The
Function procedure performs a task and then returns control to the calling code. When it returns control, it also returns a
value to the calling code.
Each time the procedure is called, its statements run, starting with the first executable statement after the Function statement
and ending with the first End Function, Exit Function, or Return statement encountered.
You can define a Function procedure in a module, class, or structure. It is Public by default, which means you can call it from
anywhere in your application that has access to the module, class, or structure in which you defined it.
A Function procedure can take arguments, such as constants, variables, or expressions, which are passed to it by the calling
code.
Declaration Syntax
The syntax for declaring a Function procedure is as follows:
[ modifiers ] Function functionname [( parameterlist )] As returntype
' Statements of the Function procedure.
End Function

The modifiers can specify access level and information regarding overloading, overriding, sharing, and shadowing. For more
information, see Function Statement (Visual Basic).
You declare each parameter the same way you do for Sub Procedures.
Data Type
Every Function procedure has a data type, just as every variable does. This data type is specified by the As clause in the
Function statement, and it determines the data type of the value the function returns to the calling code. The following sample
declarations illustrate this.

Function yesterday() As Date


End Function
Function findSqrt(ByVal radicand As Single) As Single
End Function

For more information, see "Parts" in Function Statement (Visual Basic).


Returning Values
The value a Function procedure sends back to the calling code is called its return value. The procedure returns this value in
one of two ways:
It assigns a value to its own function name in one or more statements of the procedure. Control does not return to the
calling program until an Exit Function or End Function statement is executed. The following example illustrates this.
Function functionname [( parameterlist )] As returntype
' The following statement does not transfer control back to the calling code.

functionname = expression
' When control returns to the calling code, expression is the return value.

End Function

It uses the Return statement to specify the return value, and returns control immediately to the calling program. The
following example illustrates this.
Function functionname [( parameterlist )] As returntype
' The following statement immediately transfers control back to the calling code and returns the value
of expression .
Return expression

End Function

The advantage of assigning the return value to the function name is that control does not return from the procedure until it
encounters an Exit Function or End Function statement. This allows you to assign a preliminary value and adjust it later if
necessary.
For more information, see "Return Value" in Function Statement (Visual Basic).
Returning Arrays
If the Function procedure returns an array data type, you cannot access the individual elements of the array within the
function. If you attempt to do this, the compiler interprets it as a recursive call to the procedure. The following example
illustrates this.
Function allOnes(ByVal n As Integer) As Integer()
For i As Integer = 1 To n - 1
' The following statement generates a COMPILER ERROR .
allOnes(i) = 1
Next i
' The following statement generates a COMPILER ERROR .
Return allOnes()
End Function

In the preceding example, the compiler interprets the attempted assignment allOnes(i) = 1 as a call to allOnes on the left
side of an assignment statement. It interprets the attempted Return allOnes() as a call with no argument. Both statements
generate compiler errors.
Calling Syntax
You invoke a Function procedure by including its name and arguments either on the right side of an assignment statement or
in an expression. You must provide values for all arguments that are not optional, and you must enclose the argument list in
parentheses. If no arguments are supplied, you can optionally omit the parentheses.
The syntax for a call to a Function procedure is as follows:
lvalue = functionname [( argumentlist )]
If (( functionname [( argumentlist )] / 3) <= expression ) Then

When you call a Function procedure, you do not have to use its return value. If you do not, all the actions of the function are
performed, but the return value is ignored. MsgBox is often called in this manner.
Illustration of Declaration and Call
The following Function procedure calculates the longest side, or hypotenuse, of a right triangle, given the values for the other
two sides.
VB
Function hypotenuse(ByVal side1 As Single, ByVal side2 As Single) As Single
Return Math.Sqrt((side1 ^ 2) + (side2 ^ 2))
End Function

The following example shows a typical call to hypotenuse.


VB
Dim testLength, testHypotenuse As Single
testHypotenuse = hypotenuse(testLength, 10.7)

Visual Basic Runtime Functions


The Visual Basic runtime provides many functions, located in the Microsoft.VisualBasic namespace. These include such
common functions as the Beep Function, MsgBox Function (Visual Basic), and StrComp Function (Visual Basic). You call these
functions the same way you call your own Function procedures.
See Also
Tasks
How to: Create a Procedure that Returns a Value
How to: Return a Value from a Procedure
How to: Call a Procedure that Returns a Value
Reference
Function Statement (Visual Basic)
Concepts
Procedures in Visual Basic
Sub Procedures
Property Procedures
Operator Procedures
Procedure Parameters and Arguments
Visual Basic Language Concepts

How to: Create a Procedure that Returns a Value


You use a Function procedure to return a value to the calling code.
To create a procedure that returns a value
1. Outside any other procedure, use a Function statement, followed by an End Function statement.
2. In the Function statement, follow the Function keyword with the name of the procedure, and then the parameter list in
parentheses.
3. Follow the parentheses with an As clause to specify the data type of the returned value.
4. Place the procedure's code statements between the Function and End Function statements.
5. Use a Return statement to return the value to the calling code.
The following Function procedure calculates the longest side, or hypotenuse, of a right triangle, given the values for the
other two sides.
VB
Function hypotenuse(ByVal side1 As Single, ByVal side2 As Single) As Single
Return Math.Sqrt((side1 ^ 2) + (side2 ^ 2))
End Function

The following example shows a typical call to hypotenuse.

VB
Dim testLength, testHypotenuse As Single
testHypotenuse = hypotenuse(testLength, 10.7)

See Also
Tasks
How to: Return a Value from a Procedure
How to: Call a Procedure that Returns a Value
Reference
Function Statement (Visual Basic)
Concepts
Procedures in Visual Basic
Sub Procedures
Property Procedures
Operator Procedures
Procedure Parameters and Arguments
Visual Basic Language Concepts

How to: Return a Value from a Procedure


A Function procedure returns a value to the calling code either by executing a Return statement or by encountering an Exit
Function or End Function statement.
To return a value using the Return statement
1. Put a Return statement at the point where the procedure's task is completed.
2. Follow the Return keyword with an expression that yields the value you want to return to the calling code.
3. You can have more than one Return statement in the same procedure.
The following Function procedure calculates the longest side, or hypotenuse, of a right triangle, and returns it to the
calling code.
VB
Function hypotenuse(ByVal side1 As Single, ByVal side2 As Single) As Single
Return Math.Sqrt((side1 ^ 2) + (side2 ^ 2))
End Function

The following example shows a typical call to hypotenuse, which stores the returned value.
VB
Dim testLength, testHypotenuse As Single
testHypotenuse = hypotenuse(testLength, 10.7)

To return a value using Exit Function or End Function


1. In at least one place in the Function procedure, assign a value to the procedure's name.
2. When you execute an Exit Function or End Function statement, Visual Basic returns the value most recently assigned
to the procedure's name.
3. You can have more than one Exit Function statement in the same procedure, and you can mix Return and Exit
Function statements in the same procedure.
4. You can have only one End Function statement in a Function procedure.
For more information and an example, see "Return Value" in Function Statement (Visual Basic).
See Also
Tasks
How to: Create a Procedure that Returns a Value
How to: Call a Procedure that Returns a Value
Reference
Function Statement (Visual Basic)
Return Statement (Visual Basic)
Concepts
Procedures in Visual Basic
Sub Procedures
Property Procedures
Operator Procedures
Procedure Parameters and Arguments
Visual Basic Language Concepts

How to: Call a Procedure that Returns a Value


A Function procedure returns a value to the calling code. You call it by including its name and arguments either on the right
side of an assignment statement or in an expression.
You can use the Call keyword to call a Function procedure. However, this technique ignores the value returned by the
procedure.
To call a Function procedure within an expression
1. Use the Function procedure name the same way you would use a variable. You can use a Function procedure call
anywhere you can use a variable or constant in an expression.
2. Follow the procedure name with parentheses to enclose the argument list. If there are no arguments, you can optionally
omit the parentheses. However, using the parentheses makes your code easier to read.
3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the
arguments in the same order that the Function procedure defines the corresponding parameters.
Alternatively, you can pass one or more arguments by name. For more information, see
Argument Passing by Position and by Name.
4. The value returned from the procedure participates in the expression just as the value of a variable or constant would.
To call a Function procedure in an assignment statement
1. Use the Function procedure name following the equal (=) sign in the assignment statement.
2. Follow the procedure name with parentheses to enclose the argument list. If there are no arguments, you can optionally
omit the parentheses. However, using the parentheses makes your code easier to read.
3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the
arguments in the same order that the Function procedure defines the corresponding parameters, unless you are passing
them by name.
4. The value returned from the procedure is stored in the variable or property on the left side of the assignment statement.
Example
The following example calls the Visual Basic Environ Function to retrieve the value of an operating system environment
variable. The first line calls Environ within an expression, and the second line calls it in an assignment statement. Environ
takes the variable name as its sole argument. It returns the variable's value to the calling code.
VB
MsgBox("Value of PATH is " & Environ("PATH"))
Dim currentPath As String = Environ("PATH")

See Also
Tasks
How to: Create a Procedure that Returns a Value
How to: Return a Value from a Procedure
How to: Call a Procedure that Does Not Return a Value
Reference
Function Statement (Visual Basic)
Concepts
Function Procedures
Procedure Parameters and Arguments
Visual Basic Language Concepts

Property Procedures
A property procedure is a series of Visual Basic statements that manipulate a custom property on a module, class, or structure.
Property procedures are also known as property accessors.
Visual Basic provides for the following property procedures:
A Get procedure returns the value of a property. It is called when you access the property in an expression.
A Set procedure sets a property to a value, including an object reference. It is called when you assign a value to the
property.
You usually define property procedures in pairs, using the Get and Set statements, but you can define either procedure alone if
the property is read-only (Get Statement) or write-only (Set Statement (Visual Basic)).
You can define properties in classes, structures, and modules. Properties are Public by default, which means you can call them
from anywhere in your application that can access the property's container.
For a comparison of properties and variables, see Differences Between Properties and Variables in Visual Basic.
Declaration Syntax
A property itself is defined by a block of code enclosed within the Property Statement and the End Property statement. Inside
this block, each property procedure appears as an internal block enclosed within a declaration statement (Get or Set) and the
matching End declaration.
The syntax for declaring a property and its procedures is as follows:
[Default] [modifiers] Property propertyname[(parameterlist)] As datatype
[accesslevel] Get
' Statements of the Get procedure.
' The following statement returns expression as the property's value.
Return expression
End Get
[accesslevel] Set[(ByVal newvalue As datatype)]
' Statements of the Set procedure.
' The following statement assigns newvalue as the property's value.
lvalue = newvalue
End Set
End Property

The modifiers can specify access level and information regarding overloading, overriding, sharing, and shadowing, as well as
whether the property is read-only or write-only. The access level on the Get or Set procedure can be any level that is more
restrictive than the access level specified for the property itself. For more information, see Property Statement.
Data Type
A property's data type and principal access level are defined in the Property statement, not in the property procedures. A
property can have only one data type. For example, you cannot define a property to store a Decimal value but retrieve a
Double value.
Access Level
However, you can define a principal access level for a property and further restrict the access level in one of its property
procedures. For example, you can define a Public property and then define a Private Set procedure. The Get procedure
remains Public. You can change the access level in only one of a property's procedures, and you can only make it more
restrictive than the principal access level. For more information, see How to: Declare a Property with Mixed Access Levels.
Parameter Declaration
You declare each parameter the same way you do for Sub Procedures, except that the passing mechanism must be ByVal.
The syntax for each parameter in the parameter list is as follows:
[Optional] ByVal [ParamArray] parametername As datatype

If the parameter is optional, you must also supply a default value as part of its declaration. The syntax for specifying a default
value is as follows:
Optional ByVal parametername As datatype = defaultvalue

Property Value
In a Get procedure, the return value is supplied to the calling expression as the value of the property.
In a Set procedure, the new property value is passed to the parameter of the Set statement. If you explicitly declare a
parameter, you must declare it with the same data type as the property. If you do not declare a parameter, the compiler uses
the implicit parameter Value to represent the new value to be assigned to the property.
Calling Syntax
You invoke a property procedure implicitly by making reference to the property. You use the name of the property the same
way you would use the name of a variable, except that you must provide values for all arguments that are not optional, and
you must enclose the argument list in parentheses. If no arguments are supplied, you can optionally omit the parentheses.
The syntax for an implicit call to a Set procedure is as follows:
propertyname[(argumentlist)] = expression

The syntax for an implicit call to a Get procedure is as follows:


lvalue = propertyname[(argumentlist)]
Do While (propertyname[(argumentlist)] > expression)
Illustration of Declaration and Call
The following property stores a full name as two constituent names, the first name and the last name. When the calling code
reads fullName, the Get procedure combines the two constituent names and returns the full name. When the calling code
assigns a new full name, the Set procedure attempts to break it into two constituent names. If it does not find a space, it stores
it all as the first name.
VB
Dim firstName, lastName As String
Property fullName() As String
Get
If lastName = "" Then
Return firstName
Else
Return firstName & " " & lastName
End If

End Get
Set(ByVal Value As String)
Dim space As Integer = Value.IndexOf(" ")
If space < 0 Then
firstName = Value
lastName = ""
Else
firstName = Value.Substring(0, space)
lastName = Value.Substring(space + 1)
End If
End Set
End Property

The following example shows typical calls to the property procedures of fullName.
VB
fullName = "MyFirstName MyLastName"
MsgBox(fullName)
See Also
Tasks
How to: Create a Property
How to: Call a Property Procedure
How to: Declare and Call a Default Property in Visual Basic
How to: Put a Value in a Property
How to: Get a Value from a Property
Concepts
Procedures in Visual Basic
Function Procedures
Operator Procedures
Procedure Parameters and Arguments
Differences Between Properties and Variables in Visual Basic
Visual Basic Language Concepts

Differences Between Properties and Variables in Visual Basic


Variables and properties both represent values that you can access. However, there are differences in storage and
implementation.
Variables
A variable corresponds directly to a memory location. You define a variable with a single declaration statement. A variable can
be a local variable, defined inside a procedure and available only within that procedure, or it can be a member variable,
defined in a module, class, or structure but not inside any procedure. A member variable is also called a field.
Properties
A property is a data element defined on a module, class, or structure. You define a property with a code block between the
Property and End Property statements. The code block contains a Get procedure, a Set procedure, or both. These procedures
are called property procedures or property accessors. In addition to retrieving or storing the property's value, they can also
perform custom actions, such as updating an access counter.
Differences
The following table shows some important differences between variables and properties.
Point of difference Variable Property
Declaration Single declaration statem Series of statements in a code block
ent

Implementation Single storage location Executable code (property procedures)

Storage Directly associated with v Typically has internal storage not available outside the prope
ariable's value rty's containing class or module
Property's value might or might not exist as a stored elemen
t1

Executable code None Must have at least one procedure

Read and write access Read/write or read-only Read/write, read-only, or write-only

Custom actions (in addition to acceptin Not possible Can be performed as part of setting or retrieving property v
g or returning value) alue

1 Unlike a variable, the value of a property might not correspond directly to a single item of storage. The storage might be split
into pieces for convenience or security, or the value might be stored in an encrypted form. In these cases the Get procedure
would assemble the pieces or decrypt the stored value, and the Set procedure would encrypt the new value or split it into the
constituent storage. A property value might be ephemeral, like time of day, in which case the Get procedure would calculate it
on the fly each time you access the property.
See Also
Tasks
How to: Create a Property
How to: Declare a Property with Mixed Access Levels
How to: Call a Property Procedure
How to: Declare and Call a Default Property in Visual Basic
How to: Put a Value in a Property
How to: Get a Value from a Property
Reference
Property Statement
Dim Statement (Visual Basic)
Concepts
Property Procedures
Procedure Parameters and Arguments
Visual Basic Language Concepts

How to: Create a Property


You enclose a property definition between a Property statement and an End Property statement. Within this definition you
define a Get procedure, a Set procedure, or both. All the property's code lies within these procedures.
The Get procedure retrieves the property's value, and the Set procedure stores a value. If you want the property to have
read/write access, you must define both procedures. For a read-only property, you define only Get, and for a write-only
property, you define only Set.
To create a property
1. Outside any property or procedure, use a Property Statement, followed by an End Property statement.
2. If the property takes parameters, follow the Property keyword with the name of the procedure, then the parameter list in
parentheses.
3. Follow the parentheses with an As clause to specify the data type of the property's value. You must specify the data type
even for a write-only property.
4. Add Get and Set procedures, as appropriate. See the following directions.
To create a Get procedure that retrieves a property value
1. Between the Property and End Property statements, write a Get Statement, followed by an End Get statement. You do
not need to define any parameters for the Get procedure.
2. Place the code statements to retrieve the property's value between the Get and End Get statements. This code can
include other calculations and data manipulations in addition to generating and returning the property's value.
3. Use a Return statement to return the property's value to the calling code.
You must write a Get procedure for a read-write property and for a read-only property. You must not define a Get procedure
for a write-only property.
To create a Set procedure that writes a property's value
1. Between the Property and End Property statements, write a Set Statement (Visual Basic), followed by an End Set
statement.
2. In the Set statement, follow the Set keyword with a parameter list in parentheses. This parameter list must include at
least a value parameter for the value passed by the calling code. The default name for this value parameter is Value, but
you can use a different name if appropriate. The value parameter must have the same data type as the property itself.
3. Place the code statements to store a value in the property between the Set and End Set statements. This code can
include other calculations and data manipulations in addition to validating and storing the property's value.
4. Use the value parameter to accept the value supplied by the calling code. You can either store this value directly in an
assignment statement, or use it in an expression to calculate the internal value to be stored.
You must write a Set procedure for a read-write property and for a write-only property. You must not define a Set procedure
for a read-only property.
Example
The following example creates a read/write property that stores a full name as two constituent names, the first name and the
last name. When the calling code reads fullName, the Get procedure combines the two constituent names and returns the full
name. When the calling code assigns a new full name, the Set procedure attempts to break it into two constituent names. If it
does not find a space, it stores it all as the first name.
VB
Dim firstName, lastName As String
Property fullName() As String
Get
If lastName = "" Then
Return firstName
Else
Return firstName & " " & lastName
End If

End Get
Set(ByVal Value As String)
Dim space As Integer = Value.IndexOf(" ")
If space < 0 Then
firstName = Value
lastName = ""
Else
firstName = Value.Substring(0, space)
lastName = Value.Substring(space + 1)
End If
End Set
End Property

The following example shows typical calls to the property procedures of fullName. The first call sets the property value and the
second call retrieves it.
VB
fullName = "MyFirstName MyLastName"
MsgBox(fullName)

See Also
Tasks
How to: Declare a Property with Mixed Access Levels
How to: Call a Property Procedure
How to: Declare and Call a Default Property in Visual Basic
How to: Put a Value in a Property
How to: Get a Value from a Property
Concepts
Procedures in Visual Basic
Property Procedures
Procedure Parameters and Arguments
Differences Between Properties and Variables in Visual Basic
Visual Basic Language Concepts

How to: Declare a Property with Mixed Access Levels


If you want the Get and Set procedures on a property to have different access levels, you can use the more permissive level in
the Property statement and the more restrictive level in either the Get or Set statement. You use mixed access levels on a
property when you want certain parts of the code to be able to get the property's value, and certain other parts of the code to
be able to change the value.
For more information on access levels, see Access Levels in Visual Basic.
To declare a property with mixed access levels
1. Declare the property in the normal way, and specify the less restrictive access level (such as Public) in the Property
statement.
2. Declare either the Get or the Set procedure specifying the more restrictive access level (such as Friend).
3. Do not specify an access level on the other property procedure. It assumes the access level declared in the Property
statement. You can restrict access on only one of the property procedures.
VB
Public Class employee
Private salaryValue As Double
Protected Property salary() As Double
Get
Return salaryValue
End Get
Private Set(ByVal value As Double)
salaryValue = value
End Set
End Property
End Class

In the preceding example, the Get procedure has the same Protected access as the property itself, while the Set
procedure has Private access. A class derived from employee can read the salary value, but only the employee class can
set it.
See Also
Tasks
How to: Create a Property
How to: Call a Property Procedure
How to: Declare and Call a Default Property in Visual Basic
How to: Put a Value in a Property
How to: Get a Value from a Property
Reference
Property Statement
Concepts
Procedures in Visual Basic
Property Procedures
Procedure Parameters and Arguments
Differences Between Properties and Variables in Visual Basic
Visual Basic Language Concepts

How to: Call a Property Procedure


You call a property procedure by storing a value in the property or retrieving its value. You access a property the same way
you access a variable.
The property's Set procedure stores a value, and its Get procedure retrieves the value. However, you do not explicitly call these
procedures by name. You use the property in an assignment statement or an expression, just as you would store or retrieve the
value of a variable. Visual Basic makes the calls to the property's procedures.
To call a property's Get procedure
1. Use the property name in an expression the same way you would use a variable name. You can use a property anywhere
you can use a variable or a constant.
-or-
Use the property name following the equal (=) sign in an assignment statement.
The following example reads the value of the Now Property, implicitly calling its Get procedure.
VB
Dim ThisMoment As Date
' The following statement calls the Get procedure of the Visual Basic Now property.
ThisMoment = Now

2. If the property takes arguments, follow the property name with parentheses to enclose the argument list. If there are no
arguments, you can optionally omit the parentheses.
3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the
arguments in the same order that the property defines the corresponding parameters.
The value of the property participates in the expression just as a variable or constant would, or it is stored in the variable or
property on the left side of the assignment statement.
To call a property's Set procedure
1. Use the property name on the left side of an assignment statement.
The following example sets the value of the TimeOfDay Property, implicitly calling the Set procedure.
VB
' The following statement calls the Set procedure of the Visual Basic TimeOfDay proper
ty.
TimeOfDay = #12:00:00 PM#

2. If the property takes arguments, follow the property name with parentheses to enclose the argument list. If there are no
arguments, you can optionally omit the parentheses.
3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the
arguments in the same order that the property defines the corresponding parameters.
The value generated on the right side of the assignment statement is stored in the property.
See Also
Tasks
How to: Create a Property
How to: Declare a Property with Mixed Access Levels
How to: Declare and Call a Default Property in Visual Basic
How to: Put a Value in a Property
How to: Get a Value from a Property
Reference
Property Statement
Get Statement
Set Statement (Visual Basic)
Concepts
Property Procedures
Procedure Parameters and Arguments
Differences Between Properties and Variables in Visual Basic
Visual Basic Language Concepts

How to: Declare and Call a Default Property in Visual Basic


A default property is a class or structure property that your code can access without specifying it. When calling code names a
class or structure but not a property, and the context allows access to a property, Visual Basic resolves the access to that class
or structure's default property if one exists.
A class or structure can have at most one default property. However, you can overload a default property and have more than
one version of it.
For more information, see Default Properties.
To declare a default property
1. Declare the property in the normal way. Do not specify the Shared or Private keyword.
2. Include the Default keyword in the property declaration.
3. Specify at least one parameter for the property. You cannot define a default property that does not take at least one
argument.
VB
Default Property myProperty(ByVal index As Integer) As String

To call a default property


1. Declare a variable of the containing class or structure type.
VB
Dim x As New class1(3)

2. Use the variable name alone in an expression where you would normally include the property name.
VB
MsgBox(x)

3. Follow the variable name with an argument list in parentheses. A default property must take at least one argument.
VB
MsgBox(x(1))

4. To retrieve the default property value, use the variable name, with an argument list, in an expression or following the
equal (=) sign in an assignment statement.
VB
MsgBox(x(1) & x(2) & x(3))

5. To set the default property value, use the variable name, with an argument list, on the left side of an assignment
statement.
VB
x(1) = "Hello"
x(2) = " "
x(3) = "World"

6. You can always specify the default property name together with the variable name, just as you would do to access any
other property.
VB
x.myProperty(1) = "Hello"
x.myProperty(2) = " "
x.myProperty(3) = "World"

Example
The following example declares a default property on a class.
VB
Public Class class1
Private myStrings() As String
Sub New(ByVal size As Integer)
ReDim myStrings(size)
End Sub
Default Property myProperty(ByVal index As Integer) As String
Get
' The Get property procedure is called when the value
' of the property is retrieved.
Return myStrings(index)
End Get
Set(ByVal Value As String)
' The Set property procedure is called when the value
' of the property is modified.
' The value to be assigned is passed in the argument
' to Set.
myStrings(index) = Value
End Set
End Property
End Class

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
The following example demonstrates how to call the default property myProperty on class class1. The three assignment
statements store values in myProperty, and the MsgBox call reads the values.
VB
Sub Test()
Dim x As New class1(3)
x(1) = "Hello"
x(2) = " "
x(3) = "World"
MsgBox(x(1) & x(2) & x(3))
End Sub

The most common use of a default property is the Item Property (Collection Object) on various collection classes.
Robust Programming
Default properties can result in a small reduction in source code-characters, but they can make your code more difficult to
read. If the calling code is not familiar with your class or structure, when it makes a reference to the class or structure name it
cannot be certain whether that reference accesses the class or structure itself, or a default property. This can lead to compiler
errors or subtle run-time logic errors.
You can somewhat reduce the chance of default property errors by always using the Option Strict Statement to set compiler
type checking to On.
If you are planning to use a predefined class or structure in your code, you must determine whether it has a default property,
and if so, what its name is.
Because of these disadvantages, you should consider not defining default properties. For code readability, you should also
consider always referring to all properties explicitly, even default properties.
See Also
Tasks
How to: Create a Property
How to: Declare a Property with Mixed Access Levels
How to: Call a Property Procedure
How to: Put a Value in a Property
How to: Get a Value from a Property
Reference
Property Statement
Default (Visual Basic)
Concepts
Property Procedures
Procedure Parameters and Arguments
Default Property Changes for Visual Basic 6.0 Users
Differences Between Properties and Variables in Visual Basic
Visual Basic Language Concepts

How to: Put a Value in a Property


You store a value in a property by putting the property name on the left side of an assignment statement.
The property's Set procedure stores a value, but you do not explicitly call it by name. You use the property just as you would
use a variable. Visual Basic makes the calls to the property's procedures.
To store a value in a property
1. Use the property name on the left side of an assignment statement.
The following example sets the value of the Visual Basic TimeOfDay property to noon, implicitly calling its Set
procedure.
VB
' The following statement calls the Set procedure of the Visual Basic TimeOfDay proper
ty.
TimeOfDay = #12:00:00 PM#

2. If the property takes arguments, follow the property name with parentheses to enclose the argument list. If there are no
arguments, you can optionally omit the parentheses.
3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the
arguments in the same order that the property defines the corresponding parameters.
4. The value generated on the right side of the assignment statement is stored in the property.
See Also
Tasks
How to: Create a Property
How to: Declare a Property with Mixed Access Levels
How to: Call a Property Procedure
How to: Declare and Call a Default Property in Visual Basic
How to: Get a Value from a Property
Reference
Property Statement
TimeOfDay Property
Concepts
Property Procedures
Procedure Parameters and Arguments
Differences Between Properties and Variables in Visual Basic
Visual Basic Language Concepts

How to: Get a Value from a Property


You retrieve a property's value by including the property name in an expression.
The property's Get procedure retrieves the value, but you do not explicitly call it by name. You use the property just as you
would use a variable. Visual Basic makes the calls to the property's procedures.
To retrieve a value from a property
1. Use the property name in an expression the same way you would use a variable name. You can use a property anywhere
you can use a variable or a constant.
-or-
Use the property name following the equal (=) sign in an assignment statement.
The following example reads the value of the Visual Basic Now property, implicitly calling its Get procedure.
VB
Dim ThisMoment As Date
' The following statement calls the Get procedure of the Visual Basic Now property.
ThisMoment = Now

2. If the property takes arguments, follow the property name with parentheses to enclose the argument list. If there are no
arguments, you can optionally omit the parentheses.
3. Place the arguments in the argument list within the parentheses, separated by commas. Be sure you supply the
arguments in the same order that the property defines the corresponding parameters.
The value of the property participates in the expression just as a variable or constant would, or it is stored in the variable or
property on the left side of the assignment statement.
See Also
Tasks
How to: Create a Property
How to: Declare a Property with Mixed Access Levels
How to: Call a Property Procedure
How to: Declare and Call a Default Property in Visual Basic
How to: Put a Value in a Property
Reference
Property Statement
Concepts
Procedures in Visual Basic
Property Procedures
Procedure Parameters and Arguments
Differences Between Properties and Variables in Visual Basic
Visual Basic Language Concepts

Operator Procedures
An operator procedure is a series of Visual Basic statements that define the behavior of a standard operator (such as *, <>, or
And) on a class or structure you have defined. This is also called operator overloading.
When to Define Operator Procedures
When you have defined a class or structure, you can declare variables to be of the type of that class or structure. Sometimes
such a variable needs to participate in an operation as part of an expression. To do this, it must be an operand of an operator.
Visual Basic defines operators only on its fundamental data types. You can define the behavior of an operator when one or
both of the operands are of the type of your class or structure.
For more information, see Operator Statement.
Types of Operator Procedure
An operator procedure can be one of the following types:
A definition of a unary operator where the argument is of the type of your class or structure.
A definition of a binary operator where at least one of the arguments is of the type of your class or structure.
A definition of a conversion operator where the argument is of the type of your class or structure.
A definition of a conversion operator that returns the type of your class or structure.
Conversion operators are always unary, and you always use CType as the operator you are defining.
Declaration Syntax
The syntax for declaring an operator procedure is as follows:
Public Shared [Widening | Narrowing] Operator operatorsymbol ( operand1 [, operand2 ]) As datatype
' Statements of the operator procedure.
End Operator

You use the Widening or Narrowing keyword only on a type conversion operator. The operator symbol is always
CType Function for a type conversion operator.
You declare two operands to define a binary operator, and you declare one operand to define a unary operator, including a
type conversion operator. All operands must be declared ByVal.
You declare each operand the same way you declare parameters for Sub Procedures.
Data Type
Because you are defining an operator on a class or structure you have defined, at least one of the operands must be of the data
type of that class or structure. For a type conversion operator, either the operand or the return type must be of the data type of
the class or structure.
For more details, see Operator Statement.
Calling Syntax
You invoke an operator procedure implicitly by using the operator symbol in an expression. You supply the operands the same
way you do for predefined operators.
The syntax for an implicit call to an operator procedure is as follows:
Dim testStruct As structurename
Dim testNewStruct As structurename = testStruct operatorsymbol 10
Illustration of Declaration and Call
The following structure stores a signed 128-bit integer value as the constituent high-order and low-order parts. It defines the +
operator to add two veryLong values and generate a resulting veryLong value.
VB
Public Structure veryLong
Dim highOrder As Long
Dim lowOrder As Long
Public Shared Operator +(ByVal v As veryLong, _
ByVal w As veryLong) As veryLong
Dim sum As New veryLong
sum = v
Try
sum.lowOrder += w.lowOrder
Catch ex As System.OverflowException
sum.lowOrder -= (Long.MaxValue - w.lowOrder + 1)
sum.highOrder += 1
End Try
sum.highOrder += w.highOrder
Return sum
End Operator
End Structure

The following example shows a typical call to the + operator defined on veryLong.

VB
Dim v1, v2, v3 As veryLong
v1.highOrder = 1
v1.lowOrder = Long.MaxValue
v2.highOrder = 0
v2.lowOrder = 4
v3 = v1 + v2

See Also
Tasks
How to: Define an Operator
How to: Define a Conversion Operator
How to: Call an Operator Procedure
How to: Use a Class that Defines Operators
Reference
Operator Statement
Concepts
Procedures in Visual Basic
Sub Procedures
Function Procedures
Property Procedures
Procedure Parameters and Arguments
Visual Basic Language Concepts

How to: Define an Operator


If you have defined a class or structure, you can define the behavior of a standard operator (such as *, <>, or And) when one
or both of the operands is of the type of your class or structure.
Define the standard operator as an operator procedure within the class or structure. All operator procedures must be Public
Shared.
Defining an operator on a class or structure is also called overloading the operator.
Example
The following example defines the + operator for a structure called height. The structure uses heights measured in feet and
inches. One inch is 2.54 centimeters, and one foot is 12 inches. To ensure normalized values (inches < 12.0), the constructor
performs modulo 12 arithmetic. The + operator uses the constructor to generate normalized values.
VB
Public Shadows Structure height
' Need Shadows because System.Windows.Forms.Form also defines property Height.
Private feet As Integer
Private inches As Double
Public Sub New(ByVal f As Integer, ByVal i As Double)
Me.feet = f + (CInt(i) \ 12)
Me.inches = i Mod 12.0
End Sub
Public Overloads Function ToString() As String
Return Me.feet & "' " & Me.inches & """"
End Function
Public Shared Operator +(ByVal h1 As height, ByVal h2 As height) _
As height
Return New height(h1.feet + h2.feet, h1.inches + h2.inches)
End Operator
End Structure

You can test the structure height with the following code.
VB
Public Sub consumeHeight()
Dim p1 As New height(3, 10)
Dim p2 As New height(4, 8)
Dim p3 As height = p1 + p2
Dim s As String = p1.ToString() & " + " & p2.ToString() _
& " = " & p3.ToString() & " (= 8' 6"" ?)"
Dim p4 As New height(2, 14)
s &= vbCrLf & "2' 14"" = " & p4.ToString() & " (= 3' 2"" ?)"
Dim p5 As New height(4, 24)
s &= vbCrLf & "4' 24"" = " & p5.ToString() & " (= 6' 0"" ?)"
MsgBox(s)
End Sub

See Also
Tasks
How to: Define a Conversion Operator
How to: Call an Operator Procedure
How to: Use a Class that Defines Operators
How to: Declare a Structure
Reference
Operator Statement
Structure Statement
Concepts
Operator Procedures
Visual Basic Language Concepts

How to: Define a Conversion Operator


If you have defined a class or structure, you can define a type conversion operator between the type of your class or structure
and another data type (such as Integer, Double, or String).
Define the type conversion as a CType Function procedure within the class or structure. All conversion procedures must be
Public Shared, and each one must specify either Widening or Narrowing.
Defining an operator on a class or structure is also called overloading the operator.
Example
The following example defines conversion operators between a structure called digit and a Byte.
VB
Public Structure digit
Private dig As Byte
Public Sub New(ByVal b As Byte)
If (b < 0 OrElse b > 9) Then Throw New _
System.ArgumentException("Argument outside range for Byte")
Me.dig = b
End Sub
Public Shared Widening Operator CType(ByVal d As digit) As Byte
Return d.dig
End Operator
Public Shared Narrowing Operator CType(ByVal b As Byte) As digit
Return New digit(b)
End Operator
End Structure

You can test the structure digit with the following code.
VB
Public Sub consumeDigit()
Dim d1 As New digit(4)
Dim d2 As New digit(7)
Dim d3 As digit = CType(CByte(3), digit)
Dim s As String = "Initial 4 generates " & CStr(CType(d1, Byte)) _
& vbCrLf & "Initial 7 generates " & CStr(CType(d2, Byte)) _
& vbCrLf & "Converted 3 generates " & CStr(CType(d3, Byte))
Try
Dim d4 As digit
d4 = CType(CType(d1, Byte) + CType(d2, Byte), digit)
Catch e4 As System.Exception
s &= vbCrLf & "4 + 7 generates " & """" & e4.Message & """"
End Try
Try
Dim d5 As digit = CType(CByte(10), digit)
Catch e5 As System.Exception
s &= vbCrLf & "Initial 10 generates " & """" & e5.Message & """"
End Try
MsgBox(s)
End Sub

See Also
Tasks
How to: Define an Operator
How to: Call an Operator Procedure
How to: Use a Class that Defines Operators
How to: Declare a Structure
Reference
Operator Statement
Structure Statement
Concepts
Operator Procedures
Implicit and Explicit Conversions
Widening and Narrowing Conversions
Visual Basic Language Concepts

How to: Call an Operator Procedure


You call an operator procedure by using the operator symbol in an expression. In the case of a conversion operator, you call it
by calling the CType Function to convert a value from one data type to another.
You do not call operator procedures explicitly. You simply use the operator, or the CType function, in an assignment statement
or an expression, the same way you normally use an operator. Visual Basic makes the call to the operator procedure.
Defining an operator on a class or structure is also called overloading the operator.
To call an operator procedure
1. Use the operator symbol in an expression in the normal way.
2. Be sure the data types of the operands are appropriate for the operator, and in the correct order.
3. The operator contributes to the value of the expression as expected.
To call a conversion operator procedure
1. Use CType inside an expression.
2. Be sure the data types of the operands are appropriate for the conversion, and in the correct order.
3. CType calls the conversion operator procedure and returns the converted value.
Example
The following example creates two TimeSpan structures, adds them together, and stores the result in a third TimeSpan
structure. The TimeSpan structure defines operator procedures to overload several standard operators.
VB
Dim firstSpan As New TimeSpan(3, 30, 0)
Dim secondSpan As New TimeSpan(1, 30, 30)
Dim combinedSpan As TimeSpan = firstSpan + secondSpan
Dim s As String = firstSpan.ToString() & _
" + " & secondSpan.ToString() & _
" = " & combinedSpan.ToString()
MsgBox(s)

Because TimeSpan overloads the standard + operator, the preceding example calls an operator procedure when it calculates
the value of combinedSpan.
For an example of calling a conversation operator procedure, see How to: Use a Class that Defines Operators.
Compiling the Code
Be sure the class or structure you are using defines the operator you want to use.
See Also
Tasks
How to: Define an Operator
How to: Define a Conversion Operator
How to: Declare a Structure
Reference
Operator Statement
Widening
Narrowing
Structure Statement
Concepts
Operator Procedures
Implicit and Explicit Conversions
Widening and Narrowing Conversions
Visual Basic Language Concepts

How to: Use a Class that Defines Operators


If you are using a class or structure that defines its own operators, you can access those operators from Visual Basic.
Defining an operator on a class or structure is also called overloading the operator.
Example
The following example accesses the SQL structure SqlString, which defines the conversion operators (CType Function) in both
directions between a SQL string and a Visual Basic string. Use CType(SQL string expression, String) to convert a SQL string to
a Visual Basic string, and CType(Visual Basic string expression, SqlString) to convert in the other direction.
VB
' Insert the following line at the beginning of your source file.
Imports System.Data.SqlTypes

VB
Public Sub setJobString(ByVal g As Integer)
Dim title As String
Dim jobTitle As System.Data.SqlTypes.SqlString
Select Case g
Case 1
title = "President"
Case 2
title = "Vice President"
Case 3
title = "Director"
Case 4
title = "Manager"
Case Else
title = "Worker"
End Select
jobTitle = CType(title, SqlString)
MsgBox("Group " & CStr(g) & " generates title """ _
& CType(jobTitle, String) & """")
End Sub

The SqlString structure defines a conversion operator (CType Function) from String to SqlString and another from SqlString
to String. The statement that assigns title to jobTitle makes use of the first operator, and the
MsgBox Function (Visual Basic) call uses the second.
Compiling the Code
Be sure the class or structure you are using defines the operator you want to use. Do not assume that the class or structure has
defined every operator available for overloading. For a list of available operators, see Operator Statement.
Include the appropriate Imports statement for the SQL string at the beginning of your source file (in this case
System.Data.SqlTypes).
Your project must have references to System.Data and System.XML. If you need to add them, see
How to: Add and Remove References in Visual Studio (C#, J#).
See Also
Tasks
How to: Define an Operator
How to: Define a Conversion Operator
How to: Call an Operator Procedure
How to: Declare a Structure
Reference
Widening
Narrowing
Structure Statement
Concepts
Operator Procedures
Implicit and Explicit Conversions
Widening and Narrowing Conversions
Visual Basic Language Concepts

Procedure Parameters and Arguments


In most cases, a procedure needs some information about the circumstances in which it has been called. A procedure that
performs repeated or shared tasks uses different information for each call. This information consists of variables, constants,
and expressions that you pass to the procedure when you call it.
A parameter represents a value that the procedure expects you to supply when you call it. The procedure's declaration defines
its parameters.
You can define a procedure with no parameters, one parameter, or more than one. The part of the procedure definition that
specifies the parameters is called the parameter list.
An argument represents the value you supply to a procedure parameter when you call the procedure. The calling code supplies
the arguments when it calls the procedure. The part of the procedure call that specifies the arguments is called the argument
list.
The following illustration shows code calling the procedure safeSquareRoot from two different places. The first call passes the
value of the variable x (4.0) to the parameter number, and the return value in root (2.0) is assigned to the variable y. The second
call passes the literal value 9.0 to number, and assigns the return value (3.0) to variable z.
Passing an argument to a parameter

For more information, see Differences Between Parameters and Arguments.


Parameter Data Type
You define a data type for a parameter by using the As clause in its declaration. For example, the following function accepts a
string and an integer.
VB
Function appointment(ByVal day As String, ByVal hour As Integer) As String
' Insert code to return any appointment for the given day and time.
Return "appointment"
End Function

If the type checking switch (Option Strict Statement) is Off, the As clause is optional, except that if any one parameter uses it,
all parameters must use it. If type checking is On, the As clause is required for all procedure parameters.
If the calling code expects to supply an argument with a data type different from that of its corresponding parameter, such as
Byte to a String parameter, it must do one of the following:
Supply only arguments with data types that widen to the parameter data type;
Set Option Strict Off to allow implicit narrowing conversions; or
Use a conversion keyword to explicitly convert the data type.
Type Parameters
A generic procedure also defines one or more type parameters in addition to its normal parameters. A generic procedure
allows the calling code to pass different data types each time it calls the procedure, so it can tailor the data types to the
requirements of each individual call. See Generic Procedures in Visual Basic.
See Also
Tasks
How to: Define a Parameter for a Procedure
How to: Pass Arguments to a Procedure
Concepts
Procedures in Visual Basic
Sub Procedures
Function Procedures
Property Procedures
Operator Procedures
Argument Passing By Value and By Reference
Procedure Overloading
Other Resources
Type Conversions in Visual Basic
Visual Basic Language Concepts

Differences Between Parameters and Arguments


In most cases, a procedure needs some information about the circumstances in which it has been called. A procedure that
performs repeated or shared tasks uses different information for each call. This information consists of variables, constants,
and expressions that you pass to the procedure when you call it.
To communicate this information to the procedure, the procedure defines a parameter, and the calling code passes an
argument to that parameter. You can think of the parameter as a parking place and the argument as an automobile. Just as
different automobiles can park in the parking place at different times, the calling code can pass a different argument to the
same parameter each time it calls the procedure.
Parameters
A parameter represents a value that the procedure expects you to pass when you call it. The procedure's declaration defines its
parameters.
When you define a Function or Sub procedure, you specify a parameter list in parentheses immediately following the
procedure name. For each parameter, you specify a name, a data type, and a passing mechanism (ByVal or ByRef). You can also
indicate that a parameter is optional, meaning the calling code does not have to pass a value for it.
The name of each parameter serves as a local variable within the procedure. You use the parameter name the same way you
use any other variable.
Arguments
An argument represents the value you pass to a procedure parameter when you call the procedure. The calling code supplies
the arguments when it calls the procedure.
When you call a Function or Sub procedure, you include an argument list in parentheses immediately following the
procedure name. Each argument corresponds to the parameter in the same position in the list.
In contrast to parameter definition, arguments do not have names. Each argument is an expression, which can contain zero or
more variables, constants, and literals. The data type of the evaluated expression should normally match the data type defined
for the corresponding parameter, and in any case it must be convertible to the parameter type.
See Also
Tasks
How to: Define a Parameter for a Procedure
How to: Pass Arguments to a Procedure
Concepts
Procedures in Visual Basic
Sub Procedures
Function Procedures
Property Procedures
Operator Procedures
Argument Passing By Value and By Reference
Recursive Procedures
Procedure Overloading
Visual Basic Language Concepts

How to: Define a Parameter for a Procedure


A parameter allows the calling code to pass a value to the procedure when it calls it. You declare each parameter for a
procedure the same way you declare a variable, specifying its name and data type. You also specify the passing mechanism,
and whether the parameter is optional.
For more information, see Procedure Parameters and Arguments.
To define a procedure parameter
1. In the procedure declaration, add the parameter name to the procedure's parameter list, separating it from other
parameters by commas.
2. Decide the data type of the parameter.
3. Follow the parameter name with an As clause to specify the data type.
4. Decide the passing mechanism you want for the parameter. Normally you pass a parameter by value, unless you want
the procedure to be able to change its value in the calling code.
5. Precede the parameter name with ByVal or ByRef to specify the passing mechanism. For more information, see
Differences Between Passing an Argument By Value and By Reference.
6. If the parameter is optional, precede the passing mechanism with Optional (Visual Basic) and follow the parameter data
type with an equal sign (=) and a default value.
The following example defines the outline of a Sub procedure with three parameters. The first two are required and the
third is optional. The parameter declarations are separated in the parameter list by commas.
VB
Sub updateCustomer(ByRef c As customer, ByVal region As String, _
Optional ByVal level As Integer = 0)
' Insert code to update a customer object.
End Sub

The first parameter accepts a customer object, and updateCustomer can directly update the variable passed to c because
the argument is passed ByRef. The procedure cannot change the values of the last two arguments because they are
passed ByVal.
If the calling code does not supply a value for the level parameter, Visual Basic sets it to the default value of 0.
If the type checking switch (Option Strict Statement) is Off, the As clause is optional when you define a parameter.
However, if any one parameter uses an As clause, all of them must use it. If the type checking switch is On, the As clause
is required for every parameter definition.
Specifying data types for all your programming elements is known as strong typing. When you set Option Strict On,
Visual Basic enforces strong typing. This is strongly recommended, for the following reasons:
It enables IntelliSense support for your variables and parameters. This allows you to see their properties and other
members as you type in your code.
It allows the compiler to perform type checking. This helps catch statements that can fail at run time due to errors
such as overflow. It also catches calls to methods on objects that do not support them.
It results in faster execution of your code. One reason for this is that if you do not specify a data type for a
programming element, the Visual Basic compiler assigns it the Object type. Your compiled code might have to
convert back and forth between Object and other data types, which reduces performance.
See Also
Tasks
How to: Pass Arguments to a Procedure
Concepts
Procedures in Visual Basic
Sub Procedures
Function Procedures
Argument Passing By Value and By Reference
Recursive Procedures
Procedure Overloading
Other Resources
Object-Oriented Programming in Visual Basic
Visual Basic Language Concepts

How to: Pass Arguments to a Procedure


When you call a procedure, you follow the procedure name with an argument list in parentheses. You supply an argument
corresponding to every required parameter the procedure defines, and you can optionally supply arguments to the Optional
parameters. If you do not supply an Optional parameter in the call, you must include a comma to mark its place in the
argument list if you are supplying any subsequent arguments.
If you intend to pass an argument of a data type different from that of its corresponding parameter, such as Byte to String,
you can set the type-checking switch (Option Strict Statement) to Off. If Option Strict is On, you must use either widening
conversions or explicit conversion keywords. For more information, see Widening and Narrowing Conversions and
Type Conversion Functions.
For more information, see Procedure Parameters and Arguments.
To pass one or more arguments to a procedure
1. In the calling statement, follow the procedure name with parentheses.
2. Inside the parentheses, put an argument list. Include an argument for each required parameter the procedure defines,
and separate the arguments with commas.
3. Make sure each argument is a valid expression that evaluates to a data type convertible to the type the procedure defines
for the corresponding parameter.
4. If a parameter is defined as Optional (Visual Basic), you can either include it in the argument list or omit it. If you omit it,
the procedure uses the default value defined for that parameter.
5. If you omit an argument for an Optional parameter and there is another parameter after it in the parameter list, you can
mark the place of the omitted argument by an extra comma in the argument list.
The following example calls the Visual Basic MsgBox Function (Visual Basic).
VB
Dim mbResult As MsgBoxResult
Dim displayString As String = "Show this string to the user"
mbResult = MsgBox(displayString, , "Put this in the title bar")

The preceding example supplies the required first argument, which is the message string to be displayed. It omits an
argument for the optional second parameter, which specifies the buttons to be displayed on the message box. Because
the call does not supply a value, MsgBox uses the default value, MsgBoxStyle.OKOnly, which displays only an OK
button.
The second comma in the argument list marks the place of the omitted second argument, and the last string is passed to
the optional third parameter of MsgBox, which is the text to be displayed in the title bar.
See Also
Tasks
How to: Define a Parameter for a Procedure
Concepts
Sub Procedures
Function Procedures
Property Procedures
Operator Procedures
Argument Passing By Value and By Reference
Recursive Procedures
Procedure Overloading
Other Resources
Object-Oriented Programming in Visual Basic
Visual Basic Language Concepts

Argument Passing By Value and By Reference


In Visual Basic, you can pass an argument to a procedure by value or by reference. This is known as the passing mechanism,
and it determines whether the procedure can modify the programming element underlying the argument in the calling code.
The procedure declaration determines the passing mechanism for each parameter by specifying the ByVal or ByRef keyword.
Distinctions
When passing an argument to a procedure, be aware of several different distinctions that interact with each other:
Whether the underlying programming element is modifiable or nonmodifiable
Whether the argument itself is modifiable or nonmodifiable
Whether the argument is being passed by value or by reference
Whether the argument data type is a value type or a reference type
For more information, see Differences Between Modifiable and Nonmodifiable Arguments and
Differences Between Passing an Argument By Value and By Reference.
Choice of Passing Mechanism
You should choose the passing mechanism carefully for each argument.
Protection. In choosing between the two passing mechanisms, the most important criterion is the exposure of calling
variables to change. The advantage of passing an argument ByRef is that the procedure can return a value to the calling
code through that argument. The advantage of passing an argument ByVal is that it protects a variable from being
changed by the procedure.
Performance. Although the passing mechanism can affect the performance of your code, the difference is usually
insignificant. One exception to this is a value type passed ByVal. In this case, Visual Basic copies the entire data contents
of the argument. Therefore, for a large value type such as a structure, it can be more efficient to pass it ByRef.
For reference types, only the pointer to the data is copied (four bytes on 32-bit platforms, eight bytes on 64-bit
platforms). Therefore, you can pass arguments of type String or Object by value without harming performance.
Determination of the Passing Mechanism
The procedure declaration specifies the passing mechanism for each parameter. The calling code cannot override a ByVal
mechanism, but if a parameter is declared with ByRef, the calling code can force the mechanism to ByVal by enclosing the
argument name in parentheses in the call.
The default in Visual Basic is to pass arguments by value. You can make your code easier to read by using the ByVal keyword.
It is good programming practice to include either the ByVal or ByRef keyword with every declared parameter.
When To Pass an Argument by Value
If the calling code element underlying the argument is a nonmodifiable element, declare the corresponding parameter
ByVal. No code can change the value of a nonmodifiable element.
If the underlying element is modifiable, but you do not want the procedure to be able to change its value, declare the
parameter ByVal. Only the calling code can change the value of a modifiable element passed by value.
When To Pass an Argument by Reference
If the procedure has a genuine need to change the underlying element in the calling code, declare the corresponding
parameter ByRef.
If the correct execution of the code depends on the procedure changing the underlying element in the calling code,
declare the parameter ByRef. If you pass it by value, or if the calling code overrides the ByRef passing mechanism by
enclosing the argument in parentheses, the procedure call might produce unexpected results.
See Also
Tasks
How to: Pass Arguments to a Procedure
How to: Change the Value of a Procedure Argument
How to: Protect a Procedure Argument Against Value Changes
How to: Force an Argument to Be Passed by Value
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing by Position and by Name
Value Types and Reference Types
Visual Basic Language Concepts

Differences Between Modifiable and Nonmodifiable


Arguments
When you call a procedure, you typically pass one or more arguments to it. Each argument corresponds to an underlying
programming element. Both the underlying elements and the arguments themselves can be either modifiable or
nonmodifiable.
Modifiable and Nonmodifiable Elements
A programming element can be either a modifiable element, which can have its value changed, or a nonmodifiable element,
which has a fixed value once it has been created.
The following table lists modifiable and nonmodifiable programming elements.
Modifiable elements Nonmodifiable elements
Local variables (declared inside procedures), including object variables, except for Read-only variables, fields, and properties
read-only

Fields (member variables of modules, classes, and structures), except for read-onl Constants and literals
y

Properties, except for read-only Enumeration members

Array elements Expressions (even if their elements are modi


fiable)

Modifiable and Nonmodifiable Arguments


A modifiable argument is one with a modifiable underlying element. The calling code can store a new value at any time, and if
you pass the argument ByRef, the code in the procedure can also modify the underlying element in the calling code.
A nonmodifiable argument either has a nonmodifiable underlying element or is passed ByVal. The procedure cannot modify
the underlying element in the calling code, even if it is a modifiable element. If it is a nonmodifiable element, the calling code
itself cannot modify it.
The called procedure might modify its local copy of a nonmodifiable argument, but that modification does not affect the
underlying element in the calling code.
See Also
Tasks
How to: Pass Arguments to a Procedure
How to: Change the Value of a Procedure Argument
How to: Protect a Procedure Argument Against Value Changes
How to: Force an Argument to Be Passed by Value
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Differences Between Passing an Argument By Value and By Reference
Argument Passing by Position and by Name
Value Types and Reference Types
Visual Basic Language Concepts

Differences Between Passing an Argument By Value and By


Reference
When you pass one or more arguments to a procedure, each argument corresponds to an underlying programming element
in the calling code. You can pass either the value of this underlying element, or a reference to it. This is known as the passing
mechanism.
Passing by Value
You pass an argument by value by specifying the ByVal keyword for the corresponding parameter in the procedure definition.
When you use this passing mechanism, Visual Basic copies the value of the underlying programming element into a local
variable in the procedure. The procedure code does not have any access to the underlying element in the calling code.
Passing by Reference
You pass an argument by reference by specifying the ByRef keyword for the corresponding parameter in the procedure
definition. When you use this passing mechanism, Visual Basic gives the procedure a direct reference to the underlying
programming element in the calling code.
Passing Mechanism and Element Type
The choice of passing mechanism is not the same as the classification of the underlying element type. Passing by value or by
reference refers to what Visual Basic supplies to the procedure code. A value type or reference type refers to how a
programming element is stored in memory.
However, the passing mechanism and element type are interrelated. The value of a reference type is a pointer to the data
elsewhere in memory. This means that when you pass a reference type by value, the procedure code has a pointer to the
underlying element's data, even though it cannot access the underlying element itself. For example, if the element is an array
variable, the procedure code does not have access to the variable itself, but it can access the array members.
Ability to Modify
When you pass a nonmodifiable element as an argument, the procedure can never modify it in the calling code, whether it is
passed ByVal or ByRef.
For a modifiable element, the following table summarizes the interaction between the element type and the passing
mechanism.
Element type Passed ByVal Passed ByRef
Value type (contains only a valu The procedure cannot change the variable or any The procedure can change the variable an
e) of its members. d its members.

Reference type (contains a point The procedure cannot change the variable but can The procedure can change the variable an
er to a class or structure instanc change members of the instance to which it point d members of the instance to which it poin
e) s. ts.

See Also
Tasks
How to: Pass Arguments to a Procedure
How to: Change the Value of a Procedure Argument
How to: Protect a Procedure Argument Against Value Changes
How to: Force an Argument to Be Passed by Value
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Differences Between Modifiable and Nonmodifiable Arguments
Argument Passing by Position and by Name
Value Types and Reference Types
Visual Basic Language Concepts

How to: Change the Value of a Procedure Argument


When you call a procedure, each argument you supply corresponds to one of the parameters defined in the procedure. In
some cases, the procedure code can change the value underlying an argument in the calling code. In other cases, the procedure
can change only its local copy of an argument.
When you call the procedure, Visual Basic makes a local copy of every argument that is passed ByVal. For each argument
passed ByRef, Visual Basic gives the procedure code a direct reference to the programming element underlying the argument
in the calling code.
If the underlying element in the calling code is a modifiable element and the argument is passed ByRef, the procedure code
can use the direct reference to change the element's value in the calling code.
Changing the Underlying Value
To change the underlying value of a procedure argument in the calling code
1. In the procedure declaration, specify ByRef for the parameter corresponding to the argument.
2. In the calling code, pass a modifiable programming element as the argument.
3. In the calling code, do not enclose the argument in parentheses in the argument list.
4. In the procedure code, use the parameter name to assign a value to the underlying element in the calling code.
See the example further down for a demonstration.
Changing Local Copies
If the underlying element in the calling code is a nonmodifiable element, or if the argument is passed ByVal, the procedure
cannot change its value in the calling code. However, the procedure can change its local copy of such an argument.
To change the copy of a procedure argument in the procedure code
1. In the procedure declaration, specify ByVal for the parameter corresponding to the argument.
-or-
In the calling code, enclose the argument in parentheses in the argument list. This forces Visual Basic to pass the
argument by value, even if the corresponding parameter specifies ByRef.
2. In the procedure code, use the parameter name to assign a value to the local copy of the argument. The underlying value
in the calling code is not changed.
Example
The following example shows two procedures that take an array variable and operate on its elements. The increase procedure
simply adds one to each element. The replace procedure assigns a new array to the parameter a() and then adds one to each
element.
VB
Public Sub increase(ByVal a() As Long)
For j As Integer = 0 To UBound(a)
a(j) = a(j) + 1
Next j
End Sub

VB
Public Sub replace(ByRef a() As Long)
Dim k() As Long = {100, 200, 300}
a = k
For j As Integer = 0 To UBound(a)
a(j) = a(j) + 1
Next j
End Sub

VB
Dim n() As Long = {10, 20, 30, 40}
Call increase(n)
MsgBox("After increase(n): " & CStr(n(0)) & ", " & _
CStr(n(1)) & ", " & CStr(n(2)) & ", " & CStr(n(3)))
Call replace(n)
MsgBox("After replace(n): " & CStr(n(0)) & ", " & _
CStr(n(1)) & ", " & CStr(n(2)) & ", " & CStr(n(3)))

The first MsgBox call displays "After increase(n): 11, 21, 31, 41". Because the array n is a reference type, replace can change
its members, even though the passing mechanism is ByVal.
The second MsgBox call displays "After replace(n): 101, 201, 301". Because n is passed ByRef, replace can modify the
variable n in the calling code and assign a new array to it. Because n is a reference type, replace can also change its
members.
You can prevent the procedure from modifying the variable itself in the calling code. See
How to: Protect a Procedure Argument Against Value Changes.
Compiling the Code
When you pass a variable by reference, you must use the ByRef keyword to specify this mechanism.
The default in Visual Basic is to pass arguments by value. However, it is good programming practice to include either the ByVal
or ByRef keyword with every declared parameter. This makes your code easier to read.
Security
There is always a potential risk in allowing a procedure to change the value underlying an argument in the calling code. Make
sure you expect this value to be changed, and be prepared to check it for validity before using it.
See Also
Tasks
How to: Pass Arguments to a Procedure
How to: Protect a Procedure Argument Against Value Changes
How to: Force an Argument to Be Passed by Value
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Differences Between Modifiable and Nonmodifiable Arguments
Differences Between Passing an Argument By Value and By Reference
Argument Passing by Position and by Name
Value Types and Reference Types
Visual Basic Language Concepts

How to: Protect a Procedure Argument Against Value Changes


If a procedure declares a parameter as ByRef, Visual Basic gives the procedure code a direct reference to the programming
element underlying the argument in the calling code. This permits the procedure to change the value underlying the argument
in the calling code. In some cases the calling code might want to protect against such a change.
You can always protect an argument from change by declaring the corresponding parameter ByVal in the procedure. If you
want to be able to change a given argument in some cases but not others, you can declare it ByRef and let the calling code
determine the passing mechanism in each call. It does this by enclosing the corresponding argument in parentheses to pass it
by value, or not enclosing it in parentheses to pass it by reference. For more information, see
How to: Force an Argument to Be Passed by Value.
Example
The following example shows two procedures that take an array variable and operate on its elements. The increase procedure
simply adds one to each element. The replace procedure assigns a new array to the parameter a() and then adds one to each
element. However, the reassignment does not affect the underlying array variable in the calling code.
VB
Public Sub increase(ByVal a() As Long)
For j As Integer = 0 To UBound(a)
a(j) = a(j) + 1
Next j
End Sub

VB
Public Sub replace(ByVal a() As Long)
Dim k() As Long = {100, 200, 300}
a = k
For j As Integer = 0 To UBound(a)
a(j) = a(j) + 1
Next j
End Sub

VB
Dim n() As Long = {10, 20, 30, 40}
Call increase(n)
MsgBox("After increase(n): " & CStr(n(0)) & ", " & _
CStr(n(1)) & ", " & CStr(n(2)) & ", " & CStr(n(3)))
Call replace(n)
MsgBox("After replace(n): " & CStr(n(0)) & ", " & _
CStr(n(1)) & ", " & CStr(n(2)) & ", " & CStr(n(3)))

The first MsgBox call displays "After increase(n): 11, 21, 31, 41". Because the array n is a reference type, replace can change
its members, even though the passing mechanism is ByVal.
The second MsgBox call displays "After replace(n): 11, 21, 31, 41". Because n is passed ByVal, replace cannot modify the
variable n in the calling code by assigning a new array to it. When replace creates the new array instance k and assigns it to
the local variable a, it loses the reference to n passed in by the calling code. When it changes the members of a, only the local
array k is affected. Therefore, replace does not increment the values of array n in the calling code.
Compiling the Code
The default in Visual Basic is to pass arguments by value. However, it is good programming practice to include either the ByVal
or ByRef keyword with every declared parameter. This makes your code easier to read.
See Also
Tasks
How to: Pass Arguments to a Procedure
How to: Change the Value of a Procedure Argument
How to: Force an Argument to Be Passed by Value
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Differences Between Modifiable and Nonmodifiable Arguments
Differences Between Passing an Argument By Value and By Reference
Argument Passing by Position and by Name
Value Types and Reference Types
Visual Basic Language Concepts

How to: Force an Argument to Be Passed by Value


The procedure declaration determines the passing mechanism. If a parameter is declared ByRef, Visual Basic expects to pass
the corresponding argument by reference. This allows the procedure to change the value of the programming element
underlying the argument in the calling code. If you wish to protect the underlying element against such change, you can
override the ByRef passing mechanism in the procedure call by enclosing the argument name in parentheses. These
parentheses are in addition to the parentheses enclosing the argument list in the call.
The calling code cannot override a ByVal mechanism.
To force an argument to be passed by value
If the corresponding parameter is declared ByVal in the procedure, you do not need to take any additional steps. Visual
Basic already expects to pass the argument by value.
If the corresponding parameter is declared ByRef in the procedure, enclose the argument in parentheses in the
procedure call.
Example
The following example overrides a ByRef parameter declaration. In the call that forces ByVal, note the two levels of
parentheses.
VB
Sub setNewString(ByRef inString As String)
inString = "This is a new value for the inString argument."
MsgBox(inString)
End Sub

VB
Dim str As String = "Cannot be replaced if passed ByVal"

' The following call passes str ByVal even though it is declared ByRef.
Call setNewString((str))
' The parentheses around str protect it from change.
MsgBox(str)
' The following call allows str to be passed ByRef as declared.
Call setNewString(str)
' Variable str is not protected from change.
MsgBox(str)

When str is enclosed in extra parentheses within the argument list, the setNewString procedure cannot change its value in the
calling code, and MsgBox displays "Cannot be replaced if passed ByVal". When str is not enclosed in extra parentheses, the
procedure can change it, and MsgBox displays "This is a new value for the inString argument."
Compiling the Code
When you pass a variable by reference, you must use the ByRef keyword to specify this mechanism.
The default in Visual Basic is to pass arguments by value. However, it is good programming practice to include either the ByVal
or ByRef keyword with every declared parameter. This makes your code easier to read.
Robust Programming
If a procedure declares a parameter ByRef, the correct execution of the code might depend on being able to change the
underlying element in the calling code. If the calling code overrides this calling mechanism by enclosing the argument in
parentheses, or if it passes a nonmodifiable argument, the procedure cannot change the underlying element. This might
produce unexpected results in the calling code.
Security
There is always a potential risk in allowing a procedure to change the value underlying an argument in the calling code. Make
sure you expect this value to be changed, and be prepared to check it for validity before using it.
See Also
Tasks
How to: Pass Arguments to a Procedure
How to: Change the Value of a Procedure Argument
How to: Protect a Procedure Argument Against Value Changes
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Differences Between Modifiable and Nonmodifiable Arguments
Differences Between Passing an Argument By Value and By Reference
Argument Passing by Position and by Name
Value Types and Reference Types
Visual Basic Language Concepts

Argument Passing by Position and by Name


When you call a Sub or Function procedure, you can pass arguments by position — in the order in which they appear in the
procedure's definition — or you can pass them by name, without regard to position.
When you pass an argument by name, you specify the argument's declared name followed by a colon and an equal sign (:=),
followed by the argument value. You can supply named arguments in any order.
For example, the following Sub procedure takes three arguments:
VB
Sub studentInfo(ByVal name As String, _
Optional ByVal age As Short = 0, _
Optional ByVal birth As Date = #1/1/2000#)

Debug.WriteLine("Name = " & name & _


"; age = " & CStr(age) & _
"; birth date = " & CStr(birth))
End Sub

When you call this procedure, you can supply the arguments by position, by name, or by using a mixture of both.
Passing Arguments by Position
You can call the procedure studentInfo with its arguments passed by position and delimited by commas, as shown in the
following example:
VB
Call studentInfo("Mary", 19, #9/21/1981#)

If you omit an optional argument in a positional argument list, you must hold its place with a comma. The following example
calls studentInfo without the age argument:
VB
Call studentInfo("Mary", , #9/21/1981#)

Passing Arguments by Name


Alternatively, you can call studentInfo with the arguments passed by name, also delimited by commas, as shown in the
following example:
VB
Call studentInfo(age:=19, birth:=#9/21/1981#, name:="Mary")

Mixing Arguments by Position and by Name


You can supply arguments both by position and by name in a single procedure call, as shown in the following example:
VB
Call studentInfo("Mary", birth:=#9/21/1981#)

In the preceding example, no extra comma is necessary to hold the place of the omitted age argument, since birth is passed
by name.
When you supply arguments by a mixture of position and name, the positional arguments must all come first. Once you supply
an argument by name, the remaining arguments must all be by name.
Supplying Optional Arguments by Name
Passing arguments by name is especially useful when you call a procedure that has more than one optional argument. If you
supply arguments by name, you do not have to use consecutive commas to denote missing positional arguments. Passing
arguments by name also makes it easier to keep track of which arguments you are passing and which ones you are omitting.
Restrictions on Supplying Arguments by Name
You cannot pass arguments by name to avoid entering required arguments. You can omit only the optional arguments.
You cannot pass a parameter array by name. This is because when you call the procedure, you supply an indefinite number of
comma-separated arguments for the parameter array, and the compiler cannot associate more than one argument with a
single name.
See Also
Tasks
How to: Pass Arguments to a Procedure
How to: Pass Arguments to a Procedure by Name
Reference
Optional (Visual Basic)
ParamArray
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Optional Parameters
Parameter Arrays
Visual Basic Language Concepts

How to: Pass Arguments to a Procedure by Name


When you call a Sub or Function procedure, you can pass arguments to it by name, without regard to the order in which the
corresponding parameters appear in the procedure's definition.
Passing arguments by name makes your calling code easier to read because it gives meaning to the argument values in the
procedure call. If the procedure has optional parameters, passing by name also makes it easier to keep track of which
arguments you are passing and which ones you are omitting.
For rules and restrictions on supplying arguments by name, see Argument Passing by Position and by Name.
To pass an argument by name
1. Examine the source code of the procedure's declaration to determine the exact spelling of the parameter names.
2. In the calling code, prepare the procedure call in the normal way, with the argument list in parentheses following the
procedure name.
3. For each argument you intend to pass by name, supply the parameter's declared name followed by a colon and an equal
sign (:=), followed by the value you are passing for the argument.
4. You can supply named arguments in any order, but you must supply all positional arguments before supplying any
named arguments.
Example
The following example shows a Sub procedure with three parameters, and a Call Statement (Visual Basic) that passes
arguments to these parameters by name.
VB
Sub studentInfo(ByVal name As String, _
Optional ByVal age As Short = 0, _
Optional ByVal birth As Date = #1/1/2000#)

Debug.WriteLine("Name = " & name & _


"; age = " & CStr(age) & _
"; birth date = " & CStr(birth))
End Sub

VB
Call studentInfo(age:=19, birth:=#9/21/1981#, name:="Mary")

When you pass arguments by name, you do not have to supply them in the same order as the procedure declares them.
Compiling the Code
Make sure the parameter name in the argument list exactly matches the name declared by the procedure.
See Also
Tasks
How to: Pass Arguments to a Procedure
Reference
Optional (Visual Basic)
ParamArray
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Argument Passing by Position and by Name
Optional Parameters
Parameter Arrays
Visual Basic Language Concepts

Optional Parameters
You can specify that a procedure parameter is optional and no argument has to be supplied for it when the procedure is called.
Optional parameters are indicated by the Optional keyword in the procedure definition. The following rules apply:
Every optional parameter in the procedure definition must specify a default value.
The default value for an optional parameter must be a constant expression.
Every parameter following an optional parameter in the procedure definition must also be optional.
The following syntax shows a procedure declaration with an optional parameter:

Sub sub name(ByVal parameter 1 As data type 1, Optional ByVal parameter 2 As data type 2 =
default value)

Calling Procedures with Optional Parameters


When you call a procedure with an optional parameter, you can choose whether to supply the argument. If you do not, the
procedure uses the default value declared for that parameter.
When you omit one or more optional arguments in the argument list, you use successive commas to mark their positions. The
following example call supplies the first and fourth arguments but not the second or third:

Call sub name(argument 1, , , argument 4)

Determining Whether an Optional Argument Is Present


A procedure cannot detect at run time whether a given argument has been omitted or the calling code has explicitly supplied
the default value. If you need to make this distinction, you can set an unlikely value as the default. The following procedure
defines the optional parameter office, and tests for its default value, QJZ, to see if it has been omitted in the call:
VB
Sub notify(ByVal company As String, Optional ByVal office As String = "QJZ")
If office = "QJZ" Then
Debug.WriteLine("office not supplied -- using Headquarters")
office = "Headquarters"
End If
' Insert code to notify headquarters or specified office.
End Sub

If the optional parameter is a reference type such as a String, you can use Nothing as the default value, provided this is not an
expected value for the argument.
Optional Parameters and Overloading
Another way to define a procedure with optional parameters is to use overloading. If you have one optional parameter, you
can define two overloaded versions of the procedure, one accepting the parameter and one without it. This approach becomes
more complicated as the number of optional parameters increases. However, its advantage is that you can be absolutely sure
whether the calling program supplied each optional argument.
See Also
Tasks
How to: Define Optional Parameters for a Procedure
How to: Call a Procedure that Takes Optional Parameters
How to: Determine Whether an Optional Parameter Was Supplied
Reference
Optional (Visual Basic)
ParamArray
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Argument Passing by Position and by Name
Parameter Arrays
Procedure Overloading
Visual Basic Language Concepts

How to: Define Optional Parameters for a Procedure


You can specify that a procedure parameter is optional, so that the calling code does not have to supply an argument for it
when it calls the procedure. When you do this, you define a default value that the procedure uses if the argument is not
supplied.
You can define more than one optional parameter, but all the optional parameters must be at the end of the parameter list. All
the required parameters must precede every optional parameter.
To define an optional parameter
1. In the procedure declaration, precede the parameter name in the parameter list with the Optional keyword.
2. Follow the parameter name with an As clause as usual, and follow the As clause with an equal sign (=).
3. Follow the equal sign with the default value for the parameter. This must be a constant expression, so that the compiler
can completely evaluate it at compile time.
4. You must declare every subsequent parameter as Optional.
Example
The following example shows a procedure declaration with an optional parameter.
VB
Sub notify(ByVal company As String, Optional ByVal office As String = "QJZ")
If office = "QJZ" Then
Debug.WriteLine("office not supplied -- using Headquarters")
office = "Headquarters"
End If
' Insert code to notify headquarters or specified office.
End Sub

If the calling code does not supply a value for office in the argument list, Visual Basic supplies the default value of "QJZ".
Compiling the Code
You must specify a default value for every optional parameter in the procedure declaration. Be sure that each default value is a
constant that the compiler can evaluate at compile time.
See Also
Tasks
How to: Call a Procedure that Takes Optional Parameters
How to: Determine Whether an Optional Parameter Was Supplied
Reference
Optional (Visual Basic)
ParamArray
Concepts
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Argument Passing by Position and by Name
Optional Parameters
Parameter Arrays
Procedure Overloading
Visual Basic Language Concepts

How to: Call a Procedure that Takes Optional Parameters


When you call a procedure with an optional parameter, you can choose whether to supply the corresponding argument. If you
do not, the procedure uses the default value declared for that parameter.
If you intend to supply the argument, include it in the argument list in the normal way, between commas.
If you intend to omit the argument, use successive commas in the argument list to mark its omission.
If you omit the argument and you are supplying arguments by name, you do not need to indicate the omitted argument
either by name or by commas.

Example
The following example makes several calls to the MsgBox function. MsgBox has one required parameter and two optional
parameters.
VB
MsgBox("Important message", MsgBoxStyle.Critical, "MsgBox Example")
MsgBox("Just display this message.")
MsgBox("Test message", , "Title bar text")
MsgBox(Title:="Title bar text", Prompt:="Test message")

The first call to MsgBox supplies all three arguments in the order MsgBox defines them. The second call supplies only the
required argument. The third and fourth calls supply the first and third arguments. The third call does this by position, and the
fourth call does it by name.
Compiling the Code
Before you omit an argument from the argument list, be sure the corresponding parameter is optional, and also be sure you
want the procedure to use the default value for that parameter.
If you supply an argument by name, be sure the name in the argument list exactly matches the declared parameter name.
See Also
Tasks
How to: Define Optional Parameters for a Procedure
How to: Determine Whether an Optional Parameter Was Supplied
Reference
Optional (Visual Basic)
ParamArray
Concepts
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Argument Passing by Position and by Name
Optional Parameters
Parameter Arrays
Procedure Overloading
Visual Basic Language Concepts

How to: Determine Whether an Optional Parameter Was


Supplied
When a procedure defines an optional parameter, it might be necessary to determine whether or not the calling code has
supplied the corresponding argument or omitted it.
If the parameter value compares equal to its default value, this could be for one of two possible reasons:
The calling code omitted the argument in the procedure call; or
The calling code supplied the argument with a value exactly equal to the parameter's default value.
The procedure code cannot distinguish between these two possibilities. Often it does not matter, but in some cases the
procedure might need to take different actions for each possibility. The best available approach is to define an unlikely value as
the default, although this does not guarantee that the calling code cannot supply it.
If it is important to be absolutely certain whether the calling program supplied an optional argument, the safest approach is to
define overloaded versions of the procedure. See How to: Define Multiple Versions of a Procedure and
Considerations in Overloading Procedures.
To determine whether an argument has been passed to an optional parameter
1. Define an extremely unlikely value as the default for the parameter.
2. If the optional parameter is a reference type such as a String, you can use Nothing as the default value, provided this is
not an expected value for the argument.
3. In the procedure code, compare the parameter against the default value and take the appropriate action.
Overloading a Procedure with and without an Optional Parameter
Another way to define a procedure with optional parameters is to use overloading. If you have one optional parameter, you
can define two overloaded versions of the procedure, one accepting the parameter and one not accepting it. This approach
becomes more complicated as the number of optional parameters increases. However, its advantage is that you can be
absolutely sure whether the calling program supplied each optional argument.
To define different versions of the procedure to cover inclusion and omission of an argument
1. Define one version of the procedure with the parameter in the argument list. Do not declare the parameter as Optional.
2. Define another version of the procedure without the parameter. The declaration should be identical to that of the first
version in every other respect.
3. Place the code appropriate to each call in the respective version of the procedure.
Example
The following procedure defines the optional parameter office, and tests for its default value, QJZ, to see if it has been omitted
in the call.
VB
Sub notify(ByVal company As String, Optional ByVal office As String = "QJZ")
If office = "QJZ" Then
Debug.WriteLine("office not supplied -- using Headquarters")
office = "Headquarters"
End If
' Insert code to notify headquarters or specified office.
End Sub

If the calling code does not supply a value for office in the argument list, Visual Basic supplies the default value of "QJZ".
If the optional parameter is a reference type such as a String, you can use Nothing (Visual Basic) as the default value, provided
this is not an expected value for the argument.
For an example of using overloads to determine whether an optional parameter was passed, see
How to: Overload a Procedure that Takes Optional Parameters.
See Also
Tasks
How to: Define Optional Parameters for a Procedure
How to: Call a Procedure that Takes Optional Parameters
Reference
Optional (Visual Basic)
ParamArray
Concepts
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Argument Passing by Position and by Name
Optional Parameters
Parameter Arrays
Procedure Overloading
Visual Basic Language Concepts

Parameter Arrays
Usually, you cannot call a procedure with more arguments than the procedure declaration specifies. When you need an
indefinite number of arguments, you can declare a parameter array, which allows a procedure to accept an array of values for
a parameter. You do not have to know the number of elements in the parameter array when you define the procedure. The
array size is determined individually by each call to the procedure.
Declaring a ParamArray
You use the ParamArray keyword to denote a parameter array in the parameter list. The following rules apply:
A procedure can define only one parameter array, and it must be the last parameter in the procedure definition.
The parameter array must be passed by value. It is good programming practice to explicitly include the ByVal keyword in
the procedure definition.
The parameter array is automatically optional. Its default value is an empty one-dimensional array of the parameter
array's element type.
All parameters preceding the parameter array must be required. The parameter array must be the only optional
parameter.
For more information, see How to: Define a Procedure with an Indefinite Number of Parameters.
Calling a ParamArray
When you call a procedure that defines a parameter array, you can supply the argument in any one of the following ways:
Nothing — that is, you can omit the ParamArray argument. In this case, an empty array is passed to the procedure. You
can also pass the Nothing (Visual Basic) keyword, with the same effect.
A list of an arbitrary number of arguments, separated by commas. The data type of each argument must be implicitly
convertible to the ParamArray element type.
An array with the same element type as the parameter array's element type.
In all cases, the code within the procedure treats the parameter array as a one-dimensional array with elements of the same
data type as the ParamArray data type.
For more information, see How to: Call a Procedure that Takes an Indefinite Number of Parameters.
Security Note
Whenever you deal with an array which can be indefinitely large, there is a risk of overrunning some internal capacity of you
r application. If you accept a parameter array, you should test for the size of the array that the calling code passed to it. Take a
ppropriate steps if it is too large for your application. For more information, see How to: Determine the Size of an Array.

See Also
Reference
Optional (Visual Basic)
UBound Function (Visual Basic)
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Argument Passing by Position and by Name
Optional Parameters
Procedure Overloading
Type Checking in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Define a Procedure with an Indefinite Number of


Parameters
You can declare a parameter array as the last entry in a procedure's parameter list. This allows the procedure to accept a set of
values for that parameter, instead of just a single value. You do not have to know the number of values in the set when you
define the procedure. The set is determined individually by each call to the procedure, and each call can pass a different
number of values.
For more information, see Parameter Arrays.
To define a procedure that can accept an indefinite number of values for its last parameter
1. In the procedure declaration, define the parameter list in the normal way. All parameters except the last one must be
required (not Optional (Visual Basic)).
2. Precede the last parameter name with the keywords ByVal ParamArray. This parameter is automatically optional. Do
not include the Optional keyword.
3. Follow the parameter array name with an empty pair of parentheses.
4. Follow the empty parentheses with the usual As clause.
5. Do not follow the As clause with a default value. The parameter array's default value is automatically an empty one-
dimensional array of the data type you specified in the As clause.
Working with the Parameter Array Values
The code within the procedure must treat the parameter array as a one-dimensional array, each element of which is the same
data type as the ParamArray data type.
To access one of the values of a parameter array
1. In the procedure code, determine the length of the array passed to the parameter array by calling the
UBound Function (Visual Basic) on the parameter array name.
2. In an executable statement in the procedure code, follow the parameter array name with a subscript in parentheses. This
subscript should be between 0 and the upper bound returned by UBound.
Security Note
Whenever you deal with an array which can be indefinitely large, there is a risk of overrunning some internal capacity of you
r application. If you accept a parameter array from the calling code, you should test its length and take appropriate steps if it i
s too large for your application.

Example
The following example defines a procedure with a parameter array, and outputs the values of all the array elements passed to
the parameter array.
VB
Sub studentScores(ByVal name As String, ByVal ParamArray scores() As String)
Debug.WriteLine("Scores for " & name & ":" & vbCrLf)
' Use UBound to determine largest subscript of the array.
For i As Integer = 0 To UBound(scores, 1)
Debug.WriteLine("Score " & i & ": " & scores(i))
Next i
End Sub

The following examples show typical calls to studentScores.


VB
Call studentScores("Anne", "10", "26", "32", "15", "22", "24", "16")
Call studentScores("Mary", "High", "Low", "Average", "High")
Dim JohnScores() As String = {"35", "Absent", "21", "30"}
Call studentScores("John", JohnScores)

Compiling the Code


Make sure the ParamArray is the last parameter in the parameter list, and that none of the preceding parameters is declared
Optional.
See Also
Tasks
How to: Call a Procedure that Takes an Indefinite Number of Parameters
Reference
ByVal
ParamArray
Concepts
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Argument Passing by Position and by Name
Optional Parameters
Procedure Overloading
Type Checking in Visual Basic
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Call a Procedure that Takes an Indefinite Number of


Parameters
A procedure can declare the last entry in its parameter list to be a parameter array. This allows it to accept an indefinite
number of values for that parameter, instead of just a single value.
For more information, see Parameter Arrays.
To call a procedure with a parameter array and omit the corresponding argument
1. Write the procedure call in the normal way. The parameter array must be the last argument.
2. Terminate the argument list with the next-to-last argument. The parameter array is optional, and all the preceding
parameters must be required.
-or-
Supply the Nothing keyword as the argument for the parameter array.
3. Visual Basic passes an empty one-dimensional array to the procedure for the parameter array.
To call a procedure with a parameter array and supply a list of arguments
1. Write the procedure call in the normal way. The parameter array must be the last argument.
2. Supply any number of arguments, separated by commas, for the parameter array. The data type of each argument must
be implicitly convertible to the ParamArray element type.
3. Visual Basic passes a one-dimensional array to the procedure, containing all the values you supplied.
To call a procedure with a parameter array and supply an array of arguments
1. Write the procedure call in the normal way. The parameter array must be the last argument.
2. For the parameter array, supply a one-dimensional array with the same element type as the parameter array's element
type.
3. Visual Basic passes your array to the procedure.
Example
The following examples show typical calls to the studentScores procedure defined in
How to: Define a Procedure with an Indefinite Number of Parameters.
VB
Call studentScores("George")
... Call studentScores("Anne", "10", "26", "32", "15", "22", "24", "16")
Call studentScores("Mary", "High", "Low", "Average", "High")
Dim JohnScores() As String = {"35", "Absent", "21", "30"}
Call studentScores("John", JohnScores)

The first call omits the parameter array altogether and supplies only the required first argument. The studentScores
procedure treats this call as passing an empty array.
The second and third calls supply argument lists of different lengths to the parameter array. Each such list is passed as an array
of values.
The fourth call passes an array to the parameter array.
See Also
Reference
Optional (Visual Basic)
ParamArray
ByVal
UBound Function (Visual Basic)
Concepts
Procedure Parameters and Arguments
Argument Passing By Value and By Reference
Argument Passing by Position and by Name
Optional Parameters
Procedure Overloading
Type Checking in Visual Basic
Visual Basic Language Concepts

Recursive Procedures
A recursive procedure is one that calls itself. In general, this is not the most effective way to write Visual Basic code.
The following procedure uses recursion to calculate the factorial of its original argument.
VB
Function factorial(ByVal n As Integer) As Integer
If n <= 1 Then
Return 1
Else
Return factorial(n - 1) * n
End If
End Function

Considerations with Recursive Procedures


Limiting Conditions. You must design a recursive procedure to test for at least one condition that can terminate the
recursion, and you must also handle the case where no such condition is satisfied within a reasonable number of recursive
calls. Without at least one condition that can be met without fail, your procedure runs a high risk of executing in an infinite
loop.
Memory Usage. Your application has a limited amount of space for local variables. Each time a procedure calls itself, it uses
more of that space for additional copies of its local variables. If this process continues indefinitely, it eventually causes a
StackOverflowException error.
Efficiency. You can almost always substitute a loop for recursion. A loop does not have the overhead of passing arguments,
initializing additional storage, and returning values. Your performance can be much better without recursive calls.
Mutual Recursion. You might observe very poor performance, or even an infinite loop, if two procedures call each other. Such
a design presents the same problems as a single recursive procedure, but can be harder to detect and debug.
Calling with Parentheses. When a Function procedure calls itself recursively, you must follow the procedure name with
parentheses, even if there is no argument list. Otherwise, the function name is taken as representing the return value of the
function.
Testing. If you write a recursive procedure, you should test it very carefully to make sure it always meets some limiting
condition. You should also ensure that you cannot run out of memory due to having too many recursive calls.
See Also
Tasks
Troubleshooting Procedures
Troubleshooting Exceptions: System.StackOverflowException
Reference
StackOverflowException
Concepts
Procedures in Visual Basic
Sub Procedures
Function Procedures
Property Procedures
Operator Procedures
Procedure Parameters and Arguments
Procedure Overloading
Loop Structures
Visual Basic Language Concepts

Procedure Overloading
Overloading a procedure means defining it in multiple versions, using the same name but different parameter lists. The
purpose of overloading is to define several closely related versions of a procedure without having to differentiate them by
name. You do this by varying the parameter list.
Overloading Rules
When you overload a procedure, the following rules apply:
Same Name. Each overloaded version must use the same procedure name.
Different Signature. Each overloaded version must differ from all other overloaded versions in at least one of the
following respects:
Number of parameters
Order of the parameters
Data types of the parameters
Number of type parameters (for a generic procedure)
Return type (only for a conversion operator)
Together with the procedure name, the preceding items are collectively called the signature of the procedure. When you
call an overloaded procedure, the compiler uses the signature to check that the call correctly matches the definition.
Items Not Part of Signature. You cannot overload a procedure without varying the signature. In particular, you cannot
overload a procedure by varying only one or more of the following items:
Procedure modifier keywords, such as Public, Shared, and Static
Parameter or type parameter names
Type parameter constraints (for a generic procedure)
Parameter modifier keywords, such as ByRef and Optional
Whether it returns a value
The data type of the return value (except for a conversion operator)
The items in the preceding list are not part of the signature. Although you cannot use them to differentiate between
overloaded versions, you can vary them among overloaded versions that are properly differentiated by their signatures.
Late-Bound Arguments. If you intend to pass a late bound object variable to an overloaded version, you must declare
the appropriate parameter as Object.
Multiple Versions of a Procedure
Suppose you are writing a Sub procedure to post a transaction against a customer's balance, and you want to be able to refer
to the customer either by name or by account number. To accommodate this, you can define two different Sub procedures, as
in the following example:
VB
Sub postName(ByVal custName As String, ByVal amount As Single)
' Insert code to access customer record by customer name.
End Sub
Sub postAcct(ByVal custAcct As Integer, ByVal amount As Single)
' Insert code to access customer record by account number.
End Sub

Overloaded Versions
An alternative is to overload a single procedure name. You can use the Overloads keyword to define a version of the procedure
for each parameter list, as follows:
VB
Overloads Sub post(ByVal custName As String, ByVal amount As Single)
' Insert code to access customer record by customer name.
End Sub
Overloads Sub post(ByVal custAcct As Integer, ByVal amount As Single)
' Insert code to access customer record by account number.
End Sub

Additional Overloads
If you also wanted to accept a transaction amount in either Decimal or Single, you could further overload post to allow for
this variation. If you did this to each of the overloads in the preceding example, you would have four Sub procedures, all with
the same name but with four different signatures.
Advantages of Overloading
The advantage of overloading a procedure is in the flexibility of the call. To use the post procedure declared in the preceding
example, the calling code can obtain the customer identification as either a String or an Integer, and then call the same
procedure in either case. The following example illustrates this:
VB
Imports MSVB = Microsoft.VisualBasic

VB
Dim customer As String
Dim accountNum As Integer
Dim amount As Single
customer = MSVB.Interaction.InputBox("Enter customer name or number")
amount = MSVB.Interaction.InputBox("Enter transaction amount")
Try
accountNum = CInt(customer)
Call post(accountNum, amount)
Catch
Call post(customer, amount)
End Try

See Also
Tasks
How to: Define Multiple Versions of a Procedure
How to: Call an Overloaded Procedure
How to: Overload a Procedure that Takes Optional Parameters
How to: Overload a Procedure that Takes an Indefinite Number of Parameters
Reference
Overloads
Concepts
Procedures in Visual Basic
Considerations in Overloading Procedures
Overload Resolution
Generic Types in Visual Basic
Visual Basic Language Concepts

How to: Define Multiple Versions of a Procedure


You can define a procedure in multiple versions by overloading it, using the same name but a different parameter list for each
version. The purpose of overloading is to define several closely related versions of a procedure without having to differentiate
them by name.
For more information, see Procedure Overloading.
To define multiple versions of a procedure
1. Write a Sub or Function declaration statement for each version of the procedure you want to define. Use the same
procedure name in every declaration.
2. Precede the Sub or Function keyword in each declaration with the Overloads keyword. You can optionally omit
Overloads in the declarations, but if you include it in any of the declarations, you must include it in every declaration.
3. Following each declaration statement, write procedure code to handle the specific case where the calling code supplies
arguments matching that version's parameter list. You do not have to test for which parameters the calling code has
supplied. Visual Basic passes control to the matching version of your procedure.
4. Terminate each version of the procedure with the End Sub or End Function statement as appropriate.
Example
The following example defines a Sub procedure to post a transaction against a customer's balance. It uses the Overloads
keyword to define two versions of the procedure, one that accepts the customer by name and the other by account number.
VB
Overloads Sub post(ByVal custName As String, ByVal amount As Single)
' Insert code to access customer record by customer name.
End Sub
Overloads Sub post(ByVal custAcct As Integer, ByVal amount As Single)
' Insert code to access customer record by account number.
End Sub

The calling code can obtain the customer identification as either a String or an Integer, and then use the same calling
statement in either case.
For information on how to call these versions of the post procedure, see How to: Call an Overloaded Procedure.
Compiling the Code
Make sure each of your overloaded versions has the same procedure name but a different parameter list.
See Also
Tasks
Troubleshooting Procedures
How to: Overload a Procedure that Takes Optional Parameters
How to: Overload a Procedure that Takes an Indefinite Number of Parameters
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Considerations in Overloading Procedures
Overload Resolution
Visual Basic Language Concepts

How to: Call an Overloaded Procedure


The advantage of overloading a procedure is in the flexibility of the call. The calling code can obtain the information it needs to
pass to the procedure and then call a single procedure name, no matter what arguments it is passing.
To call a procedure that has more than one version defined
1. In the calling code, determine which data to pass to the procedure.
2. Write the procedure call in the normal way, presenting the data in the argument list. Be sure the arguments match the
parameter list in one of the versions defined for the procedure.
3. You do not have to determine which version of the procedure to call. Visual Basic passes control to the version matching
your argument list.
The following example calls the post procedure declared in How to: Define Multiple Versions of a Procedure. It obtains
the customer identification, determines whether it is a String or an Integer, and then in either case calls the same
procedure.
VB
Imports MSVB = Microsoft.VisualBasic

VB
Dim customer As String
Dim accountNum As Integer
Dim amount As Single
customer = MSVB.Interaction.InputBox("Enter customer name or number")
amount = MSVB.Interaction.InputBox("Enter transaction amount")
Try
accountNum = CInt(customer)
Call post(accountNum, amount)
Catch
Call post(customer, amount)
End Try

See Also
Tasks
Troubleshooting Procedures
How to: Define Multiple Versions of a Procedure
How to: Overload a Procedure that Takes Optional Parameters
How to: Overload a Procedure that Takes an Indefinite Number of Parameters
Reference
Overloads
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Procedure Overloading
Considerations in Overloading Procedures
Overload Resolution
Visual Basic Language Concepts

How to: Overload a Procedure that Takes Optional Parameters


If a procedure has one or more Optional (Visual Basic) parameters, you cannot define an overloaded version matching any of
its implicit overloads. For more information, see "Implicit Overloads for Optional Parameters" in
Considerations in Overloading Procedures.
One Optional Parameter
To overload a procedure that takes one optional parameter
1. Write a Sub or Function declaration statement that includes the optional parameter in the parameter list. Do not use the
Optional keyword in this overloaded version.
2. Precede the Sub or Function keyword with the Overloads keyword.
3. Write the procedure code that should execute when the calling code supplies the optional argument.
4. Terminate the procedure with the End Sub or End Function statement as appropriate.
5. Write a second declaration statement that is identical to the first declaration except that it does not include the optional
parameter in the parameter list.
6. Write the procedure code that should execute when the calling code does not supply the optional argument. Terminate
the procedure with the End Sub or End Function statement as appropriate.
The following example shows a procedure defined with an optional parameter, an equivalent set of two overloaded
procedures, and finally examples of both invalid and valid overloaded versions.
VB
Sub q(ByVal b As Byte, Optional ByVal j As Long = 6)

VB
' The preceding definition is equivalent to the following two overloads.
' Overloads Sub q(ByVal b As Byte)
' Overloads Sub q(ByVal b As Byte, ByVal j As Long)

VB
' Therefore, the following overload is not valid because the signature is already in u
se.
' Overloads Sub q(ByVal c As Byte, ByVal k As Long)
' The following overload uses a different signature and is valid.
Overloads Sub q(ByVal b As Byte, ByVal j As Long, ByVal s As Single)

Multiple Optional Parameters


For a procedure with more than one optional parameter, you normally need more than two overloaded versions. For example,
if there are two optional parameters, and the calling code can supply or omit each one independently of the other, you need
four overloaded versions, one for each possible combination of supplied arguments.
As the number of optional parameters increases, the complexity of the overloading increases. Unless some combinations of
supplied arguments are not acceptable, for N optional parameters you need 2 ^ N overloaded versions. Depending on the
nature of the procedure, you might find that the clarity of logic justifies the extra effort of defining all the overloaded versions.
To overload a procedure that takes more than one optional parameter
1. Determine which combinations of supplied optional arguments are acceptable to the logic of the procedure. An
unacceptable combination might arise if one optional parameter depends on another. For example, if one parameter
accepts a spouse's name and another accepts the spouse's age, a combination of arguments supplying the age but
omitting the name is unacceptable.
2. For each acceptable combination of supplied optional arguments, write a Sub or Function declaration statement that
defines the corresponding parameter list. Do not use the Optional keyword.
3. In each declaration, precede the Sub or Function keyword with the Overloads keyword.
4. Following each declaration, write the procedure code that should execute when the calling code supplies an argument list
corresponding to that declaration's parameter list.
5. Terminate each procedure with the End Sub or End Function statement as appropriate.
See Also
Tasks
Troubleshooting Procedures
How to: Define Multiple Versions of a Procedure
How to: Call an Overloaded Procedure
How to: Overload a Procedure that Takes an Indefinite Number of Parameters
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Optional Parameters
Parameter Arrays
Procedure Overloading
Overload Resolution
Visual Basic Language Concepts

How to: Overload a Procedure that Takes an Indefinite Number


of Parameters
If a procedure has a ParamArray parameter, you cannot define an overloaded version taking a one-dimensional array for the
parameter array. For more information, see "Implicit Overloads for a ParamArray Parameter" in
Considerations in Overloading Procedures.
To overload a procedure that takes a variable number of parameters
1. Ascertain that the procedure and calling code logic benefits from overloaded versions more than from a ParamArray
parameter. See "Overloads and ParamArrays" in Considerations in Overloading Procedures.
2. Determine which numbers of supplied values the procedure should accept in the variable part of the parameter list. This
might include the case of no value, and it might include the case of a single one-dimensional array.
3. For each acceptable number of supplied values, write a Sub or Function declaration statement that defines the
corresponding parameter list. Do not use either the Optional or the ParamArray keyword in this overloaded version.
4. In each declaration, precede the Sub or Function keyword with the Overloads keyword.
5. Following each declaration, write the procedure code that should execute when the calling code supplies values
corresponding to that declaration's parameter list.
6. Terminate each procedure with the End Sub or End Function statement as appropriate.
Example
The following example shows a procedure defined with a ParamArray parameter, and then an equivalent set of overloaded
procedures.
VB
Sub p(ByVal d As Date, ByVal ParamArray c() As Char)

VB
' The preceding definition is equivalent to the following overloads.
' Overloads Sub p(ByVal d As Date)
' Overloads Sub p(ByVal d As Date, ByVal c() As Char)
' Overloads Sub p(ByVal d As Date, ByVal c1 As Char)
' Overloads Sub p(ByVal d As Date, ByVal c1 As Char, ByVal c2 As Char)
' And so on, with an additional Char argument in each successive overload.

You cannot overload such a procedure with a parameter list that takes a one-dimensional array for the parameter array.
However, you can use the signatures of the other implicit overloads. The following declarations illustrate this.
VB
' The following overload is not valid because it takes an array for the parameter array.
' Overloads Sub p(ByVal x As Date, ByVal y() As Char)
' The following overload takes a single value for the parameter array and is valid.
Overloads Sub p(ByVal z As Date, ByVal w As Char)

The code in the overloaded versions does not have to test whether the calling code supplied one or more values for the
ParamArray parameter, or if so, how many. Visual Basic passes control to the version matching the calling argument list.
Compiling the Code
Because a procedure with a ParamArray parameter is equivalent to a set of overloaded versions, you cannot overload such a
procedure with a parameter list corresponding to any of these implicit overloads. For more information, see
Considerations in Overloading Procedures.
Security
Whenever you deal with an array which can be indefinitely large, there is a risk of overrunning some internal capacity of your
application. If you accept a parameter array, you should test for the length of the array the calling code passed to it, and take
appropriate steps if it is too large for your application.
See Also
Tasks
Troubleshooting Procedures
How to: Define Multiple Versions of a Procedure
How to: Call an Overloaded Procedure
How to: Overload a Procedure that Takes Optional Parameters
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Optional Parameters
Parameter Arrays
Procedure Overloading
Overload Resolution
Visual Basic Language Concepts

Considerations in Overloading Procedures


When you overload a procedure, you must use a different signature for each overloaded version. This usually means each
version must specify a different parameter list. For more information, see "Different Signature" in Procedure Overloading.
You can overload a Function procedure with a Sub procedure, and vice versa, provided they have different signatures. Two
overloads cannot differ only in that one has a return value and the other does not.
You can overload a property the same way you overload a procedure, and with the same restrictions. However, you cannot
overload a procedure with a property, or vice versa.
Alternatives to Overloaded Versions
You sometimes have alternatives to overloaded versions, particularly when the presence of arguments is optional or their
number is variable.
Keep in mind that optional arguments are not necessarily supported by all languages, and parameter arrays are limited to
Visual Basic. If you are writing a procedure that is likely to be called from code written in any of several different languages,
overloaded versions offer the greatest flexibility.
Overloads and Optional Arguments
When the calling code can optionally supply or omit one or more arguments, you can define multiple overloaded versions or
use optional parameters.
When to Use Overloaded Versions
You can consider defining a series of overloaded versions in the following cases:
The logic in the procedure code is significantly different depending on whether the calling code supplies an optional
argument or not.
The procedure code cannot reliably test whether the calling code has supplied an optional argument. This is the case, for
example, if there is no possible candidate for a default value that the calling code could not be expected to supply.
When to Use Optional Parameters
You might prefer one or more optional parameters in the following cases:
The only required action when the calling code does not supply an optional argument is to set the parameter to a default
value. In such a case, the procedure code can be less complicated if you define a single version with one or more
Optional parameters.
For more information, see Optional Parameters.
Overloads and ParamArrays
When the calling code can pass a variable number of arguments, you can define multiple overloaded versions or use a
parameter array.
When to Use Overloaded Versions
You can consider defining a series of overloaded versions in the following cases:
You know that the calling code never passes more than a small number of values to the parameter array.
The logic in the procedure code is significantly different depending on how many values the calling code passes.
The calling code can pass values of different data types.
When to Use a Parameter Array
You are better served by a ParamArray parameter in the following cases:
You are not able to predict how many values the calling code can pass to the parameter array, and it could be a large
number.
The procedure logic lends itself to iterating through all the values the calling code passes, performing essentially the
same operations on every value.
For more information, see Parameter Arrays.
Implicit Overloads for Optional Parameters
A procedure with an Optional (Visual Basic) parameter is equivalent to two overloaded procedures, one with the optional
parameter and one without it. You cannot overload such a procedure with a parameter list corresponding to either of these.
The following declarations illustrate this.
VB
Overloads Sub q(ByVal b As Byte, Optional ByVal j As Long = 6)

VB
' The preceding definition is equivalent to the following two overloads.
' Overloads Sub q(ByVal b As Byte)
' Overloads Sub q(ByVal b As Byte, ByVal j As Long)

VB
' Therefore, the following overload is not valid because the signature is already in use.
' Overloads Sub q(ByVal c As Byte, ByVal k As Long)
' The following overload uses a different signature and is valid.
Overloads Sub q(ByVal b As Byte, ByVal j As Long, ByVal s As Single)

For a procedure with more than one optional parameter, there is a set of implicit overloads, arrived at by logic similar to that in
the preceding example.
Implicit Overloads for a ParamArray Parameter
The compiler considers a procedure with a ParamArray parameter to have an infinite number of overloads, differing from each
other in what the calling code passes to the parameter array, as follows:
One overload for when the calling code does not supply an argument to the ParamArray
One overload for when the calling code supplies a one-dimensional array of the ParamArray element type
For every positive integer, one overload for when the calling code supplies that number of arguments, each of the
ParamArray element type
The following declarations illustrate these implicit overloads.
VB
Overloads Sub p(ByVal d As Date, ByVal ParamArray c() As Char)

VB
' The preceding definition is equivalent to the following overloads.
' Overloads Sub p(ByVal d As Date)
' Overloads Sub p(ByVal d As Date, ByVal c() As Char)
' Overloads Sub p(ByVal d As Date, ByVal c1 As Char)
' Overloads Sub p(ByVal d As Date, ByVal c1 As Char, ByVal c2 As Char)
' And so on, with an additional Char argument in each successive overload.

You cannot overload such a procedure with a parameter list that takes a one-dimensional array for the parameter array.
However, you can use the signatures of the other implicit overloads. The following declarations illustrate this.
VB
' The following overload is not valid because it takes an array for the parameter array.
' Overloads Sub p(ByVal x As Date, ByVal y() As Char)
' The following overload takes a single value for the parameter array and is valid.
Overloads Sub p(ByVal z As Date, ByVal w As Char)

Typeless Programming as an Alternative to Overloading


If you want to allow the calling code to pass different data types to a parameter, an alternative approach is
Typeless Programming in Visual Basic. You can set the type checking switch to Off with either the Option Strict Statement or
the /optionstrict compiler option. Then you do not have to declare the parameter's data type. However, this approach has the
following disadvantages compared to overloading:
Typeless programming produces less efficient execution code.
The procedure must test for every data type it anticipates being passed.
The compiler cannot signal an error if the calling code passes a data type that the procedure does not support.

See Also
Tasks
Troubleshooting Procedures
How to: Define Multiple Versions of a Procedure
How to: Call an Overloaded Procedure
How to: Overload a Procedure that Takes Optional Parameters
How to: Overload a Procedure that Takes an Indefinite Number of Parameters
Reference
Overloads
Concepts
Procedures in Visual Basic
Procedure Parameters and Arguments
Overload Resolution
Visual Basic Language Concepts

Overload Resolution
When the Visual Basic compiler encounters a call to a procedure that is defined in several overloaded versions, the compiler
must decide which of the overloads to call. It does this by performing the following steps:
1. Accessibility. It eliminates any overload with an access level that prevents the calling code from calling it.
2. Number of Parameters. It eliminates any overload that defines a different number of parameters than are supplied in
the call.
3. Parameter Data Types. It eliminates any overload for which the data types of the calling arguments cannot be
converted to the parameter types defined in the overload.
4. Narrowing Conversions. It eliminates any overload that requires a narrowing conversion from the calling argument
types to the defined parameter types. This is true whether the type checking switch (Option Strict Statement) is On or
Off.
5. Least Widening. It considers the remaining overloads in pairs. For each pair, it compares the data types of the defined
parameters. If the types in one of the overloads all widen to the corresponding types in the other, the compiler eliminates
the latter. That is, it retains the overload that calls for the least amount of widening.
6. Single Candidate. It continues considering overloads in pairs until only one overload remains, and it resolves the call to
that overload. If the compiler cannot reduce the overloads to a single candidate, it generates an error.
The following illustration shows the process that determines which of a set of overloaded versions to call.
Resolving among overloaded versions

The following example illustrates this overload resolution process.


VB
Overloads Sub z(ByVal x As Byte, ByVal y As Double)
End Sub
Overloads Sub z(ByVal x As Short, ByVal y As Single)
End Sub
Overloads Sub z(ByVal x As Integer, ByVal y As Single)
End Sub

VB
Dim r, s As Short
Call z(r, s)
Dim p As Byte, q As Short
' The following statement causes an overload resolution error.
Call z(p, q)

In the first call, the compiler eliminates the first overload because the type of the first argument (Short) narrows to the type of
the corresponding parameter (Byte). It then eliminates the third overload because each argument type in the second overload
(Short and Single) widens to the corresponding type in the third overload (Integer and Single). The second overload requires
less widening, so the compiler uses it for the call.
In the second call, the compiler cannot eliminate any of the overloads on the basis of narrowing. It eliminates the third
overload for the same reason as in the first call, because it can call the second overload with less widening of the argument
types. However, the compiler cannot resolve between the first and second overloads. Each has one defined parameter type that
widens to the corresponding type in the other (Byte to Short, but Single to Double). The compiler therefore generates an
overload resolution error.
Overloaded Optional and ParamArray Arguments
If two overloads of a procedure have identical signatures except that the last parameter is declared Optional (Visual Basic) in
one and ParamArray in the other, the compiler resolves a call to that procedure as follows:
If the call supplies the last argument as The compiler resolves the call to the overload declaring the last argume
nt as
No value (argument omitted) Optional

A single value Optional

Two or more values in a comma-separated list ParamArray

An array of any length (including an empty arr ParamArray


ay)

See Also
Tasks
Troubleshooting Procedures
How to: Define Multiple Versions of a Procedure
How to: Call an Overloaded Procedure
How to: Overload a Procedure that Takes Optional Parameters
How to: Overload a Procedure that Takes an Indefinite Number of Parameters
Reference
Overloads
Concepts
Optional Parameters
Parameter Arrays
Procedure Overloading
Considerations in Overloading Procedures
Visual Basic Language Concepts

Troubleshooting Procedures
This page lists some common problems that can occur when working with procedures.
Returning an Array Type from a Function Procedure
If a Function procedure returns an array data type, you cannot use the Function name to store values in the elements of the
array. If you attempt to do this, the compiler interprets it as a call to the Function. The following example generates compiler
errors.
Function allOnes(ByVal n As Integer) As Integer()
For i As Integer = 1 To n - 1
' The following statement generates a COMPILER ERROR .
allOnes(i) = 1
Next i
' The following statement generates a COMPILER ERROR .
Return allOnes()
End Function

The statement allOnes(i) = 1 generates a compiler error because it appears to call allOnes with an argument of the wrong
data type (a singleton Integer instead of an Integer array). The statement Return allOnes() generates a compiler error
because it appears to call allOnes with no argument.
Correct Approach: To be able to modify the elements of an array that is to be returned, define an internal array as a local
variable. The following example compiles without error.
VB
Function allOnes(ByVal n As Integer) As Integer()
Dim i As Integer, iArray(n) As Integer
For i = 0 To n - 1
iArray(i) = 1
Next i
Return iArray
End Function

Argument Not Being Modified by Procedure Call


If you intend to allow a procedure to change a programming element underlying an argument in the calling code, you must
pass it by reference. But a procedure can access the elements of a reference type argument even if you pass it by value.
Underlying Variable. To allow the procedure to replace the value of the underlying variable element itself, the
procedure must declare the parameter ByRef. Also, the calling code must not enclose the argument in parentheses,
because that would override the ByRef passing mechanism.
Reference Type Elements. If you declare a parameter ByVal, the procedure cannot modify the underlying variable
element itself. However, if the argument is a reference type, the procedure can modify the members of the object to
which it points, even though it cannot replace the variable's value. For example, if the argument is an array variable, the
procedure cannot assign a new array to it, but it can change one or more of its elements. The changed elements are
reflected in the underlying array variable in the calling code.
The following example defines two procedures that take an array variable by value and operate on its elements. Procedure
increase simply adds one to each element. Procedure replace assigns a new array to the parameter a() and then adds one to
each element. However, the reassignment does not affect the underlying array variable in the calling code because a() is
declared ByVal.
VB
Public Sub increase(ByVal a() As Long)
For j As Integer = 0 To UBound(a)
a(j) = a(j) + 1
Next j
End Sub

VB
Public Sub replace(ByVal a() As Long)
Dim k() As Long = {100, 200, 300}
a = k
For j As Integer = 0 To UBound(a)
a(j) = a(j) + 1
Next j
End Sub

The following example makes calls to increase and replace.


VB
Dim n() As Long = {10, 20, 30, 40}
Call increase(n)
MsgBox("After increase(n): " & CStr(n(0)) & ", " & _
CStr(n(1)) & ", " & CStr(n(2)) & ", " & CStr(n(3)))
Call replace(n)
MsgBox("After replace(n): " & CStr(n(0)) & ", " & _
CStr(n(1)) & ", " & CStr(n(2)) & ", " & CStr(n(3)))

The first MsgBox call displays "After increase(n): 11, 21, 31, 41". Because n is a reference type, increase can change its
members, even though it is passed ByVal.
The second MsgBox call displays "After replace(n): 11, 21, 31, 41". Because n is passed ByVal, replace cannot modify the
variable n by assigning a new array to it. When replace creates the new array instance k and assigns it to the local variable a, it
loses the reference to n passed in by the calling code. When it increments the members of a, only the local array k is affected.
Correct Approach: To be able to modify an underlying variable element itself, pass it by reference. The following example
shows the change in the declaration of replace that allows it to replace one array with another in the calling code.
VB
Public Sub replace(ByRef a() As Long)

Unable to Define an Overload


If you want to define an overloaded version of a procedure, you must use the same name but a different signature. If the
compiler cannot differentiate your declaration from an overload with the same signature, it generates an error.
The signature of a procedure is determined by the procedure name and the parameter list. Each overload must have the same
name as all the other overloads but must differ from all of them in at least one of the other components of the signature. For
more information, see Procedure Overloading.
The following items, even though they pertain to the parameter list, are not components of a procedure's signature:
Procedure modifier keywords, such as Public, Shared, and Static
Parameter names
Parameter modifier keywords, such as ByRef and Optional
The data type of the return value (except for a conversion operator)
You cannot overload a procedure by varying only one or more of the preceding items.
Correct Approach: To be able to define a procedure overload, you must vary the signature. Because you must use the same
name, you must vary the number, order, or data types of the parameters. In a generic procedure, you can vary the number of
type parameters. In a conversion operator (CType Function), you can vary the return type.
Overload Resolution with Optional and ParamArray Arguments
If you are overloading a procedure with one or more Optional (Visual Basic) parameters or a ParamArray parameter, you must
avoid duplicating any of the implicit overloads. For information, see Considerations in Overloading Procedures.
Calling a Wrong Version of an Overloaded Procedure
If a procedure has several overloaded versions, you should be familiar with all their parameter lists and understand how Visual
Basic resolves calls among the overloads. Otherwise you could call an overload other than the intended one.
When you have determined which overload you want to call, be careful to observe the following rules:
Supply the correct number of arguments, and in the correct order.
Ideally, your arguments should have the exact same data types as the corresponding parameters. In any case, the data
type of each argument must widen to that of its corresponding parameter. This is true even with the
Option Strict Statement set to Off. If an overload requires any narrowing conversion from your argument list, that
overload is not eligible to be called.
If you supply arguments that require widening, make their data types as close as possible to the corresponding
parameter data types. If two or more overloads accept your argument data types, the compiler resolves your call to the
overload that calls for the least amount of widening.
You can reduce the chance of data type mismatches by using the CType Function conversion keyword when preparing your
arguments.
Overload Resolution Failure
When you call an overloaded procedure, the compiler attempts to eliminate all but one of the overloads. If it succeeds, it
resolves the call to that overload. If it eliminates all the overloads, or if it cannot reduce the eligible overloads to a single
candidate, it generates an error.
The following example illustrates the overload resolution process.
VB
Overloads Sub z(ByVal x As Byte, ByVal y As Double)
End Sub
Overloads Sub z(ByVal x As Short, ByVal y As Single)
End Sub
Overloads Sub z(ByVal x As Integer, ByVal y As Single)
End Sub

VB
Dim r, s As Short
Call z(r, s)
Dim p As Byte, q As Short
' The following statement causes an overload resolution error.
Call z(p, q)

In the first call, the compiler eliminates the first overload because the type of the first argument (Short) narrows to the type of
the corresponding parameter (Byte). It then eliminates the third overload because each argument type in the second overload
(Short and Single) widens to the corresponding type in the third overload (Integer and Single). The second overload requires
less widening, so the compiler uses it for the call.
In the second call, the compiler cannot eliminate any of the overloads on the basis of narrowing. It eliminates the third
overload for the same reason as in the first call, because it can call the second overload with less widening of the argument
types. However, the compiler cannot resolve between the first and second overloads. Each has one defined parameter type that
widens to the corresponding type in the other (Byte to Short, but Single to Double). The compiler therefore generates an
overload resolution error.
Correct Approach: To be able to call an overloaded procedure without ambiguity, use CType Function to match the argument
data types to the parameter types. The following example shows a call to z that forces resolution to the second overload.
VB
Call z(CType(p, Short), CType(q, Single))
Overload Resolution with Optional and ParamArray Arguments
If two overloads of a procedure have identical signatures except that the last parameter is declared Optional (Visual Basic) in
one and ParamArray in the other, the compiler resolves a call to that procedure according to the closest match. For more
information, see Overload Resolution.
See Also
Concepts
Procedures in Visual Basic
Sub Procedures
Function Procedures
Property Procedures
Operator Procedures
Procedure Parameters and Arguments
Procedure Overloading
Considerations in Overloading Procedures
Overload Resolution
Visual Basic Language Concepts

Control Flow in Visual Basic


Left unregulated, a program proceeds through its statements from beginning to end. Some very simple programs can be
written with only this unidirectional flow. However, much of the power and utility of any programming language comes from
the ability to change execution order with control statements and loops.
Control structures allow you to regulate the flow of your program's execution. Using control structures, you can write Visual
Basic code that makes decisions or that repeats actions. Other control structures let you guarantee disposal of a resource or
run a series of statements on the same object reference.
In This Section
Decision Structures
Describes control structures used for branching.
Loop Structures
Discusses control structures used to repeat processes.
Other Control Structures
Describes control structures used for resource disposal and object access.
Nested Control Structures
Covers control structures inside other control structures.
How to: Transfer Control Out of a Control Structure
Summarizes how to transfer directly out of a control structure.
Related Sections
Control Statement for Visual Basic 6.0 Users
Lists changes to the behavior and syntax of control structures from previous versions of Visual Basic.
Control Flow Summary
Provides links to language reference pages on this subject.
Visual Basic Language Concepts

Decision Structures
Visual Basic allows you to test conditions and perform different operations depending on the results of that test. You can test
for a condition being true or false, for various values of an expression, or for various exceptions generated when you execute a
series of statements.
The following illustration shows a decision structure that tests for a condition being true and takes different actions depending
on whether it is true or false.
Taking different actions when a condition is true and when it is false

If...Then...Else Construction
If...Then...Else constructions allow you to test for one or more conditions and run one or more statements depending on each
condition. You can test conditions and take actions in the following ways:
Run one or more statements if a condition is True
Run one or more statements if a condition is False
Run some statements if a condition is True and others if it is False
Test an additional condition if a prior condition is False
The control structure that offers all these possibilities is the If...Then...Else Statement (Visual Basic). You can use a single-line
version if you have just one test and one statement to run. If you have a more complex set of conditions and actions, you can
use the multiple-line version.
Select...Case Construction
The Select...Case construction allows you to evaluate an expression once and run different sets of statements based on
different possible values. For more information, see Select...Case Statement (Visual Basic).
Try...Catch...Finally Construction
Try...Catch...Finally constructions allow you to run a set of statements under an environment that retains control if any of
your statements causes an exception. You can take different actions for different exceptions. You can optionally specify a block
of code that is to run before you exit the entire Try...Catch...Finally construction, no matter what happens. For more
information, see Try...Catch...Finally Statement (Visual Basic).
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Run Statements Depending on One or More Conditions
How to: Test for Several Values of an Expression
How to: Retain Control When an Error Occurs
Concepts
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts

How to: Run Statements Depending on One or More


Conditions
You can use an If...Then...Else Statement (Visual Basic) to run a specific statement or block of statements depending on the
Boolean Data Type (Visual Basic) value of a condition. The condition usually results from a comparison of two values, but it can
be any expression that evaluates to a Boolean value (True or False). This includes values of other data types, such as numeric
types, that have been converted to Boolean.
To run one or more statements if a condition is True
If you have only one statement to run, use the single-line syntax of the If...Then...Else construction. You do not need the
Else or End If statements. The following example illustrates this.

Sub fixDate()
Dim myDate As Date = #2/13/1973#
If myDate < Now Then myDate = Now
End Sub

-or-
To execute more than one line of code when the condition is True, use the multiple-line syntax, which includes the End If
statement. If you have no code to run when the condition is False, you omit the Else statement. The following example
illustrates this.

Dim alertLabel As New System.Windows.Forms.Label


Sub alertUser(ByVal value As Long)
If value = 0 Then
alertLabel.ForeColor = System.Drawing.Color.Red
alertLabel.Font = New Font(alertLabel.Font, _
FontStyle.Bold Or FontStyle.Italic)
End If
End Sub

To run some statements if a condition is True and others if it is False


Use an If...Then...Else construction with the Else (Visual Basic) statement to define two blocks of statements. Visual Basic
runs one block if the condition is True and the other if it is False. The following example illustrates this.

Dim alertLabel As New System.Windows.Forms.Label


Sub alertUser(ByVal value As Long)
If value = 0 Then
alertLabel.ForeColor = System.Drawing.Color.Red
alertLabel.Font = New Font(alertLabel.Font, _
FontStyle.Bold Or FontStyle.Italic)
Else
alertLabel.Forecolor = System.Drawing.Color.Black
alertLabel.Font = New Font(alertLabel.Font, _
FontStyle.Regular)
End If
End Sub

To test additional conditions if the first condition is False


Use an If...Then...Else construction with one or more ElseIf (Visual Basic) statements to test additional conditions if the
first condition is False. In the following example, the Function procedure computes a payroll bonus based on
performance rating. The statement block following the Else statement runs only if the conditions in the If and ElseIf
statements are all False.

Function bonus(ByVal performance As Integer, ByVal salary As Decimal) _


As Decimal
If performance = 1 Then
Return salary * 0.1
ElseIf performance = 2 Then
Return salary * 0.09
ElseIf performance = 3 Then
Return salary * 0.07
Else
Return 0
End If
End Function

Visual Basic tests the conditions in the order they appear in the If...Then...Else statements. When it encounters a True
condition or an Else statement, it runs the corresponding statement block. Control then passes to the statement
following the End If statement.
You can have any number of ElseIf statements, or none at all. You can include or omit one Else statement regardless of
whether you have any ElseIf statements.

See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Test for Several Values of an Expression
How to: Retain Control When an Error Occurs
Concepts
Decision Structures
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts

How to: Test for Several Values of an Expression


When you are comparing the same expression to several different values, you can use the Select...Case Statement (Visual Basic)
construction as an alternative to the If...Then...Else Statement (Visual Basic) construction. Whereas the If and ElseIf (Visual Basic)
statements can evaluate a different expression in each statement, the Select statement evaluates a single expression only once
and uses it for every comparison.
To evaluate an expression once and test several values
Use the Select...Case construction to specify the expression and the values to test. Each Case statement can contain one
or more values, a range of values, or a combination of values and comparison operators. You can use a Case Else
statement to handle all values not tested by the previous Case statements. The following example illustrates these
possibilities.

Function bonus(ByVal performance As Integer, ByVal salary As Decimal) _


As Decimal
Select performance
Case 1
Return salary * 0.1
Case 2, 3
Return salary * 0.09
Case 5 To 7
Return salary * 0.07
Case 4, 8 To 10
Return salary * 0.05
Case Is < 15
Return 100
Case Else
Return 0
End Select
End Function

Visual Basic compares the value of the expression to the values in the Case statements in the order they appear in the
Select...Case construction. If it finds a match or a Case Else statement, it runs the corresponding statement block. In any
case, it then branches to the statement following the End Select statement.
You can have any number of Case statements, and you can include or omit one Case Else statement regardless of
whether you have any Case statements.
A code example for the Select...Case construction is also available as an IntelliSense code snippet. In the code snippet picker, it
is located in Visual Basic Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Run Statements Depending on One or More Conditions
How to: Retain Control When an Error Occurs
Concepts
Decision Structures
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts

How to: Retain Control When an Error Occurs


You can use the Try...Catch...Finally Statement (Visual Basic) construction for structured exception handling. This allows you to
run a particular block of statements if a specified exception occurs while your code is running. When this happens, the code is
said to throw the exception, and you catch it with the appropriate Catch statement.
To run a set of statements if your code causes an exception
Use the Try...Catch...Finally construction to enclose the code that might cause an exception. Then, specify the code to run
if an exception occurs, and optionally provide a set of statements to run before control leaves the Try...Catch...Finally
construction.
The following example attempts to calculate the date and time exactly 100 years after the value provided in the Object
variable givenDate.

Dim givenDate As Object


Dim nextCentury As Date
Try
nextCentury = Microsoft.VisualBasic.DateAdd("yyyy", 100, givenDate)
Catch thisExcep As System.ArgumentOutOfRangeException
' The resulting date/time is later than December 31, 9999.
Catch thisExcep As System.ArgumentException
' At least one argument has an invalid value.
Catch thisExcep As System.InvalidCastException
' The value in givenDate cannot be interpreted as a date/time.
Catch
' An unforeseen exception has occurred.
Finally
' This block is always run before leaving the Try structure.
End Try

The first three Catch blocks handle the exceptions that you can anticipate from the DateAdd Function (Visual Basic). You
can deal with any unexpected exception in the last Catch block.
No matter what happens, the Finally block is always the last code to be run before leaving the Try...Catch...Finally
construction. If you create or open resources such as objects or database connections in a Try or Catch block, you can
use the Finally block to close them and dispose of them, if appropriate.
If the exception variable thisExcep does not appear in a declaration statement such as Dim, the Catch statement with
the As clause serves as a declaration.

See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Run Statements Depending on One or More Conditions
How to: Test for Several Values of an Expression
Concepts
Decision Structures
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts

Loop Structures
Visual Basic loop structures allow you to run one or more lines of code repetitively. You can repeat the statements in a loop
structure until a condition is True, until a condition is False, a specified number of times, or once for each element in a
collection.
The following illustration shows a loop structure that runs a set of statements until a condition becomes true.
Running a set of statements until a condition becomes true

While Loops
The While...End While construction runs a set of statements as long as the condition specified in the While statement is True.
For more information, see While...End While Statement (Visual Basic).
Do Loops
The Do...Loop construction allows you to test a condition at either the beginning or the end of a loop structure. You can also
specify whether to repeat the loop while the condition remains True or until it becomes True. For more information, see
Do...Loop Statement (Visual Basic).
For Loops
The For...Next construction performs the loop a set number of times. It uses a loop control variable, also called a counter, to
keep track of the repetitions. You specify the starting and ending values for this counter, and you can optionally specify the
amount by which it increases from one repetition to the next. For more information, see For...Next Statement (Visual Basic).
For Each Loops
The For Each...Next construction runs a set of statements once for each element in a collection. You specify the loop control
variable, but you do not have to determine starting or ending values for it. For more information, see
For Each...Next Statement (Visual Basic).
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Run Several Statements Repeatedly
How to: Run Several Statements for Each Element in a Collection or Array
How to: Improve the Performance of a Loop
How to: Skip to the Next Iteration of a Loop
Concepts
Decision Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts

How to: Run Several Statements Repeatedly


You can use loop structures to run a block of statements repeatedly. The loop can run an indeterminate number of times,
depending on the Boolean value of a condition, or for a set number of times controlled by a special variable.
Looping an Indeterminate Number of Times
To run a group of statements as long as a condition is True
Use the While...End While Statement (Visual Basic) to specify the condition that controls repetition of the loop. The
following example repeats the statement block as long as number is greater than 6.

Sub checkWhile()
Dim counter As Integer = 0
Dim number As Integer = 10
While number > 6
number -= 1
counter += 1
End While
MsgBox("The loop ran " & counter & " times.")
End Sub

The While statement always checks the condition before it begins the loop. If number had been initialized to 6 instead of
10, the statements inside the loop would never run.
To run a group of statements while a condition remains True
Use the Do...Loop Statement (Visual Basic) and specify the testing condition at either the beginning or the end of the loop.
The placement of the While (Visual Basic) keyword determines where the condition is tested. The following example
illustrates this.

Sub checkWhileFirst()
Dim counter As Integer = 0
Dim number As Integer = 10
Do While number > 6
number -= 1
counter += 1
Loop
MsgBox("The loop ran " & counter & " times.")
End Sub
Sub checkWhileLast()
Dim counter As Integer = 0
Dim number As Integer = 5
Do
number -= 1
counter += 1
Loop While number > 6
MsgBox("The loop ran " & counter & " times.")
End Sub

In the preceding example, the first Do loop runs four times and the second Do loop runs one time.
To run a group of statements until a condition becomes True
Use the Do...Loop construction with the Until keyword instead of While. As with While, the placement of the keyword
determines where the condition is tested. The following example illustrates this.
Sub checkUntilFirst()
Dim counter As Integer = 0
Dim number As Integer = 20
Do Until number = 15
number -= 1
counter += 1
Loop
MsgBox("The loop ran " & counter & " times.")
End Sub
Sub checkUntilLast()
Dim counter As Integer = 0
Dim number As Integer = 20
Do
number -= 1
counter += 1
Loop Until number = 15
MsgBox("The loop ran " & counter & " times.")
End Sub

In the preceding example, each Do loop runs five times.


Looping a Set Number of Times
While and Do loops work well when you do not know in advance how many times you need to run the statements in a loop.
However, when you expect to run the loop a specific number of times, the For...Next Statement (Visual Basic) is a better choice.
Unlike a While or Do loop, a For...Next loop uses a control variable that increases or decreases in value during each repetition
of the loop.
To run a group of statements a set number of times
1. Determine the starting and ending values of the control variable, and use the For statement to specify them.

For i As Integer = 1 To 10

If the control variable is not declared outside the loop, you can use the As clause to declare it as part of the For statement.
2. Use the Step keyword to indicate the amount the control variable should increase for each iteration. It increases by 1
unless you specify otherwise. Use a negative value to cause the control variable to decrease.

For i As Integer = 10 To 1 Step -1

3. Complete the For...Next construction with a Next statement following the last statement to be repeated. You can specify
the control variable in the Next statement.

Function addBackward(ByVal highest As Integer) As Integer


Dim total As Integer = 0
For i As Integer = highest To 1 Step -1
total += i
Next i
Return total
End Function

The preceding example returns the sum of all the whole numbers from 1 through the value passed to the parameter
highest.

See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Run Several Statements for Each Element in a Collection or Array
How to: Improve the Performance of a Loop
How to: Skip to the Next Iteration of a Loop
Reference
For Each...Next Statement (Visual Basic)
Concepts
Decision Structures
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts

How to: Run Several Statements for Each Element in a


Collection or Array
The For Each statement construction is similar to the For...Next loop, but it runs the statement block for each element in a
collection, instead of a specified number of times. A For Each...Next loop uses an element variable that represents a different
element of the collection during each repetition of the loop.
Repeating a Statement Block for a Collection
To run a group of statements for each element in a collection
1. Identify the collection on which to run the statement block, and use the For Each...Next Statement (Visual Basic) to specify
both the element variable and the collection.

For Each thisControl As System.Windows.Forms.Control In thisForm.Contr


ols

If the element variable is not declared outside the loop, you can use the As clause to declare it as part of the For Each
statement.
Visual Basic automatically substitutes a different element of the collection for each iteration.
2. Complete the For Each...Next construction with a Next statement following the last statement to be repeated. You can
specify the element variable in the Next statement.

Sub lightBlueBackground(ByVal thisForm As System.Windows.Forms.Form)


For Each thisControl As System.Windows.Forms.Control In thisForm.Controls
thisControl.BackColor = System.Drawing.Color.LightBlue
Next thisControl
End Sub

You can read the elements of the collection, but you cannot make any changes to the collection itself, such as adding,
deleting, or replacing any element. However, if an element is a reference type, you can access and set its members.
Because each Control element is a reference type, the code in the preceding example can change its BackColor property.
Repeating a Statement Block for an Array
You can also iterate through an array with a For Each...Next loop. However, as with collections, you can only read the array
elements, not change them.
To run a group of statements for each element of an array
1. Use the For Each statement to specify both the element variable and the array. Do not follow the array name with
parentheses.
Visual Basic treats the array the same way it treats a collection.
2. Follow the statement block with a Next statement. You can specify the element variable in the Next statement.
The following procedure is intended to find the sum of the elements of an array and reset each element to zero.

Function sumAndReset(ByRef numbers() As Integer) As Integer


Dim sum As Integer = 0
For Each elt As Integer In numbers
sum += elt
' The following statement works only on the local copy
' of the array, not on the original array.
elt = 0
Next elt
Return sum
End Function

The summation works as intended because it relies only on reading the elements. However, the resetting to zero does
not work as intended, because only the local copy of each element is reset to zero, while the original element is left
unchanged in the original array.
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Run Several Statements Repeatedly
How to: Improve the Performance of a Loop
How to: Skip to the Next Iteration of a Loop
Reference
For...Next Statement (Visual Basic)
Concepts
Decision Structures
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts

How to: Improve the Performance of a Loop


You can optimize the performance of a loop by using the most efficient data types. For a short loop that does not run many
times the difference might be negligible. However, if the loop runs a large number of times, the performance savings could be
considerable.
Integer and UInteger are the most efficient types on current platforms. Short, Long, UShort, and ULong are not as efficient,
and Decimal is considerably slower. For more information, see Numeric Data Types.
To optimize the performance of a For...Next loop
Use the most efficient data type for the control variable. The following example shows some possible variations on a
loop. The absolute timings are dependent on the platform, but the run-time comparisons are still valid.

For fastest As Integer = 0 to 1000000


' Insert statements to execute for each value of fastest.
Next fastest
For notAsFast As Long = 0 to 1000000
' Insert statements to execute for each value of notAsFast.
Next notAsFast
For muchSlower As Decimal = 0 to 1000000
' Insert statements to execute for each value of muchSlower.
Next muchSlower

The first case takes slightly less time to run than the second case. However, Integer can handle values only up to
2,147,483,647, and UInteger only up to 4,294,967,295. The second and third cases can handle larger values, because
both Long and Decimal accept a wider range of integers, but they run more slowly. You might have to make a design
decision between speed and capacity of the data types you use.
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Run Several Statements Repeatedly
How to: Run Several Statements for Each Element in a Collection or Array
How to: Skip to the Next Iteration of a Loop
Reference
For...Next Statement (Visual Basic)
Concepts
Loop Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts

How to: Skip to the Next Iteration of a Loop


If you have completed your processing for the current iteration of a Do, For, or While loop, you can skip immediately to the
next iteration by using a Continue Statement (Visual Basic).
Skipping to the Next Iteration
To skip to the next iteration of a For...Next loop
1. Write the For...Next loop in the normal way.
2. Use Continue For at any place you want to terminate the current iteration and proceed immediately to the next iteration.

Public Function findLargestRatio(ByVal high() As Double, _


ByVal low() As Double) As Double
Dim ratio As Double
Dim largestRatio As Double = Double.MinValue
For counter As Integer = 0 To low.GetUpperBound(0)
If Math.Abs(low(counter)) < System.Double.Epsilon _
Then Continue For
ratio = high(counter) / low(counter)
If Double.IsInfinity(ratio) OrElse Double.IsNaN(ratio) _
Then Continue For
If ratio > largestRatio Then largestRatio = ratio
Next counter
Return largestRatio
End Function

Skipping from Within a Nested Loop


If you have Do, For, or While loops nested one within another, you can skip immediately to the next iteration of any level in
the nesting. This is only true, however, when the loops are of different types. If you have nested loops of the same type, for
example nested While loops, Continue While skips to the next iteration of the innermost While loop.
To skip to the next iteration of a Do loop from within a nested For loop
1. Write the nested loops in the normal way.
2. Use Continue Do at any place that you want to terminate the current iteration of the inner For loop and skip to the next
iteration of the outer Do loop.

Public Sub divideElements(ByRef matrix(,) As Double)


Dim i As Integer = -1
Do Until i > matrix.GetUpperBound(0)
i += 1
For j As Integer = 0 To matrix.GetUpperBound(1)
If matrix(j, j) = 0 Then Continue Do
matrix(i, j) /= matrix(j, j)
Next j
Loop
End Sub

See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Run Several Statements Repeatedly
How to: Run Several Statements for Each Element in a Collection or Array
How to: Improve the Performance of a Loop
Reference
While...End While Statement (Visual Basic)
Do...Loop Statement (Visual Basic)
For...Next Statement (Visual Basic)
Concepts
Loop Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts

Other Control Structures


Visual Basic provides control structures that help you dispose of a resource or reduce the number of times you have to repeat
an object reference.
Using...End Using Construction
The Using...End Using construction establishes a statement block within which you make use of a resource such as a SQL
connection. You can optionally acquire the resource with the Using statement. When you exit the Using block, Visual Basic
automatically disposes of the resource so that it is available for other code to use. The resource must be local and disposable.
For more information, see Using Statement (Visual Basic).
With...End With Construction
The With...End With construction allows you to specify an object reference once and then run a series of statements that
access its members. This can simplify your code and improve performance because Visual Basic does not have to re-establish
the reference for each statement that accesses it. For more information, see With...End With Statement (Visual Basic).
See Also
Tasks
How to: Transfer Control Out of a Control Structure
Reference
Using Statement (Visual Basic)
With...End With Statement (Visual Basic)
Concepts
Decision Structures
Loop Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts

How to: Dispose of a System Resource


You can use a Using block to guarantee that the system disposes of a resource when your code exits the block. This is useful if
you are using a system resource that consumes a large amount of memory, or that other components also want to use.
To dispose of a database connection when your code is finished with it
1. Make sure you include the appropriate Imports Statement for the database connection at the beginning of your source
file (in this case, System.Data.SqlClient).
2. Create a Using block with the Using and End Using statements. Inside the block, put the code that deals with the
database connection.
3. Declare the connection and create an instance of it as part of the Using statement.

' Insert the following line at the beginning of your source file.
Imports System.Data.SqlClient
Public Sub AccessSql(ByVal s As String)
Using sqc As New System.Data.SqlClient.SqlConnection(s)
MsgBox("Connected with string """ & sqc.ConnectionString & """")
End Using
End Sub

The system disposes of the resource no matter how you exit the block, including the case of an unhandled exception.
Note that you cannot access sqc from outside the Using block, because its scope is limited to the block.
You can use this same technique on a system resource such as a file handle or a COM wrapper. You use a Using block
when you want to be sure to leave the resource available for other components after you have exited the Using block.
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Perform Multiple Actions on an Object
Reference
Using Statement (Visual Basic)
SqlConnection
Concepts
Decision Structures
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts

How to: Perform Multiple Actions on an Object


In Visual Basic you must usually specify an object in every statement that calls one of its methods or accesses one of its
properties. However, if you have a series of statements that all operate on the same object, you can use a With...End With
structure to specify the object once for all of the statements. This can make your procedures run faster and help you avoid
repetitive typing.
Example
The following example sets the foreground color and font style of a Label depending on the value of a procedure argument.

Imports draw = System.Drawing


' The preceding statement must appear at the beginning of the source file.
Dim alertLabel As New System.Windows.Forms.Label
Sub alertUser(ByVal value As Long)
With alertLabel
If value = 0 Then
.ForeColor = draw.Color.Red
.Font = New draw.Font(.Font, draw.FontStyle.Bold Or draw.FontStyle.Italic)
Else
.Forecolor = draw.Color.Black
.Font = New draw.Font(.Font, draw.FontStyle.Regular)
End If
End With
End Sub

Note the use of the Or Operator (Visual Basic) to combine font styles. This specifies the desired combination of bit flags. The
And Operator (Visual Basic) would have produced 0 because all the FontStyle enumeration members use different bits.
Note also the use of the Imports Statement to establish the import alias draw, which makes each reference to System.Drawing
members shorter and easier to read.
You can also nest With...End With statements by placing one inside another, as in the following code:
VB
Sub setupForm()
Dim anotherForm As New System.Windows.Forms.Form
Dim button1 As New System.Windows.Forms.Button
With anotherForm
.Show()
.Top = 250
.Left = 250
.ForeColor = System.Drawing.Color.LightBlue
.BackColor = System.Drawing.Color.DarkBlue
.Controls.Add(button1)
With .Controls.Item(1)
.BackColor = System.Drawing.Color.Thistle
.Text = "Text on button1"
End With
End With
End Sub

Within the nested With statement, however, the syntax refers to the nested object; properties of the object in the outer With
statement are not set.
See Also
Tasks
How to: Transfer Control Out of a Control Structure
How to: Dispose of a System Resource
How to: Speed Up Access to an Object with a Long Qualification Path
Reference
With...End With Statement (Visual Basic)
Concepts
Decision Structures
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts

Nested Control Structures


You can place control statements inside other control statements, for example an If...Then...Else block within a For...Next
loop. A control statement placed inside another control statement is said to be nested.
Nesting Levels
Control structures in Visual Basic can be nested to as many levels as you want. It is common practice to make nested structures
more readable by indenting the body of each one. The integrated development environment (IDE) editor automatically does
this.
In the following example, the procedure sumRows adds together the positive elements of each row of the matrix.

Public Sub sumRows(ByVal a(,) As Double, ByRef r() As Double)


Dim i, j As Integer
For i = 0 To UBound(a, 1)
r(i) = 0
For j = 0 To UBound(a, 2)
If a(i, j) > 0 Then
r(i) = r(i) + a(i, j)
End If
Next j
Next i
End Sub

In the preceding example, the first Next statement closes the inner For loop and the last Next statement closes the outer For
loop.
Likewise, in nested If statements, the End If statements automatically apply to the nearest prior If statement. Nested Do loops
work in a similar fashion, with the innermost Loop statement matching the innermost Do statement.
Nesting Different Kinds of Control Structures
You can nest one kind of control structure within another kind. The following example uses a With block inside a For Each
loop and nested If blocks inside the With block.

For Each ctl As System.Windows.Forms.Control In Me.Controls


With ctl
.BackColor = System.Drawing.Color.Yellow
.ForeColor = System.Drawing.Color.Black
If .CanFocus Then
.Text = "Colors changed"
If Not .Focus() Then
' Insert code to process failed focus.
End If
End If
End With
Next ctl

Overlapping Control Structures


You cannot overlap control structures. This means that any nested structure must be completely contained within the next
innermost structure. For example, the following arrangement is invalid because the For loop terminates before the inner With
block terminates.
Invalid nesting of For and With structures

The Visual Basic compiler detects such overlapping control structures and signals a compile-time error.
See Also
Tasks
How to: Transfer Control Out of a Control Structure
Concepts
Decision Structures
Loop Structures
Other Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts

How to: Transfer Control Out of a Control Structure


You can use the Exit Statement (Visual Basic) to exit directly from a control structure. Exit immediately transfers execution to
the statement following the last statement of the control structure. The syntax of the Exit statement specifies which type of
control structure you are transferring out of. The following versions of the Exit statement are possible:
Exit Select
Exit Try
Exit While
Exit Do
Exit For
Exit statements can appear as many times as needed within a control structure that supports them. Exit is useful when a
control structure has done everything it needs to do and does not need to run any more statements.
Control Structures that Do Not Support Exit. You cannot use the Exit statement to transfer out of an If, Using, or With
block. To achieve the same result, you can put a statement label on the block's End statement and transfer to it using a GoTo
statement. For more information on statement labels, see How to: Label Statements.
Example
If an Exit statement is encountered within nested control structures, control passes to the statement following the end of the
innermost structure of the kind specified in the Exit statement. The following example illustrates this.

Public Sub invertElements(ByRef a(,) As Double)


For i As Integer = 0 To UBound(a, 1)
For j As Integer = 0 To UBound(a, 2)
If a(i, j) = 0 Then
' Cannot complete this row; resume outer loop.
Exit For
Else
a(i, j) = 1.0 / a(i, j)
End If
Next j
' Control comes here directly from the Exit For statement.
Next i
End Sub

In the preceding example, the Exit For statement is located in the inner For loop, so it passes control to the statement
following that loop and continues with the outer For loop.
See Also
Tasks
How to: Label Statements
Reference
Exit Statement (Visual Basic)
GoTo Statement
Concepts
Decision Structures
Loop Structures
Other Control Structures
Nested Control Structures
Other Resources
Control Flow in Visual Basic
Visual Basic Language Concepts

Object-Oriented Programming in Visual Basic


Objects are central to Visual Basic programming: Forms and controls are objects. Databases are objects. If you have used Visual
Basic for a while, or if you have worked through the examples in the documentation, then you have already programmed with
objects, but there is a lot more to objects than what you have seen so far.
In the following topics, you will see how easy it is to create your own objects from the classes you define and to use objects to
simplify your coding and increase code reuse.
In This Section
Introduction to Objects in Visual Basic
Provides an introduction to the terms and concepts used in object-oriented programming.
Early and Late Binding
Describes binding, which is performed by the compiler when an object is assigned to an object variable, and the differences
between early-bound and late-bound objects.
Shared Members in Visual Basic
Describes members that can be used without instances.
Creating and Using Objects
Shows how to create and use instances of classes.
Managing Groups of Objects
Provides techniques for working with arrays and collections of objects.
Obtaining Class Information at Run Time
Shows how to determine the class that an object belongs to.
Understanding Classes
Covers object creation and lifetime issues in a step-by-step procedure.
Events in Visual Basic
Shows how to declare and use events.
Delegates in Visual Basic
Shows how to declare and use delegates.
Interfaces in Visual Basic
Describes what interfaces are and how you can use them in your applications.
Inheritance in Visual Basic
Describes how to define classes that serve as the basis for other classes.
Related Sections
Objects in Visual Basic
Describes what objects are and how they are used.
Programming with Components
Demonstrates how you can use Visual Basic to control objects provided by other applications.
Visual Basic Language Concepts

Introduction to Objects in Visual Basic


An object is a structure containing data and methods that manipulate the data. Almost everything you do in Visual Basic is
associated with objects. If you are new to object-oriented programming, the following terms and concepts will help you get
started.
Classes and Objects
The words "class" and "object" are used so much in object-oriented programming that it is easy to get the terms mixed up.
Generally speaking, a class is an abstract representation of something, whereas an object is a usable example of the thing the
class represents. The one exception to this rule is shared class members, which are usable in both instances of a class and
object variables declared as the type of the class.
Fields, Properties, Methods, and Events
Classes are made of fields, properties, methods, and events. Fields and properties represent information that an object
contains. Fields are like variables in that they can be read or set directly. For example, if you have an object named "Car" you
could store its color in a field named "Color."
Properties are retrieved and set like fields, but are implemented using property Get and property Set procedures, which
provide more control on how values are set or returned. The layer of indirection between the value being stored and the
procedures that use this value helps isolate your data and allows you to validate values before they are assigned or retrieved.
Methods represent actions that an object can perform. For example, a "Car" object could have "StartEngine," "Drive," and "Stop"
methods. You define methods by adding procedures, either Sub routines or functions, to your class.
Events are notifications an object receives from, or transmits to, other objects or applications. Events allow objects to perform
actions whenever a specific occurrence takes place. An example of an event for the "Car" class would be a "Check_Engine"
event. Because Microsoft Windows is an event-driven operating system, events can come from other objects, applications, or
user input such as mouse clicks or key presses.
Encapsulation, Inheritance, and Polymorphism
Fields, properties, methods, and events are only one half of the object-oriented programming equation. True object-orient
programming requires objects to support three qualities: encapsulation, inheritance, and polymorphism.
Encapsulation means that a group of related properties, methods, and other members are treated as a single unit or object.
Objects can control how properties are changed and methods are executed. For example, an object can validate values before
allowing property changes. Encapsulation also makes it easier to change your implementation at a latter date by letting you
hide implementation details of your objects, a practice called data hiding.
Inheritance describes the ability to create new classes based on an existing class. The new class inherits all the properties and
methods and events of the base class, and can be customized with additional properties and methods. For example, you can
create a new class named "Truck" based on the "Car" class. The "Truck" class inherits the "Color" property from the "Car" class
and can have additional properties such as "FourWheelDrive."
Polymorphism means that you can have multiple classes that can be used interchangeably, even though each class implements
the same properties or methods in different ways. Polymorphism is essential to object-oriented programming because it
allows you to use items with the same names, no matter what type of object is in use at the moment. For example, given a base
class of "Car," polymorphism enables the programmer to define different "StartEngine" methods for any number of derived
classes. The "StartEngine" method of a derived class named "DieselCar" may be completely different from the method with the
same name in the base class. Other procedures or methods can use the "StartEngine" method of the derived classes in exactly
the same way, no matter what type of "Car" object is being used at the time.
Overloading, Overriding, and Shadowing
Overloading, overriding, and shadowing are similar concepts that can be easy to confuse. Although all three techniques allow
you to create members with the same name, there are some important differences.
Overloaded members are used to provide different versions of a property or method that have the same name, but that
accept different number of parameters, or parameters with different data types.
Overridden properties and methods are used to replace an inherited property or method that is not appropriate in a
derived class. Overridden members must accept the same data type and number of arguments. Derived classes inherit
overridden members.
Shadowed members are used to locally replace a member that has broader scope. Any type can shadow any other type.
For example, you can declare a property that shadows an inherited method with the same name. Shadowed members
cannot be inherited.
See Also
Concepts
Classes: Blueprints for Objects
Overloaded Properties and Methods
Overriding Properties and Methods
Shadowing in Visual Basic
Other Resources
Objects in Visual Basic
Creating and Using Objects
Inheritance in Visual Basic
Visual Basic Language Concepts

Understanding Classes
Classes are important in object-oriented programming because they allow you to group related items as a unit, as well as
control their visibility and accessibility to other procedures. Classes can also inherit and reuse code defined in other classes.
In This Section
Classes: Blueprints for Objects
Provides an overview of encapsulation, inheritance, and shared members.
Walkthrough: Defining Classes
Steps through the process of creating a class.
Classes vs. Modules
Explains the differences between classes and standard modules.
Object Lifetime: How Objects Are Created and Destroyed
Discusses creating and disposing of class instances.
How to: Implement the Dispose Finalize Pattern (Visual Basic)
Explains how to ensure that an object's resources are released when they are no longer needed.
Using Constructors and Destructors
Discusses how to initialize new instances of classes and dispose of resources when they are no longer needed.
Class Properties, Fields, and Methods
Explains the fields, properties, and methods that make up a class.
Related Sections
Creating and Using Objects
Demonstrates how to create and use instances of classes.
Interfaces in Visual Basic
Describes what interfaces are and how to use them in your applications.
Inheritance in Visual Basic
Describes how to define classes that serve as the basis for other classes.
Visual Basic Language Concepts

Classes: Blueprints for Objects


Classes are symbolic representations of objects; classes describe the properties, fields, methods, and events that form objects
in the same way that blueprints describe the items that form buildings. Just as a blueprint can be used to create multiple
buildings, a single class can be used to create as many objects as necessary. Just as a blueprint defines which parts of a
building are accessible to people who use the building, so too can classes control user access to object items through
encapsulation.
Classes and Objects
The terms class and object are sometimes used interchangeably, but in fact, classes describe the structure of objects, while
objects are usable instances of classes. Each instance is an exact yet distinct copy of its class. Because an object is an instance of
a class, the act of creating an object is called instantiation.
Using the blueprint analogy, a class is a blueprint, and an object is a building made from that blueprint. Usually, changing the
data in one object does not change the data in any other object. (The exception is shared members, class members declared
with the Shared modifier, which exist independently of specific instances of a class.)
Encapsulation
Encapsulation is the ability to contain and control access to a group of associated items. Classes provide one of the most
common ways to encapsulate items. In the example below, the BankAccount class encapsulates the methods, fields, and
properties that describe a bank account.
Without encapsulation, you would declare separate procedures and variables to store and manage information for the bank
account, and it would be difficult for you to work with more than one bank account at a time. With encapsulation you can use
the data and procedures in the BankAccount class as a unit. You can work with multiple bank accounts at the same time
without confusion because each account is represented by a unique instance of the class.
Encapsulation also allows you to control how the data and procedures are used. You can use access modifiers, such as Private
or Protected, to prevent outside procedures from executing class methods or reading and modifying data in properties and
fields. You should declare internal details of a class as Private to prevent them from being used outside of your class; this
technique is called data hiding, and is how customer information such as the account balance is protected.
One basic rule of encapsulation is that class data should be modified or retrieved only via Property procedures or methods.
Hiding the implementation details of your classes prevents classes from being used in undesired ways, and lets you to later
modify such items without risk of compatibility problems. For example, later versions of the BankAccount class could change
the data type of the AccountBalance field without breaking other applications that rely on this field having a specific data type.
Inheritance
Like Visual Basic structures, you can use classes to define data types that encapsulate a group of related items. Unlike
structures, however, Visual Basic classes can inherit and extend the characteristics of other classes. Classes that serve as a basis
for new classes are called base classes. Classes derived from base classes are called derived classes. Derived classes inherit all
the fields, properties, methods, and events of the base class. This means you can develop and debug a class once, and then
reuse it as the basis for other classes.
The following example defines a base class that represents a generic bank account, and a specific class that inherits the
properties of the base class but is customized to describe a checking account.
VB
Class BankAccount
Private AccountNumber As String
Private AccountBalance As Decimal
Private HoldOnAccount As Boolean = False
Public Sub PostInterest()
' Add code to calculate the interest for this account.
End Sub
ReadOnly Property Balance() As Decimal
Get
' Return the available balance.
Return AccountBalance
End Get
End Property
End Class
Class CheckingAccount
Inherits BankAccount
Sub ProcessCheck()
' Add code to process a check drawn on this account.
End Sub
End Class

For more information about inheritance, see Inheritance Basics.


Shared Members
By default, class data is specific to each instance of the class, but there may be occasions when you want a single data item to
be shared among all objects created from a class. In such cases, use the Shared modifier to cause a variable to share the same
value in all instances of a class (Shared members are sometimes referred to as "static members" in other programming
languages). You can call shared methods directly using a class name without first creating an instance of the class.
For more information about shared members, see Shared Members in Visual Basic.
Shadowing
Derived classes can use the Shadows keyword to declare a member with the same name as an inherited member. Shadowed
members do not need to be the same data type as the member being shadowed. For example, a property can shadow a
variable of type Integer.
For more information about shared members, see Shadowing in Visual Basic.
See Also
Reference
Shadows
Shared (Visual Basic)
Concepts
Structures and Classes
Inheritance Basics
Shared Members in Visual Basic
Shadowing in Visual Basic
Other Resources
Creating and Using Objects
Inheritance in Visual Basic
Visual Basic Language Concepts

Walkthrough: Defining Classes


This walkthrough demonstrates how to define classes, which you can then use to create objects. It also shows you how to add
properties and methods to the new class, and demonstrates how to initialize an object.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To define a class
1. Create a project by clicking New Project on the File menu. The New Project dialog box appears.
2. Select Windows Application from the list of Visual Basic project templates to display the new project.
3. Add a new class to the project by clicking Add Class on the Project menu. The Add New Item dialog box appears.
4. Select the Class template.
5. Name the new class UserNameInfo.vb, and then click Add to display the code for the new class.
VB
Public Class UserNameInfo
End Class

Note
You can use the Visual Basic Code Editor to add a class to your startup form by typing the Class keyword followed by
the name of the new class. The Code Editor provides a corresponding End Class statement for you.

6. Define a private field for the class by placing the following code between the Class and End Class statements:
VB
Private userNameValue As String

Declaring the field as Private means it can be used only within the class. You can make fields accessible from outside a
class by using access modifiers such as Public that provide greater access. For more information, see
Access Levels in Visual Basic.
7. Define a property for the class by adding the following code:
VB
Public Property UserName() As String
Get
' Gets the property value.
Return userNameValue
End Get
Set(ByVal Value As String)
' Sets the property value.
userNameValue = Value
End Set
End Property
8. Define a method for the class by adding the following code:
VB
Public Sub Capitalize()
' Capitalize the value of the property.
userNameValue = UCase(userNameValue)
End Sub

9. Define a parameterized constructor for the new class by adding a procedure named Sub New:

VB
Public Sub New(ByVal UserName As String)
' Set the property value.
Me.UserName = UserName
End Sub

The Sub New constructor is called automatically when an object based on this class is created. This constructor sets the
value of the field that holds the user name.

To create a button to test the class


1. Change the startup form to design mode by right-clicking its name in Solution Explorer, and then clicking View
Designer. The startup form for Windows Application projects is named Form1.vb by default. The main form will then
appear.
2. Add a button to the main form and double-click it to display the code for the Button1_Click event handler. Add the
following code to call the test procedure:
VB
' Create an instance of the class.
Dim user As New UserNameInfo("Moore, Bobby")
' Capitalize the value of the property.
user.Capitalize()
' Display the value of the property.
MsgBox("The original UserName is: " & user.UserName)
' Change the value of the property.
user.UserName = "Worden, Joe"
' Redisplay the value of the property.
MsgBox("The new UserName is: " & user.UserName)

To run your application


1. Run your application by pressing F5. Click the button on the form to call the test procedure. It displays a message stating
that the original UserName is "MOORE, BOBBY", because the procedure called the object's Capitalize method.
2. Click OK to dismiss the message box. The Button1 Click procedure changes the value of the UserName property, and
displays a message stating that the new value of UserName is "Worden, Joe".
See Also
Tasks
How to: Add Events to a Class
Reference
Imports Statement
Concepts
Classes vs. Modules
Other Resources
Understanding Classes
Class Properties, Fields, and Methods
Visual Basic Language Concepts

Classes vs. Modules


Both classes and modules are reference types that encapsulate the items defined within, but they differ in how items are
accessed from other procedures.
Differences Between Classes and Modules
The main difference between classes and modules is that classes can be instantiated as objects while standard modules cannot.
Because there is only one copy of a standard module's data, when one part of your program changes a public variable in a
standard module, any other part of the program gets the same value if it then reads that variable. In contrast, object data exists
separately for each instantiated object. Another difference is that unlike standard modules, classes can implement interfaces.
Note
When the Shared modifier is applied to a class member, it is associated with the class itself instead of a particular instance of
the class. The member is accessed directly by using the class name, the same way module members are accessed. For more i
nformation about shared members, see Shared Members in Visual Basic.

Classes and modules also use different scopes for their members. Members defined within a class are scoped within a specific
instance of the class and exist only for the lifetime of the object. To access class members from outside a class, you must use
fully qualified names in the format of Object.Member.
On the other hand, members declared within a module are publicly accessible by default, and can be accessed by any code that
can access the module. This means that variables in a standard module are effectively global variables because they are visible
from anywhere in your project, and they exist for the life of the program.
See Also
Reference
Shared (Visual Basic)
Concepts
Structures and Classes
Shared Members in Visual Basic
Other Resources
Understanding Classes
Visual Basic Language Concepts

Object Lifetime: How Objects Are Created and Destroyed


An instance of a class, an object, is created by using the New keyword. Initialization tasks often must be performed on new
objects before they are used. Common initialization tasks include opening files, connecting to databases, and reading values of
registry keys. Microsoft Visual Basic 2005 controls the initialization of new objects using procedures called constructors (special
methods that allow control over initialization).
After an object leaves scope, it is released by the common language runtime (CLR). Visual Basic 2005 controls the release of
system resources using procedures called destructors. Together, constructors and destructors support the creation of robust
and predictable class libraries.
Sub New and Sub Finalize
The Sub New and Sub Finalize procedures in Visual Basic 2005 initialize and destroy objects; they replace the
Class_Initialize and Class_Terminate methods used in Visual Basic 6.0 and earlier versions. Unlike Class_Initialize, the Sub
New constructor can run only once when a class is created. It cannot be called explicitly anywhere other than in the first line of
code of another constructor from either the same class or from a derived class. Furthermore, the code in the Sub New method
always runs before any other code in a class. Visual Basic 2005 implicitly creates a Sub New constructor at run time if you do
not explicitly define a Sub New procedure for a class.
Before releasing objects, the CLR automatically calls the Finalize method for objects that define a Sub Finalize procedure. The
Finalize method can contain code that needs to execute just before an object is destroyed, such as code for closing files and
saving state information. There is a slight performance penalty for executing Sub Finalize, so you should define a Sub
Finalize method only when you need to release objects explicitly.
Note
The garbage collector in the CLR does not (and cannot) dispose of unmanaged objects, objects that the operating system exe
cutes directly, outside the CLR environment. This is because different unmanaged objects must be disposed of in different wa
ys. That information is not directly associated with the unmanaged object; it must be found in the documentation for the obje
ct. A class that uses unmanaged objects must dispose of them in its Finalize method.

The Finalize destructor is a protected method that can be called only from the class it belongs to, or from derived classes. The
system calls Finalize automatically when an object is destroyed, so you should not explicitly call Finalize from outside of a
derived class's Finalize implementation.
Unlike Class_Terminate, which executes as soon as an object is set to nothing, there is usually a delay between when an object
loses scope and when Visual Basic 2005 calls the Finalize destructor. Visual Basic 2005 allows for a second kind of destructor,
Dispose, which can be explicitly called at any time to immediately release resources.
Note
A Finalize destructor should not throw exceptions, because they cannot be handled by the application and can cause the app
lication to terminate.

IDisposable Interface
Class instances often control resources not managed by the CLR, such as Windows handles and database connections. These
resources must be disposed of in the Finalize method of the class, so that they will be released when the object is destroyed
by the garbage collector. However, the garbage collector destroys objects only when the CLR requires more free memory. This
means that the resources may not be released until long after the object goes out of scope.
To supplement garbage collection, your classes can provide a mechanism to actively manage system resources if they
implement the IDisposable interface. IDisposable has one method, Dispose, which clients should call when they finish using
an object. You can use the Dispose method to immediately release resources and perform tasks such as closing files and
database connections. Unlike the Finalize destructor, the Dispose method is not called automatically. Clients of a class must
explicitly call Dispose when you want to immediately release resources.
Implementing IDisposable
A class that implements the IDisposable interface should include these sections of code:
A field for keeping track of whether the object has been disposed:
Protected disposed As Boolean = False

An overload of the Dispose that frees the class's resources. This method should be called by the Dispose and Finalize
methods of the base class:

Protected Overridable Sub Dispose(ByVal disposing As Boolean)


If Not Me.disposed Then
If disposing Then
' Insert code to free unmanaged resources.
End If
' Insert code to free shared resources.
End If
Me.disposed = True
End Sub

An implementation of Dispose that contains only the following code:

Public Sub Dispose() Implements IDisposable.Dispose


Dispose(True)
GC.SuppressFinalize(Me)
End Sub

An override of the Finalize method that contains only the following code:

Protected Overrides Sub Finalize()


Dispose(False)
MyBase.Finalize()
End Sub

Deriving from a Class that Implements IDisposable


A class that derives from a base class that implements the IDisposable interface does not need to override any of the base
methods unless it uses additional resources that need to be disposed. In that situation, the derived class should override the
base class's Dispose(disposing) method to dispose of the derived class's resources. This override must call the base class's
Dispose(disposing) method.

Protected Overrides Sub Dispose(ByVal disposing As Boolean)


If Not Me.disposed Then
If disposing Then
' Insert code to free unmanaged resources.
End If
' Insert code to free shared resources.
End If
MyBase.Dispose(disposing)
End Sub

A derived class should not override the base class's Dispose and Finalize methods. When those methods are called from an
instance of the derived class, the base class's implementation of those methods call the derived class's override of the
Dispose(disposing) method.
Visualization
The following diagram shows which methods are inherited and which methods are overridden in the derived class.
When this Dispose Finalize pattern is followed, the resources of the derived class and base class are correctly disposed. The
following diagram shows which methods get called when the classes are disposed and finalized.

Garbage Collection and the Finalize Destructor


The .NET Framework uses the reference-tracing garbage collection system to periodically release unused resources. Visual
Basic 6.0 and earlier versions used a different system called reference counting to manage resources. Although both systems
perform the same function automatically, there are a few important differences.
The CLR periodically destroys objects when the system determines that such objects are no longer needed. Objects are
released more quickly when system resources are in short supply, and less frequently otherwise. The delay between when an
object loses scope and when the CLR releases it means that, unlike with objects in Visual Basic 6.0 and earlier versions, you
cannot determine exactly when the object will be destroyed. In such a situation, objects are said to have non-deterministic
lifetime. In most cases, non-deterministic lifetime does not change how you write applications, as long as you remember that
the Finalize destructor may not immediately execute when an object loses scope.
Another difference between the garbage-collection systems involves the use of Nothing. To take advantage of reference
counting in Visual Basic 6.0 and earlier versions, programmers sometimes assigned Nothing to object variables to release the
references those variables held. If the variable held the last reference to the object, the object's resources were released
immediately. In Visual Basic 2005, while there may be cases in which this procedure is still valuable, performing it never causes
the referenced object to release its resources immediately. To release resources immediately, use the object's Dispose method,
if available. The only time you should set a variable to Nothing is when its lifetime is long relative to the time the garbage
collector takes to detect orphaned objects.
See Also
Tasks
How to: Implement the Dispose Finalize Pattern (Visual Basic)
Reference
Using Constructors and Destructors
New (Visual Basic)
Nothing (Visual Basic)
Dispose
Concepts
Initialization and Termination of Components
Finalize Methods and Destructors
Other Resources
Language Changes for Visual Basic 6.0 Users
Visual Basic Language Concepts

How to: Implement the Dispose Finalize Pattern (Visual Basic)


The Dispose Finalize pattern ensures that resources are released when the object is no longer needed.
Example
The ResourceClass class in the following example utilizes managed and unmanaged resources and then uses the Dispose
Finalize pattern to dispose of them properly. The resources and their functions are:
The implementation of the Dispose method, which allows users of the class to dispose of class instances. This method
calls Dispose(True) to dispose of the object's resources, and then calls SuppressFinalize to prevent the finalization code
from executing a second time.
The override of the base Finalize method, which allows the common language runtime (CLR) garbage collector to
dispose of class instances. This method calls Dispose(False) to dispose of the object's resources. Notice that if Dispose
was called previously for the object, its call to SuppressFinalize would prevent the garbage collector from calling the
Finalize method.
The overload of the Dispose method, which does the disposing work. It takes a Boolean parameter, disposing, which
indicates whether your code initiated the object's disposal. When you dispose of an object, all of its resources must be
disposed of. When the CLR garbage collector disposes of an object, only the unmanaged resources must be disposed of;
the garbage collector automatically disposes of the managed resources when necessary.
For more information, see Object Lifetime: How Objects Are Created and Destroyed.
VB
Public Class ResourceClass
Implements IDisposable

Private managedResource As System.ComponentModel.Component


Private unmanagedResource As IntPtr
Protected disposed As Boolean = False

Public Sub New()


' Insert appropriate constructor code here.
End Sub

Protected Overridable Overloads Sub Dispose( _


ByVal disposing As Boolean)
If Not Me.disposed Then
If disposing Then
managedResource.Dispose()
End If
' Add code here to release the unmanaged resource.
unmanagedResource = IntPtr.Zero
' Note that this is not thread safe.
End If
Me.disposed = True
End Sub

Public Sub AnyOtherMethods()


If Me.disposed Then
Throw New ObjectDisposedException(Me.GetType().ToString, _
"This object has been disposed.")
End If
End Sub
#Region " IDisposable Support "
' Do not change or add Overridable to these methods.
' Put cleanup code in Dispose(ByVal disposing As Boolean).
Public Overloads Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Protected Overrides Sub Finalize()
Dispose(False)
MyBase.Finalize()
End Sub
#End Region
End Class

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
Access to the members of the System and System.ComponentModel namespaces. Add an Imports statement if you are
not fully qualifying member names in your code. For more information, see Imports Statement.
These changes must be made in the code:
Replace ResourceClass with the name of the class that implements IDisposable.
Use the test in AnyOtherMethods in any methods using resources that may have been disposed of.
Replace the managedResource declaration with declarations of any managed objects in your class that need to be
disposed of. If a class implements IDisposable or has a Close method, it probably needs to be disposed of. In the
Dispose method, close or dispose of these objects.
Replace the unManagedResource declaration with declarations of unmanaged objects in your class that need to be
disposed of. The method for disposing of these objects depends on how the object is defined. For details, consult the
documentation on the object.

Robust Programming
Once the Dispose method has been called, contained objects in your collection will not be valid. You should test the disposed
field before performing any operations on your object. For an example, see the AnyOtherMethods method in the code example.
See Also
Reference
IDisposable
Concepts
Implementing a Dispose Method
Other Resources
Garbage Collection
Visual Basic Language Concepts

Using Constructors and Destructors


Constructors and destructors control the creation and destruction of objects.
Constructors
To create a constructor for a class, create a procedure named Sub New anywhere in the class definition. To create a
parameterized constructor, specify the names and data types of arguments to Sub New just as you would specify arguments
for any other procedure, as in the following code:
VB
Sub New(ByVal s As String)

Constructors are frequently overloaded, as in the following code:


VB
Sub New(ByVal s As String, i As Integer)

When you define a class derived from another class, the first line of a constructor must be a call to the constructor of the base
class, unless the base class has an accessible constructor that takes no parameters. A call to the base class containing the above
constructor, for example, would be MyBase.New(s). Otherwise, MyBase.New is optional, and the Visual Basic runtime calls it
implicitly.
After writing code to call the parent object's constructor, you can add any additional initialization code to the Sub New
procedure. Sub New can accept arguments when called as a parameterized constructor. These parameters are passed from
the procedure calling the constructor, for example, Dim AnObject As New ThisClass(X).
Destructors
The following code shows how to use Dispose and Finalize to release resources in a base class.
Note
You should follow the guidelines for implementing IDisposable set out in
Object Lifetime: How Objects Are Created and Destroyed.

VB
' Design pattern for a base class.
Public Class Base
Implements IDisposable
' Keep track of when the object is disposed.
Protected disposed As Boolean = False

' This method disposes the base object's resources.


Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposed Then
If disposing Then
' Insert code to free unmanaged resources.
End If
' Insert code to free shared resources.
End If
Me.disposed = True
End Sub

#Region " IDisposable Support "


' Do not change or add Overridable to these methods.
' Put cleanup code in Dispose(ByVal disposing As Boolean).
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Protected Overrides Sub Finalize()
Dispose(False)
MyBase.Finalize()
End Sub
#End Region
End Class

The following code shows how to use Dispose and Finalize to release resources in a derived class.
VB
' Design pattern for a derived class.
Public Class Derived
Inherits Base
' This method disposes the derived object's resources.
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposed Then
If disposing Then
' Insert code to free unmanaged resources.
End If
' Insert code to free shared resources.
End If
MyBase.Dispose(disposing)
End Sub

' The derived class does not have a Finalize method


' or a Dispose method with parameters because it inherits
' them from the base class.
End Class

The following code shows a common design pattern for the Dispose destructor, using a Using block and an equivalent
Try...Finally block.
VB
Sub DemonstrateUsing()
Using d As New Derived
' Code to use the Derived object goes here.
End Using
End Sub

Sub DemonstrateTry()
Dim d As Derived = Nothing
Try
d = New Derived
' Code to use the Derived object goes here.
Finally
' Call the Dispose method when done, even if there is an exception.
If Not d Is Nothing Then
d.Dispose()
End If
End Try
End Sub

The next example creates an object using a parameterized constructor, and then calls destructors when the object is no longer
needed.
Note
Although this example uses Collect to demonstrate which methods the garbage collector calls to dispose methods, in general
you should let the common language runtime (CLR) manage garbage collection.
VB
Sub TestConstructorsAndDestructors()
' Demonstrate how the Using statement calls the Dispose method.
Using AnObject As New ThisClass(6)
' Place statements here that use the object.
MsgBox("The value of ThisProperty after being initialized " & _
" by the constructor is " & AnObject.ThisProperty & ".")
End Using
' Demonstrate how the garbage collector calls the Finalize method.
Dim AnObject2 As New ThisClass(6)
AnObject2 = Nothing
GC.Collect()
End Sub

Public Class BaseClass


Sub New()
MsgBox("BaseClass is initializing with Sub New.")
End Sub

Protected Overrides Sub Finalize()


MsgBox("BaseClass is shutting down with Sub Finalize.")
' Place final cleanup tasks here.
MyBase.Finalize()
End Sub
End Class

Public Class ThisClass


Inherits BaseClass
Implements IDisposable

Sub New(ByVal SomeValue As Integer)


' Call MyBase.New if this is a derived class.
MyBase.New()
MsgBox("ThisClass is initializing with Sub New.")
' Place initialization statements here.
ThisPropertyValue = SomeValue
End Sub

Private ThisPropertyValue As Integer


Property ThisProperty() As Integer
Get
CheckIfDisposed()
ThisProperty = ThisPropertyValue
End Get
Set(ByVal Value As Integer)
CheckIfDisposed()
ThisPropertyValue = Value
End Set
End Property

Protected Overrides Sub Finalize()


MsgBox("ThisClass is shutting down with Sub Finalize.")
Dispose(False)
End Sub

' Do not add Overridable to this method.


Public Overloads Sub Dispose() Implements IDisposable.Dispose
MsgBox("ThisClass is shutting down with Sub Dispose.")
Dispose(True)
GC.SuppressFinalize(Me)
End Sub

Private disposed As Boolean = False


Public Sub CheckIfDisposed()
If Me.disposed Then
Throw New ObjectDisposedException(Me.GetType().ToString, _
"This object has been disposed.")
End If
End Sub

Protected Overridable Overloads Sub Dispose( _


ByVal disposing As Boolean)
MsgBox("ThisClass is shutting down with the Sub Dispose overload.")
' Place final cleanup tasks here.
If Not Me.disposed Then
If disposing Then
' Dispose of any managed resources.
End If
' Dispose of any unmanaged resource.

' Call MyBase.Finalize if this is a derived class,


' and the base class does not implement Dispose.
MyBase.Finalize()
End If
Me.disposed = True
End Sub

End Class

When you run this example, the class ThisClass calls the Sub New constructor of the class BaseClass. After the constructor in
the base class is finished, the class ThisClass runs the remaining statements in Sub New that initialize a value for the property
ThisProperty.

When the class is no longer needed, the Dispose destructor is called in ThisClass.
This example displays the following:
BaseClass is initializing with Sub New.
ThisClass is initializing with Sub New.
The value of ThisProperty after being initialized by the constructor is 6.
ThisClass is shutting down with Sub Dispose.
ThisClass is shutting down with the Sub Dispose overload.
BaseClass is shutting down with Sub Finalize.
BaseClass is initializing with Sub New.
ThisClass is initializing with Sub New.
ThisClass is shutting down with Sub Finalize.
ThisClass is shutting down with the Sub Dispose overload.
BaseClass is shutting down with Sub Finalize.

See Also
Reference
Dispose
Concepts
Object Lifetime: How Objects Are Created and Destroyed
Finalize Methods and Destructors
How New and Finalize Methods Work in a Class Hierarchy
Visual Basic Language Concepts

Class Properties, Fields, and Methods


In general, fields and properties represent information about an object, whereas methods represent actions an object can take.
The following topics describe the mechanisms for adding properties, fields, and methods to classes, and address issues
associated with these items.
In This Section
How to: Add Fields and Properties to a Class
Provides information on declaring fields and properties.
Properties and Property Procedures
Explains how Property procedures work, and how to implement common property types.
Property Procedures vs. Fields
Helps you decide when to use fields to store data in a class, and when properties are a better choice.
Class Methods
Discusses the public procedures you add to your class.
Properties vs. Methods
Helps you decide whether your desired functionality is best implemented as a property or a method.
Default Properties
Discusses properties used when no specific property is named.
Overloaded Properties and Methods
Covers how to define multiple properties or methods with the same name, but work with different data types.
Overriding Properties and Methods
Discusses redefining an inherited property or method.
Related Sections
Creating and Using Objects
Demonstrates how to create and use instances of classes.
Events in Visual Basic
Demonstrates how to declare and use events.
Delegates in Visual Basic
Demonstrates how to declare and use delegates.
Managing Your Objects with Collections
Provides information on using collections to store and retrieve objects.
Visual Basic Language Concepts

How to: Add Fields and Properties to a Class


You can use both fields and properties to store information in an object. Although fields and properties are almost
indistinguishable from a client-application perspective, they are declared differently within a class. Whereas fields are simply
public variables that a class exposes, properties use Property procedures to control how values are set or returned.
To add a field to a class
Declare a public variable in the class definition, as in the following code:
VB
Class ThisClass
Public ThisField As String
End Class

To add a property to a class


1. Declare a local variable within the class to store the property value. This step is necessary because properties do not
allocate any storage on their own. To protect their values from direct modification, variables used to store property
values should be declared as Private.
2. Preface property declarations with modifiers, such as Public and Shared, as appropriate. Use the Property keyword to
declare the property name, and declare the data type that the property stores and returns.
3. Define Get and Set property procedures within the property definition. Get property procedures are used to return the
value of a property and are roughly equivalent to functions in syntax. They accept no arguments and can be used to
return the value of private local variables declared within the class used to store the property value. Set property
procedures are used to set the value of a property; they have a parameter, usually called Value, with the same data type
as the property itself. Whenever the value of the property is changed, Value is passed to the Set property procedure,
where it can be validated and stored in a local variable.
4. Terminate Get and Set property procedures with End Get and End Set statements as appropriate.
5. Terminate the property block with an End Property statement.
Note
If you are working within the Visual Studio integrated development environment (IDE), you can direct it to create empt
y Get and Set property procedures. Type Property PropName As DataType (where PropName is the name of your pr
operty, and DataType is a specific data type, such as Integer), and the property procedures appear in the Code Editor.

The following example declares a property in a class:


VB
Class ThisClass
Private m_PropVal As String
Public Property One() As String
Get
' Return the value stored in the local variable.
Return m_PropVal
End Get
Set(ByVal Value As String)
' Store the value in a local variable.
m_PropVal = Value
End Set
End Property
End Class
When you create an instance of ThisClass and set the value of the property One, the Set property procedure is called and
the value is passed in the Value parameter, which is stored in a local variable named m_PropVal. When the value of this
property is retrieved, the Get property procedure is called like a function and returns the value stored in the local variable
m_PropVal.

See Also
Tasks
How to: Add Events to a Class
Reference
Property Statement
Public (Visual Basic)
Shared (Visual Basic)
Concepts
Properties and Property Procedures
Visual Basic Language Concepts

Properties and Property Procedures


You can use both properties and fields to store information in an object. Whereas fields are simply public variables, properties
use property procedures to control how values are set or returned. Property procedures are blocks of code declared within
property definitions that you can use to execute code when a property value is set or retrieved.
Visual Basic has two types of property procedures: the Get property procedures for retrieving a property value, and the Set
property procedures for assigning a value to a property. For example, a property that stores the balance of a bank account
might use code in a Get property procedure to post interest and check for service fees before returning the available balance.
You could then use the Set property procedure to validate the balance and prevent it from being incorrectly updated. In short,
property procedures allow an object to protect and validate its own data.
The following code fragment compares how fields and properties validate values.
VB
Protected Sub TestFieldsAndProperties()
' Assume, for this example, that the only valid values for
' the field and property are numbers less than 10.
Dim NewClass As New ThisClass

' Test data validation.

' Works because there is no data validation.


NewClass.ThisField = 36
' Will print 36.
MsgBox("ThisField = " & NewClass.ThisField)

' The attempt to set the field to a value greater than 10 will silently fail.
NewClass.ThisProperty = 36
' The next statement will print the old value of 0 instead.
MsgBox("ThisProperty = " & NewClass.ThisProperty)
End Sub

Public Class ThisClass


' Declare a field.
Public ThisField As Integer
' Field used for Property Set operations.
Private thisPropertyValue As Integer = 0
' Declare a property.
Public Property ThisProperty() As Integer
Get
Return thisPropertyValue
End Get
Set(ByVal Value As Integer)
' Only allow Set operation for values less than 10.
If Value < 10 Then thisPropertyValue = Value
End Set
End Property
End Class

The procedure TestFieldsAndProperties creates an instance of the class and sets and retrieves the values of the fields and
properties. For the sake of this example, it is assumed that the only valid values are numbers less than 10. Because there is no
way to validate values assigned to fields, setting the field to value 36 is allowed. The property, however, only performs
assignment for numbers less than 10, so the attempt to set it to 36 is ignored.
Read-Only and Write-Only Properties
Most properties have both Get and Set property procedures you can use to read and modify the value stored inside. However,
you can use the ReadOnly or WriteOnly modifiers to restrict properties from being modified or read.
Read-only properties cannot have Set property procedures; such properties are useful for items that you want to expose, but
not allow to be modified. For example, you could use a read-only property to provide the processor speed of a computer.
Write-only properties cannot have Get property procedures and are useful for configuring objects with data that should not or
cannot be stored in the object. For example, a write-only property could be used to take a password and change the object's
state without storing the password.
Note
Previous versions of Visual Basic support Let property procedures for use when assigning objects to properties. Visual Basic
eliminates the need for Let property procedures because object assignment is handled like any other kind of assignment.

See Also
Reference
Get Statement
Set Statement (Visual Basic)
ReadOnly (Visual Basic)
WriteOnly
Concepts
Property Procedures
Property Procedures vs. Fields
Visual Basic Language Concepts

Property Procedures vs. Fields


Properties and fields both store and retrieve information in an object. Their similarity can make it difficult to determine which is
a better programming choice in a given case.
Use property procedures when:
You need to control when and how a value is set or retrieved.
The property has a well-defined set of values that need to be validated.
Setting the value causes some perceptible change in the object's state, such as an IsVisible property.
Setting the property causes changes to other internal variables or to the values of other properties.
A set of steps must be performed before the property can be set or retrieved.
Use fields when:
The value is of a self-validating type. For example, an error or automatic data conversion occurs if a value other than
True or False is assigned to a Boolean variable.
Any value in the range supported by the data type is valid. This is true of many properties of type Single or Double.
The property is a String data type, and there is no constraint on the size or value of the string.
See Also
Concepts
Classes vs. Modules
Properties and Property Procedures
Data Types in Visual Basic
Visual Basic Language Concepts

Class Methods
The methods of a class are just Sub or Function procedures declared within the class. For example, to create a Withdrawal
method for a class named Account, you could add this Public function to the class module:
VB
Public Function WithDrawal(ByVal Amount As Decimal, _
ByVal TransactionCode As Byte) As Double
' Add code here to perform the withdrawal,
' return a transaction code,
' or to raise an overdraft error.
End Function

Shared Methods
Shared methods can be invoked directly from the class without first creating an instance of the class. Shared methods are
useful when you do not want a method to be associated with a specific instance of a class. Shared methods cannot be declared
using the Overridable, NotOverridable, or MustOverride modifiers. Methods declared in modules are implicitly shared and
cannot explicitly use the Shared modifier.
Example
VB
Class ShareClass
Shared Sub SharedSub()
MsgBox("Shared method.")
End Sub
End Class

Sub Test()
' Call the method.
ShareClass.SharedSub()
End Sub

Protecting Implementation Details


Utility procedures that are used internally by a class should be declared as Private, Protected, or Friend. Restricting the
accessibility of such methods protects the developers who use your objects, by allowing you to make future changes without
affecting code that uses the objects.
Protecting the details of an object's implementation is another facet of encapsulation. Encapsulation allows you to enhance the
performance of methods, or completely change the way a method is implemented, without having to change code that uses
the method.
See Also
Tasks
How to: Add Events to a Class
Reference
Overridable
NotOverridable
MustOverride
Shared (Visual Basic)
Public (Visual Basic)
Private (Visual Basic)
Protected (Visual Basic)
Friend (Visual Basic)
Concepts
Properties vs. Methods
Shared Members in Visual Basic
Visual Basic Language Concepts

Properties vs. Methods


Properties and methods are similar in that both are implemented as procedures that accept arguments. In general, properties
store data for an object, and methods are actions an object can be asked to perform. Some object characteristics are obviously
properties, such as Name, and some are obviously methods, such as Move and Show. In other cases, it is not obvious which class
members should be properties and which should be methods. For example, the Item method of a collection class stores and
retrieves data and can be implemented as an indexed property. On the other hand, it is also reasonable to implement Item as a
method.
Property Syntax vs. Method Syntax
One way to decide how to implement a class member is to consider how you want it to be used. Although the syntax for
retrieving information from a parameterized property is almost identical to the syntax used with a method implemented as a
function, the syntax for modifying such a value is slightly different. For example, if you implement the member of a class as a
property, then the following syntax describes how it would be used:
ThisObject.ThisProperty(Index) = NewValue
If you implement the class member as a method, then the value being modified must be an argument. The following code
fragment describes equivalent syntax usage:
ThisObject.ThisProperty(Index, NewValue)
Error Messages
Another factor to consider when choosing how to implement a class member is what kind of messages will be generated when
your class is used incorrectly. If someone accidentally attempts to assign a value to a read-only property, a different error
message is returned than in response to a similar call to a method. Correctly implemented class members return error
messages that are easier to interpret.
See Also
Tasks
How to: Add Fields and Properties to a Class
Reference
Item Property (Collection Object)
Concepts
Class Methods
Visual Basic Language Concepts

Default Properties
A property that accepts arguments can be declared as the default property for a class. A default property is the property that
Visual Basic will use when no specific property has been named for an object. Default properties are useful because they allow
you to make your source code more compact by omitting frequently used property names.
The best candidates for default properties are those properties that accept parameters and that you think will be used the most
often. For example, the Item property is a good choice for the default property of a collection class because it is used
frequently.
The following rules apply to default properties:
A type can have only one default property, including properties inherited from a base class. There is one exception to this
rule. A default property defined in a base class can be shadowed by another default property in a derived class.
If a default property from a base class is shadowed by a non-default property in a derived class, the default property is
still accessible using default property syntax.
A default property may not be Shared or Private.
If an overloaded property is a default property, all overloaded properties with that same name must also specify Default.
Default properties must accept at least one argument.
Example
The following example declares a property that contains an array of strings as the default property for a class:
VB
Class Class2
' Define a local variable to store the property value.
Private PropertyValues As String()
' Define the default property.
Default Public Property Prop1(ByVal Index As Integer) As String
Get
Return PropertyValues(Index)
End Get
Set(ByVal Value As String)
If PropertyValues Is Nothing Then
' The array contains Nothing when first accessed.
ReDim PropertyValues(0)
Else
' Re-dimension the array to hold the new element.
ReDim Preserve PropertyValues(UBound(PropertyValues) + 1)
End If
PropertyValues(Index) = Value
End Set
End Property
End Class

Accessing Default Properties


You can access default properties using abbreviated syntax. For example, the following code fragment uses both standard and
default property syntax:
VB
Dim C As New Class2
' The first two lines of code access a property the standard way.
' Property assignment.
C.Prop1(0) = "Value One"
' Property retrieval.
MsgBox(C.Prop1(0))
' The following two lines of code use default property syntax.
' Property assignment.
C(1) = "Value Two"
' Property retrieval.
MsgBox(C(1))

See Also
Reference
Default (Visual Basic)
Concepts
Upgrade Recommendation: Resolve Parameterless Default Properties
Default Property Changes for Visual Basic 6.0 Users
Visual Basic Language Concepts

Overloaded Properties and Methods


Overloading is the creation of more than one procedure, instance constructor, or property in a class with the same name but
different argument types.
Overloading Usage
Overloading is especially useful when your object model dictates that you employ identical names for procedures that operate
on different data types. For example, a class that can display several different data types could have Display procedures that
look like this:
VB
Overloads Sub Display(ByVal theChar As Char)
' Add code that displays Char data.
End Sub
Overloads Sub Display(ByVal theInteger As Integer)
' Add code that displays Integer data.
End Sub
Overloads Sub Display(ByVal theDouble As Double)
' Add code that displays Double data.
End Sub

Without overloading, you would need to create distinct names for each procedure, even though they do the same thing, as
shown next:
VB
Sub DisplayChar(ByVal theChar As Char)
' Add code that displays Char data.
End Sub
Sub DisplayInt(ByVal theInteger As Integer)
' Add code that displays Integer data.
End Sub
Sub DisplayDouble(ByVal theDouble As Double)
' Add code that displays Double data.
End Sub

Overloading makes it easier to use properties or methods because it provides a choice of data types that can be used. For
example, the overloaded Display method discussed previously can be called with any of the following lines of code:
VB
' Call Display with a literal of type Char.
Display("9"c)
' Call Display with a literal of type Integer.
Display(9)
' Call Display with a literal of type Double.
Display(9.9R)

At run time, Visual Basic calls the correct procedure based on the data types of the parameters you specify.
Note
Overloading, overriding, and shadowing are similar concepts that can be easy to confuse. For more information, see
Introduction to Objects in Visual Basic.

Overloading Rules
You create an overloaded member for a class by adding two or more properties or methods with the same name. Except for
overloaded derived members, each overloaded member must have different parameter lists, and the following items cannot be
used as a differentiating feature when overloading a property or procedure:
Modifiers, such as ByVal or ByRef, that apply to a member, or parameters of the member.
Names of parameters
Return types of procedures
The Overloads keyword is optional when overloading, but if any overloaded member uses the Overloads keyword, then all
other overloaded members with the same name must also specify this keyword.
Derived classes can overload inherited members with members that have identical parameters and parameter types, a process
known as shadowing by name and signature. If the Overloads keyword is used when shadowing by name and signature, the
derived class's implementation of the member will be used instead of the implementation in the base class, and all other
overloads for that member will be available to instances of the derived class.
If the Overloads keyword is omitted when overloading an inherited member with a member that has identical parameters and
parameter types, then the overloading is called shadowing by name. Shadowing by name replaces the inherited
implementation of a member, and it makes all other overloads unavailable to instances of the derived class and its decedents.
The Overloads and Shadows modifiers cannot both be used with the same property or method.
Example
The following example creates overloaded methods that accept either a String or Decimal representation of a dollar amount
and return a string containing the sales tax.
To use this example to create an overloaded method
1. Open a new project and add a class named TaxClass.
2. Add the following code to the TaxClass class.
VB
Public Class TaxClass
Overloads Function TaxAmount(ByVal decPrice As Decimal, _
ByVal TaxRate As Single) As String
TaxAmount = "Price is a Decimal. Tax is $" & _
(CStr(decPrice * TaxRate))
End Function

Overloads Function TaxAmount(ByVal strPrice As String, _


ByVal TaxRate As Single) As String
TaxAmount = "Price is a String. Tax is $" & _
CStr((CDec(strPrice) * TaxRate))
End Function
End Class

3. Add the following procedure to your form.


VB
Sub ShowTax()
' 8% tax rate.
Const TaxRate As Single = 0.08
' $64.00 Purchase as a String.
Dim strPrice As String = "64.00"
' $64.00 Purchase as a Decimal.
Dim decPrice As Decimal = 64
Dim aclass As New TaxClass
'Call the same method with two different kinds of data.
MsgBox(aclass.TaxAmount(strPrice, TaxRate))
MsgBox(aclass.TaxAmount(decPrice, TaxRate))
End Sub

4. Add a button to your form and call the ShowTax procedure from the Button1_Click event of the button.
5. Run the project and click the button on the form to test the overloaded ShowTax procedure.
At run time, the compiler chooses the appropriate overloaded function that matches the parameters being used. When you
click the button, the overloaded method is called first with a Price parameter that is a string and the message, "Price is a
String. Tax is $5.12" is displayed. TaxAmount is called with a Decimal value the second time and the message, "Price is a
Decimal. Tax is $5.12" is displayed.
See Also
Reference
Sub Statement (Visual Basic)
Shadows
ByVal
ByRef
Overloads
Shadows
Concepts
Shadowing in Visual Basic
Introduction to Objects in Visual Basic
Overriding Properties and Methods
Visual Basic Language Concepts

Overriding Properties and Methods


A derived class inherits the properties and methods defined in its base class. This is useful because you can reuse these items
when appropriate for the derived class. If the property or method in the base class is marked with the Overridable keyword,
you can define a new implementation for the member in the derived class. Use the Overrides keyword to shadow the member
by redefining it in the derived class. This is useful when you cannot use the member "as is."
In practice, overridden members are often used to implement polymorphism. For more information, see Polymorphism.
The following rules apply to overriding methods.
You can only override members that are marked with the Overridable keyword in their base class.
Properties and methods are NotOverridable by default.
Overridden members must have the same arguments as the inherited members from the base class.
The new implementation of a member can call the original implementation in the parent class by specifying MyBase
before the method name.
Note
Overloading, overriding, and shadowing are similar concepts that can be easy to confuse. For more information, see
Introduction to Objects in Visual Basic.

Example
Suppose you want to define classes to handle payroll. You could define a generic Payroll class that contains a RunPayroll
method that calculates payroll for a normal week. You could then use Payroll as a base class for a more specialized
BonusPayroll class, which could be used when distributing employee bonuses.

The BonusPayroll class can inherit, and override, the PayEmployee method defined in the base Payroll class.
The following example defines a base class, Payroll, and a derived class, BonusPayroll, which overrides an inherited method,
PayEmployee. A procedure, RunPayroll, creates and then passes a Payroll object and a BonusPayroll object to a function, Pay,
that executes the PayEmployee method of both objects.
VB
Const BonusRate As Decimal = 1.45D
Const PayRate As Decimal = 14.75D
Class Payroll
Overridable Function PayEmployee( _
ByVal HoursWorked As Decimal, _
ByVal PayRate As Decimal) _
As Decimal

PayEmployee = HoursWorked * PayRate


End Function
End Class

Class BonusPayroll
Inherits Payroll
Overrides Function PayEmployee( _
ByVal HoursWorked As Decimal, _
ByVal PayRate As Decimal) _
As Decimal
' The following code calls the original method in the base
' class, and then modifies the returned value.
PayEmployee = MyBase.PayEmployee(HoursWorked, PayRate) * BonusRate
End Function
End Class

Sub RunPayroll()
Dim PayrollItem As Payroll = New Payroll
Dim BonusPayrollItem As New BonusPayroll
Dim HoursWorked As Decimal = 40

MsgBox("Normal pay is: " & _


PayrollItem.PayEmployee(HoursWorked, PayRate))
MsgBox("Pay with bonus is: " & _
BonusPayrollItem.PayEmployee(HoursWorked, PayRate))
End Sub

See Also
Concepts
Overloaded Properties and Methods
Override Modifiers
Shadowing in Visual Basic
Other Resources
Polymorphism
Visual Basic Language Concepts

Override Modifiers
You can use the NotOverridable and MustOverride modifiers in a base class to control how derived classes override its
properties and methods.
The NotOverridable modifier defines a method of a base class that cannot be overridden in derived classes. All methods are
NotOverridable unless marked with the Overridable modifier. You can use the NotOverridable modifier when you do not
want to allow an overridden method to be overridden again in a derived class.
Methods defined with the MustOverride modifier have no implementation in the base class and must be implemented in
derived classes. Classes that contain MustOverride methods must be marked with the MustInherit modifier.
Example
VB
MustInherit Class BaseClass
Public MustOverride Sub aProcedure()
End Class

Class DerivedClass
Inherits BaseClass
Public NotOverridable Overrides Sub aProcedure()
' Override a procedure inherited from the base class
' and mark it with the NotOverridable modifier so that
' it cannot be overridden in classes derived from this class.
End Sub
End Class

See Also
Concepts
Overloaded Properties and Methods
Visual Basic Language Concepts

Creating and Using Objects


Objects are combinations of code and data that can be treated as single units. Nearly everything you do in Visual Basic involves
objects, from the controls you use to the forms on which you place them. This section discusses where objects originate and
how to use them.
In This Section
Objects from Visual Basic and Other Sources
Discusses how to use objects from Microsoft Word, Microsoft Excel, and other applications.
How to: Set and Retrieve Properties
Discusses how to change and obtain property values.
How to: Perform Actions with Methods
Describes what methods are and how to use them.
How to: Treat Forms as Objects
Shows how to use forms in the same way as ordinary objects.
How to: Access a Form
Demonstrates how to access the members of a form without having to create a variable.
How to: Use the New Keyword
Shows how to create instances of forms, classes defined in class modules, and collections.
Resource Management
Discusses how to save memory and system resources by releasing references to objects.
How to: Pass Objects to Procedures
Describes how to pass objects as arguments to procedures.
Walkthrough: Persisting an Object in Visual Basic
Demonstrates how serialization can be used to persist an object's data between instances, allowing you to store values and
retrieve them the next time the object is instantiated.
How to: Inherit from a Class in Visual Basic
Shows how to define a base class and declare classes that extend the base class.
Related Sections
Objects in Visual Basic
Covers object-oriented programming fundamentals.
Managing Groups of Objects
Lists techniques for working with arrays and collections of objects.
How to: Perform Multiple Actions on an Object
Covers using the With...End With statement to simplify property access.
Visual Basic Language Concepts

Objects from Visual Basic and Other Sources


The objects you use in Visual Basic come from both internal and external sources. Examples of internal objects include intrinsic
objects and classes in your project; examples of external objects include assemblies and COM objects.
Internal Objects
Intrinsic (or built-in) objects are objects that Visual Basic natively provides. These include the primitive scalar types such as
Integer and Double as well as the Array and String types. You do not need to create references to internal objects before
using them in your project.
Other internal objects are instances of classes in your current project. You can use these classes wherever necessary within
your project, and you can make them available for use by other applications when you create an assembly.
External Objects
External objects are those that come from other projects or assemblies that are not available to your project by default. You
must create project references to external objects before using them in your project.
Assemblies are the most common source of objects for Visual Basic applications. The .NET Framework includes assemblies that
contain commonly used objects. Some objects in the .NET Framework are treated as intrinsic objects, but most assemblies
must be explicitly imported using the Imports statement before they can be used. Any language compliant with the Common
Language Specification (CLS), such as Visual Basic or Visual C#, can create and use assemblies. For more information, see
Assemblies.
In the past, COM components were a traditional source of objects for Visual Basic programmers, but today .NET Framework
assemblies are a better choice for new objects. You can still use existing COM components in your applications; however, COM
objects must be accessed by means of .NET Framework interoperability classes. Accessing a COM library requires the use of an
interoperability assembly containing interoperability classes for each COM class defined within the COM library. For more
information, see COM Interop.
In addition to accessing native .NET Framework classes and COM classes, it is also possible to call functions defined in
dynamic-link libraries (DLLs), such as those in the Win32 API. Visual Basic allows you to call functions in DLLs after they have
been declared with a Declare statement. Visual Basic adds functionality to the Declare statement by allowing you to use the
DllImportAttribute attribute to specify defaults for things such as CallingConvention, ExactSpelling, and SetLastError.
Parameters for Declare statements can be annotated with the MarshalAsAttribute attribute, which supports conversion of
parameters in ways that were not possible in earlier versions of Visual Basic.
See Also
Tasks
Walkthrough: Implementing Inheritance with COM Objects
How to: Set and Retrieve Properties
Reference
Declare Statement
Imports Statement
Integer Data Type (Visual Basic)
Double Data Type (Visual Basic)
String Data Type (Visual Basic)
DllImportAttribute
MarshalAsAttribute
Concepts
Relationships Among Objects
Other Resources
Creating and Using Objects
Visual Basic Language Concepts

How to: Set and Retrieve Properties


When working with forms and controls in Visual Basic, you can set their properties programmatically at run time, or you can
set them in design mode using the Properties window. The properties of most other objects, such as objects from assemblies
or objects you create, can only be set programmatically.
Properties you can set and read are called read-write properties. Properties you can read but not modify are called read-only
properties. Properties you can write but not read are called write-only properties.
You set the value of a property when you want to change the appearance or behavior of an object. For example, you change
the Text property of a text box control to modify the contents of the text box.
You get the value of a property when you want to find the state of an object before your code performs additional actions, such
as assigning the value to another object. For example, you can return the Text property of a text box control to determine the
contents of the text box before running code that might change the value.
To set property values
Use the following syntax:
Object . property = expression
The following statements provide examples of how to set properties:
VB
' Set the Top property to 200 twips.
TextBox1.Top = 200
' Display the text box.
TextBox1.Visible = True
' Display 'hello' in the text box.
TextBox1.Text = "hello"

Note
You can also set a property by passing it to ByRef parameters, in which case the property is modified by the result retu
rned by the ByRef parameter.

To get property values


Use the following syntax:
variable = Object.property
You can also get a property value as part of a more complex expression, without assigning the property to a variable. The
following code changes the Top property of a radio button control:
VB
RadioButton1.Top += 20

See Also
Tasks
How to: Perform Actions with Methods
Concepts
Objects from Visual Basic and Other Sources
Other Resources
Creating and Using Objects
Visual Basic Language Concepts

How to: Perform Actions with Methods


Methods are procedures associated with objects. Unlike fields and properties, which represent information an object can store,
methods represent actions that an object can perform. Methods can affect the values of properties. For example, to use a radio
analogy, you can employ a SetVolume method to change the value of a Volume property. Similarly, in Visual Basic, the items of
list boxes have a List property, which you can change with the Clear and Add methods.
When you use a method in code, the way you write the statement depends on how many arguments the method requires and
whether it returns a value. Generally, you use methods just like you use subroutines or function calls. More specifically, you
invoke methods in the same way as module procedures, except that you can qualify methods with an expression specifying the
object instance whose method is to be called. When unqualified, the instance is implicitly the Me variable.
To use a method that does not require arguments
Use the following syntax:
Object.method()
In the following example, the Refresh method repaints the picture box:
VB
' Force the control to repaint.
PictureBox1.Refresh()

Note
Some methods, such as Refresh, do not have arguments and do not return values.

To use a method that requires multiple arguments


Place the arguments in parentheses and separate them with commas. In the following example, the MsgBox method
uses arguments that specify the message to display and the style of the message box:
VB
MsgBox("Database update complete", _
MsgBoxStyle.OKOnly Or MsgBoxStyle.Exclamation, _
"My Application")

To use a method that returns a value


Assign the return value to a variable, or directly use the method call as a parameter to another call. The following code
stores the return value:
VB
Dim Response As MsgBoxResult
Response = MsgBox("Do you want to exit?", _
MsgBoxStyle.YesNo Or MsgBoxStyle.Question, _
"My Application")

This example uses the value returned from the Len method as an argument to MsgBox.
VB
Dim TestStr As String = "Some String"
' Display the string "String length is : 11".
MsgBox("String length is : " & Len(TestStr))

See Also
Tasks
How to: Set and Retrieve Properties
Concepts
Relationships Among Objects
Other Resources
Creating and Using Objects
Visual Basic Language Concepts

How to: Treat Forms as Objects


Forms are graphical objects that make up your application's user interface. Within Visual Basic, classes define how forms are
displayed and what they can do. When a form is displayed at run time, Visual Basic creates an instance of the Form class that
you can use like any other object. You can add custom methods and properties to forms and access them from other forms or
classes in your application.
To create a new method for a form
Add a procedure declared as Public, as in the following code:
VB
' Create a custom method on a form.
Public Sub PrintMyJob()
' Insert the code for your method here.
End Sub

To add a new field to a form


Declare a public variable in the form module, as in the following code:
VB
Public IDNumber As Integer

To access methods on a different form


1. Create a new instance of the form whose methods you want to access. When you reference a form name, you are
actually referencing the class the form belongs to, not the object itself.
Note
Visual Basic provides an implicit global variable with the same name as the form for each form class. For more informa
tion, see How to: Access a Form.

2. Assign the form to an object variable. The object variable references a new instance of the form class.
The following example correctly calls the PrintMyJob procedure:
VB
Dim newForm1 As New Form1
newForm1.PrintMyJob()

In the previous example, the new form is not displayed. It is not necessary to show a form object to use its methods. To
display the new form, you need to add the following code:
VB
newForm1.Show()

See Also
Tasks
How to: Use the New Keyword
Concepts
Property Procedures
Visual Basic Language Concepts

How to: Access a Form


You can access the members of a Visual Basic form without having to create a variable. The following examples demonstrate
this by changing colors on a form.
Accessing a Form
To access Form1
1. Make sure your project has a reference to the System.Drawing namespace. This is necessary to work with the color
settings, not to access the form.
2. Change the colors directly on Form1.
3. Call the Show method directly on Form1.
VB
Public Sub ChangeForm1Colors()
Form1.ForeColor = System.Drawing.Color.Coral
Form1.BackColor = System.Drawing.Color.Cyan
Form1.Show()
End Sub

If Form1 does not already exist, Visual Basic creates it for you. You do not have to declare a variable for it.

Creating an Additional Instance of a Form


If you want to create a new form, rather than access an existing one, you can declare a variable and initialize it using the New
keyword.
To create an additional copy of Form1
1. Make sure your project has a reference to the System.Drawing namespace. This is necessary to work with the color
settings, not to access the form.
2. Assign New Form1 to a variable.

VB
Public Sub GetSecondInstance()
Dim newForm1 As New Form1
newForm1.BackColor = System.Drawing.Color.YellowGreen
newForm1.Show()
End Sub

If you want to display two or more copies of the same form, you must create the additional copies. The preceding
example creates a second copy of Form1 and paints it a different color. You can then access the original copy using Form1
and the second copy using newForm1.

See Also
Reference
New (Visual Basic)
System.Drawing
Form
Visual Basic Language Concepts

How to: Use the New Keyword


To create an instance of a class, use the New keyword. Unlike value types, such as Integer and Double, objects are reference
types, and you must explicitly create them before you can use them. For example, consider the following two lines of code:
VB
Dim Button1 As System.Windows.Forms.Button
Dim Button2 As New System.Windows.Forms.Button()

The first statement declares an object variable that can contain a reference to a button object. However, the variable Button1
contains the value Nothing until you assign an object of type Button to it. The second statement also defines a variable that
can contain a button object, but the New keyword creates a button object and assigns it to the variable Button2.
Because forms and controls are actually classes, you can use the New keyword to create new instances of these items as
needed.
To create new instances of a class with New
1. Open a new Windows Application project and place a command button and several other controls on a form named
Form1.

2. Add the following code to the command button's Click event procedure:
VB
Dim f As New Form1
f.Show()

3. Run the application, and click the command button several times.
4. Move the front form aside. Because a form is a class with a visible interface, you can see the additional copies. Each copy
has the same controls, in the same positions as those on the original form at design time.
You can use the New keyword to create objects from within classes. The following procedure provides an example.
To see how New creates instances of a class
1. Open a new project, and place a command button on a form named Form1.
2. From the Project menu, choose Add Class to add a class to the project.
3. Name the new class ShowMe.vb.
4. Add the following procedure to ShowMe:
VB
Public Class ShowMe
Sub ShowFrm()
Dim frmNew As Form1
frmNew = New Form1
frmNew.Show()
frmNew.WindowState = FormWindowState.Minimized
End Sub
End Class

5. Add the following code to handle the Click event of Button1 on your form:
VB
Protected Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim clsNew As New ShowMe
clsNew.ShowFrm()
End Sub

6. To use the example, run the application and click the command button several times. A minimized form icon appears on
your taskbar as each new instance of the ShowMe class is created.

See Also
Other Resources
Creating and Using Objects
Visual Basic Language Concepts

Resource Management
All objects consume system resources such as memory, file handles, and database connections. The Common Language
Runtime (CLR) manages resources automatically, and usually you do not need to worry about releasing unneeded objects.
However, understanding how resource management works can help you design your applications to be more efficient.
Garbage Collection
The CLR uses a system called garbage collection to manage allocated resources. The system garbage collector releases an
object's resources when that object can no longer be reached by any running code in your application. The garbage collection
algorithm is nondeterministic, so you cannot determine when the CLR will release an object's resources. The following sections
describe some of the changes to the way resources are managed in Visual Basic.
Assigning Objects to Nothing
Nothing is a keyword used by Visual Basic to indicate that an object variable does not contain a reference to an object.
Previous versions of Visual Basic encouraged you to assign unused objects to Nothing to disassociate the object variable from
the object and release resources. You can still assign unused objects to Nothing, but because of the way Visual Basic manages
resources, this process does not guarantee that objects will be released immediately. Generally speaking, you should only
assign long-lived objects—such as shared members or global variables—to Nothing.
Dispose
Some objects support a method named Dispose; its purpose is to release system resources more expeditiously. Classes that
support the Dispose method must implement the IDisposable interface. The Dispose method needs to be explicitly called
when you want to release object resources. For example:
ThisObject.Dispose()
Finalize
Another method supported by some classes, Finalize, runs automatically when an object is released and can be used to
perform other cleanup tasks. The Finalize method is similar to the Class_Terminate() method used in previous versions of
Visual Basic. After an object becomes inaccessible, the CLR will eventually call the object's Finalize method. Because the
garbage collection algorithm is nondeterministic, the Finalize method might be called immediately, or it might be called
several hours later.
See Also
Reference
Nothing (Visual Basic)
Dispose
IDisposable
Concepts
Object Lifetime: How Objects Are Created and Destroyed
Initialization and Termination of Components
Visual Basic Language Concepts

How to: Pass Objects to Procedures


Visual Basic allows you to pass objects as arguments to procedures in the same way that you pass other types of arguments.
The following procedures demonstrate how.
To pass a new instance of a form to a procedure
1. Open a project, create a new form named Form1, and add a command button named Button1 to it.
2. Copy the following code into the form:
VB

Private Sub Button1_Click(ByVal sender As Object, _


ByVal e As System.EventArgs) Handles Button1.Click

Dim newForm As New Form1


newForm.Show()
CenterForm(newForm)
End Sub

Sub CenterForm(ByVal TheForm As Form)


' Centers the form on the screen.
Dim RecForm As Rectangle = Screen.GetBounds(TheForm)
TheForm.Left = CInt((RecForm.Width - TheForm.Width) / 2)
TheForm.Top = CInt((RecForm.Height - TheForm.Height) / 2)
End Sub

You can also pass an object as an argument by reference and then, inside the procedure, set the argument to a new
object.
To pass an object reference to a procedure on another form
1. Open a project and create a form named Form1.
2. Add a second form named Form2.
3. Place a picture box control on each form.
4. Name the picture box on Form1 PictureBox1.
5. Name the picture box on Form2 PictureBox2.
6. Assign a picture to PictureBox2 by clicking the Image property in the Properties window. Any small images will work;
you can find .bmp and .jpg files in your Windows directory.
7. Add the following code to Form2:
VB
Public Sub GetPicture(ByVal x As PictureBox)
Dim objX As PictureBox
' Assign the passed-in picture box to an object variable.
objX = x
' Assign the value of the Picture property to the Form1 picture box.
objX.Image = PictureBox2.Image
End Sub
8. Add the following code to the Form1_Click event on Form1:
VB
Protected Sub Form1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs)
Dim newForm2 As New Form2
newForm2.GetPicture(PictureBox1)
End Sub

9. Run the application and click Form1. The picture from Form2 appears in the picture box on Form1.
The Form1_Click event procedure calls the GetPicture procedure in Form2, and passes the empty picture box to it. The
GetPicture procedure in Form2 assigns the Image property of the picture box on Form2 to the empty picture box on
Form1, and the image from Form2 is displayed on Form1.

See Also
Concepts
Resource Management
Other Resources
Object-Oriented Programming in Visual Basic
Programming with Components
Visual Basic Language Concepts

Walkthrough: Persisting an Object in Visual Basic


Although you can set an object's properties to default values at design time, any values entered at run time are lost when the
object is destroyed. You can use serialization in Visual Basic to persist an object's data between instances, allowing you to store
values and retrieve them the next time the object is instantiated.
When storing simple data, such as a name or number, you can use the My.Settings object. For more information, see
My.Settings Object.
In this walkthrough, you will create a simple Loan object and persist its data to a file, then retrieve the data from the file when
you recreate the object. You will then modify the code to persist the object in a SOAP format.
Security Note
This example creates a new file, if the file does not already exist. If an application needs to create a file, that application needs
Create permission for the folder. Permissions are set using access control lists. If the file already exists, the application needs
only Write permission, a lesser privilege. Where possible, it is more secure to create the file during deployment, and only gra
nt Read privileges to a single file (rather than Create privileges for a folder). Also, it is more secure to write data to user folde
rs than to the root folder or the Program Files folder.

Security Note
This example stores data in a binary or SOAP format file. These formats should not be used for sensitive data, such as passw
ords or credit card information.

Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

Creating the Loan Object


The first step is to create a Loan class and a test application that uses the class.
To create the Loan class
1. Create a new Class Library project and name it "LoanClass". For more information, see
How to: Create Solutions and Projects.
2. In the Code Editor, change the name of the class from "Class1" to "Loan".
3. Add the following public members to the class:
VB
Public LoanAmount As Double = 10000.0
Public InterestRate As Double = 7.5
Public Term As Integer = 36
Public Customer As String

You will also need to create a simple application that uses the Loan class.
To create a test application
1. From the File menu, add a Windows Application project to your solution by pointing to Add and then clicking New
Project.
2. In the Add New Project dialog box, enter LoanApp as the name of the project, and click OK to close the dialog box.
3. In Solution Explorer, select the LoanApp project.
4. On the Project menu, click Set as StartUp Project.
5. On the Project menu, click Add Reference.
6. In the Add Reference dialog box, click the Projects tab and select the LoanClass project.
7. Click OK to close the dialog box.
8. In the designer, add four TextBox controls to the form.
9. In the Code Editor, add the following code:
VB
Private TestLoan As New LoanClass.Loan
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
TextBox1.Text = TestLoan.LoanAmount.ToString
TextBox2.Text = TestLoan.InterestRate.ToString
TextBox3.Text = TestLoan.Term.ToString
TextBox4.Text = TestLoan.Customer
End Sub

At this point, you can build and run the application. Note that the default values from the Loan class appear in the text boxes.
Try changing the interest-rate value from 7.5 to 7.1, then close the application and run it again—the value reverts to the default
of 7.5.
In the real world, interest rates change periodically, but not necessarily every time the application is run. Rather than making
the user update the interest rate each time the application is run, it would be better to preserve the most recent interest rate
between instances of the application. In the next step, you will do just that by adding serialization to the Loan class.
Using Serialization to Persist the Object
In order to persist the values for the Loan class, you must first mark the class with the Serializable attribute.
To mark a class as serializable
Change the class declaration for the Loan class as follows:
VB
<Serializable()> Public Class Loan

The Serializable attribute tells the compiler that everything within the class can be persisted to a file. In this case, you want to
persist only the InterestRate member, but you probably do not want to persist the Customer, LoanAmount, or Period
members. The NonSerialized attribute can be used to mark class members that should not be persisted. For simplicity in this
example, everything except the Customer member is persisted.
To prevent a member from being serialized
Change the declaration for the Customer member as follows:
VB
<NonSerialized()> Public Customer As String

The next step is to add the serialization code to the LoanApp application. In order to serialize the class and write it to a file, you
will use the System.IO and System.Xml.Serialization namespaces. To avoid typing the fully qualified names, you can use the
Imports statement.
To add references to namespaces
Add the following Imports statements to the top of the Form1 class:
VB
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary

In this case, you are using a binary formatter to save the object in a binary format. Later in this walkthrough, you will
modify the code to save the object in a SOAP format.
The next step is to add code to deserialize the object from the file when the object is created.
To deserialize an object
1. Add a constant to the class for the serialized data's file name.
VB
Const FileName As String = "SavedLoan.bin"

2. Modify the code in the Form1_Load event procedure as follows:


VB
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
If File.Exists(FileName) Then
Dim TestFileStream As Stream = File.OpenRead(FileName)
Dim deserializer As New BinaryFormatter
TestLoan = CType(deserializer.Deserialize(TestFileStream), LoanClass.Loan)
TestFileStream.Close()
End If
TextBox1.Text = TestLoan.LoanAmount.ToString
TextBox2.Text = TestLoan.InterestRate.ToString
TextBox3.Text = TestLoan.Term.ToString
TextBox4.Text = TestLoan.Customer
End Sub

Note that you first need to check that the file exists. If it exists, create a Stream class to read the binary file and a
BinaryFormatter class to translate the file. The CType method is used to convert from the stream to the Loan object type.
Next you need to add code to save the data entered in the text boxes to the Loan class, and then you need to serialize the class
to a file.
To save the data and serialize the class
Add the following code to the Form1_Closing event procedure:
VB
Private Sub Form1_Closing(ByVal sender As System.Object, ByVal e As _
System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
TestLoan.LoanAmount = CType(TextBox1.Text, Double)
TestLoan.InterestRate = CType(TextBox2.Text, Double)
TestLoan.Term = CType(TextBox3.Text, Integer)
TestLoan.Customer = TextBox4.Text

Dim TestFileStream As Stream = File.Create(FileName)


Dim serializer As New BinaryFormatter
serializer.Serialize(TestFileStream, TestLoan)
TestFileStream.Close()
End Sub

At this point, you can once again build and run the application. Initially the default values appear in the text boxes. Try changing
the values and entering a name in the fourth text box. Close the application and then run it again. Note that the new values
now appear in the text boxes, except for the customer name that was marked as NonSerialized.
Persisting the Object Using a SOAP Format
The example so far has demonstrated how to persist an object to a text file using a binary format. A binary format is fine for
most Windows applications. For Web applications or XML Web services, you may want to persist the object to an XML file
using a SOAP format, which makes the object easy to share.
In order to persist the object to a SOAP format, you must first reference the SoapFormatter class. The SoapFormatter class
resides in its own namespace: System.Runtime.Serialization.Formatters.Soap.
To persist the object using SOAP format
1. In Solution Explorer, select the LoanApp project.
2. On the Project menu, click Add Reference.
3. In the Add Reference dialog box, click the .NET tab and select the System.Runtime.Serialization.Formatters.Soap
component.
4. Click OK to close the dialog box.
5. In the Code Editor, add an Imports statement to the top of the Form1 module:
VB
Imports System.Runtime.Serialization.Formatters.Soap

6. Change the file name from SavedLoan.bin to SavedLoan.xml.


7. In the Form1_Load event procedure, change the Dim statement from Dim deserializer As New BinaryFormatter to:

VB
Dim deserializer As New SoapFormatter

8. In the Form1_Closing event procedure, change the Dim statement from Dim serializer As New BinaryFormatter to:

VB
Dim serializer As New SoapFormatter

At this point, you can build and test the application. When you first run the application, the SavedLoan.xml file is created. You
can view this file by choosing the Show All Files option in Solution Explorer; it will be in the Bin node for the Windows
Application project.
Note
If you are already in Show All Files mode, you need to refresh the view by choosing Refresh from the View menu in order t
o see the file.

Note that the three members of the LoanClass are displayed in XML format. Try changing the InterestRate value in the XML
file, then save it and run the application again. The new interest rate appears in the second text box.
See Also
Concepts
PropertyBag Equivalents for Visual Basic 6.0 Users
Basics of .NET Framework Serialization
Visual Basic Language Concepts

How to: Inherit from a Class in Visual Basic


This example defines the Circle and Rectangle classes, which both inherit from the Shape class, and the Square class, which
inherits from the Rectangle class.
Example
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
VB
Public Class Shape
' Definitions of properties, methods, fields, and events.
End Class
Public Class Circle : Inherits Shape
' Specialized properties, methods, fields, events for Circle.
End Class
Public Class Rectangle : Inherits Shape
' Specialized properties, methods, fields, events for Rectangle.
End Class
Public Class Square : Inherits Rectangle
' Specialized properties, methods, fields, events for Square.
End Class

Compiling the Code


This example requires:
A reference to the System namespace.
Note
Make sure the class from which you want to inherit is not defined as NotInheritable.

See Also
Tasks
How to: Draw an Outlined Shape
Reference
NotInheritable
Other Resources
Inheritance in Visual Basic
Creating and Using Objects
Visual Basic: Samples

How to: Read Object Data from an XML File in Visual Basic
This example reads object data that was previously written to an XML file using the XmlSerializer class.
Example
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in XML. For more
information, see How to: Insert Snippets Into Your Code (Visual Basic).
VB
Public Class Book
Public Title As String
Public Sub New()
End Sub
End Class

Public Sub ReadXML()


Dim reader As New System.Xml.Serialization.XmlSerializer(GetType(Book))
Dim file As New System.IO.StreamReader("c:\IntroToVB.xml")
Dim introToVB As Book
introToVB = CType(reader.Deserialize(file), Book)
End Sub

Compiling the Code


Replace the file name "c:\IntroToVB.xml" with the name of the file containing the serialized data. For more information about
serializing data, see How to: Write Object Data to an XML File in Visual Basic.
The class must have a public constructor without parameters.
Only public properties and fields are deserialized.
Robust Programming
The following conditions may cause an exception:
The class being serialized does not have a public, parameterless constructor.
The data in the file does not represent data from the class to be deserialized.
The file does not exist (IOException).
Security
Always verify inputs, and never deserialize data from an untrusted source. The re-created object runs on a local computer with
the permissions of the code that deserialized it. Verify all inputs before using the data in your application.
See Also
Tasks
How to: Write Object Data to an XML File in Visual Basic
How to: Read Text from Files with a StreamReader (Visual Basic)
Reference
StreamWriter
Visual Basic: Samples

How to: Write Object Data to an XML File in Visual Basic


This example writes the object from a class to an XML file using the XmlSerializer class.
Example
This code example defines a class named Book, creates an instance of the class, and uses XML serialization to write the instance
to an XML file.
Code similar to this is available as an IntelliSense code snippet. In the code snippet picker, it is located in XML. For more
information, see How to: Insert Snippets Into Your Code (Visual Basic).
VB
Public Class Book
Public Title As String
Public Sub New()
End Sub
End Class

Public Sub WriteXML()


Dim introToVB As New Book
introToVB.Title = "Intro to Visual Basic"
Dim writer As New System.Xml.Serialization.XmlSerializer(GetType(Book))
Dim file As New System.IO.StreamWriter("c:\IntroToVB.xml")
writer.Serialize(file, introToVB)
file.Close()
End Sub

Compiling the Code


The class must have a public constructor without parameters.
Robust Programming
The following conditions may cause an exception:
The class being serialized does not have a public, parameterless constructor.
The file exists and is read-only (IOException).
The path is too long (PathTooLongException).
The disk is full (IOException).
Security
This example creates a new file, if the file does not already exist. If an application needs to create a file, that application needs
Create access for the folder. If the file already exists, the application needs only Write access, a lesser privilege. Where
possible, it is more secure to create the file during deployment, and only grant Read access to a single file, rather than Create
access for a folder.
See Also
Tasks
How to: Read Object Data from an XML File in Visual Basic
Reference
StreamWriter
Other Resources
File Access with Visual Basic
Visual Basic Language Concepts

Collections in Visual Basic


In general terms, a collection is an object used for grouping and managing related objects. For example, every Form has a
collection of controls. (You can access this collection through the form's Controls property.) This collection is an object that
represents all the controls on that form. It allows you to retrieve a control in the collection by its index, and to loop through the
elements of the collection using a For Each...Next Statement (Visual Basic).
However, there are several kinds of collections, and they differ from each other in several ways.
Different Kinds of Collections
Visual Basic also provides a Collection class, with which you can define and create your own collections. Like a form's
Controls collection, the Collection class also provides you with the built-in functionality to loop through elements using For
Each...Next and to retrieve elements by index. For more information, see Collection Object (Visual Basic).
However, the two types of collections do not interoperate with each other. For example, the following code generates a
compiler error.
Dim localControls As Collection
' The following line generates a COMPILER ERROR.
localControls = Me.Controls()

The collections are incompatible because the Controls collection is a .NET Framework collection, while the variable
localControls is a Visual Basic Collection. The two kinds of collections are implemented from different classes. Their
methods are similar but not identical, and their indexing schemes are different.
Zero-Based and One-Based Collections
A collection can be zero-based or one-based, depending on what its starting index is. The former means that the index of the
first item in the collection is 0, and the latter means that it is 1. An example of a zero-based collection is the .NET
Framework Controls collection, discussed earlier on this page. The Visual Basic Collection object is an example of a one-
based collection.
One-based collections can be more intuitive to Visual Basic users, because the index ranges from 1 through the value of the
Count Property (Collection Object), which returns the number of items in a collection. The index of a zero-based collection, by
contrast, ranges from 0 through one less than the value of the Count property. This can be appropriate when the index values
are offsets from a base value or correspond to members of a zero-based enumeration.
.NET Framework collections are zero-based for the purpose of standardization. The Visual Basic Collection class is one-based
for the purpose of compatibility with previous versions.
Index and Key Values
Instances of the Visual Basic Collection class allow you to access an item using either a numeric index or a String key. You can
add items to Visual Basic Collection objects either with or without specifying a key. If you add an item without a key, you must
use its numeric index to access it.
By contrast, collections such as System.Collections.ArrayList allow only a numeric index. You cannot associate keys with the
elements of these collections, unless you construct your own mapping based, for example, on a String array holding the keys.
Adding and Removing Items
Collections also differ in whether or not you can add items to them, and if so, how those items are added. Because the Visual
Basic Collection object is a general-purpose programming tool, it is more flexible than some other collections. It has an
Add Method (Collection Object) for putting items into the collection and a Remove Method (Collection Object) for taking items
out.
Certain specialized collections, on the other hand, do not allow you to add or remove elements using code. For example, the
System.Windows.Forms.CheckedListBox.CheckedItems property returns a collection of references to items by index, but your
code cannot add or remove items from the collection. Only the user can do this — by selecting or clearing the appropriate box
in the user interface. Thus there is no Add or Remove method for this collection.
See Also
Tasks
How to: Create a Collection of Objects
How to: Create an Array of Objects
How to: Add, Delete, and Retrieve Items of a Collection
How to: Define Collections in Your Classes
How to: Iterate through a Collection in Visual Basic
Troubleshooting Collections
Concepts
Managing Groups of Objects
Visual Basic Collection Class
Managing Your Objects with Collections
Visual Basic Language Concepts

Managing Groups of Objects


For many applications, you want to be able to create and manage groups of related objects. There are two ways to group
objects: by creating arrays of objects, and by creating collections of objects.
Arrays of Objects
Arrays are relatively inflexible structures. If you want to change the size of the array at run time, you must use the
ReDim Statement (Visual Basic) to redeclare it. All elements of the array must be of the same type. On the other hand, arrays
allow you to process all your elements sequentially, and you can have empty elements of an array. For these reasons, arrays
are most useful for creating and working with a fixed number of strongly-typed objects.
For more information, see How to: Create an Array of Objects.
Collections of Objects
Collections provide a more flexible way of working with groups of objects. A collection is a class, so you must declare a new
collection before you can add elements to that collection. Unlike arrays, the group of objects you work with can grow and
shrink dynamically as the needs of the application change. You can assign a key to any object that you put into a collection so
that you can retrieve it and manipulate it based on that key.
You can create a generalized collection from the Visual Basic Collection Class. If you want a specific functionality in a collection,
for example a dictionary or a linked list, you can create it from one of the classes in the System.Collections namespace of the
.NET Framework. Even more specialized collection classes are available in the System.Collections.Specialized namespace.
If your collection is limited to elements of only one data type, you can use one of the classes in the System.Collections.Generic
namespace. A generic collection enforces type safety so that no other data type can be added to it. When you retrieve an
element from a generic collection, you do not have to determine its data type or convert it.
For more information, see How to: Create a Collection of Objects.
See Also
Tasks
How to: Add, Delete, and Retrieve Items of a Collection
Reference
System.Collections
System.Collections.Generic
System.Collections.Specialized
Concepts
Collections in Visual Basic
Visual Basic Collection Class
Other Resources
Arrays in Visual Basic
Creating and Using Objects
Visual Basic Language Concepts

Managing Your Objects with Collections


Collections provide an ideal way to manage a variety of objects. You can add and remove objects from a collection, retrieve
them based on an index or a key, and use the For Each...Next Statement (Visual Basic) to iterate through the items in your
collection.
Type-Unsafe Collections
However, the very flexibility of collections can undermine the robustness of your classes. For example, the collection provided
by Visual Basic stores all its elements as type Object, so you can add an item of any data type. There is no safeguard against
inappropriate data types being added, and when you access an element, you must convert it from Object to the desired data
type.
Specialized Collections
The .NET Framework provides several alternatives to the Visual Basic collection. The System.Collections namespace contains
collection classes with specific functionality, such as a queue or a sorted list, and the System.Collections.Specialized namespace
contains collection classes of specialized nature, such as HybridDictionary.
Type-Safe Collections
To avoid the disadvantages of elements of type Object, you can use the generic collections of the System.Collections.Generic
namespace. These collections provide type safety and allow you to limit the elements of a collection to only one specific data
type.
Approaches to Using Collections
There are three general approaches you can take to implementing object management using collections. Consider an
application that defines a widgetRepository class, which organizes and exposes widget objects to client components. To
implement widgetRepository with a collection, you can use one of the following strategies.
Use a Collection Class. In the widgetRepository class, declare a widgetsColl variable as an instance of the
Visual Basic Collection Class or of one of the classes in the System.Collections, System.Collections.Generic, or
System.Collections.Specialized namespaces. Make the variable public, and use the New (Visual Basic) keyword to
create an instance of the collection. For more information, see How to: Define Collections in Your Classes.
Inherit a Collection Base Class. Implement your own widgetsColl class by inheriting from the CollectionBase class. In
the widgetRepository class, define an instance of the widgetsColl class and a property that returns that instance. For
more information, see How to: Define Collections in Your Classes.
Write the Collection Yourself. Implement collection functionality in the widgetRepository class by writing the
appropriate classes and procedures. This approach is most useful if you need collection functionality in your class but
cannot inherit from any of the existing collection classes. This could be possible, for example, in the rare case that your
class needed to inherit from a class other than a collection class. Because it cannot inherit from more than one class, you
would have to define and implement collection members.
See Also
Reference
System.Collections
System.Collections.Generic
System.Collections.Specialized
Concepts
Managing Groups of Objects
Visual Basic Collection Class
Visual Basic Language Concepts

Visual Basic Collection Class


A collection is a way of grouping a set of related items. Many different types of collections exist. Predefined collections are used
in Visual Basic applications for many purposes, for example the ControlCollection on a Form, returned by the form's Controls
property. You can also create your own collections to organize and manipulate objects.
Collections are a good way to keep track of objects that your application might need to dynamically create and destroy. The
following code fragment shows how you can use the Add Method of a Visual Basic Collection Object to keep a list of widget
objects the user has created.

' Declare and create the Collection object.


Public widgetColl As New Microsoft.VisualBasic.Collection()
' Create a new widget and add it to the widgetColl collection.
Private Sub makeAWidget()
Dim tempWidget As New widget()
widgetColl.Add(tempWidget)
End Sub

In the preceding example, the widgetColl collection organizes and exposes all of the widget objects created through the
makeAWidget procedure. You can retrieve object references to each widget through the index of the collection. The size of the
collection is adjusted automatically as each new widget object is added. You can use the
For Each...Next Statement (Visual Basic) to iterate through the collection. If you want to give the widget object a key by which it
can be retrieved, you can supply a text string as the second parameter of the Add method.
The Visual Basic Collection object stores all its elements as type Object, so you can add an item of any data type. There is no
safeguard against inappropriate data types being added. To avoid this limitation, you can use the generic collections of the
System.Collections.Generic namespace. For more information, see How to: Create a Collection of Objects.
Creating and Destroying a Collection Object
The New (Visual Basic) keyword in the declaration for the variable widgetColl causes a Collection object to be created when
control passes to the declaration statement. Because Collection is a class, rather than a value type, you must create an
instance of it and keep a reference to that instance in a variable. This instance is a Visual Basic Collection Object.
Like any other object, a Collection object is marked for garbage collection (GC) when the last variable that contains a
reference to it is set to Nothing (Visual Basic) or goes out of scope. All the object references it contains are released when it is
reclaimed by garbage collection. For this reason, the variable widgetColl in the preceding example is declared in the parent
class, so that it exists throughout the life of the program.
A collection maintains references to the objects it controls but does not contain the objects themselves. Therefore, destroying a
Collection object does not destroy the objects it controls. Each individual object that had been an element of the collection
continues to exist until it is individually marked for garbage collection.
Working with Elements
The basic services of adding, deleting, and retrieving elements from a collection depend on keys and indexes. A key is a String
value. It could be a name, a driver's license number, a phone number, or simply an integer converted to a string. The Add
method allows you to associate a key with an element, as described in How to: Add, Delete, and Retrieve Items of a Collection.
An index in the Collection class is an integer between 1 and the number of items in the collection. The
Count Property (Collection Object) returns the current number of items. You can control the initial value of an item's index by
using the Before or After parameters when you call Add, but the index value could change as other items are added and
deleted. For more information, see Add Method (Collection Object).
You can remove a single element from a collection by passing either its key or its index to the
Remove Method (Collection Object). You can empty a collection and remove all elements with the
Clear Method (Collection Object).
Accessing Elements
You can pass a key value to the Contains Method (Collection Object) to test whether a collection contains an element with that
key. You can retrieve an element by passing either its key or its index to the Item Property (Collection Object).
You can use index values and the Item property to iterate over the items in a collection, or you can use the
For Each...Next Statement (Visual Basic). The following example shows two ways to give all the employees in a collection of
employee objects a 10 percent raise, assuming that the variable employeesColl contains a reference to a Collection object.

Option Strict On
' The following alternative uses the Count and Item properties.
Dim emp As employee
For counter As Integer = 1 To employeesColl.Count
emp = CType(employeesColl.Item(counter), employee)
emp.payRate *= 1.1
Next counter
' The following alternative uses the For Each...Next statements.
For Each emp As employee In employeesColl
emp.payRate *= 1.1
Next emp

However, if you have added one or more elements to employeesColl that are not of type employee, the For Each loop throws
an ArgumentException exception at run time.
Data Type of Elements
A Visual Basic Collection Object stores each item with data type Object. Therefore, the range of data types you can add to a
Collection object is the same as the range of data types you can store in an Object variable. This includes standard data types,
objects, and arrays, as well as user-defined structures and class instances.
Because the Collection object stores each item as an Object, the Item property returns an Object value. To use the item in
your code, you must typically convert from Object to the run-time data type of the item. The way you do this depends on the
setting of the type checking switch in the Option Strict Statement.
Implicitly Converting from Object
If Option Strict is Off, you can implicitly convert an element of the Collection to its appropriate data type, as shown in the
following example.

Option Strict Off


Dim sampleColl As New Microsoft.VisualBasic.Collection()
Dim sampleString As String = "This is a string"
Dim aString As String
sampleColl.Add(sampleString)
' The following statements convert the collection item to a string.
Try
aString = sampleColl.Item(1)
Catch ex As Exception
' Insert code to run if the collection item cannot be converted to String.
End Try

Explicitly Converting from Object


If Option Strict is On, you must explicitly convert from Object to the run-time data type of the element. To obtain an element
from Item in this way, you can use the CType Function to perform the conversion, as shown in the following example.

Option Strict On
Dim sampleColl As New Microsoft.VisualBasic.Collection()
Dim sampleString As String = "This is a string"
Dim aString As String
sampleColl.Add(sampleString)
' The following statements convert the collection item to a string.
Try
aString = CType(sampleColl.Item(1), String)
Catch ex As Exception
' Insert code to run if the collection item cannot be converted to String.
End Try

Additional Services
The properties and methods of the Collection object provide only the most basic services for collections. For example, the
Add method cannot check the type of an element being added to a collection, which you might want to do to ensure that the
collection contains only one kind of element. If you can ensure this in the Add method, you have a strongly-typed collection,
and you do not have to convert the return from the Item property to its run-time data type. This improves your performance.
You can provide more robust functionality — and additional properties, methods, and events — by creating your own
collection class, as described in How to: Define Collections in Your Classes.
See Also
Reference
Collection Object (Visual Basic)
Concepts
Collections as an Alternative to Arrays
Collections in Visual Basic
Visual Basic Language Concepts

How to: Define Collections in Your Classes


You can add a collection to one of your classes to manage groups of objects your class uses. The simplest way of doing this is
to add a public variable of type Collection to your class. Consider a hypothetical class called widgetRepository that manages
and exposes widget objects. You might create a widgetColl variable to refer to a widget collection, as discussed in the
following procedure.
Defining a Simple Collection
To define a simple collection in a class
Create a public variable to act as a collection for your objects.

Public Class widgetRepository


Public widgetColl As New Microsoft.VisualBasic.Collection()
' Insert code to implement additional functionality.
End Class

The class widgetRepository now has a public collection to which you can add widget objects. You can then use a
For Each...Next Statement (Visual Basic) to process the collection elements, as the following code demonstrates.

For Each aWidget As widget In widgetColl


' Insert code to process widgetColl elements
Next aWidget

The widgetColl collection defined in the preceding example is not strongly typed, which means you can add any type of
object to it, not just widget objects. This can lead to type safety problems. For example, suppose you add a String to the
collection, as in the following code.

Dim notWidget As String = "This is not a widget object!"


widgetColl.Add(notWidget)

If you do this, the For Each loop in the previous procedure throws an ArgumentException exception at run time because
an element of the collection is not of type widget.
We recommend that you define a generic class when you want to ensure type safety. For more information and an
example, see How to: Define Type-Safe Collections.
See Also
Tasks
How to: Define Type-Safe Collections
Reference
Option Strict Statement
Concepts
Visual Basic Collection Class
Collections in Visual Basic
Generic Types in Visual Basic
Visual Basic Language Concepts

How to: Define Type-Safe Collections


You can define and create a collection using the Collection class provided by Visual Basic, as the following example illustrates.
VB
Public Class widgetRepository
Public widgetColl As New Microsoft.VisualBasic.Collection()
' Insert code to implement additional functionality.
End Class

However, this widgetColl collection is not strongly typed. You can add any type of element to it, not just widget objects. When
you retrieve an element, you might have to try to convert it to a widget. This can lead to type safety problems. For example,
suppose you add a String to the collection using the following code.
VB
Dim notWidget As String = "This is not a widget object!"
widgetColl.Add(notWidget)

If you do this, any subsequent attempt to retrieve that element throws an ArgumentException exception at run time because
the element of the collection is not of type widget.
Protecting Against Type Safety Problems
We recommend that you maximize type safety by defining a generic class. This enforces strong typing and also provides
flexibility in the particular data type it works with. For more information, see Generic Types in Visual Basic.
To define a type-safe collection in a class
Use one of the generic classes in the System.Collections.Generic namespace, for example List, for your collection class.
Then you can create a collection that is restricted to widget members only. The following example illustrates how the
declaration in the preceding example could be modified to create a generic collection.
VB
Public widgetColl As New System.Collections.Generic.List(Of widget)

When you do this, the strong typing allows you to add only widget items to the collection, and every element you
retrieve through the Item property is a widget object. Also because of this strong typing, the retrieving code can use all
the properties and methods exposed by widget.
-or-
Create your own collection class without using any predefined classes. Restrict your Add method to accept only widget
objects, and implement your Item property with a return type of widget. For more information, see
How to: Define Type-Safe Collections.
If Item returned elements of type Object, you would have explicit access only to the properties and methods defined on
the Object class. To access the widget members, you would have to either turn Option Strict Off or use the
CType Function to explicitly convert the returned element to widget, as in the following code.
VB
Dim nextWidget As widget
Try
nextWidget = CType(widgetColl.Item(1), widget)
Catch ex As Exception
' Insert code to run if the collection item is not a widget.
End Try

In either case, using Object elements in this way causes Visual Basic to employ late binding, which degrades your
performance.
Note that the Visual Basic Collection class accepts and returns Object elements, so it also has the disadvantages of
weak typing and late binding.
See Also
Reference
Option Strict Statement
System.Collections
System.Collections.Generic
System.Collections.Specialized
Concepts
Visual Basic Collection Class
Collections in Visual Basic
Generic Types in Visual Basic
Visual Basic Language Concepts

How to: Create a Collection of Objects


As with any object, you declare a variable to hold the object, then create the collection object and assign it to the variable.
For a collection object, you can use either the Visual Basic Collection Class or a .NET Framework collection class. In particular,
you can create a generic collection by using one of the classes in the System.Collections.Generic namespace. A generic
collection is useful when every item in the collection has the same data type. Generic collections enforce strong typing by
allowing only the desired data type to be added. For more information, see How to: Define Type-Safe Collections.
Once the collection object is created, you can add and remove items and access items in the collection.
Two examples about creating collections follow. Each collection holds String items and associates a String key with each item.
The first two procedures create a collection using the Visual Basic collection class. The last two procedures create a collection
using a .NET Framework generic collection class.
To create a collection using the Visual Basic collection class
1. Declare and create a Visual Basic Collection variable, as the following example shows.

Dim sampleVisualBasicColl As New Microsoft.VisualBasic.Collection()

The collection in sampleVisualBasicColl can accept items of any data type.


2. Use the Add Method (Collection Object) to add elements to the collection. The following example creates four String
elements and adds them to the collection. It creates a unique String value as the key for each new element and passes
this value to the Add method.

Dim item1, item2, item3, item4 As String


item1 = "Items"
item2 = "In"
item3 = "A"
item4 = "Collection"
sampleVisualBasicColl.Add(item1, "firstkey")
sampleVisualBasicColl.Add(item2, "secondkey")
sampleVisualBasicColl.Add(item3, "thirdkey")
sampleVisualBasicColl.Add(item4, "fourthkey")

The Key argument is optional in a Visual Basic collection.


3. If you want to remove an element from the collection, you can use the Remove Method (Collection Object), identifying
the element either by its positional index or by its optional key. The following example illustrates this.

' Remove the first element of the Visual Basic collection.


sampleVisualBasicColl.Remove(1)
' Remove the element with the key "secondkey".
sampleVisualBasicColl.Remove("secondkey")

Note that when an element is removed from a Visual Basic Collection, the index values are renumbered from 1 through
the value of the Count Property (Collection Object).
To use For Each...Next to process the elements of your Visual Basic collection
1. Declare a variable of the type stored in the collection. For the preceding example, declare a variable of type String, as the
following example shows.

' Insert code from the preceding example.


Dim aString As String
2. Use a For Each...Next Statement (Visual Basic) to examine each element of the collection. The following example searches
for a particular string and displays it if found.

For Each aString in sampleVisualBasicColl


If aString = "Collection" Then
MsgBox(aString)
End If
Next aString

To create a collection using a generic collection class


1. Declare and create a .NET Framework System.Collections.Generic.Dictionary variable, as the following example shows.

Dim sampleGenericColl As New System.Collections.Generic.Dictionary(Of String, String)

The sampleGenericColl variable holds a type-safe collection that accepts items and keys only of type String.
2. Use the System.Collections.Generic.Dictionary.Add( method to add elements to the collection. The following example
creates four String elements and adds them to the collection. It creates a unique String value as the key for each new
element and passes this value to the Add method.

Dim item1, item2, item3, item4 As String


item1 = "Items"
item2 = "In"
item3 = "A"
item4 = "Collection"
sampleGenericColl.Add("firstkey", item1)
sampleGenericColl.Add("secondkey", item2)
sampleGenericColl.Add("thirdkey", item3)
sampleGenericColl.Add("fourthkey", item4)

The Key argument is required in this generic collection.


3. To remove an element from the collection, use the System.Collections.Generic.IDictionary.Remove( method. You must
supply the key to identify the element to remove. The following example illustrates this.

If Not sampleGenericColl.Remove("thirdkey")
' Insert code to handle "thirdkey" not found in collection.
End If

You can use a For Each...Next statement to loop through and process the elements of a collection, as the following
procedure demonstrates.

To use For Each...Next to process the elements of your generic collection


1. Declare a variable of the type stored in the collection. For the preceding example, declare a variable of type String, as the
following example shows.

' Insert code from the preceding example.


Dim aPair As KeyValuePair(Of String, String)

2. Use a For Each...Next Statement (Visual Basic) to examine each element of the collection. The following example searches
for a particular string and displays it if found.

For Each aPair In sampleGenericColl


If aPair.Value = "Items" Then
MsgBox(aPair.Key & " -- " & aPair.Value)
End If
Next aPair

See Also
Tasks
How to: Create an Array of Objects
Reference
Collection Object (Visual Basic)
System.Collections
System.Collections.Generic
System.Collections.Specialized
Concepts
Visual Basic Collection Class
Visual Basic Language Concepts

How to: Create an Array of Objects


Every object is a reference type. You declare and use an array of a reference type just as you would declare and use an array of
any data type. The elements of an object type array can be retrieved by their index and can be manipulated as any object of the
given type would be.
Arrays also have built-in functionality for searching and sorting that can be accessed through the array variable. For more
information on these methods, see Array.
To create an array of objects
1. Declare the array as shown in the following example. Because arrays are zero-based, they contain one element more than
the upper bound you declare.

Dim x(10) As widget


' x now contains 11 elements of type widget, x(0) through x(10).

2. Create each element of the array, or assign to each element a reference to an already existing object. The following
example demonstrates this.

' Create each element of an array by using a loop.


For q As Integer = 0 To 10
x(q) = New widget()
Next q
' Assign a reference to an existing object to two array elements.
Dim specialWidget As New widget()
x(0) = specialWidget
x(1) = specialWidget

Note that you can assign references to the same object to different elements of the array.
See Also
Tasks
How to: Create a Collection of Objects
Concepts
Managing Groups of Objects
Value Types and Reference Types
Other Resources
Arrays in Visual Basic
Visual Basic Language Concepts

How to: Add, Delete, and Retrieve Items of a Collection


The Visual Basic Collection class contains built-in functionality to allow you to add, delete, and retrieve items.
You might want to add an item to a collection as soon as the item is newly created or obtained, such as a new customer.
You might want to delete an item from a collection when it no longer belongs in the collection, for example when an
employee leaves your company.
You might want to retrieve an item from a collection to edit its contents, for example to change a student's telephone
number.
Note
Collection objects update their numeric index numbers automatically as you add and delete elements. Because of this, the n
umeric index of a given element can change often. Therefore, do not save a numeric index value and expect it to retrieve the s
ame element later in your program. Use keys for this purpose.

To add an item to a collection


Use the Add Method (Collection Object) and specify the item by its Key.
object.Add(Item, Key [, {Before | After}])

For example, to add a work order object to a collection of work orders using the work order's ID property as its key, you
can make the following call.

workOrders.Add(woNew, woNew.ID)

The preceding call assumes that the ID property is a string. If it is a number (for example, a Long integer), use its ToString
method to convert it to the String value required for the Key argument.

workOrders.Add(woNew, woNew.ID.ToString())

The use of a key is optional. If you do not want to associate a key with the object in your collection, you may add it
without a key.

workOrders.Add(woNew)

You can use the optional Before and After arguments to maintain an ordered collection of objects. The item to be added
is placed in the collection before or after the item identified by the Before or After argument, respectively. For example,
setting Before equal to 1 inserts an item at the beginning of the collection, because Collection objects are 1-based.

workOrders.Add(woNew, woNew.ID, 1)

Similarly, the After argument adds an item after the specified index. The following example adds an item as the third
element.

workOrders.Add(woNew, woNew.ID,,2)

You can specify a value for either Before or After, but not both.
To delete an item from a collection
Use the Remove Method (Collection Object) and specify the item by either its Index or its Key.
object.Remove({Index | Key})
The Index argument is the position of the item you want to delete. The Key argument is the same string you used to add
the item to the collection. If the key of the third element in a collection is "W017493", you can use either of the following
two statements to delete it.

workOrders.Remove(3)
workOrders.Remove("W017493")

To delete all items from a collection


Use the Clear Method (Collection Object).
object.Clear()

The Clear method empties the collection.


To retrieve an item from a collection
1. Use the Item Property (Collection Object) and specify the item by either its Index or its Key.
variable = object.Item({Index | Key})

As with the Remove method, the Index argument is the item's position in the collection, and the Key argument is the
string used when the item was added. Using the same example as for the Remove method, either of the following
statements retrieves the third element in the collection.

woCurrent = workOrders.Item(3)
woCurrent = workOrders.Item("W017493")

Note
If you use numbers as keys, you must use their ToString methods to convert them to strings before passing them to th
e Add or Remove method, or to the Item property. A Visual Basic Collection object always assumes that a number is
an index, rather than a key string.

2. If you know the key at compile time, you can alternatively use the dictionary access operator (!) to access an element of
the collection without enclosing the key in quotation marks or parentheses. The preceding call could be written as
follows.

woCurrent = workOrders!W017493

See Also
Reference
Collection Object Members
Add Method (Collection Object)
Remove Method (Collection Object)
Clear Method (Collection Object)
Item Property (Collection Object)
Concepts
Visual Basic Collection Class
Collections as an Alternative to Arrays
Collections in Visual Basic
Visual Basic Language Concepts

How to: Iterate through a Collection in Visual Basic


You can use a For Each loop to iterate through every element of a collection.
Example
The following example uses the For Each...Next Statement (Visual Basic) to access every item in a collection.

Dim testCollection As New Microsoft.VisualBasic.Collection()


' The collection is empty until you add one or more items to it.
For Each collectionItem As Object In testCollection
' Perform desired processing on each item.
Next collectionItem

Compiling the Code


This example requires:
Access to the System namespace.

See Also
Tasks
How to: Add, Delete, and Retrieve Items of a Collection
Reference
For Each...Next Statement (Visual Basic)
Concepts
Collections in Visual Basic
Visual Basic Language Concepts

Troubleshooting Collections
This page lists some common problems that can occur when working with collections.
Using the Wrong Type of Collection
There are several types of collections available to a Visual Basic developer: the Visual Basic Collection class and the collection
classes furnished by the .NET Framework. These classes are not compatible with each other. This means that if you declare a
variable to be of one type of collection, you cannot assign an object of another type to that variable. Also, you can access only
the methods and properties of the collection type you have declared.
The main differences between the Visual Basic and .NET Framework collection classes include the following:
Index Base. .NET Framework collections are zero-based, while the Visual Basic collection is one-based. This means that
the elements of a Visual Basic collection have index values from 1 through the value of the
Count Property (Collection Object), whereas the elements of a .NET Framework collection have index values from 0
through one less than the value of the collection's Count property.
Element Type. The Visual Basic collection supports elements of type Object, which is not type-safe because you can add
an element of any data type. This usually results in degraded performance because the compiler must box and unbox the
elements to convert them to and from the Object Data Type. Some of the .NET Framework collections also have elements
of type Object, but many others are strongly typed, meaning they support elements of a specific type, which makes them
type-safe and usually results in optimal performance.
Keyed Elements. The Visual Basic collection allows you to specify a key when you add an element to it. The key is a
unique String value which you can use later to access that particular element. The .NET Framework collections vary in
regard to keys. Some support keys and some do not.
The namespaces that contain the various collection class definitions are the following:
Microsoft.VisualBasic — the Visual Basic Collection class
System.Collections — specific collection classes such as lists, queues, bit arrays, hash tables, and dictionaries
System.Collections.Generic — generic collection classes, which allow you to create strongly typed collections and specify
the element data type when you create them
System.Collections.Specialized — specialized and strongly typed collection classes, such as linked-list and hybrid
dictionaries, bit-vector and name-object collections, and string-only collections
Correct Approach
Determine which type of collection is most appropriate for your needs. Declare your collection variable to be of that type, and
be sure to create an object of that same type. Use full qualification to ensure that you are specifying the collection type you
intend to. The following example shows two declarations with full qualification.
VB
Dim customers As New Microsoft.VisualBasic.Collection()
Dim stringQueue As New System.Collections.Generic.Queue(Of String)

Once you have created a collection of a specific type, be sure you use only the methods and properties defined on that type.
Set Option Strict On to catch any incorrect object assignments or member accesses at compile time.
See Also
Reference
Option Strict Statement
Concepts
Collections in Visual Basic
Visual Basic Collection Class
Visual Basic Language Concepts

Events in Visual Basic


An event is a message sent by an object announcing that something has happened. Events are implemented using delegates, a
form of object-oriented function pointer that allows a function to be invoked indirectly by way of a reference to the function.
In This Section
Events and Event Handlers
Provides an overview of events, event handlers, and associated terminology.
WithEvents and the Handles Clause
Demonstrates how to use the WithEvents keyword and the Handles clause to associate an event with an event handler.
AddHandler and RemoveHandler
Demonstrates how to use the AddHandler and RemoveHandler statements to dynamically associate an event with an
event handler.
How to: Add Events to a Class
Describes the process of defining events.
How to: Create Event Handlers in the Visual Basic Code Editor
Gives directions for using the Visual Basic Code Editor to write code to respond to events.
How to: Raise an Event (Visual Basic)
Demonstrates how to define an event and uses the RaiseEvent statement to cause the event to occur
How to: Create an Event and Handler (Visual Basic)
Demonstrates how to define an event and an event handler, and how to use the AddHandler statement to associate them.
How to: Write Event Handlers
Demonstrates how to write event handlers using the Handles clause or the AddHandler statement.
How to: Handle Events in Visual Basic
Defines a class that raises an event when you call the CauseEvent method.
Walkthrough: Declaring and Raising Events
Steps you through the process of declaring and raising events for a class.
Walkthrough: Handling Events
Demonstrates how to write an event-handler procedure.
How to: Declare Events That Avoid Blocking
Demonstrates how to define a custom event that allows its event handlers to be called asynchronously.
How to: Declare Events That Conserve Memory Use
Demonstrates how to define a custom event that uses memory only when the event is handled.
Troubleshooting Inherited Event Handlers in Visual Basic 2005
Lists common issues that arise with event handlers in inherited components.
Related Sections
Delegates in Visual Basic
Overview of delegates in Visual Basic.
Handling and Raising Events
Provides an overview of the event model in the .NET Framework.
Creating Event Handlers in Windows Forms
Describes how to work with events associated with Windows Forms objects.
Describes how to work with events associated with Windows Forms objects.
Visual Basic Language Concepts

Events and Event Handlers


While you might visualize a Visual Studio project as a series of procedures that execute in a sequence, in reality, most
programs are event driven—meaning the flow of execution is determined by external occurrences called events.
An event is a signal that informs an application that something important has occurred. For example, when a user clicks a
control on a form, the form can raise a Click event and call a procedure that handles the event. Events also allow separate tasks
to communicate. Say, for example, that your application performs a sort task separately from the main application. If a user
cancels the sort, your application can send a cancel event instructing the sort process to stop.
Event Terms and Concepts
This section describes the terms and concepts used with events in Visual Basic.
Declaring Events
You declare events within classes, structures, modules, and interfaces using the Event keyword, as in the following example:
VB
Event AnEvent(ByVal EventNumber As Integer)

Raising Events
An event is like a message announcing that something important has occurred. The act of broadcasting the message is called
raising the event. In Visual Basic, you raise events with the RaiseEvent statement, as in the following example:
VB
RaiseEvent AnEvent(EventNumber)

Events must be raised within the scope of the class, module, or structure where they are declared. For example, a derived class
cannot raise events inherited from a base class.
Event Senders
Any object capable of raising an event is an event sender, also known as an event source. Forms, controls, and user-defined
objects are examples of event senders.
Event Handlers
Event handlers are procedures that are called when a corresponding event occurs. You can use any valid subroutine with a
matching signature as an event handler. You cannot use a function as an event handler, however, because it cannot return a
value to the event source.
Visual Basic uses a standard naming convention for event handlers that combines the name of the event sender, an
underscore, and the name of the event. For example, the Click event of a button named button1 would be named Sub
button1_Click.

Note
We recommend that you use this naming convention when defining event handlers for your own events, but it is not require
d; you can use any valid subroutine name.

Associating Events with Event Handlers


Before an event handler becomes usable, you must first associate it with an event by using either the Handles or AddHandler
statement.
The WithEvents statement and Handles clause provide a declarative way of specifying event handlers. Events raised by an
object declared with WithEvents can be handled by any subroutine with a Handles clause that names this event. Although the
Handles clause is the standard way of associating an event with an event handler, it is limited to associating events with event
handlers at compile time.
The AddHandler and RemoveHandler statements are more flexible than the Handles clause. They allow you to dynamically
connect and disconnect the events with one or more event handlers at run time, and they do not require you to declare object
variables using WithEvents. However, there are some restrictions with using WithEvents. For more information, see
WithEvents and the Handles Clause.
In some cases, such as with events associated with forms or controls, Visual Basic automatically stubs out an empty event
handler and associates it with an event. For example, when you double-click a command button on a form in design mode,
Visual Basic creates an empty event handler and a WithEvents variable for the command button, as in the following code:
VB
Friend WithEvents Button1 As System.Windows.Forms.Button
Protected Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
End Sub

See Also
Tasks
How to: Write Event Handlers
Reference
Handles
AddHandler Statement
Concepts
AddHandler and RemoveHandler
WithEvents and the Handles Clause
Visual Basic Language Concepts

WithEvents and the Handles Clause


The WithEvents statement and the Handles clause provide a declarative way of specifying event handlers. An event raised by
an object declared with the WithEvents keyword can be handled by any procedure with a Handles statement for that event,
as shown in the following example:
VB
' Declare a WithEvents variable.
Dim WithEvents EClass As New EventClass

' Call the method that raises the object's events.


Sub TestEvents()
EClass.RaiseEvents()
End Sub

' Declare an event handler that handles multiple events.


Sub EClass_EventHandler() Handles EClass.XEvent, EClass.YEvent
MsgBox("Received Event.")
End Sub

Class EventClass
Public Event XEvent()
Public Event YEvent()
' RaiseEvents raises both events.
Sub RaiseEvents()
RaiseEvent XEvent()
RaiseEvent YEvent()
End Sub
End Class

The WithEvents statement and the Handles clause are often the best choice for event handlers because the declarative syntax
they use makes event handling easier to code, read and debug. However, be aware of the following limitations on the use of
WithEvents variables:
You cannot use a WithEvents variable as an object variable. That is, you cannot declare it as Object—you must specify
the class name when you declare the variable.
Because shared events are not tied to class instances, you cannot use WithEvents to declaratively handle shared events.
Similarly, you cannot use WithEvents or Handles to handle events from a Structure. In both cases, you can use the
AddHandler statement to handle those events.
You cannot create arrays of WithEvents variables.
WithEvents variables allow a single event handler to handle one or more kind of event, or one or more event handlers
to handle the same kind of event.
See Also
Reference
Handles
WithEvents
AddHandler Statement
Concepts
AddHandler and RemoveHandler
Visual Basic Language Concepts

AddHandler and RemoveHandler


The AddHandler statement is similar to the Handles clause in that both allow you to specify an event handler. However,
AddHandler, used with RemoveHandler, provides greater flexibility than the Handles clause, allowing you to dynamically
add, remove, and change the event handler associated with an event. If you want to handle shared events or events from a
structure, you must use AddHandler.
AddHandler takes two arguments: the name of an event from an event sender such as a control, and an expression that
evaluates to a delegate. You do not need to explicitly specify the delegate class when using AddHandler, since the AddressOf
statement always returns a reference to the delegate. The following example associates an event handler with an event raised
by an object:
VB
AddHandler Obj.XEvent, AddressOf Me.XEventHandler

RemoveHandler, which disconnects an event from an event handler, uses the same syntax as AddHandler. For example:
VB
RemoveHandler Obj.XEvent, AddressOf Me.XEventHandler

See Also
Tasks
How to: Write Event Handlers
Reference
AddHandler Statement
Concepts
Events and Event Handlers
WithEvents and the Handles Clause
Visual Basic Language Concepts

How to: Add Events to a Class


You add events to a class by declaring them with the Events statement. The declaration includes the name of the event and the
arguments it uses.
Adding an event to a class specifies that an object of this class can raise a specific event. To cause an event to actually happen,
you must use the RaiseEvent statement. You can use the Handles keyword or the AddHandler statement to associate the
event with an event-handler procedure. Events must be raised within the scope where they are declared. For example, a
derived class cannot raise events inherited from a base class.
Note
Events cannot have return values, optional arguments, or ParamArray arguments.

To add an event to a class


In the declarations section of the class module that defines the class, use the Event statement to declare the event with
whatever arguments you want it to have. For example:
VB
Public Event PercentDone(ByVal Percent As Single, _
ByRef Cancel As Boolean)

See Also
Tasks
Walkthrough: Declaring and Raising Events
Walkthrough: Handling Events
How to: Write Event Handlers
Reference
RaiseEvent Statement
Handles
AddHandler Statement
Concepts
Events and Event Handlers
Delegates and the AddressOf Operator
AddHandler and RemoveHandler
Other Resources
Polymorphism
Visual Basic Language Concepts

How to: Create Event Handlers in the Visual Basic Code Editor
The Visual Basic Code Editor provides an easy way to create event handlers for your Windows Forms. Although it does not
allow you to connect multiple events to a single event handler (see
How to: Connect Multiple Events to a Single Event Handler in Windows Forms), it does provide a quick and easy way to create
event handlers while working on your form's code without having to display the form in the Windows Forms Designer.
To create an event handler using the Visual Basic Code Editor
1. In the Code Editor, from the Class Name drop-down list, choose the form or control that you want to create an event
handler for.
2. From the Method Name list at the top of the Code Editor, choose the event that you want to create an event handler
for.
Visual Basic creates an event handler and adds it to your form's class.

See Also
Tasks
How to: Create Event Handlers Using the Designer
Troubleshooting Inherited Event Handlers in Visual Basic 2005
Concepts
Event Handlers Overview (Windows Forms)
Other Resources
Creating Event Handlers in Windows Forms
Creating a New Windows Form
Visual Basic Language Concepts

How to: Raise an Event (Visual Basic)


This example defines an event (TimeExpired) and uses the RaiseEvent statement to cause the event to occur.
Example
VB
Public Event TimeExpired(ByVal Status As String)
Public Sub RaiseTimeExpiredEvent()
RaiseEvent TimeExpired("Your time has run out")
End Sub

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
Compiling the Code
This example requires:
Access to the members of the System namespace. Add an Imports statement if you are not fully qualifying member
names in your code. For more information, see Imports Statement.
The Event statement to be at class level and not inside any procedure.
The RaiseEvent statement to be inside some procedure in your application.
See Also
Tasks
How to: Create an Event and Handler (Visual Basic)
Reference
Event Statement
RaiseEvent Statement
Concepts
Events and Event Handlers
Other Resources
Events in Visual Basic
Visual Basic Language Concepts

How to: Create an Event and Handler (Visual Basic)


This example defines an event, TimeExpired, and an event handler, HandleTimeExpired, and uses the AddHandler statement
to associate them.
Example
VB
Public Event TimeExpired(ByVal Status As String)
Public Sub HandleTimeExpired(ByVal Status As String)
' Perform desired processing for when time has expired.
MsgBox("HandleTimeExpired caught the TimeExpired event" & _
vbCrLf & "Status = " & Status)
End Sub
Public Sub SetUpEventHandler()
AddHandler TimeExpired, AddressOf HandleTimeExpired
End Sub

Compiling the Code


This example requires:
Access to the members of the System namespace. Add an Imports statement if you are not fully qualifying member
names in your code. For more information, see Imports Statement.
The Event statement to be at class level and not inside any procedure.
The Event statement and both procedures (HandleTimeExpired and SetUpEventHandler) to be defined in the same class
or module. Otherwise the AddHandler statement must qualify the event and the handler to the objects in which they are
defined.
See Also
Tasks
How to: Raise an Event (Visual Basic)
Reference
Event Statement
AddHandler Statement
Concepts
Events and Event Handlers
Other Resources
Events in Visual Basic
Visual Basic Language Concepts

How to: Write Event Handlers


The way you construct an event handler depends on how you want to associate it with events. The standard way to create an
event handler is to use the Handles keyword with the WithEvents keyword. Visual Basic provides a second way to handle
events: the AddHandler statement. AddHandler and RemoveHandler allow you to dynamically start and stop event
handling for a specific event. You can use either approach, but you should not use both WithEvents and AddHandler with the
same event.
Handling Events Using WithEvents
The WithEvents keyword allows you to create class or module-level object variables that can be used with the Handles clause
in event handlers.
To handle events using WithEvents and the Handles clause
1. Create a simple class that contains an event.
VB
Class Class1
Public Event AnEvent(ByVal EventNumber As Integer)
End Class

2. In the class or module that will handle the event, use the WithEvents keyword to declare an object variable for the
source of your events, as in the following example:
VB
Public WithEvents ClassInst As Class1

3. In the Code Editor, choose the WithEvents variable you just declared from the Class Name drop-down list on the left.
4. Choose the event you want to handle from the Method Name drop-down list on the right. The Code Editor creates the
empty event-handler procedure with a Handles clause.
Note
This step is optional. You can create the event-handler procedure manually as long as the procedure you create is a sub
routine, has the correct argument list to match the event being handled, and has a Handles clause that specifies the ev
ent being handled.

5. Add event-handling code to the event-handler procedure using the supplied arguments. The following code provides an
example:
VB
Public Sub ClassInst_AnEvent(ByVal EventNumber As Integer) _
Handles ClassInst.AnEvent
MsgBox("Received event number: " & CStr(EventNumber))
End Sub

Handling Events Using AddHandler


You can use the AddHandler statement to dynamically connect events with event-handler procedures.
To handle events using AddHandler
1. Create a subroutine to handle the event, as in the following example:
VB
Public Sub EHandler(ByVal EventNumber As Integer)
MsgBox("Received event number " & CStr(EventNumber))
End Sub

2. Declare an object variable of the class that is the source of the events you want to handle. Unlike a WithEvents variable,
this can be a local variable in a procedure. For example:
VB
Public Sub TestAddHandler()
Dim CI As New Class1
End Sub

3. Use the AddHandler statement to specify the name of the event sender, and the AddressOf statement to provide the
name of your event handler. For example, add the following code to the end of the TestAddHandler subroutine:
VB
AddHandler CI.AnEvent, AddressOf EHandler

Any procedure can serve as an event handler as long as it supports the correct arguments for the event being handled.

Using RemoveHandler to Stop Handling Events


You can use the RemoveHandler statement to dynamically disconnect events from event-handler procedures.
To stop handling events using RemoveHandler
Use the RemoveHandler statement to specify the name of the event sender and the AddressOf statement to provide
the name of your event handler. The syntax for RemoveHandler statements will always closely match the AddHandler
statement used to start event handling. For example:
VB
RemoveHandler CI.AnEvent, AddressOf EHandler

Handling Events Inherited from a Base Class


Derived classes—classes that inherit characteristics from a base class—can handle events raised by their base class using the
Handles MyBase statement.
To handle events from a base class
Declare an event handler in the derived class by adding a Handles MyBase.eventname statement to the declaration line
of your event-handler procedure, where eventname is the name of the event in the base class you are handling. For
example:
VB
Public Class BaseClass
Public Event BaseEvent(ByVal i As Integer)
' Place methods and properties here.
End Class

Public Class DerivedClass


Inherits BaseClass
Sub EventHandler(ByVal x As Integer) Handles MyBase.BaseEvent
' Place code to handle events from BaseClass here.
End Sub
End Class

See Also
Reference
Handles
AddHandler Statement
Concepts
Events and Event Handlers
Delegates and the AddressOf Operator
AddHandler and RemoveHandler
Visual Basic Language Concepts

How to: Handle Events in Visual Basic


The following example defines a class that raises an event when you call the CauseEvent method. This event is handled by an
event-handler procedure called EventHandler.
Example
To run this example, add the following code to the form class of a Visual Basic Windows Application project, and call the
TestEvents procedure with an integer argument.

VB
Public Class Class1
' Declare an event for this class.
Public Event Event1(ByVal EventNumber As Integer)
' Define a method that raises an event.
Sub CauseEvent(ByVal EventNumber As Integer)
RaiseEvent Event1(EventNumber)
End Sub
End Class

Protected Sub TestEvents(ByVal EventNumber As Integer)


Dim Obj As New Class1
AddHandler Obj.Event1, AddressOf Me.EventHandler
' Cause the object to raise an event.
Obj.CauseEvent(EventNumber)
End Sub

Sub EventHandler(ByVal EventNumber As Integer)


MsgBox("Received event number " & EventNumber.ToString)
End Sub

See Also
Tasks
How to: Write Event Handlers
Concepts
Events and Event Handlers
Delegates and the AddressOf Operator
AddHandler and RemoveHandler
Visual Basic Language Concepts

Walkthrough: Declaring and Raising Events


This walkthrough demonstrates how to declare and raise events for a class named Widget. After you complete the steps, you
might want to read the companion topic, Walkthrough: Handling Events, which shows how to use events from Widget objects
to provide status information in an application.
The Widget Class
Assume for the moment that you have a Widget class. Your Widget class has a method that can take a long time to execute, and
you want your application to be able to put up some kind of completion indicator.
Of course, you could make the Widget object show a percent-complete dialog box, but then you would be stuck with that
dialog box in every project in which you used the Widget class. A good principle of object design is to let the application that
uses an object handle the user interface—unless the whole purpose of the object is to manage a form or dialog box.
The purpose of Widget is to perform other tasks, so it is better to add a PercentDone event and let the procedure that calls
Widget's methods handle that event and display status updates. The PercentDone event can also provide a mechanism for
canceling the task.
To build the code example for this topic
1. Open a new Visual Basic Windows Application project and create a form named Form1.
2. Add two buttons and a label to Form1.
3. Name the objects as shown in the following table.
Object Property Setting
Button1 Text Start Task

Button2 Text Cancel

Label (Name), Text lblPercentDone, 0

4. On the Project menu, choose Add Class to add a class named Widget.vb to the project.

To declare an event for the Widget class


Use the Event keyword to declare an event in the Widget class. Note that an event can have ByVal and ByRef
arguments, as Widget's PercentDone event demonstrates:
VB
Public Event PercentDone(ByVal Percent As Single, _
ByRef Cancel As Boolean)

When the calling object receives a PercentDone event, the Percent argument contains the percentage of the task that is
complete. The Cancel argument can be set to True to cancel the method that raised the event.
Note
You can declare event arguments just as you do arguments of procedures, with the following exceptions: Events cannot have
Optional or ParamArray arguments, and events do not have return values.

The PercentDone event is raised by the LongTask method of the Widget class. LongTask takes two arguments: the length of time
the method pretends to be doing work, and the minimum time interval before LongTask pauses to raise the PercentDone event.
To raise the PercentDone event
1. To simplify access to the Timer property used by this class, add an Imports statement to the top of the declarations
section of your class module, above the Class Widget statement.

VB
Imports Microsoft.VisualBasic.DateAndTime

2. Add the following code to the Widget class:


VB
Public Sub LongTask(ByVal Duration As Single, _
ByVal MinimumInterval As Single)
Dim Threshold As Single
Dim Start As Single
Dim blnCancel As Boolean

' The Timer property of the DateAndTime object returns the seconds
' and milliseconds that have passed since midnight.
Start = CSng(Timer)
Threshold = MinimumInterval

Do While CSng(Timer) < (Start + Duration)


' In a real application, some unit of work would
' be done here each time through the loop.
If CSng(Timer) > (Start + Threshold) Then
RaiseEvent PercentDone( _
Threshold / Duration, blnCancel)
' Check to see if the operation was canceled.
If blnCancel Then Exit Sub
Threshold = Threshold + MinimumInterval
End If
Loop
End Sub

When your application calls the LongTask method, the Widget class raises the PercentDone event every MinimumInterval
seconds. When the event returns, LongTask checks to see if the Cancel argument was set to True.
A few disclaimers are necessary here. For simplicity, the LongTask procedure assumes you know in advance how long the task
will take. This is almost never the case. Dividing tasks into chunks of even size can be difficult, and often what matters most to
users is simply the amount of time that passes before they get an indication that something is happening.
You may have spotted another flaw in this sample. The Timer property returns the number of seconds that have passed since
midnight; therefore, the application gets stuck if it is started just before midnight. A more careful approach to measuring time
would take boundary conditions such as this into consideration, or avoid them altogether, using properties such as Now.
Now that the Widget class can raise events, you can move to the next walkthrough. Walkthrough: Handling Events
demonstrates how to use WithEvents to associate an event handler with the PercentDone event.
See Also
Tasks
Walkthrough: Handling Events
How to: Write Event Handlers
Reference
Timer Property
WithEvents
Now Property
Event Statement
ByVal
ByRef
Imports Statement
Concepts
Events and Event Handlers
Delegates and the AddressOf Operator
AddHandler and RemoveHandler
Visual Basic Language Concepts

Walkthrough: Handling Events


This is the second of two topics that demonstrate how to work with events. The first topic,
Walkthrough: Declaring and Raising Events, shows how to declare and raise events. This section uses the form and class from
that walkthrough to show how to handle events when they take place.
The Widget class example uses traditional event-handling statements. Visual Basic provides other techniques for working with
events. As an exercise, you can modify this example to use the AddHandler and Handles statements.
To handle the PercentDone event of the Widget class
Place the following code in Form1:
VB
Private WithEvents mWidget As Widget
Private mblnCancel As Boolean

The WithEvents keyword specifies that the variable mWidget is used to handle an object's events. You specify the kind of
object by supplying the name of the class from which the object will be created.
The variable mWidget is declared in Form1 because WithEvents variables must be class-level. This is true regardless of
the type of class you place them in.
The variable mblnCancel is used to cancel the LongTask method.
Writing Code to Handle an Event
As soon as you declare a variable using WithEvents, the variable name appears in the left drop-down list of the class's Code
Editor. When you select mWidget, the Widget class's events appear in the right drop-down list. Selecting an event displays the
corresponding event procedure, with the prefix mWidget and an underscore. All the event procedures associated with a
WithEvents variable are given the variable name as a prefix.
To handle an event
1. Select mWidget from the left drop-down list in the Code Editor.
2. Select the PercentDone event from the right drop-down list. The Code Editor opens the mWidget_PercentDone event
procedure.
Note
The Code Editor is useful, but not required, for inserting new event handlers. In this walkthrough, it is more direct to ju
st copy the event handlers directly into your code.

3. Add the following code to the mWidget_PercentDone event handler:


VB
Private Sub mWidget_PercentDone( _
ByVal Percent As Single, _
ByRef Cancel As Boolean _
) Handles mWidget.PercentDone
lblPercentDone.Text = CInt(100 * Percent) & "%"
My.Application.DoEvents()
If mblnCancel Then Cancel = True
End Sub

Whenever the PercentDone event is raised, the event procedure displays the percent complete in a Label control. The
DoEvents method allows the label to repaint, and also gives the user the opportunity to click the Cancel button.
4. Add the following code for the Button2_Click event handler:
VB
Private Sub Button2_Click( _
ByVal sender As Object, _
ByVal e As System.EventArgs _
) Handles Button2.Click
mblnCancel = True
End Sub

If the user clicks the Cancel button while LongTask is running, the Button2_Click event is executed as soon as the DoEvents
statement allows event processing to occur. The class-level variable mblnCancel is set to True, and the mWidget_PercentDone
event then tests it and sets the ByRef Cancel argument to True.
Connecting a WithEvents Variable to an Object
Form1 is now set up to handle a Widget object's events. All that remains is to find a Widget somewhere.

When you declare a variable WithEvents at design time, no object is associated with it. A WithEvents variable is just like any
other object variable. You have to create an object and assign a reference to it with the WithEvents variable.
To create an object and assign a reference to it
1. Select (Form1 Events) from the left drop-down list in the Code Editor.
2. Select the Load event from the right drop-down list. The Code Editor opens the Form1_Load event procedure.
3. Add the following code for the Form1_Load event procedure to create the Widget:
VB
Private Sub Form1_Load( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) Handles MyBase.Load
mWidget = New Widget
End Sub

When this code executes, Visual Basic creates a Widget object and connects its events to the event procedures associated with
mWidget. From that point on, whenever the Widget raises its PercentDone event, the mWidget_PercentDone event procedure is
executed.
To call the LongTask method
Add the following code to the Button1_Click event handler:
VB
Private Sub Button1_Click( _
ByVal sender As Object, _
ByVal e As System.EventArgs _
) Handles Button1.Click
mblnCancel = False
lblPercentDone.Text = "0%"
lblPercentDone.Refresh()
mWidget.LongTask(12.2, 0.33)
If Not mblnCancel Then lblPercentDone.Text = CStr(100) & "%"
End Sub
Before the LongTask method is called, the label that displays the percent complete must be initialized, and the class-level
Boolean flag for canceling the method must be set to False.
LongTask is called with a task duration of 12.2 seconds. The PercentDone event is raised once every one-third of a second. Each
time the event is raised, the mWidget_PercentDone event procedure is executed.
When LongTask is done, mblnCancel is tested to see if LongTask ended normally, or if it stopped because mblnCancel was set to
True. The percent complete is updated only in the former case.
To run the program
1. Press F5 to put the project in run mode.
2. Click the Start Task button. Each time the PercentDone event is raised, the label is updated with the percentage of the
task that is complete.
3. Click the Cancel button to stop the task. Notice that the appearance of the Cancel button does not change immediately
when you click it. The Click event cannot happen until the My.Application.DoEvents statement allows event
processing.
Note
The My.Application.DoEvents method does not process events in exactly the same way as the form does. For exampl
e, in this walkthrough, you must click the Cancel button twice. To allow the form to handle the events directly, you can
use multithreading. For more information, see Multithreading in Visual Basic.

You may find it instructive to run the program with F11 and step through the code a line at a time. You can clearly see how
execution enters LongTask, and then briefly re-enters Form1 each time the PercentDone event is raised.
What would happen if, while execution was back in the code of Form1, the LongTask method were called again? At worst, a
stack overflow might occur if LongTask were called every time the event was raised.
You can cause the variable mWidget to handle events for a different Widget object by assigning a reference to the new Widget
to mWidget. In fact, you can make the code in Button1_Click do this every time you click the button.
To handle events for a different widget
Add the following line of code to the Button1_Click procedure, immediately preceding the line that reads
mWidget.LongTask(12.2, 0.33):

VB
mWidget = New Widget
' Create a new Widget object.

The code above creates a new Widget each time the button is clicked. As soon as the LongTask method completes, the
reference to the Widget is released, and the Widget is destroyed.
A WithEvents variable can contain only one object reference at a time, so if you assign a different Widget object to mWidget,
the previous Widget object's events will no longer be handled. If mWidget is the only object variable containing a reference to
the old Widget, the object is destroyed. If you want to handle events from several Widget objects, use the AddHandler
statement to process events from each object separately.
Note
You can declare as many WithEvents variables as you need, but arrays of WithEvents variables are not supported.

See Also
Tasks
Walkthrough: Declaring and Raising Events
How to: Write Event Handlers
Reference
Handles
WithEvents
Concepts
Events and Event Handlers
Delegates and the AddressOf Operator
AddHandler and RemoveHandler
Other Resources
Polymorphism
Visual Basic Language Concepts

How to: Declare Events That Avoid Blocking


There are several circumstances when it is important that one event handler not block subsequent event handlers. Custom
events allow the event to call its event handlers asynchronously.
By default, the backing-store field for an event declaration is a multicast delegate that serially combines all the event handlers.
This means that if one handler takes a long time to complete, it blocks the other handlers until it completes. (Well-behaved
event handlers should never perform lengthy or potentially blocking operations.)
Instead of using the default implementation of events that Visual Basic provides, you can use a custom event to execute the
event handlers asynchronously.
Example
In this example, the AddHandler accessor adds the delegate for each handler of the Click event to an ArrayList stored in the
EventHandlerList field.

When code raises the Click event, the RaiseEvent accessor invokes all the event handler delegates asynchronously using the
BeginInvoke method. That method invokes each handler on a worker thread and returns immediately, so handlers cannot
block one another.
VB
Public NotInheritable Class ReliabilityOptimizedControl
'Defines a list for storing the delegates
Private EventHandlerList As New ArrayList

'Defines the Click event using the custom event syntax.


'The RaiseEvent always invokes the delegates asynchronously
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
EventHandlerList.Add(value)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
EventHandlerList.Remove(value)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
For Each handler As EventHandler In EventHandlerList
If handler IsNot Nothing Then
handler.BeginInvoke(sender, e, Nothing, Nothing)
End If
Next
End RaiseEvent
End Event
End Class

See Also
Tasks
How to: Declare Events That Conserve Memory Use
Reference
Event Statement
ArrayList
BeginInvoke
Visual Basic Language Concepts

How to: Declare Events That Conserve Memory Use


There are several circumstances when it is important that an application keep its memory usage low. Custom events allow the
application to use memory only for the events that it handles.
By default, when a class declares an event, the compiler allocates memory for a field to store the event information. If a class
has many unused events, they needlessly take up memory.
Instead of using the default implementation of events that Visual Basic provides, you can use custom events to manage the
memory usage more carefully.
Example
In this example, the class uses one instance of the EventHandlerList class, stored in the Events field, to store information about
the events in use. The EventHandlerList class is an optimized list class designed to hold delegates.
All events in the class use the Events field to keep track of what methods are handling each event.
VB
Public Class MemoryOptimizedBaseControl
' Define a delegate store for all event handlers.
Private Events As New System.ComponentModel.EventHandlerList

' Define the Click event to use the delegate store.


Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
Events.AddHandler("ClickEvent", value)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
Events.RemoveHandler("ClickEvent", value)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
CType(Events("ClickEvent"), EventHandler).Invoke(sender, e)
End RaiseEvent
End Event

' Define the Click event to use the same delegate store.
Public Custom Event DoubleClick As EventHandler
AddHandler(ByVal value As EventHandler)
Events.AddHandler("DoubleClickEvent", value)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
Events.RemoveHandler("DoubleClickEvent", value)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
CType(Events("DoubleClickEvent"), EventHandler).Invoke(sender, e)
End RaiseEvent
End Event
' Define additional events to use the same delegate store.
' ...
End Class

See Also
Tasks
How to: Declare Events That Avoid Blocking
Reference
Event Statement
EventHandlerList
Visual Basic Language Concepts

Troubleshooting Inherited Event Handlers in Visual Basic 2005


This topic lists common issues that arise with event handlers in inherited components.
Procedures
Code in Event Handler Executes Twice for Every Call
An inherited event handler must not include a Handles clause. The method in the base class is already associated with the
event and will fire accordingly. Remove the Handles clause from the inherited method.
VB
' INCORRECT
Protected Overrides Sub Button1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click

' The Handles clause will cause all code


' in this block to be executed twice.
End Sub

If the inherited method does not have a Handles keyword, verify that your code does not contain an extra
AddHandler Statement or any additional methods that handle the same event.
See Also
Tasks
How to: Write Event Handlers
Concepts
Events and Event Handlers
How to: Handle Events in Visual Basic
Other Resources
Events in Visual Basic
Visual Basic Language Concepts

Delegates in Visual Basic


A delegate is a form of object-oriented function pointer that allows a function to be invoked indirectly by way of a reference to
the function. Delegates can be used to hook up event handlers and pass a procedure from one procedure to another.
In This Section
Delegates and the AddressOf Operator
Provides an introduction to delegates and how they are used.
How to: Invoke a Delegate Method
Creates a sort procedure in a class that uses the standard alphabetic sort on most list boxes, but is able to switch at run time
to a custom sort procedure. To do this, you pass the custom sort procedure to the sort class at run time, using delegates.
How to: Pass Procedures to Another Procedure in Visual Basic
Demonstrates how to use delegates to pass one procedure to another procedure.
Related Sections
Events in Visual Basic
Overview of events in Visual Basic.
Handling and Raising Events
Provides an overview of the event model in the .NET Framework.
Creating Event Handlers in Windows Forms
Describes how to work with events associated with Windows Forms objects.
Visual Basic Language Concepts

Delegates and the AddressOf Operator


Delegates are objects you can use to call the methods of other objects. They are sometimes described as type-safe function
pointers because they are similar to function pointers used in other programming languages. But unlike function pointers,
Visual Basic delegates are a reference type based on the class System.Delegate. Delegates can reference both shared methods
— methods that can be called without a specific instance of a class — and instance methods.
Delegates and Events
Delegates are useful in situations where you need an intermediary between a calling procedure and the procedure being
called. For example, you might want an object that raises events to be able to call different event handlers under different
circumstances. Unfortunately, the object raising the events cannot know ahead of time which event handler is handling a
specific event. Visual Basic lets you dynamically associate event handlers with events by creating a delegate for you when you
use the AddHandler statement. At run time, the delegate forwards calls to the appropriate event handler.
Although you can create your own delegates, in most cases Visual Basic creates the delegate and takes care of the details for
you. For example, an Event statement implicitly defines a delegate class named <EventName>EventHandler as a nested class of
the class containing the Event statement, and with the same signature as the event. The AddressOf statement implicitly
creates an instance of a delegate. For example, the following two lines of code are equivalent:
VB
AddHandler Button1.Click, AddressOf Me.Button1_Click
' The previous line of code is shorthand for the next line of code.
AddHandler Button1.Click, New EventHandler(AddressOf Button1_Click)

You can use the shorthand way of creating delegates anywhere the compiler can determine the delegate's type by the context.
Declaring Events that Use an Existing Delegate Type
In some situations, you may want to declare an event to use an existing delegate type as its underlying delegate. The following
syntax demonstrates how:
VB
Delegate Sub DelegateType()
Event AnEvent As DelegateType

This is useful when you want to route multiple events to the same handler.
Delegate Variables and Parameters
You can use delegates for other, non-event related tasks, such as free threading or with procedures that need to call different
versions of functions at compile time.
For example, suppose you have a classified-ad application that includes a list box with the names of cars. The ads are sorted by
title, which is normally the make of the car. A problem you may face occurs when some cars include the year of the car before
the make. The problem is that the built-in sort functionality of the list box sorts only by character codes; it places all the ads
starting with dates first, followed by the ads starting with the make.
To fix this, you can create a sort procedure in a class that uses the standard alphabetic sort on most list boxes, but is able to
switch at run time to the custom sort procedure for car ads. To do this, you pass the custom sort procedure to the sort class at
run time, using delegates.
Each delegate class defines a constructor that takes a specification of an object method. The following syntax provides an
example of a parameter to such a delegate constructor:
AddressOf [expression.]methodname
The compile-time type of expression must be a class or an interface with a method by the specified name whose signature
matches the signature of the delegate class. The method can be either a shared (class) method or an instance method.
See Also
Tasks
How to: Pass Procedures to Another Procedure in Visual Basic
How to: Invoke a Delegate Method
How to: Write Event Handlers
Reference
Delegate Statement
AddressOf Operator
Concepts
Events and Event Handlers
AddHandler and RemoveHandler
Multithreaded Applications
Visual Basic Language Concepts

How to: Invoke a Delegate Method


This example shows how to associate a method with a delegate and then invoke that method through the delegate.
Create the delegate and matching procedures
1. Create a delegate named MySubDelegate.

Delegate Sub MySubDelegate(ByVal x As Integer)

2. Declare a class that contains a method with the same signature as the delegate.

Class class1
Sub Sub1(ByVal x As Integer)
MsgBox("The value of x is: " & CStr(x))
End Sub
End Class

3. Define a method that creates an instance of the delegate and invokes the method associated with the delegate by calling
the built-in Invoke method.

Protected Sub DelegateTest()


Dim c1 As New class1
' Create an instance of the delegate.
Dim msd As MySubDelegate = AddressOf c1.Sub1
' Call the method.
msd.Invoke(10)
End Sub

See Also
Tasks
How to: Write Event Handlers
Reference
Delegate Statement
Concepts
Delegates and the AddressOf Operator
Events and Event Handlers
AddHandler and RemoveHandler
Multithreaded Applications
Visual Basic Language Concepts

How to: Pass Procedures to Another Procedure in Visual Basic


This example shows how to use delegates to pass a procedure to another procedure.
A delegate is a type that you can use like any other type in Visual Basic. The AddressOf operator returns a delegate object
when applied to a procedure name.
This example has a procedure with a delegate parameter that can take a reference to another procedure, obtained with the
AddressOf operator.
Create the delegate and matching procedures
1. Create a delegate named MathOperator.
VB
Delegate Function MathOperator( _
ByVal x As Double, _
ByVal y As Double _
) As Double

2. Create a procedure named AddNumbers with parameters and return value that match those of MathOperator, so that the
signatures match.
VB
Function AddNumbers( _
ByVal x As Double, _
ByVal y As Double _
) As Double
Return x + y
End Function

3. Create a procedure named SubtractNumbers with a signature that matches MathOperator.


VB
Function SubtractNumbers( _
ByVal x As Double, _
ByVal y As Double _
) As Double
Return x - y
End Function

4. Create a procedure named DelegateTest that takes a delegate as a parameter.


This procedure can accept a reference to AddNumbers or SubtactNumbers, because their signatures match the
MathOperator signature.

VB
Sub DelegateTest( _
ByVal x As Double, _
ByVal op As MathOperator, _
ByVal y As Double _
)
Dim ret As Double
ret = op.Invoke(x, y) ' Call the method.
MsgBox(ret)
End Sub

5. Create a procedure named Test that calls DelegateTest once with the delegate for AddNumbers as a parameter, and again
with the delegate for SubtractNumbers as a parameter.
VB
Protected Sub Test()
DelegateTest(5, AddressOf AddNumbers, 3)
DelegateTest(9, AddressOf SubtractNumbers, 3)
End Sub

When Test is called, it first displays the result of AddNumbers acting on 5 and 3, which is 8. Then the result of
SubtractNumbers acting on 9 and 3 is displayed, which is 6.

See Also
Tasks
How to: Invoke a Delegate Method
Reference
AddressOf Operator
Delegate Statement
Other Resources
Delegates in Visual Basic
Visual Basic Language Concepts

Interfaces in Visual Basic


Interfaces define the properties, methods, and events that classes can implement. Interfaces allow you to define features as
small groups of closely related properties, methods, and events; this reduces compatibility problems because you can develop
enhanced implementations for your interfaces without jeopardizing existing code. You can add new features at any time by
developing additional interfaces and implementations.
In previous versions of Visual Basic, you could consume interfaces but not create them directly. In this version, you can use the
Interface statement, which allows you to define true interfaces as distinct entities from classes, and to implement them with
an improved version of the Implements keyword.
In This Section
Interfaces Overview
Provides an overview of what interfaces are and how Visual Basic implements them.
Interface Definition
Describes how to define interfaces with the Interface and End Interface statements.
Implements Keyword and Implements Statement
Describes how to signify that a section of code implements a specific interface.
Interface Implementation Examples in Visual Basic
Provides three examples of interface implementation.
When to Use Interfaces
Discusses when to use interfaces instead of an inheritance hierarchy.
How to: Create and Implement Interfaces
Lists the steps involved in defining and implementing an interface, plus provides examples.
Walkthrough: Creating and Implementing Interfaces
Provides a detailed procedure that takes you through the process of defining and implementing your own interface.
Related Sections
Inheritance in Visual Basic
Describes how Visual Basic supports inheritance, allowing you to define classes that serve as the basis for derived classes.
Visual Basic Language Concepts

Interfaces Overview
Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide
implementation. They are implemented by classes, and defined as separate entities from classes.
An interface represents a contract, in that a class that implements an interface must implement every aspect of that interface
exactly as it is defined.
With interfaces, you can define features as small groups of closely related members. You can develop enhanced
implementations for your interfaces without jeopardizing existing code, thus minimizing compatibility problems. You can also
add new features at any time by developing additional interfaces and implementations.
Although interface implementations can evolve, interfaces themselves cannot be changed once published. Changes to a
published interface may break existing code. If you think of an interface as a contract, it is clear that both sides of the contract
have a role to play. The publisher of an interface agrees never to change that interface, and the implementer agrees to
implement the interface exactly as it was designed.
In previous versions of Visual Basic, you could consume interfaces but not create them directly. Now you can define true
interfaces using the Interface statement, and you can implement interfaces with an improved version of the Implements
keyword.
See Also
Tasks
How to: Create and Implement Interfaces
Walkthrough: Creating and Implementing Interfaces
Reference
Interface Statement (Visual Basic)
Concepts
Interface Definition
Implements Keyword and Implements Statement
Interface Implementation Examples in Visual Basic
When to Use Interfaces
Other Resources
Inheritance in Visual Basic
Visual Basic Language Concepts

Interface Definition
Interface definitions are enclosed within the Interface and End Interface statements. Following the Interface statement, you
can add an optional Inherits statement that lists one or more inherited interfaces. The Inherits statements must precede all
other statements in the declaration except comments. The remaining statements in the interface definition should be Event,
Sub, Function, Property, Interface, Class, Structure, and Enum statements. Interfaces cannot contain any implementation
code or statements associated with implementation code, such as End Sub or End Property.
In a namespace, interface statements are Friend by default, but they can also be explicitly declared as Public or Friend.
Interfaces defined within classes, modules, interfaces, and structures are Public by default, but they can also be explicitly
declared as Public, Friend, Protected, or Private.
Note
The Shadows keyword can be applied to all interface members. The Overloads keyword can be applied to Sub, Function, a
nd Property statements declared in an interface definition. In addition, Property statements can have the Default, ReadOnl
y, or WriteOnly modifiers. None of the other modifiers—Public, Private, Friend, Protected, Shared, Overrides, MustOve
rride, or Overridable—are allowed. For more information, see Declaration Contexts and Default Access Levels.

See Also
Tasks
How to: Create and Implement Interfaces
Walkthrough: Creating and Implementing Interfaces
Reference
Interface Statement (Visual Basic)
Inherits Statement
Overloads
Default (Visual Basic)
Concepts
Interfaces Overview
Implements Keyword and Implements Statement
Interface Implementation Examples in Visual Basic
When to Use Interfaces
Other Resources
Inheritance in Visual Basic
Visual Basic Language Concepts

Implements Keyword and Implements Statement


The Visual Basic reserved word Implements is used in two ways. The Implements statement signifies that a class or structure
implements an interface. The Implements keyword signifies that a class member or structure member implements a specific
interface member.
Implementing Statement
If a class or structure implements one or more interfaces, it must include the Implements statement immediately after the
Class or Structure statement. The Implements statement requires a comma-separated list of interfaces to be implemented by
a class. The class or structure must implement all interface members using the Implements keyword.
Implements Keyword
The Implements keyword requires a comma-separated list of interface members to be implemented. Generally, only a single
interface member is specified, but you can specify multiple members. The specification of an interface member consists of the
interface name, which must be specified in an implements statement within the class; a period; and the name of the member
function, property, or event to be implemented. The name of a member that implements an interface member can use any
legal identifier, and it is not limited to the InterfaceName_MethodName convention used in earlier versions of Visual Basic.
For example, the following code shows how to declare a subroutine named Sub1 that implements a method of an interface:
VB
Class Class1
Implements interfaceclass.interface2

Sub Sub1(ByVal i As Integer) Implements interfaceclass.interface2.Sub1


End Sub
End Class

The parameter types and return types of the implementing member must match the interface property or member declaration
in the interface. The most common way to implement an element of an interface is with a member that has the same name as
the interface, as shown in the previous example.
To declare the implementation of an interface method, you can use any attributes that are legal on instance method
declarations, including Overloads, Overrides, Overridable, Public, Private, Protected, Friend, Protected Friend,
MustOverride, Default, and Static. The Shared attribute is not legal since it defines a class rather than an instance method.
Using Implements, you can also write a single method that implements multiple methods defined in an interface, as in the
following example:
VB
Class Class2
Implements I1, I2

Protected Sub M1() Implements I1.M1, I1.M2, I2.M3, I2.M4


End Sub
End Class

You can use a private member to implement an interface member. When a private member implements a member of an
interface, that member becomes available by way of the interface even though it is not available directly on object variables for
the class.
See Also
Tasks
How to: Create and Implement Interfaces
Walkthrough: Creating and Implementing Interfaces
Reference
Implements Statement
Implements (Visual Basic)
Concepts
Interfaces Overview
Interface Definition
Interface Implementation Examples in Visual Basic
When to Use Interfaces
Other Resources
Inheritance in Visual Basic
Visual Basic Language Concepts

Interface Implementation Examples in Visual Basic


Classes that implement an interface must implement all its properties, methods, and events.
The following example defines two interfaces. The second interface, Interface2, inherits Interface1 and defines an additional
property and method.
VB
Interface Interface1
Sub sub1(ByVal i As Integer)
End Interface

' Demonstrates interface inheritance.


Interface Interface2
Inherits Interface1
Sub M1(ByVal y As Integer)
ReadOnly Property Num() As Integer
End Interface

The next example implements Interface1, the interface defined in the previous example:
VB
Public Class ImplementationClass1
Implements Interface1
Sub Sub1(ByVal i As Integer) Implements Interface1.sub1
' Insert code here to implement this method.
End Sub
End Class

The final example implements Interface2, including a method inherited from Interface1:
VB
Public Class ImplementationClass2
Implements Interface2
Dim INum As Integer = 0
Sub sub1(ByVal i As Integer) Implements Interface2.sub1
' Insert code here that implements this method.
End Sub
Sub M1(ByVal x As Integer) Implements Interface2.M1
' Insert code here to implement this method.
End Sub

ReadOnly Property Num() As Integer Implements _


Interface2.Num
Get
Num = INum
End Get
End Property
End Class

See Also
Tasks
How to: Create and Implement Interfaces
Walkthrough: Creating and Implementing Interfaces
Reference
Interface Statement (Visual Basic)
Implements Statement
Concepts
Interfaces Overview
Interface Definition
Implements Keyword and Implements Statement
When to Use Interfaces
Visual Basic Language Concepts

When to Use Interfaces


Interfaces are a powerful programming tool because they allow you to separate the definition of objects from their
implementation. Interfaces and class inheritance each have advantages and disadvantages, and you may end up using a
combination of both in your projects. This page and When to Use Inheritance will help you determine which approach is best
for your situation.
Flexibility in Implementation
There are several other reasons why you might want to use interfaces instead of class inheritance:
Interfaces are better suited to situations in which your applications require many possibly unrelated object types to
provide certain functionality.
Interfaces are more flexible than base classes because you can define a single implementation that can implement
multiple interfaces.
Interfaces are better in situations in which you do not need to inherit implementation from a base class.
Interfaces are useful in cases where you cannot use class inheritance. For example, structures cannot inherit from classes,
but they can implement interfaces.
See Also
Tasks
How to: Create and Implement Interfaces
Walkthrough: Creating and Implementing Interfaces
Concepts
When to Use Inheritance
Interfaces Overview
Interface Definition
Implements Keyword and Implements Statement
Interface Implementation Examples in Visual Basic
Other Resources
Inheritance in Visual Basic
Visual Basic Language Concepts

How to: Create and Implement Interfaces


As explained in Interfaces Overview, interfaces describe the properties, methods, and events of a class without providing any
implementation.
To create an interface
1. Define your interface by adding code to it that begins with the Interface keyword and the name of the interface, and
ends with the End Interface statement. For example, the following code defines an interface named IAsset.
VB
Interface IAsset
End Interface

2. Add statements that define the properties, methods, and events your interface supports. For example, the following code
defines one function, one property, and one event.
VB
Interface IAsset
Event ComittedChange(ByVal Success As Boolean)
Property Division() As String
Function GetID() As Integer
End Interface

To implement an interface
1. If the interface that you are implementing is not part of your project, add a reference to the assembly containing the
interface.
2. Create a new class that implements your interface, and include the Implements keyword in the line following the class
name. For example, to implement the IAsset interface, you could name the implementation class Computer, as in the
following code.
VB
Class Computer
Implements IAsset
End Class

3. Add procedures to implement the properties, methods, and events of the class as in the following code, which builds on
the example in the previous step:
VB
Class Computer
Implements IAsset

Public Event ComittedChange(ByVal Success As Boolean) _


Implements IAsset.ComittedChange

Private divisionValue As String

Public Property Division() As String _


Implements IAsset.Division
Get
Return divisionValue
End Get
Set(ByVal value As String)
divisionValue = value
RaiseEvent ComittedChange(True)
End Set
End Property

Private IDValue As Integer

Public Function GetID() As Integer _


Implements IAsset.GetID

Return IDValue
End Function

Public Sub New(ByVal Division As String, ByVal ID As Integer)


Me.divisionValue = Division
Me.IDValue = ID
End Sub
End Class

See Also
Tasks
Walkthrough: Creating and Implementing Interfaces
Reference
Interface Statement (Visual Basic)
Concepts
Interfaces Overview
Interface Definition
Implements Keyword and Implements Statement
Interface Implementation Examples in Visual Basic
When to Use Interfaces
Other Resources
Inheritance in Visual Basic
Visual Basic Language Concepts

Walkthrough: Creating and Implementing Interfaces


Interfaces describe the characteristics of properties, methods, and events, but leave the implementation details up to structures
or classes.
This walkthrough demonstrates how to declare and implement an interface.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To define an interface
1. Open a new Visual Basic Windows Application project.
2. Add a new module to the project by clicking Add Module on the Project menu.
3. Name the new module Module1.vb and click Add. The code for the new module is displayed.
4. Define an interface named TestInterface within Module1 by typing Interface TestInterface between the Module and
End Module statements, and then pressing ENTER. The Code Editor indents the Interface keyword and adds an End
Interface statement to form a code block.
5. Define a property, method, and event for the interface by placing the following code between the Interface and End
Interface statements:
VB
Property Prop1() As Integer
Sub Method1(ByVal X As Integer)
Event Event1()

Implementation
You may notice that the syntax used to declare interface members is different from the syntax used to declare class members.
This difference reflects the fact that interfaces cannot contain implementation code.
To implement the interface
1. Add a class named ImplementationClass by adding the following statement to Module1, after the End Interface
statement but before the End Module statement, and then pressing ENTER:
VB
Class ImplementationClass

If you are working within the integrated development environment, the Code Editor supplies a matching End Class
statement when you press ENTER.
2. Add the following Implements statement to ImplementationClass, which names the interface the class implements:
VB
Implements TestInterface

When listed separately from other items at the top of a class or structure, the Implements statement indicates that the
class or structure implements an interface.
If you are working within the integrated development environment, the Code Editor implements the class members
required by TestInterface when you press ENTER, and you can skip the next step.
3. If you are not working within the integrated development environment, you must implement all the members of the
interface MyInterface. Add the following code to ImplementationClass to implement Event1, Method1, and Prop1:
VB
Event Event1() Implements TestInterface.Event1

Public Sub Method1(ByVal X As Integer) Implements TestInterface.Method1


End Sub

Public Property Prop1() As Integer Implements TestInterface.Prop1


Get
End Get
Set(ByVal value As Integer)
End Set
End Property

The Implements statement names the interface and interface member being implemented.
4. Complete the definition of Prop1 by adding a private field to the class that stored the property value:
VB
' Holds the value of the property.
Private pval As Integer

Return the value of the pval from the property get accessor.
VB
Return pval

Set the value of pval in the property set accessor.


VB
pval = value

5. Complete the definition of Method1 by adding the following code.


VB
MsgBox("The X parameter for Method1 is " & X)
RaiseEvent Event1()

To test the implementation of the interface


1. Right-click the startup form for your project in the Solution Explorer, and click View Code. The editor displays the class
for your startup form. By default, the startup form is called Form1.
2. Add the following testInstance field to the Form1 class:
VB
Dim WithEvents testInstance As TestInterface

By declaring testInstance as WithEvents, the Form1 class can handle its events.
3. Add the following event handler to the Form1 class to handle events raised by testInstance:
VB
Sub EventHandler() Handles testInstance.Event1
MsgBox("The event handler caught the event.")
End Sub

4. Add a subroutine named Test to the Form1 class to test the implementation class:
VB
Sub Test()
' Create an instance of the class.
Dim T As New ImplementationClass
' Assign the class instance to the interface.
' Calls to the interface members are
' executed through the class instance.
testInstance = T
' Set a property.
testInstance.Prop1 = 9
' Read the property.
MsgBox("Prop1 was set to " & testInstance.Prop1)
' Test the method and raise an event.
testInstance.Method1(5)
End Sub

The Test procedure creates an instance of the class that implements MyInterface, assigns that instance to the
testInstance field, sets a property, and runs a method through the interface.

5. Add code to call the Test procedure from the Form1 Load procedure of your startup form:

VB
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Test() ' Test the class.
End Sub

6. Run the Test procedure by pressing F5. The message "Prop1 was set to 9" is displayed. After you click OK, the message
"The X parameter for Method1 is 5" is displayed. Click OK, and the message "The event handler caught the event" is
displayed.
See Also
Tasks
How to: Create and Implement Interfaces
Reference
Implements Statement
Interface Statement (Visual Basic)
Event Statement
Concepts
When to Use Interfaces
Other Resources
Interfaces in Visual Basic
Visual Basic Language Concepts

Inheritance in Visual Basic


Visual Basic supports inheritance, the ability to define classes that serve as the basis for derived classes. Derived classes inherit,
and can extend, the properties, methods, and events of the base class. Derived classes can also override inherited methods with
new implementations. All classes created with Visual Basic are inheritable by default.
Inheritance allows you to write and debug a class once, and then reuse that code over and over as the basis of new classes.
Inheritance also allows you to use inheritance-based polymorphism, the ability to define classes that can be used
interchangeably by client code at run time, but with functionally different, yet identically named methods or properties.
In This Section
Inheritance Basics
Covers inheritance modifiers, overriding methods and properties, MyClass, and MyBase.
How to: Create Derived Classes
Steps you through the process of creating derived classes.
When to Use Inheritance
Discusses when to use inheritance instead of interfaces.
Inheritance and the .NET Framework
Explains how the .NET Framework supports inheritance.
Walkthrough: Implementing Inheritance with COM Objects
Describes using existing COM objects as the basis for new objects.
Inheritance and the Base Object Class
Provides an overview of the class that serves as the basis for all other classes.
How New and Finalize Methods Work in a Class Hierarchy
Describes how constructors and destructors are called in a class hierarchy.
Polymorphism
Summarizes polymorphism and how it is used.
Designing an Inheritance Hierarchy
Provides information about designing and implementing a class hierarchy.
Related Sections
Interfaces in Visual Basic
Summarizes what interfaces are and how they are used.
Object-Oriented Programming in Visual Basic
Introduces the concepts of object-oriented programming as they are used in Visual Basic.
Visual Basic Language Concepts

Inheritance Basics
The Inherits statement is used to declare a new class, called a derived class, based on an existing class, known as a base class.
Derived classes inherit, and can extend, the properties, methods, events, fields, and constants defined in the base class. The
following section describes some of the rules for inheritance, and the modifiers you can use to change the way classes inherit
or are inherited:
All classes are inheritable by default unless marked with the NotInheritable keyword. Classes can inherit from other
classes in your project or from classes in other assemblies that your project references.
Unlike languages that permit multiple inheritance, Visual Basic permits only single inheritance in classes; that is, derived
classes can have only one base class. Although multiple inheritance is not allowed in classes, classes can implement
multiple interfaces, which can effectively accomplish the same ends.
To prevent exposing restricted items in a base class, the access type of a derived class must be equal to or more
restrictive than its base class. For example, a Public class cannot inherit a Friend or a Private class, and a Friend class
cannot inherit a Private class.
Inheritance Modifiers
Visual Basic introduces the following class-level statements and modifiers to support inheritance:
Inherits statement — Specifies the base class.
NotInheritable modifier — Prevents programmers from using the class as a base class.
MustInherit modifier — Specifies that the class is intended for use as a base class only. Instances of MustInherit classes
cannot be created directly; they can only be created as base class instances of a derived class. (Other programming
languages, such as C++ and C#, use the term abstract class to describe such a class.)
Overriding Properties and Methods in Derived Classes
By default, a derived class inherits properties and methods from its base class. If an inherited property or method needs to
behave differently in the derived class it can be overridden; that is, you can define a new implementation of the method in the
derived class. The following modifiers are used to control how properties and methods are overridden:
Overridable — Allows a property or method in a class to be overridden in a derived class.
Overrides — Overrides an Overridable property or method defined in the base class.
NotOverridable — Prevents a property or method from being overridden in an inheriting class. Public methods are
NotOverridable by default.
MustOverride — Requires that a derived class override the property or method. When the MustOverride keyword is
used, the method definition consists of just the Sub, Function, or Property statement. No other statements are allowed,
and specifically there is no End Sub or End Function statement. MustOverride methods must be declared in
MustInherit classes.
For more information about overriding methods, see Overriding Properties and Methods.
The MyBase Keyword
You can use the MyBase keyword to call methods in a base class when overriding methods in a derived class. For example,
suppose you are designing a derived class that overrides a method inherited from the base class. The overridden method can
call the method in the base class and modify the return value as shown in the following code fragment:
VB
Class DerivedClass
Inherits BaseClass
Public Overrides Function CalculateShipping( _
ByVal Dist As Double, _
ByVal Rate As Double) _
As Double
' Call the method in the base class and modify the return value.
Return MyBase.CalculateShipping(Dist, Rate) * 2
End Function
End Class

The following list describes restrictions on using MyBase:


MyBase refers to the immediate base class and its inherited members. It cannot be used to access Private members in
the class.
MyBase is a keyword, not a real object. MyBase cannot be assigned to a variable, passed to procedures, or used in an Is
comparison.
The method that MyBase qualifies does not need to be defined in the immediate base class; it may instead be defined in
an indirectly inherited base class. In order for a reference qualified by MyBase to compile correctly, some base class
must contain a method matching the name and types of parameters appearing in the call.
You cannot use MyBase to call MustOverride base class methods.
MyBase cannot be used to qualify itself. Therefore, the following code is not valid:
MyBase.MyBase.BtnOK_Click()

MyBase cannot be used in modules.


MyBase cannot be used to access base class members that are marked as Friend if the base class is in a different
assembly.
The MyClass Keyword
The MyClass keyword allows you to call an Overridable method implemented in your class and make sure that
implementation of the method in this class is called rather than an overridden method in a derived class.
MyClass is a keyword, not a real object. MyClass cannot be assigned to a variable, passed to procedures, or used in an Is
comparison.
MyClass refers to the containing class and its inherited members.
MyClass can be used as a qualifier for Shared members.
MyClass cannot be used in standard modules.
MyClass can be used to qualify a method that is defined in a base class and that has no implementation of the method
provided in that class. Such a reference has the same meaning as MyBase.Method.

See Also
Tasks
How to: Create Derived Classes
Reference
Inherits Statement
Concepts
Overriding Properties and Methods
Other Resources
Language Changes for Visual Basic 6.0 Users
Visual Basic Language Concepts

How to: Create Derived Classes


The Inherits statement causes a class to inherit all the non-private members of the specified class.
To inherit from another class
Add an Inherits statement with the name of a class you want to use as a base class as the first statement in your derived
class. The Inherits statement must be the first non-comment statement after the class statement.
Example
The following example defines two classes. The first class is a base class that has two methods. The second class inherits both
methods from the base class, overrides the second method, and defines a field named Field.
VB
Class Class1
Sub Method1()
MsgBox("This is a method in the base class.")
End Sub
Overridable Sub Method2()
MsgBox("This is another method in the base class.")
End Sub
End Class

Class Class2
Inherits Class1
Public Field2 As Integer
Overrides Sub Method2()
MsgBox("This is a method in a derived class.")
End Sub
End Class

Protected Sub TestInheritance()


Dim C1 As New Class1
Dim C2 As New Class2
C1.Method1() ' Calls a method in the base class.
C1.Method2() ' Calls another method from the base class.
C2.Method1() ' Calls an inherited method from the base class.
C2.Method2() ' Calls a method from the derived class.
End Sub

When you run the procedure TestInheritance, you see the following messages:
This is a method in the base class.
This is another method in the base class.
This is a method in the base class.
This is a method in a derived class.

See Also
Concepts
Overriding Properties and Methods
Override Modifiers
Other Resources
Inheritance in Visual Basic
Class Properties, Fields, and Methods
Visual Basic Language Concepts

When to Use Inheritance


Inheritance is a useful programming concept, but it is easy to use inappropriately. Often interfaces do the job better. This topic
and When to Use Interfaces help you understand when each approach should be used.
Inheritance is a good choice when:
Your inheritance hierarchy represents an "is-a" relationship and not a "has-a" relationship.
You can reuse code from the base classes.
You need to apply the same class and methods to different data types.
The class hierarchy is reasonably shallow, and other developers are not likely to add many more levels.
You want to make global changes to derived classes by changing a base class.
These considerations are discussed in order below.
Inheritance and "Is a" Relationships
Two ways to show class relationships in object-oriented programming are "is a" and "has a" relationships. In an "is a"
relationship, the derived class is clearly a kind of the base class. For example, a class named PremierCustomer represents an "is
a" relationship with a base class named Customer because a premier customer is a customer. However, a class named
CustomerReferral represents a "has a" relationship with the Customer class because a customer referral has a customer, but a
customer referral is not a kind of customer.
Objects in an inheritance hierarchy should have an "is a" relationship with their base class because they inherit the fields,
properties, methods, and events defined in the base class. Classes that represent a "has a" relationship with other classes are
not suited to inheritance hierarchies because they may inherit inappropriate properties and methods. For example, if the
CustomerReferral class were derived from the Customer class discussed previously, it might inherit properties that make no
sense, such as ShippingPrefs and LastOrderPlaced. "Has a" relationships such as this should be represented using unrelated
classes or interfaces. The following illustration shows examples of both "is a" and "has a" relationships.

Base Classes and Code Reuse


Another reason to use inheritance is the advantage of code reuse. Well-designed classes can be debugged once and used over
and over as a basis for new classes.
A common example of effective code reuse is in connection with libraries that manage data structures. Suppose, for example,
that you have a large business application that manages several kinds of in-memory lists. One is an in-memory copy of your
customer database, read in from a database at the beginning of the session for speed. The data structure might look something
like the following:
VB
Class CustomerInfo
Protected PreviousCustomer As CustomerInfo
Protected NextCustomer As CustomerInfo
Public ID As Integer
Public FullName As String
Public Sub InsertCustomer(ByVal FullName As String)
' Insert code to add a CustomerInfo item to the list.
End Sub
Public Sub DeleteCustomer()
' Insert code to remove a CustomerInfo item from the list.
End Sub
Public Function GetNextCustomer() As CustomerInfo
' Insert code to get the next CustomerInfo item from the list.
Return NextCustomer
End Function
Public Function GetPrevCustomer() As CustomerInfo
'Insert code to get the previous CustomerInfo item from the list.
Return PreviousCustomer
End Function
End Class

Your application may also have a similar list of products the user has added to a shopping cart list, as shown in the following
code fragment:
VB
Class ShoppingCartItem
Protected PreviousItem As ShoppingCartItem
Protected NextItem As ShoppingCartItem
Public ProductCode As Integer
Public Function GetNextItem() As ShoppingCartItem
' Insert code to get the next ShoppingCartItem from the list.
Return NextItem
End Function
End Class

You can see a pattern here: two lists behave the same way (insertions, deletions, and retrievals) but operate on different data
types. Maintaining two code bases to perform essentially the same functions is not efficient. The most efficient solution is to
factor out the list management into its own class, and then inherit from that class for different data types:
VB
Class ListItem
Protected PreviousItem As ListItem
Protected NextItem As ListItem
Public Function GetNextItem() As ListItem
' Insert code to get the next item in the list.
Return NextItem
End Function
Public Sub InsertNextItem()
' Insert code to add a item to the list.
End Sub

Public Sub DeleteNextItem()


' Insert code to remove a item from the list.
End Sub

Public Function GetPrevItem() As ListItem


'Insert code to get the previous item from the list.
Return PreviousItem
End Function
End Class

The ListItem class needs only to be debugged once. Then you can build classes that use it without ever having to think about
list management again. For example:
VB
Class CustomerInfo
Inherits ListItem
Public ID As Integer
Public FullName As String
End Class
Class ShoppingCartItem
Inherits ListItem
Public ProductCode As Integer
End Class

Although inheritance-based code reuse is powerful tool, it also has associated risks. Even the best-designed systems
sometimes change in ways the designers could not foresee. Changes to an existing class hierarchy can sometimes have
unintended consequences; some examples are discussed in "The Fragile Base Class Problem," in
Base Class Design Changes After Deployment.
Interchangeable Derived Classes
Derived classes in a class hierarchy can sometimes be used interchangeably with their base class, a process called inheritance-
based polymorphism. This approach combines the best features of interface-based polymorphism with the option of reusing
or overriding code from a base class.
An example where this can be useful is in a drawing package. For example, consider the following code fragment, which does
not use inheritance:
VB
Sub Draw(ByVal Shape As DrawingShape, ByVal X As Integer, _
ByVal Y As Integer, ByVal Size As Integer)
Select Case Shape.type
Case shpCircle
' Insert circle drawing code here.
Case shpLine
' Insert line drawing code here.
End Select
End Sub

This approach poses some problems. If someone decides to add an ellipse option later, it will be necessary to alter the source
code; it is possible that your target users will not even have access to your source code. A more subtle problem is that drawing
an ellipse requires another parameter (ellipses have both a major and a minor diameter) that would be irrelevant to the line
case. If someone then wants to add a polyline (multiple connected lines), then another parameter would be added, and it would
be irrelevant to the other cases.
Inheritance solves most of these problems. Well-designed base classes leave the implementation of specific methods up to the
derived classes, so that any kind of shape can be accommodated. Other developers can implement methods in derived classes
by using the documentation for the base class. Other class items (such as the x- and y-coordinates) can be built into the base
class because all descendants use them. For example, Draw could be a MustOverride method:
VB
MustInherit Class Shape
Public X As Integer
Public Y As Integer
MustOverride Sub Draw()
End Class

Then you could add to that class as appropriate for different shapes. For example, a Line class might only need a Length field:
VB
Class Line
Inherits Shape
Public Length As Integer
Overrides Sub Draw()
' Insert code here to implement Draw for this shape.
End Sub
End Class

This approach is useful because other developers, who do not have access to your source code, can extend your base class with
new derived classes as needed. For example, a class named Rectangle could be derived from the Line class:
VB
Class Rectangle
Inherits Line
Public Width As Integer
Overrides Sub Draw()
' Insert code here to implement Draw for the Rectangle shape.
End Sub
End Class

This example shows how you can move from general-purpose classes to very specific classes by adding implementation
details at each level.
At this point it might be good to reevaluate if the derived class truly represents an "is a" relationship, or instead is a "has a"
relationship. If the new rectangle class is just composed of lines, then inheritance is not the best choice. However, if the new
rectangle is a line with a width property, then the "is a" relationship is maintained.
Shallow Class Hierarchies
Inheritance is best suited for relatively shallow class hierarchies. Excessively deep and complex class hierarchies can be difficult
to develop. The decision to use a class hierarchy involves weighing the benefits of using a class hierarchy against complexity.
As a general rule, you should limit hierarchies to six levels or fewer. However, the maximum depth for any particular class
hierarchy depends on a number of factors, including the amount of complexity at each level.
Global Changes to Derived Classes Through the Base Class
One of the most powerful features of inheritance is the ability to make changes in a base class that propagate to derived
classes. When used carefully, you can update the implementation of a single method, and dozens—or even hundreds—of
derived classes can use the new code. However, this can be a dangerous practice because such changes may cause problems
with inherited classes designed by other people. Care must be taken to ensure that the new base class is compatible with
classes that use the original. You should specifically avoid changing the name or type of base class members.
Suppose, for example, that you design a base class with a field of type Integer to store zip code information, and other
developers have created derived classes that use the inherited zip code field. Suppose further that your zip code field stores
five digits, and the post office has expanded zip codes with a hyphen and four more digits. In a worst-case scenario, you could
modify the field in the base class to store a 10-character string, but other developers would need to change and recompile the
derived classes to use the new size and data type.
The safest way to change a base class is to simply add new members. For example, you could add a new field to store the
additional four digits in the zip code example discussed previously. That way, client applications can be updated to use the new
field without breaking existing applications. The ability to extend base classes in an inheritance hierarchy is an important
benefit that does not exist with interfaces.
See Also
Concepts
When to Use Interfaces
Base Class Design Changes After Deployment
Visual Basic Language Concepts

Inheritance and the .NET Framework


Visual Studio applications can use many of the classes found in the .NET Framework as base classes. Attribute classes, for
instance, are always based on the class Attribute. Other useful .NET Framework base classes include Component, which is
inherited from to define components, and Exception, which is inherited from to define custom exception classes.
The .NET Framework is more than a source for base classes; it ensures compatibility between classes created with different
programming languages. Visual Basic classes can inherit from classes in assemblies created by any language supported by
Visual Studio. The classes you create in Visual Basic can also be used as base classes by other .NET Framework programming
languages.
See Also
Tasks
Walkthrough: Implementing Inheritance with COM Objects
Concepts
Inheritance and the Base Object Class
When to Use Inheritance
Visual Basic Language Concepts

Walkthrough: Implementing Inheritance with COM Objects


You can derive Visual Basic 2005 classes from Public classes in COM objects, even those created with previous versions of
Visual Basic. The properties and methods of classes inherited from COM objects can be overridden or overloaded in the same
way that properties and methods of any other base class can be overridden or overloaded. Inheritance from COM objects is
useful when you have an existing class library that you do not want to recompile.
The following procedure shows how to use Visual Basic 6.0 to create a COM object containing a class, and then use it as a base
class in Visual Basic 2005.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To build the COM object used in this walkthrough


1. In Visual Basic 6.0, open a new ActiveX DLL project. A project named Project1 is created with a class named Class1.
2. In the Project Explorer, right-click Project1, and then click Project1 Properties. The Project Properties dialog box is
displayed.
3. On the General tab of the Project Properties dialog box, change the project name by typing ComObject1 in the Project
Name field.
4. In the Project Explorer, right-click Class1, and then click Properties. The Properties window for the class is displayed.
5. Change the Name property to MathFunctions.
6. In the Project Explorer, right-click MathFunctions, and then click View Code. The Code Editor is displayed.
7. Add a local variable to hold the property value:

' Local variable to hold property value


Private mvarProp1 As Integer

8. Add Property Let and Property Get property procedures:

Public Property Let Prop1(ByVal vData As Integer)


'Used when assigning a value to the property.
mvarProp1 = vData
End Property
Public Property Get Prop1() As Integer
'Used when retrieving a property's value.
Prop1 = mvarProp1
End Property

9. Add a function:

Function AddNumbers( _
ByVal SomeNumber As Integer, _
ByVal AnotherNumber As Integer) _
As Integer

AddNumbers = SomeNumber + AnotherNumber


End Function
10. Create and register the COM object by choosing Make ComObject1.dll from the File menu.
Note
Although you can also expose a class created with Visual Basic as a COM object, it is not a true COM object and cannot
be used in this walkthrough. For details, see COM Interoperability in .NET Framework Applications.

Interop Assemblies
In the following procedure, you will create an interop assembly, which acts as a bridge between unmanaged code (such as a
COM object) and the managed code Visual Studio uses. The interop assembly that Visual Basic creates handles many of the
details of working with COM objects, such as interop marshaling, the process of packaging parameters and return values into
equivalent data types as they move to and from COM objects. The reference in the Visual Basic application points to the interop
assembly, not the actual COM object.
To use a COM object with Visual Basic 2005
1. Open a new Visual Basic Windows Application project.
2. On the Project menu, click Add Reference.
The Add Reference dialog box is displayed.
3. On the COM tab, double click ComObject1 in the Component Name list and click OK.
4. On the Project menu, click Add New Item.
The Add New Item dialog box is displayed.
5. In the Templates pane, click Class.
The default file name, Class1.vb, appears in the Name field. Change this field to MathClass.vb and click Add. This
creates a class named MathClass, and displays its code.
6. Add the following code to the top of MathClass to inherit from the COM class.
VB
' The inherited class is called MathFunctions in the base class,
' but the interop assembly appends the word Class to the name.
Inherits ComObject1.MathFunctionsClass

7. Overload the public method of the base class by adding the following code to MathClass:
VB
' This method overloads the method AddNumbers from the base class.
Overloads Function AddNumbers( _
ByVal SomeNumber As Integer, _
ByVal AnotherNumber As Integer) _
As Integer

Return SomeNumber + AnotherNumber


End Function

8. Extend the inherited class by adding the following code to MathClass:


VB
' The following function extends the inherited class.
Function SubtractNumbers( _
ByVal SomeNumber As Integer, _
ByVal AnotherNumber As Integer) _
As Integer

Return AnotherNumber - SomeNumber


End Function

The new class inherits the properties of the base class in the COM object, overloads a method, and defines a new method to
extend the class.
To test the inherited class
1. Add a button to your startup form, and then double-click it to view its code.
2. In the button's Click event handler procedure, add the following code to create an instance of MathClass and call the
overloaded methods:
VB
Dim Result1 As Short
Dim Result2 As Integer
Dim Result3 As Integer
Dim MathObject As New MathClass
Result1 = MathObject.AddNumbers(4S, 2S) ' Add two Shorts.
Result2 = MathObject.AddNumbers(4, 2) 'Add two Integers.
Result3 = MathObject.SubtractNumbers(2, 4) ' Subtract 2 from 4.
MathObject.Prop1 = 6 ' Set an inherited property.

MsgBox("Calling the AddNumbers method in the base class " & _


"using Short type numbers 4 and 2 = " & Result1)
MsgBox("Calling the overloaded AddNumbers method using " & _
"Integer type numbers 4 and 2 = " & Result2)
MsgBox("Calling the SubtractNumbers method " & _
"subtracting 2 from 4 = " & Result3)
MsgBox("The value of the inherited property is " & _
MathObject.Prop1)

3. Run the project by pressing F5.


When you click the button on the form, the AddNumbers method is first called with Short data type numbers, and Visual Basic
chooses the appropriate method from the base class. The second call to AddNumbers is directed to the overload method from
MathClass. The third call calls the SubtractNumbers method, which extends the class. The property in the base class is set, and
the value is displayed.
Next Steps
You may have noticed that the overloaded AddNumbers function appears to have the same data type as the method inherited
from the COM object's base class. This is because the base class method's arguments and parameters are defined as 16-bit
integers in Visual Basic 6.0, but they are exposed as 16-bit integers of type Short in Visual Basic 2005. The new function
accepts 32-bit integers, and overloads the base class function.
When working with COM objects, it is important to verify the size and data types of parameters. For example, when using a
COM object that accepts a Visual Basic 6.0 collection object as an argument, you cannot provide a Visual Basic 2005 collection.
For more information about data type changes, see Language Changes for Visual Basic 6.0 Users.
Properties and methods inherited from COM classes can be overridden, meaning that you can declare a local property or
method that replaces a property or method inherited from a base COM class. The rules for overriding inherited COM
properties are similar to the rules for overriding other properties and methods with the following exceptions:
If you override any property or method inherited from a COM class, you must override all the other inherited properties
and methods.
Properties that use ByRef parameters cannot be overridden.
See Also
Tasks
How to: Create Derived Classes
Reference
Inherits Statement
Short Data Type (Visual Basic)
Concepts
Overriding Properties and Methods
Other Resources
COM Interoperability in .NET Framework Applications
Language Changes for Visual Basic 6.0 Users
Visual Basic Language Concepts

Inheritance and the Base Object Class


Almost everything you do with Visual Basic involves objects, including some entities not normally thought of as objects, such
as strings and integers. All objects in Visual Basic are derived from, and inherit methods from, a base class called
System.Object. The System.Object class provides a common base class for all objects in the .NET Framework, ensuring
interoperability of objects developed using Visual Studio. New classes implicitly inherit the System.Object class; it is never
necessary to explicitly name this class with an Inherits statement.
Among the methods that objects inherit from System.Object, one of the most useful is GetType, which is used to return the
exact type of the current object.
See Also
Reference
Object
GetType
Concepts
Overriding Properties and Methods
Inheritance Basics
Visual Basic Language Concepts

How New and Finalize Methods Work in a Class Hierarchy


Whenever an instance of a class is created, the common language runtime (CLR) attempts to execute a procedure named New,
if it exists in that object. New is a type of procedure called a constructor that is used to initialize new objects before any other
code in an object executes. A New constructor can be used to open files, connect to databases, initialize variables, and take care
of any other tasks that need to be done before an object can be used.
When an instance of a derived class is created, the Sub New constructor of the base class executes first, followed by
constructors in derived classes. This happens because the first line of code in a Sub New constructor uses the syntax
MyBase.New()to call the constructor of the class immediately above itself in the class hierarchy. The Sub New constructor is
then called for each class in the class hierarchy until the constructor for the base class is reached. At that point, the code in the
constructor for the base class executes, followed by the code in each constructor in all derived classes and the code in the most
derived classes is executed last.

When an object is no longer needed, the CLR calls the Finalize method for that object before freeing its memory. The Finalize
method is called a destructor because it performs cleanup tasks, such as saving state information, closing files and connections
to databases, and other tasks that must be done before releasing the object.

See Also
Concepts
Object Lifetime: How Objects Are Created and Destroyed
Visual Basic Language Concepts

Polymorphism
Polymorphism refers to the ability to define multiple classes with functionally different, yet identically named methods or
properties that can be used interchangeably by client code at run time.
In This Section
How Visual Basic Provides Polymorphism
Illustrates different approaches to polymorphism.
Inheritance-Based Polymorphism
Discusses using inheritance to achieve polymorphism.
Interface-Based Polymorphism
Discusses using interfaces to achieve polymorphism.
Related Sections
When to Use Interfaces
Discusses when to use interfaces instead of an inheritance hierarchy.
When to Use Inheritance
Provides information about when you should use inheritance instead of interfaces.
Visual Basic Language Concepts

How Visual Basic Provides Polymorphism


Traditionally, polymorphism in Visual Basic was accomplished with interfaces, and interfaces can still be used for this purpose.
Now, however, Visual Basic provides the option of using inheritance to provide polymorphism as well.
As with other issues in object-oriented programming, the option to use depends on your specific requirements. In general, use
inheritance when you want to create baseline functionality that derived classes can extend; use interfaces in situations where
similar functionality needs to be provided by multiple implementations that have little in common.
See Also
Concepts
Inheritance-Based Polymorphism
Interface-Based Polymorphism
Other Resources
Designing an Inheritance Hierarchy
Visual Basic Language Concepts

Inheritance-Based Polymorphism
Most object-oriented programming systems provide polymorphism through inheritance. Inheritance-based polymorphism
involves defining methods in a base class and overriding them with new implementations in derived classes.
For example, you could define a class, BaseTax, that provides baseline functionality for computing sales tax in a state. Classes
derived from BaseTax, such as CountyTax or CityTax, could implement methods such as CalculateTax as appropriate.
Polymorphism comes from the fact that you could call the CalculateTax method of an object belonging to any class that
derived from BaseTax, without knowing which class the object belonged to.
The TestPoly procedure in the following example demonstrates inheritance-based polymorphism:
VB
' %5.3 State tax
Const StateRate As Double = 0.053
' %2.8 City tax
Const CityRate As Double = 0.028
Public Class BaseTax
Overridable Function CalculateTax(ByVal Amount As Double) As Double
' Calculate state tax.
Return Amount * StateRate
End Function
End Class

Public Class CityTax


' This method calls a method in the base class
' and modifies the returned value.
Inherits BaseTax
Private BaseAmount As Double
Overrides Function CalculateTax(ByVal Amount As Double) As Double
' Some cities apply a tax to the total cost of purchases,
' including other taxes.
BaseAmount = MyBase.CalculateTax(Amount)
Return CityRate * (BaseAmount + Amount) + BaseAmount
End Function
End Class

Sub TestPoly()
Dim Item1 As New BaseTax
Dim Item2 As New CityTax
' $22.74 normal purchase.
ShowTax(Item1, 22.74)
' $22.74 city purchase.
ShowTax(Item2, 22.74)
End Sub

Sub ShowTax(ByVal Item As BaseTax, ByVal SaleAmount As Double)


' Item is declared as BaseTax, but you can
' pass an item of type CityTax instead.
Dim TaxAmount As Double
TaxAmount = Item.CalculateTax(SaleAmount)
MsgBox("The tax is: " & Format(TaxAmount, "C"))
End Sub

In this example, the ShowTax procedure accepts a parameter named Item of type BaseTax, but you can also pass any of the
classes derived from the BaseTax class, such as CityTax. The advantage of this design is that you can add new classes derived
from the BaseTax class without changing the client code in the ShowTax procedure.
See Also
Concepts
Interface-Based Polymorphism
Other Resources
Designing an Inheritance Hierarchy
Visual Basic Language Concepts

Interface-Based Polymorphism
Interfaces provide another way you can accomplish polymorphism in Visual Basic. Interfaces describe properties and methods
like classes, but unlike classes, interfaces cannot provide any implementation. Multiple interfaces have the advantage of
allowing systems of software components to evolve without breaking existing code.
To achieve polymorphism with interfaces, you implement an interface in different ways in several classes. Client applications
can use either the old or the new implementations in exactly the same way. The advantage to interface-based polymorphism is
that you do not need to re-compile existing client applications to get them to work with new interface implementations.
The following example defines an interface named Shape2 that is implemented in a class named RightTriangleClass2 and
RectangleClass2. A procedure named ProcessShape2 calls the CalculateArea method of instances of RightTriangleClass2
or RectangleClass2:
VB
Sub TestInterface()
Dim RectangleObject2 As New RectangleClass2
Dim RightTriangleObject2 As New RightTriangleClass2
ProcessShape2(RightTriangleObject2, 3, 14)
ProcessShape2(RectangleObject2, 3, 5)
End Sub

Sub ProcessShape2(ByVal Shape2 As Shape2, ByVal X As Double, _


ByVal Y As Double)
MsgBox("The area of the object is " _
& Shape2.CalculateArea(X, Y))
End Sub

Public Interface Shape2


Function CalculateArea(ByVal X As Double, ByVal Y As Double) As Double
End Interface

Public Class RightTriangleClass2


Implements Shape2
Function CalculateArea(ByVal X As Double, _
ByVal Y As Double) As Double Implements Shape2.CalculateArea
' Calculate the area of a right triangle.
Return 0.5 * (X * Y)
End Function
End Class
Public Class RectangleClass2
Implements Shape2
Function CalculateArea(ByVal X As Double, _
ByVal Y As Double) As Double Implements Shape2.CalculateArea
' Calculate the area of a rectangle.
Return X * Y
End Function
End Class

See Also
Tasks
How to: Create and Implement Interfaces
Concepts
Inheritance-Based Polymorphism
Visual Basic Language Concepts

Designing an Inheritance Hierarchy


Inheritance hierarchies are easier to implement than to design, which makes it risky to start coding before clearly identifying
your needs. Correcting design mistakes in a class hierarchy after implementation can require code changes that disable
existing applications. This section discusses inheritance-hierarchy design considerations, giving you information that can help
you avoid such mistakes.
In This Section
Class Hierarchy Design Considerations for Extensibility
Discusses how to design class hierarchies so they can be updated or extended by other developers.
Considerations for Choosing Access Levels for Methods
Describes the correct use of accessibility levels within classes.
Base Class Design Changes After Deployment
Explains issues that developers face when attempting to make changes to a class hierarchy.
Related Sections
When to Use Interfaces
Discusses when to use interfaces instead of an inheritance hierarchy.
Interfaces in Visual Basic
Summarizes how to design and implement interfaces.
Visual Basic Language Concepts

Class Hierarchy Design Considerations for Extensibility


Even well-designed class hierarchies need to evolve over time. The early choices you make when designing a class hierarchy
can simplify your work later.
Extending Class Hierarchies
The following list contains suggestions for making your class hierarchies easier to extend:
Class hierarchies are defined from the general to the specific. Define classes to be as general as possible at each level of
an inheritance hierarchy. Derived classes can inherit, reuse, and extend methods from base classes.
Suppose, for example, you are designing a class hierarchy that models computer hardware. When you start modeling
output devices you could define classes named Display, Printer, and File. You could then define the classes that
implement the methods defined in the base classes. For example, the LCDDisplay class could be derived from Display
and implement a method named EnterPowerSaveMode.
Be generous in defining data types and storage to avoid difficult changes later on. For example, you might consider using
a variable of type Long even though your current data may only require a standard Integer variable.
Only expose items that are needed by derived classes. Private fields and methods reduce naming conflicts and protect
other users from using items that you may need to later change.
Members that are only needed by derived classes should be marked as Protected. This ensures that only the derived
classes are dependent on these members and makes it easier to update these members during development.
Make sure that base class methods do not depend on Overridable members, whose functionality can be changed by
inheriting classes.
See Also
Reference
MustInherit
MustOverride
Concepts
Considerations for Choosing Access Levels for Methods
Base Class Design Changes After Deployment
Visual Basic Language Concepts

Considerations for Choosing Access Levels for Methods


Applying the optimal access levels to members of a class hierarchy makes the hierarchy easier to maintain by allowing you to
control how such members will be used.
As a rule, you should declare class members with access modifiers that provide the least amount of access feasible. Restricting
access to class members reduces naming conflicts and prevents methods from being used in unintended ways.
Internal class members should be declared as Private; such members are only accessible from within the class in which they
are defined.
Methods that are only used within a class or by descendants of a class should use the Protected access modifier. A Protected
member is accessible within the class in which it is declared, and from within any class derived from the class that declared this
member.
Friend data members can be accessed from outside a class but only by modules that are part of the project where the class is
defined.
Public data members are visible to everyone and are often used at the bottom of a class hierarchy.
See Also
Concepts
Class Hierarchy Design Considerations for Extensibility
Base Class Design Changes After Deployment
Visual Basic Language Concepts

Base Class Design Changes After Deployment


Ideally, class hierarchies never change after deployment, because even small changes risk unintended consequences. In reality,
such changes are sometimes unavoidable: product requirements can change, and design specifications sometimes omit key
elements. One category of inheritance problems is called the fragile base class problem.
The Fragile Base Class Problem
The main drawback to using inheritance hierarchies is a problem called fragile base classes. Changes to base classes often
require the base class and all the code in derived classes to be changed, recompiled, and redistributed. This problem is even
more difficult when multiple developers author the base class and derived classes, because each party may deny access to their
source code. In a worst-case scenario, a customer might inadvertently use the compiled binary form of an updated base class
with the original and incompatible binary version of the derived classes.
Base class changes that can potentially break derived classes include overriding or changing the data type of base class
members.
Minimizing Fragile Base Class Problems
The best way to avoid the fragile base class problem is to make changes only in derived classes. However, this is not always
possible because it requires you to consider every possibility when the base class is first released; despite one's best efforts,
unforeseeable changes to the base class are sometimes inevitable.
Using MustInherit classes and MustOverride methods help reduce fragile base class problems because doing so moves
implementation details to derived classes and reduces the need for base class changes. Again, however, this is not always
possible, even with the best planning.
Shadowed data members in derived classes are also helpful, because they reduce naming conflicts with base class members.
The safest way to extend the functionality of a base class is to add new members. The only way that new members can break a
base class is if the derived class uses the Overloads keyword to inherit methods from the base class and introduce new
methods with the same name. This problem can be avoided by explicitly specifying in the derived class what base class
methods you want to inherit from the base by redefining those methods and delegating to them.
In a sense, all base classes are fragile to some degree. In the final analysis, the fragile base class problem cannot be eliminated,
but it can be minimized through careful design of class hierarchies that reduces the need for base class changes, and through
thorough testing when such changes are unavoidable.
See Also
Reference
Shadows
Other Resources
Designing an Inheritance Hierarchy
Visual Basic Language Concepts

Shared Members in Visual Basic


Shared members are properties, procedures, and fields that are shared by all instances of a class or structure. Some
programming languages refer to such items as static members.
Shared Fields and Properties
Shared fields and properties are useful when you have information that is part of a class but is not specific to any one instance
of a class. When you change the value of a shared field and property, you change the value associated with the class and all
instances of the class.
On the other hand, changing the value of a non-shared field or property associated with any one instance does not affect the
value of that field or property in other instances of the class. Non-shared fields and properties exist independently for each
instance of a class.
In this way, shared fields and properties behave like global variables that can be accessed only from instances of a class, or
with qualification of the class name. Without shared fields and properties, you would need to use module-level variables to
achieve the same effect. However, module-level variables can make your classes difficult to understand and maintain.
Furthermore, using module-level variables in this way violates the concept of encapsulation that classes represent.
Shared Procedures
Shared procedures are class methods that are not associated with a specific instance of a class. For example, the Cos method
defined within the Math class is a shared method. You can call a shared procedure as a method of an object or directly from
the class.
Shared procedures and properties do not have access to instances of the class. For this reason, only qualified references to
non-shared data members are allowed in shared methods.
Note
It is recommended that you do not write code in which you access a shared member through an instance of the class. This is
because the compiler disregards the qualification of the shared member and treats it as if it were accessed directly through t
he class. In some situations, you may intend for the qualifying object to run some code, and therefore the Visual Basic compil
er generates a warning for accessing a shared member through an instance of a class. IntelliSense does not display shared m
embers for an instance of the class.

Shared Members Example


The following example creates a shared field, two instance fields, and a shared method to demonstrate how shared members
operate in code:
VB
Public Class Item
Public Shared Count As Integer = 1
Public Shared Sub ShareMethod()
MsgBox("Current value of Count: " & Count)
End Sub

Public Sub New(ByVal Name As String)


' Use Count to initialize SerialNumber.
Me.SerialNumber = Count
Me.Name = Name
' Increment the shared variable
Count += 1
End Sub
Public SerialNumber As Integer
Public Name As String
Public Sub InstanceMethod()
MsgBox("Information in the first object: " & _
Me.SerialNumber & vbTab & Me.Name)
End Sub
End Class
Sub TestShared()
' Create two instances of the class.
Dim part1 As New Item("keyboard")
Dim part2 As New Item("monitor")
part1.InstanceMethod()
part2.InstanceMethod()
Item.ShareMethod()
End Sub

When you execute the TestShared procedure, two instances of the class are created. The constructor uses the shared field
Count to initialize the instance field SerialNumber, then increments Count. This technique automatically gives each instance a
different serial number.
After creating the two instances, the instance method InstanceMethod is called on both objects, and the shared method
ShareMethod is also called. The output is:
Information in the first object: 1 keyboard
Information in the second object: 2 monitor
Current value of the shared Count field: 3

See Also
Reference
Dim Statement (Visual Basic)
Cos
Concepts
Structures and Classes
Other Resources
Class Properties, Fields, and Methods
Structures: Your Own Data Types
Visual Basic Language Concepts

Early and Late Binding


The Visual Basic compiler performs a process called binding when an object is assigned to an object variable. An object is early
bound when it is assigned to a variable declared to be of a specific object type. Early bound objects allow the compiler to
allocate memory and perform other optimizations before an application executes. For example, the following code fragment
declares a variable to be of type FileStream:
VB
' Create a variable to hold a new object.
Dim FS As System.IO.FileStream
' Assign a new object to the variable.
FS = New System.IO.FileStream("C:\tmp.txt", _
System.IO.FileMode.Open)

Because FileStream is a specific object type, the instance assigned to FS is early bound.
By contrast, an object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold
references to any object, but lack many of the advantages of early-bound objects. For example, the following code fragment
declares an object variable to hold an object returned by the CreateObject function:
VB
' To use this example, you must have Microsoft Excel installed on your computer.
' Compile with Option Strict Off to allow late binding.
Sub TestLateBinding()
Dim xlApp As Object
Dim xlBook As Object
Dim xlSheet As Object
xlApp = CreateObject("Excel.Application")
' Late bind an instance of an Excel workbook.
xlBook = xlApp.Workbooks.Add
' Late bind an instance of an Excel worksheet.
xlSheet = xlBook.Worksheets(1)
xlSheet.Activate()
' Show the application.
xlSheet.Application.Visible = True
' Place some text in the second row of the sheet.
xlSheet.Cells(2, 2) = "This is column B row 2"
End Sub

Advantages of Early Binding


You should use early-bound objects whenever possible, because they allow the compiler to make important optimizations that
yield more efficient applications. Early-bound objects are significantly faster than late-bound objects and make your code
easier to read and maintain by stating exactly what kind of objects are being used. Another advantage to early binding is that it
enables useful features such as automatic code completion and Dynamic Help because the Visual Studio integrated
development environment (IDE) can determine exactly what type of object you are working with as you edit the code. Early
binding reduces the number and severity of run-time errors because it allows the compiler to report errors when a program is
compiled.
Note
Late binding can only be used to access type members that are declared as Public. Accessing members declared as Friend o
r Protected Friend results in a run-time error.

See Also
Reference
Object Data Type
CreateObject Function (Visual Basic)
Concepts
Object Lifetime: How Objects Are Created and Destroyed
Visual Basic Language Concepts

Obtaining Class Information at Run Time


In some situations, you may need to work with variables defined as type Object rather than variables defined as more specific
object types. Variables defined as Object can contain any other type object, such as integers, doubles, or object data types.
In This Section
Determining Object Type
Discusses determining the class an object belongs to.
Calling a Property or Method Using a String Name
Steps you through the process of specifying arguments by name instead of by position when calling a method.
Related Sections
Objects in Visual Basic
Covers the fundamentals of object-oriented programming.
Visual Basic Language Concepts

Determining Object Type


Generic object variables (that is, variables you declare as Object) can hold objects from any class. When using variables of type
Object, you may need to take different actions based on the class of the object; for example, some objects might not support a
particular property or method. Visual Basic provides two means of determining which type of object is stored in an object
variable: the TypeName function and the TypeOf...Is operator.
TypeName and TypeOf…Is
The TypeName function returns a string and is the best choice when you need to store or display the class name of an object,
as shown in the following code fragment:
VB
Dim Ctrl As Control = New TextBox
MsgBox(TypeName(Ctrl))

The TypeOf...Is operator is the best choice for testing an object's type, because it is much faster than an equivalent string
comparison using TypeName. The following code fragment uses TypeOf...Is within an If...Then...Else statement:
VB
If TypeOf Ctrl Is Button Then
MsgBox("The control is a button.")
End If

A word of caution is due here. The TypeOf...Is operator returns True if an object is of a specific type, or is derived from a
specific type. Almost everything you do with Visual Basic involves objects, which include some elements not normally thought
of as objects, such as strings and integers. These objects are derived from and inherit methods from Object. When passed an
Integer and evaluated with Object, the TypeOf...Is operator returns True. The following example reports that the parameter
InParam is both an Object and an Integer:

VB
Sub CheckType(ByVal InParam As Object)
' Both If statements evaluate to True when an
' Integer is passed to this procedure.
If TypeOf InParam Is Object Then
MsgBox("InParam is an Object")
End If
If TypeOf InParam Is Integer Then
MsgBox("InParam is an Integer")
End If
End Sub

The following example uses both TypeOf...Is and TypeName to determine the type of object passed to it in the Ctrl
argument. The TestObject procedure calls ShowType with three different kinds of controls.
To run the example
1. Create a new Windows Application project and add a Button control, a CheckBox control, and a RadioButton control to
the form.
2. From the button on your form, call the TestObject procedure.
3. Add the following code to your form:
VB
Sub ShowType(ByVal Ctrl As Object)
'Use the TypeName function to display the class name as text.
MsgBox(TypeName(Ctrl))
'Use the TypeOf function to determine the object's type.
If TypeOf Ctrl Is Button Then
MsgBox("The control is a button.")
ElseIf TypeOf Ctrl Is CheckBox Then
MsgBox("The control is a check box.")
Else
MsgBox("The object is some other type of control.")
End If
End Sub

Protected Sub TestObject()


'Test the ShowType procedure with three kinds of objects.
ShowType(Me.Button1)
ShowType(Me.CheckBox1)
ShowType(Me.RadioButton1)
End Sub

See Also
Reference
Object Data Type
TypeName Function (Visual Basic)
If...Then...Else Statement (Visual Basic)
String Data Type (Visual Basic)
Integer Data Type (Visual Basic)
Concepts
Calling a Property or Method Using a String Name
Other Resources
Obtaining Class Information at Run Time
Visual Basic Language Concepts

Calling a Property or Method Using a String Name


In most cases, you can discover the properties and methods of an object at design time, and write code to handle them. In a
few cases, however, you may not know about an object's properties and methods in advance, or you may simply want the
flexibility of allowing an end user to specify properties or execute methods at run time.
CallByName Function
Consider, for example, a client application that evaluates expressions entered by the user by passing an operator to a COM
component. Suppose you are constantly adding new functions to the component that require new operators. Using standard
object access techniques, you would need to recompile and redistribute the client application before it could use the new
operators. To avoid this, you can use the CallByName function to pass the new operators as strings, without changing the
application.
The CallByName function allows you to use a string to specify a property or method at run time. The signature for the
CallByName function looks like this:
Result = CallByName(Object, ProcedureName, CallType, Arguments())
The first argument, Object, takes the name of the object you want to act upon. The ProcedureName argument takes a string
containing the name of the method or property procedure to be invoked. The CallType argument takes a constant representing
the type of procedure to invoke: a method (Microsoft.VisualBasic.CallType.Method), a property read
(Microsoft.VisualBasic.CallType.Get), or a property set (Microsoft.VisualBasic.CallType.Set). The Arguments
argument, which is optional, takes an array of type Object containing any arguments to the procedure.
You can use CallByName with classes in your current solution, but it is most often used to access COM objects or objects
from .NET Framework assemblies.
Suppose you add a reference to an assembly that contains a class named MathClass, which has a new function named
SquareRoot, as shown in the following code:

VB
Class MathClass
Function SquareRoot(ByVal X As Double) As Double
Return Math.Sqrt(X)
End Function
Function InverseSine(ByVal X As Double) As Double
Return Math.Atan(X / Math.Sqrt(-X * X + 1))
End Function
Function Acos(ByVal X As Double) As Double
Return Math.Atan(-X / Math.Sqrt(-X * X + 1)) + 2 * Math.Atan(1)
End Function
End Class

Your application could use text box controls to control which method will be called and its arguments. For example, if TextBox1
contains the expression to be evaluated, and TextBox2 is used to enter the name of the function, you can use the following
code to invoke the SquareRoot function on the expression in TextBox1:
VB
Private Sub CallMath()
Dim Math As New MathClass
Me.TextBox1.Text = CStr(CallByName(Math, Me.TextBox2.Text, _
Microsoft.VisualBasic.CallType.Method, TextBox1.Text))
End Sub

If you enter "64" in TextBox1, "SquareRoot" in TextBox2, and then call the CallMath procedure, the square root of the number
in TextBox1 is evaluated. The code in the example invokes the SquareRoot function (which takes a string containing the
expression to be evaluated as a required argument) and returns "8" in TextBox1 (the square root of 64). Of course, if the user
enters an invalid string in TextBox2, if the string contains the name of a property instead of a method, or if the method had an
additional required argument, a run-time error occurs. You need to add robust error-handling code when you use
CallByName to anticipate these or any other errors.
Note
While the CallByName function may be useful in some situations, you need to weigh its usefulness against the performance
implications — using CallByName to invoke a procedure is slightly slower than a late-bound call. If you are invoking a funct
ion that is called repeatedly, such as inside a loop, CallByName can have a severe effect on performance.

See Also
Tasks
How to: Perform Multiple Actions on an Object
Reference
CallByName Function
Concepts
Determining Object Type
Other Resources
Obtaining Class Information at Run Time
Visual Basic Language Concepts

COM Interop
The Component Object Model (COM) allows an object to expose its functionality to other components and to host applications.
Most of today's software includes COM objects. Although .NET assemblies are the best choice for new applications, you may at
times need to employ COM objects. This section covers some of the issues associated with creating and using COM objects
with Visual Basic.
In This Section
Introduction to COM Interop
Provides an overview of COM interoperability.
How to: Reference COM Objects from Visual Basic
Covers how to add references to COM objects that have type libraries.
How to: Work with ActiveX Controls
Demonstrates how to use existing ActiveX controls to add features to the Visual Studio Toolbox.
Walkthrough: Calling Windows APIs
Steps you through the process of calling the APIs that are part of the Windows operating system.
How to: Call Windows APIs (Visual Basic)
Demonstrates how to define and call the MessageBox function in User32.dll.
Walkthrough: Creating COM Objects with Visual Basic 2005
Steps you through the process of creating COM objects with and without the COM class template.
Troubleshooting Interoperability
Covers some of the problems you may encounter when using COM.
COM Interoperability in .NET Framework Applications
Provides an overview of how to use COM objects and .NET Framework objects in the same application.
Related Sections
Walkthrough: Implementing Inheritance with COM Objects
Demonstrates how to use classes in COM objects as the basis for inheritance in Visual Basic.
Interoperating with Unmanaged Code
Describes interoperability services provided by the common language runtime.
Exposing COM Components to the .NET Framework
Describes the process of calling COM types through COM interop.
Exposing .NET Framework Components to COM
Describes the preparation and use of managed types from COM.
Applying Interop Attributes
Covers attributes you can use when working with unmanaged code.
Visual Basic Language Concepts

Introduction to COM Interop


The Component Object Model (COM) allows an object to expose its functionality to other components and to host applications.
While COM objects have been fundamental to Windows programming for many years, applications designed for the common
language runtime (CLR) offer many advantages.
.NET Framework applications will eventually replace those developed with COM. Until then, you may need to use or create
COM objects with Visual Studio. Interoperability with COM, or COM interop, enables you to use existing COM objects while
transitioning to the .NET Framework at your own pace.
By using the .NET Framework to create COM components, you can use registration-free COM interop. This lets you control
which DLL version is activated when more than one version is installed on a computer, and lets end users use XCOPY or FTP to
copy your application to an appropriate directory on their computer where it can be run. For more information, see
Registration-Free COM Interop.
Managed Code and Data
Code developed for the .NET Framework is referred to as managed code, and contains metadata that is used by the common
language runtime (CLR). Data used by .NET Framework applications is called managed data because the runtime manages
data-related tasks such as allocating and reclaiming memory and performing type checking. By default, Visual Basic 2005 uses
managed code and data, but you can access the unmanaged code and data of COM objects using interop assemblies
(described later on this page).
Assemblies
An assembly is the primary building block of a .NET Framework application. It is a collection of functionality that is built,
versioned, and deployed as a single implementation unit containing one or more files. Each assembly contains an assembly
manifest.
Type Libraries and Assembly Manifests
Type libraries describe characteristics of COM objects, such as member names and data types. Assembly manifests perform the
same function for .NET Framework applications. They include information about:
Assembly identity, version, culture, and digital signature
Files that make up the assembly implementation
Types and resources that make up the assembly, including those that are exported from it
Compile-time dependencies on other assemblies
Permissions required for the assembly to run properly
For more information on assemblies and assembly manifests, see Assemblies.
Importing and Exporting Type Libraries
Visual Studio contains a utility, Tlbimp, that lets you import information from a type library into a .NET Framework application.
You can generate type libraries from assemblies by using the Tlbexp utility.
For information on Tlbimp and Tlbexp, see Type Library Importer (Tlbimp.exe) and Type Library Exporter (Tlbexp.exe).
Interop Assemblies
Interop assemblies are .NET Framework assemblies that act as a bridge between managed and unmanaged code, mapping
COM object members to equivalent .NET Framework managed members. Interop assemblies created by Visual Basic 2005
handle many of the details of working with COM objects, such as interoperability marshaling.
Interoperability Marshaling
All .NET Framework applications share a set of common types that allow interoperability of objects, regardless of the
programming language used. The parameters and return values of COM objects sometimes use data types that are different
than those used in managed code. Interoperability marshaling is the process of packaging parameters and return values into
equivalent data types as they move to and from COM objects. For more information, see Interop Marshaling Overview.
See Also
Tasks
Walkthrough: Implementing Inheritance with COM Objects
Troubleshooting Interoperability
Reference
Type Library Importer (Tlbimp.exe)
Type Library Exporter (Tlbexp.exe)
Concepts
Assemblies
Interop Marshaling Overview
Other Resources
COM Interop
Interoperating with Unmanaged Code
Registration-Free COM Interop
Visual Basic Language Concepts

How to: Reference COM Objects from Visual Basic


In Visual Basic, adding references to COM objects that have type libraries is similar to doing so in previous versions. However,
Visual Basic adds the creation of an interop assembly to the procedure. References to the members of the COM object are
routed to the interop assembly and then forwarded to the actual COM object. Responses from the COM object are routed to
the interop assembly and forwarded to your .NET Framework application.
To add references to COM objects
1. On the Project menu, choose Add Reference and then click the COM tab in the dialog box.
2. Select the component you want to use from the list of COM objects.
3. To simplify access to the interop assembly, add an Imports statement to the top of the class or module in which you will
use the COM object.
Visual Basic automatically creates interop assemblies when you add a reference to a type library from the integrated
development environment (IDE). When working from the command line, you can use the Tlbimp utility to manually
create interop assemblies.
To create an interop assembly using Tlbimp
1. Add the location of Tlbimp to the search path, if it is not already part of the search path and you are not currently in the
directory where it is located.
2. Call Tlbimp from a command prompt, providing the following information:
Name and location of the DLL that contains the type library
Name and location of the namespace where the information should be placed
Name and location of the target interop assembly
The following code provides an example:

Tlbimp test3.dll /out:NameSpace1 /out:Interop1.dll

You can use Tlbimp to create interop assemblies for type libraries, even for unregistered COM objects. However, the
COM objects referred to by interop assemblies must be properly registered on the computer where they are to be used.
You can register a COM object by using the Regsvr32 utility included with the Windows operating system.
See Also
Tasks
Walkthrough: Implementing Inheritance with COM Objects
Troubleshooting Interoperability
Reference
Type Library Importer (Tlbimp.exe)
Type Library Exporter (Tlbexp.exe)
Imports Statement
Other Resources
COM Interop
Visual Basic Language Concepts

How to: Work with ActiveX Controls


ActiveX controls are COM components or objects you can insert into a Web page or other application to reuse packaged
functionality someone else has programmed. You can use ActiveX controls developed for Visual Basic 6.0 and earlier versions
to add features to the Toolbox of Visual Studio.
To add ActiveX controls to the toolbox
1. On the Tools menu, click Choose Toolbox Items.
The Choose Toolbox dialog box appears.
2. Click the COM Components tab.
3. Select the check box next to the ActiveX control you want to use, and then click OK.
The new control appears with the other tools in the Toolbox.
Note
You can use the Aximp utility to manually create an interop assembly for ActiveX controls. For more information, see
Windows Forms ActiveX Control Importer (Aximp.exe).

See Also
Tasks
How to: Add ActiveX Controls to Windows Forms
Troubleshooting Interoperability
Reference
Choose Toolbox Items Dialog Box (Visual Studio)
Windows Forms ActiveX Control Importer (Aximp.exe)
Concepts
Considerations When Hosting an ActiveX Control on a Windows Form
Other Resources
COM Interop
Visual Basic Language Concepts

Walkthrough: Calling Windows APIs


Windows APIs are dynamic-link libraries (DLLs) that are part of the Windows operating system. You use them to perform tasks
when it is difficult to write equivalent procedures of your own. For example, Windows provides a function named
FlashWindowEx that lets you make the title bar for an application alternate between light and dark shades.
The advantage of using Windows APIs in your code is that they can save development time because they contain dozens of
useful functions that are already written and waiting to be used. The disadvantage is that Windows APIs can be difficult to work
with and unforgiving when things go wrong.
Windows APIs represent a special category of interoperability. Windows APIs do not use managed code, do not have built-in
type libraries, and use data types that are different than those used with Visual Studio. Because of these differences, and
because Windows APIs are not COM objects, interoperability with Windows APIs and the .NET Framework is performed using
platform invoke, or PInvoke. Platform invoke is a service that enables managed code to call unmanaged functions
implemented in DLLs. For more information, see Consuming Unmanaged DLL Functions. You can use PInvoke in Visual Basic
by using either the Declare statement or applying the DllImport attribute to an empty procedure.
Windows API calls were an important part of Visual Basic programming in the past, but are seldom necessary with Visual Basic
2005. Whenever possible, you should use managed code from the .NET Framework to perform tasks, instead of Windows API
calls. This walkthrough provides information for those situations in which using Windows APIs is necessary.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

API Calls Using Declare


The most common way to call Windows APIs is by using the Declare statement.
To declare a DLL procedure
1. Determine the name of the function you want to call, plus its arguments, argument types, and return value, as well as the
name and location of the DLL that contains it.
Note
For complete information about the Windows APIs, see the Win32 SDK documentation in the Platform SDK Windows A
PI. For more information about the constants that Windows APIs use, examine the header files such as Windows.h inclu
ded with the Platform SDK.

2. Open a new Windows Application project by clicking New on the File menu, and then clicking Project. The New Project
dialog box appears.
3. Select Windows Application from the list of Visual Basic project templates. The new project is displayed.
4. Add the following Declare function either to the class or module in which you want to use the DLL:
VB
Declare Auto Function MBox Lib "user32.dll" Alias "MessageBox" ( _
ByVal hWnd As Integer, _
ByVal txt As String, _
ByVal caption As String, _
ByVal Typ As Integer) _
As Integer

Parts of the Declare Statement


The Declare statement includes the following elements.
Auto modifier
The Auto modifier instructs the runtime to convert the string based on the method name according to common language
runtime rules (or alias name if specified).
Lib and Alias keywords
The name following the Function keyword is the name your program uses to access the imported function. It can be the same
as the real name of the function you are calling, or you can use any valid procedure name and then employ the Alias keyword
to specify the real name of the function you are calling.
Specify the Lib keyword, followed by the name and location of the DLL that contains the function you are calling. You do not
need to specify the path for files located in the Windows system directories.
Use the Alias keyword if the name of the function you are calling is not a valid Visual Basic procedure name, or conflicts with
the name of other items in your application. Alias indicates the true name of the function being called.
Argument and Data Type Declarations
Declare the arguments and their data types. This part can be challenging because the data types that Windows uses do not
correspond to Visual Studio data types. Visual Basic does a lot of the work for you by converting arguments to compatible data
types, a process called marshaling. You can explicitly control how arguments are marshaled by using the MarshalAsAttribute
attribute defined in the System.Runtime.InteropServices namespace.
Note
Previous versions of Visual Basic allowed you to declare parameters As Any, meaning that data of any data type could be us
ed. Visual Basic requires that you use a specific data type for all Declare statements.

Windows API Constants


Some arguments are combinations of constants. For example, the MessageBox API shown in this walkthrough accepts an
integer argument called Typ that controls how the message box is displayed. You can determine the numeric value of these
constants by examining the #define statements in the file WinUser.h. The numeric values are generally shown in hexadecimal,
so you may want to use a calculator to add them and convert to decimal. For example, if you want to combine the constants for
the exclamation style MB_ICONEXCLAMATION 0x00000030 and the Yes/No style MB_YESNO 0x00000004, you can add the numbers
and get a result of 0x00000034, or 52 decimal. Although you can use the decimal result directly, it is better to declare these
values as constants in your application and combine them using the Or operator.
To declare constants for Windows API calls
1. Consult the documentation for the Windows function you are calling. Determine the name of the constants it uses and
the name of the .h file that contains the numeric values for these constants.
2. Use a text editor, such as Notepad, to view the contents of the header (.h) file, and find the values associated with the
constants you are using. For example, the MessageBox API uses the constant MB_ICONQUESTION to show a question mark in
the message box. The definition for MB_ICONQUESTION is in WinUser.h and appears as follows:
#define MB_ICONQUESTION 0x00000020L

3. Add equivalent Const statements to your class or module to make these constants available to your application. For
example:
VB
Const MB_ICONQUESTION As Integer = &H20
Const MB_YESNO As Integer = &H4
Const IDYES As Integer = 6
Const IDNO As Integer = 7

To call the DLL procedure


1. Add a button named Button1 to the startup form for your project, and then double-click it to view its code. The event
handler for the button is displayed.
2. Add code to the Click event handler for the button you added, to call the procedure and provide the appropriate
arguments:
VB
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click

' Stores the return value.


Dim RetVal As Integer
RetVal = MBox(0, "Declare DLL Test", "Windows API MessageBox", _
MB_ICONQUESTION Or MB_YESNO)

' Check the return value.


If RetVal = IDYES Then
MsgBox("You chose Yes")
Else
MsgBox("You chose No")
End If
End Sub

3. Run the project by pressing F5. The message box is displayed with both Yes and No response buttons. Click either one.
Data Marshaling
Visual Basic automatically converts the data types of parameters and return values for Windows API calls, but you can use the
MarshalAs attribute to explicitly specify unmanaged data types that an API expects. For more information about interop
marshaling, see Interop Marshaling
To use Declare and MarshalAs in an API call
1. Determine the name of the function you want to call, plus its arguments, data types, and return value.
2. To simplify access to the MarshalAs attribute, add an Imports statement to the top of the code for the class or module,
as in the following example:
VB
Imports System.Runtime.InteropServices

3. Add a function prototype for the imported function to the class or module you are using, and apply the MarshalAs
attribute to the parameters or return value. In the following example, an API call that expects the type void* is marshaled
as AsAny:
VB
Declare Sub SetData Lib "..\LIB\UnmgdLib.dll" ( _
ByVal x As Short, _
<MarshalAsAttribute(UnmanagedType.AsAny)> _
ByVal o As Object)

API Calls Using DllImport


The DllImport attribute provides a second way to call functions in DLLs without type libraries. DllImport is roughly equivalent
to using a Declare statement but provides more control over how functions are called.
You can use DllImport with most Windows API calls as long as the call refers to a shared (sometimes called static) method.
You cannot use methods that require an instance of a class. Unlike Declare statements, DllImport calls cannot use the
MarshalAs attribute.
To call a Windows API using the DllImport attribute
1. Open a new Windows Application project by clicking New on the File menu, and then clicking Project. The New Project
dialog box appears.
2. Select Windows Application from the list of Visual Basic project templates. The new project is displayed.
3. Add a button named Button2 to the startup form.
4. Double-click Button2 to open the code view for the form.
5. To simplify access to DllImport, add an Imports statement to the top of the code for the startup form class:
VB
Imports System.Runtime.InteropServices

6. Declare an empty function preceding the End Class statement for the form, and name the function MoveFile.
7. Apply the Public and Shared modifiers to the function declaration and set parameters for MoveFile based on the
arguments the Windows API function uses:
VB
Public Shared Function MoveFile( _
ByVal src As String, _
ByVal dst As String) _
As Boolean
' Leave the body of the function empty.
End Function

Your function can have any valid procedure name; the DllImport attribute specifies the name in the DLL. It also handles
interoperability marshaling for the parameters and return values, so you can choose Visual Studio data types that are
similar to the data types the API uses.
8. Apply the DllImport attribute to the empty function. The first parameter is the name and location of the DLL containing
the function you are calling. You do not need to specify the path for files located in the Windows system directories. The
second parameter is a named argument that specifies the name of the function in the Windows API. In this example, the
DllImport attribute forces calls to MoveFile to be forwarded to MoveFileW in KERNEL32.DLL. The MoveFileW method
copies a file from the path src to the path dst.
VB
<DllImport("KERNEL32.DLL", EntryPoint:="MoveFileW", SetLastError:=True, _
CharSet:=CharSet.Unicode, ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function MoveFile( _
ByVal src As String, _
ByVal dst As String) _
As Boolean
' Leave the body of the function empty.
End Function

9. Add code to the Button2_Click event handler to call the function:


VB
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click

Dim RetVal As Boolean = MoveFile("c:\tmp\Test.txt", "c:\Test.txt")


If RetVal = True Then
MsgBox("The file was moved successfully.")
Else
MsgBox("The file could not be moved.")
End If
End Sub

10. Create a file named Test.txt and place it in the C:\Tmp directory on your hard drive. Create the Tmp directory if necessary.
11. Press F5 to start the application. The main form appears.
12. Click Button2. The message "The file was moved successfully" is displayed if the file can be moved.
See Also
Reference
Declare Statement
Auto
Alias
Lib
DllImportAttribute
MarshalAsAttribute
Concepts
Creating Prototypes in Managed Code
Callback Sample
Other Resources
COM Interop
Visual Basic: Samples

How to: Call Windows APIs (Visual Basic)


This example defines and calls the MessageBox function in user32.dll and then passes a string to it.
Example
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic
Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
VB
' Defines the MessageBox function.
Public Class Win32
Declare Auto Function MessageBox Lib "user32.dll" ( _
ByVal hWnd As Integer, ByVal txt As String, _
ByVal caption As String, ByVal Type As Integer) _
As Integer
End Class

' Calls the MessageBox function.


Public Class DemoMessageBox
Public Shared Sub Main()
Win32.MessageBox(0, "Here's a MessageBox", "Platform Invoke Sample", 0)
End Sub
End Class

Compiling the Code


This example requires:
A reference to the System namespace.
Robust Programming
The following conditions may cause an exception:
The method is not static, is abstract, or has been previously defined. The parent type is an interface, or the length of name
or dllName is zero. (ArgumentException)
The name or dllName is Nothing. (ArgumentNullException)
The containing type has been previously created using CreateType. (InvalidOperationException)

See Also
Tasks
Walkthrough: Calling Windows APIs
Concepts
A Closer Look at Platform Invoke
Platform Invoke Examples
Consuming Unmanaged DLL Functions
Defining a Method with Reflection Emit
Other Resources
COM Interop
Visual Basic Language Concepts

Walkthrough: Creating COM Objects with Visual Basic 2005


When creating new applications or components, it is best to create .NET Framework assemblies. However, Visual Basic 2005
also makes it easy to expose a .NET Framework component to COM. This allows you to provide new components for legacy
applications suites that require COM components. This walkthrough demonstrates how to use Visual Basic to expose .NET
Framework objects as COM objects, both with and without the COM class template.
The easiest way to expose COM objects is by using the COM class template. The COM class template creates a new class, and
then configures your project to generate the class and interoperability layer as a COM object and register it with the operating
system.
Note
Although you can also expose a class created with Visual Basic as a COM object for unmanaged code to use, it is not a true C
OM object and cannot be used by Visual Basic. For more information, see
COM Interoperability in .NET Framework Applications.

Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To create a COM object using the COM class template


1. Open a new Windows Application project from the File menu by clicking New Project.
2. In the New Project dialog box under the Project Types field, check that Windows is selected. Select Class Library from
the Templates list, and then click OK. The new project is displayed.
3. Select Add New Item from the Project menu. The Add New Item dialog box is displayed.
4. Select COM Class from the Templates list, and then click Add. Visual Basic adds a new class and configures the new
project for COM interop.
5. Add code such as properties, methods, and events to the COM class.
6. Select Build ClassLibrary1 from the Build menu. Visual Basic builds the assembly and registers the COM object with the
operating system.
Creating COM Objects without the COM Class Template
You can also create a COM class manually instead of using the COM class template. This procedure is helpful when working
from the command line or when you want more control over how COM objects are defined.
To set up your project to generate a COM object
1. Open a new Windows Application project from the File menu by clicking New Project.
2. In the New Project dialog box under the Project Types field, check that Windows is selected. Select Class Library from
the Templates list, and then click OK. The new project is displayed.
3. In Solution Explorer, right-click your project, and then click Properties. The Project Designer is displayed.
4. Click the Compile tab.
5. Select the Register for COM Interop check box.
To set up the code in your class to create a COM object
1. In Solution Explorer, double-click Class1.vb to display its code.
2. Rename the class to ComClass1.
3. Add the following constants to ComClass1. They will store the Globally Unique Identifier (GUID) constants that the COM
objects are required to have.
VB
Public Const ClassId As String = ""
Public Const InterfaceId As String = ""
Public Const EventsId As String = ""

4. To obtain a Globally Unique Identifier (GUID), launch Guidgen.exe to start the Guidgen utility. Select Registry Format
from the list of formats provided by the Guidgen application. Click the New GUID button to generate the GUID, and click
the Copy button to copy the GUID to the Clipboard.
5. Replace the empty string for the ClassId with the GUID, removing the leading and trailing braces. For example, if the
GUID provided by Guidgen is "{2C8B0AEE-02C9-486e-B809-C780A11530FE}" then your code should appear as follows.
VB
Public Const ClassId As String = "2C8B0AEE-02C9-486e-B809-C780A11530FE"

6. Repeat the previous steps for the InterfaceId and EventsId constants, as in the following example.
VB
Public Const InterfaceId As String = "3D8B5BA4-FB8C-5ff8-8468-11BF6BD5CF91"
Public Const EventsId As String = "2B691787-6ED7-401e-90A4-B3B9C0360E31"

Note
Make sure that the GUIDs are new and unique; otherwise, your COM component could conflict with other COM compo
nents.

7. Add the ComClass attribute to ComClass1, specifying the GUIDs for the Class ID, Interface ID, and Events ID as in the
following example:
VB
<ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> _
Public Class ComClass1

8. COM classes must have a parameterless Public Sub New() constructor, or the class will not register correctly. Add a
parameterless constructor to the class:
VB
Public Sub New()
MyBase.New()
End Sub

9. Add properties, methods, and events to the class, ending it with an End Class statement. Select Build Solution from the
Build menu. Visual Basic builds the assembly and registers the COM object with the operating system.
Note
The COM objects you generate with Visual Basic 2005 cannot be used by other Visual Basic 2005 applications because
they are not true COM objects. Attempts to add references to such COM objects will raise an error. For details, see
COM Interoperability in .NET Framework Applications.

See Also
Tasks
Walkthrough: Implementing Inheritance with COM Objects
Troubleshooting Interoperability
Reference
ComClassAttribute Class
#Region Directive
Other Resources
COM Interop
COM Interoperability in .NET Framework Applications
Visual Basic Language Concepts

Troubleshooting Interoperability
When interoperating between COM and the managed code of the .NET Framework, you may encounter one or more of the
following common issues.
Interop Marshaling
At times, you may need to use data types that are not part of the .NET Framework. Interop assemblies handle most of the work
for COM objects, but you may need to control the data types used when managed objects are exposed to COM. For example,
structures in class libraries must specify the BStr unmanaged type on strings sent to COM objects created by Visual Basic 6.0
and earlier versions. In such cases, you can use the MarshalAsAttribute attribute to cause managed types to be exposed as
unmanaged types.
Exporting Fixed-Length Strings to Unmanaged Code
In Visual Basic 6.0 and earlier versions, strings are exported to COM objects as sequences of bytes without a null termination
character. For compatibility with other languages, Visual Basic 2005 includes a termination character when exporting strings.
The best way to address this incompatibility is to export strings lacking the termination character as arrays of Byte or Char.
Exporting Inheritance Hierarchies
Managed class hierarchies flatten out when exposed as COM objects. For example, if you define a base class with a member,
and then inherit the base class in a derived class that is exposed as a COM object, clients that use the derived class in the COM
object will not be able to use the inherited members. Base class members are accessible from COM objects only as instances of
a base class, and then only if the base class is also created as a COM object.
Overloaded Methods
Although you can create overloaded methods with Visual Basic, they are not supported by COM. When a class that contains
overloaded methods is exposed as a COM object, new method names are generated for the overloaded methods.
For example, consider a class with two overloads of the Synch method. When the class is exposed as a COM object, the new
generated method names could be Synch and Synch_2.
The renaming can cause two problems for consumers of the COM object.
1. Clients might not expect the generated method names.
2. The generated method names in the class exposed as a COM object can change when new overloads are added to the
class or its base class, which can cause versioning problems.
To solve both problems, give each method a unique name, instead of using overloading, when developing objects that will be
exposed as COM objects.
Use of COM Objects Through Interop Assemblies
You use interop assemblies almost as though they are managed code replacements for the COM objects they represent.
However, because they are wrappers and not actual COM objects, there are some differences between using interop
assemblies and standard assemblies. These areas of difference include the exposure of classes, and data types for parameters
and return values.
Classes Exposed as Both Interfaces and Classes
Unlike classes in standard assemblies, COM classes are exposed in interop assemblies as both an interface and a class that
represents the COM class. The interface's name is identical to that of the COM class. The name of the interop class is the same
as that of the original COM class, but with the word "Class" appended. For example, suppose you have a project with a
reference to an interop assembly for a COM object. If the COM class is named MyComClass, IntelliSense and the Object Browser
show an interface named MyComClass and a class named MyComClassClass.
Creating Instances of a .NET Framework Class
Generally, you create an instance of a .NET Framework class using the New statement with a class name. Having a COM class
represented by an interop assembly is the one case in which you can use the New statement with an interface. Unless you are
using the COM class with an Inherits statement, you can use the interface the same way as you would a class. The following
code demonstrates how to create a Command object in a project that has a reference to the Microsoft ActiveX Data Objects 2.8
Library COM object:
VB
Dim cmd As New ADODB.Command

However, if you are using the COM class as the base for a derived class, you must use the interop class that represents the
COM class, as in the following code:
VB
Class DerivedCommand
Inherits ADODB.CommandClass
End Class

Note
Interop assemblies implicitly implement interfaces that represent COM classes. You should not attempt to use the Impleme
nts statement to implement these interfaces or an error will result.

Data Types for Parameters and Return Values


Unlike members of standard assemblies, interop assembly members may have data types that are different from those used in
the object's original declaration. Although interop assemblies implicitly convert COM types to compatible common language
runtime types, you should pay attention to the data types used by both sides to prevent runtime errors. For example, in COM
objects created with Visual Basic 6.0 and earlier versions, values of type Integer assume the .NET Framework equivalent type,
Short. It is recommended that you use the Object Browser to examine the characteristics of imported members before using
them.
Module level COM methods
Most COM objects are used by creating an instance of a COM class using the New keyword and then calling methods of the
object. One exception to this rule involves COM objects that contain AppObj or GlobalMultiUse COM classes. Such classes
are similar to module level methods in Visual Basic 2005 classes. Visual Basic 6.0 and earlier versions implicitly create
instances of such objects for you the first time you call one of their methods. For example, in Visual Basic 6.0 you can add a
reference to the Microsoft DAO 3.6 Object Library and call the DBEngine method without first creating an instance:

Dim db As DAO.Database
' Open the database.
Set db = DBEngine.OpenDatabase("C:\nwind.mdb")
' Use the database object.

Visual Basic 2005 requires that you always create instances of COM objects before you can use their methods. To use these
methods in Visual Basic 2005, declare a variable of the desired class and use the new keyword to assign the object to the object
variable. The Shared keyword can be used when you want to make sure that only one instance of the class is created.
VB
' Class level variable.
Shared DBEngine As New DAO.DBEngine

Sub DAOOpenRecordset()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim fld As DAO.Field
' Open the database.
db = DBEngine.OpenDatabase("C:\nwind.mdb")

' Open the Recordset.


rst = db.OpenRecordset( _
"SELECT * FROM Customers WHERE Region = 'WA'", _
DAO.RecordsetTypeEnum.dbOpenForwardOnly, _
DAO.RecordsetOptionEnum.dbReadOnly)
' Print the values for the fields in the debug window.
For Each fld In rst.Fields
Debug.WriteLine(fld.Value.ToString & ";")
Next
Debug.WriteLine("")
' Close the Recordset.
rst.Close()
End Sub

Unhandled Errors in Event Handlers


One common interop problem involves errors in event handlers that handle events raised by COM objects. Such errors are
ignored unless you specifically check for errors using On Error or Try...Catch...Finally statements. For example, the following
example is from a Visual Basic 2005 project that has a reference to the Microsoft ActiveX Data Objects 2.8 Library COM object.
VB
' To use this example, add a reference to the
' Microsoft ActiveX Data Objects 2.8 Library
' from the COM tab of the project references page.
Dim WithEvents cn As New ADODB.Connection
Sub ADODBConnect()
cn.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\NWIND.MDB"
cn.Open()
MsgBox(cn.ConnectionString)
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles MyBase.Load

ADODBConnect()
End Sub

Private Sub cn_ConnectComplete( _


ByVal pError As ADODB.Error, _
ByRef adStatus As ADODB.EventStatusEnum, _
ByVal pConnection As ADODB.Connection) _
Handles cn.ConnectComplete

' This is the event handler for the cn_ConnectComplete event raised
' by the ADODB.Connection object when a database is opened.
Dim x As Integer = 6
Dim y As Integer = 0
Try
x = CInt(x / y) ' Attempt to divide by zero.
' This procedure would fail silently without exception handling.
Catch ex As Exception
MsgBox("There was an error: " & ex.Message)
End Try
End Sub

This example raises an error as expected. However, if you try the same example without the Try...Catch...Finally block, the
error is ignored as if you used the OnError Resume Next statement. Without error handling, the division by zero silently fails.
Because such errors never raise unhandled exception errors, it is vital that you use some form of exception handling in event
handlers that handle events from COM objects.
Understanding COM interop errors
Without error handling, interop calls often generate errors that provide little information. Whenever possible, use structured
error handling to provide more information about problems when they occur. This can be particularly helpful when debugging
applications For example:
VB
Try
' Place call to COM object here.
Catch ex As Exception
' Display information about the failed call.
End Try

You can find information such as the error description, HRESULT, and the source of COM errors by examining the contents of
the exception object.
ActiveX Control Issues
Most ActiveX controls that work with Visual Basic 6.0 work with Visual Basic 2005 without trouble. The main exceptions are
container controls, or controls that visually contain other controls. Some examples of older controls that do not work correctly
with Visual Studio are:
Microsoft Forms 2.0 Frame control
Up-Down control, also known as the spin control
Sheridan Tab Control
There are only a few workarounds for unsupported ActiveX control problems. You can migrate existing controls to Visual
Studio if you own the original source code. Otherwise, you can check with software vendors for updated .NET-compatible
versions of controls to replace unsupported ActiveX controls.
Passing ReadOnly Properties of Controls ByRef
Visual Basic 2005 sometimes raises COM errors such as "Error 0x800A017F CTL_E_SETNOTSUPPORTED" when you pass
ReadOnly properties of some older ActiveX controls as ByRef parameters to other procedures. Similar procedure calls from
Visual Basic 6.0 do not raise an error, and the parameters are treated as if you passed them by value. The error message you
see in Visual Basic 2005 is the COM object reporting that you are attempting to change a property that does not have a
property Set procedure.
If you have access to the procedure being called, you can prevent this error by using the ByVal keyword to declare parameters
that accept ReadOnly properties. For example:
VB
Sub ProcessParams(ByVal c As Object)
'Use the arguments here.
End Sub

If you do not have access to the source code for the procedure being called, you can force the property to be passed by value
by adding an extra set of brackets around the calling procedure. For example, in a project that has a reference to the Microsoft
ActiveX Data Objects 2.8 Library COM object, you can use:
VB
Sub PassByVal(ByVal pError As ADODB.Error)
' The extra set of parentheses around the arguments
' forces them to be passed by value.
ProcessParams((pError.Description))
End Sub

Deploying Assemblies That Expose Interop


Deploying assemblies that expose COM interfaces presents some unique challenges. For example, a potential problem arises
when separate applications reference the same COM assembly. This situation is common when a new version of an assembly
is installed and another application is still using the old version of the assembly. Uninstalling any assembly that shares a DLL
can unintentionally make it unavailable to the other assemblies.
To avoid this problem, you should install shared assemblies to the Global Assembly Cache (GAC) and use a MergeModule for
the component. If you are unable to install the application in the GAC, then it should be installed to CommonFilesFolder in a
version-specific subdirectory.
Assemblies that are not shared should be placed side by side in the directory with the calling application.
See Also
Tasks
Walkthrough: Implementing Inheritance with COM Objects
Reference
Type Library Importer (Tlbimp.exe)
Type Library Exporter (Tlbexp.exe)
Inherits Statement
MarshalAsAttribute
Concepts
Data Type Changes for Visual Basic 6.0 Users
Introduction to Merge Modules
Merge Module Projects
Global Assembly Cache
Other Resources
COM Interop
Interop Marshaling
Visual Basic Language Concepts

COM Interoperability in .NET Framework Applications


When you want to use COM objects and .NET Framework objects in the same application, you need to address the differences
in how the objects exist in memory. A .NET Framework object is located in managed memory—the memory controlled by the
common language runtime—and may be moved by the runtime as needed. A COM object is located in unmanaged memory
and is not expected to move to another memory location. Visual Studio and the .NET Framework provide tools to control the
interaction of these managed and unmanaged components. For more information about managed code, see
Common Language Runtime.
In addition to using COM objects in .NET applications, you may also want to use Visual Basic to develop objects accessible from
unmanaged code through COM.
The links on this page provide details on the interactions between COM and .NET Framework objects.
Related Sections
COM Interop
Provides links to topics covering COM interoperability in Visual Basic, including COM objects, ActiveX controls, Win32 DLLs,
managed objects, and inheritance of COM objects.
COM Interop Wrapper Error
Describes the consequences and options if the project system cannot create a COM interoperability wrapper for a particular
component.
Interoperating with Unmanaged Code
Briefly describes some of the interaction issues between managed and unmanaged code, and provides links for further
study.
COM Wrappers
Discusses runtime callable wrappers, which allow managed code to call COM methods, and COM callable wrappers, which
allow COM clients to call .NET object methods.
Advanced COM Interoperability
Provides links to topics covering COM interoperability with respect to wrappers, exceptions, inheritance, threading, events,
conversions, and marshaling.
Automating Applications Using the Office Object Model
Provides information on using Microsoft Office and Visual Studio as part of your business application.
Type Library Importer (Tlbimp.exe)
Discusses the tool you can use to convert the type definitions found within a COM type library into equivalent definitions in a
common language runtime assembly.
Visual Basic Language Concepts

Multithreading in Visual Basic


Visual Basic applications can perform multiple tasks simultaneously using multithreading (or free threading), a process in
which individual tasks execute on separate threads. Multithreading improves the performance and responsiveness of your
applications.
In This Section
Multithreaded Applications
Describes how to create and use threads.
Thread States
Describes how to determine and change a thread's state.
Parameters and Return Values for Multithreaded Procedures
Describes how to pass and return parameters with multithreaded applications.
Multithreading with Forms and Controls
Covers special considerations when working with multithreading, forms, and controls.
Walkthrough: Multithreading
Shows how to create a simple multithreaded application.
Related Sections
Advanced Multithreading with Visual Basic
Lists topics that describe how to manage threads in multithreaded applications
Multithreading in Components
Provides links to topics that describe how to use multithreading in component programming.
Walkthrough: Authoring a Simple Multithreaded Component with Visual Basic
Shows how to create multithreaded components.
Visual Basic Language Concepts

Multithreaded Applications
With Visual Basic, you can write applications that perform multiple tasks simultaneously. Tasks with the potential of holding up
other tasks can execute on separate threads, a process known as multithreading or free threading.
Applications that use multithreading are more responsive to user input because the user interface stays active while processor-
intensive tasks execute on separate threads. Multithreading is also useful when creating scalable applications, because you can
add threads as the workload increases.
Using the BackgroundWorker Component
The most reliable way to create a multithreaded application is to use the BackgroundWorker component. This class manages a
separate thread dedicated to processing the method you specify. For an example, see Walkthrough: Multithreading.
To start an operation in the background, create a BackgroundWorker and listen for events that report the progress of your
operation and signal when your operation is finished. You can create the BackgroundWorker object programmatically, or you
can drag it onto your form from the Components tab of the Toolbox. If you create the BackgroundWorker in the Forms
Designer, it appears in the Component Tray, and its properties are displayed in the Properties window.
Setting Up for a Background Operation
To set up for a background operation, add an event handler for the DoWork event. Call your time-consuming operation in this
event handler.
To start the operation, call RunWorkerAsync. To receive notifications of progress updates, handle the ProgressChanged event.
To receive a notification when the operation is completed, handle the RunWorkerCompleted event.
The methods that handle the ProgressChanged and RunWorkerCompleted events can access the application's user
interface, because those events are raised on the thread that called the RunWorkerAsync method. However, the DoWork
event handler cannot manipulate any user-interface objects because it runs on the background thread.
Creating and Using Threads
If you need more control over the behavior of your application's threads, you can manage the threads yourself. However, be
aware that writing correct multithreaded applications can be difficult: Your application may stop responding or experience
transient errors due to race conditions. For more information, see Thread-Safe Components.
You create a new thread in Visual Basic by declaring a variable of type Thread and calling the constructor with the AddressOf
statement and the name of the procedure or method you want to execute on the new thread. The following code provides an
example:
VB
Dim TestThread As New System.Threading.Thread(AddressOf TestSub)

Starting and Stopping Threads


To start the execution of a new thread, use the Start method, as in the following code:
VB
TestThread.Start()

To stop the execution of a thread, use the Abort method, as in the following code:
VB
TestThread.Abort()

Besides starting and stopping threads, you can also pause threads by calling the Sleep or Suspend method, resume a
suspended thread with the Resume method, and destroy a thread using the Abort method, as in the following code:
VB
TestThread.Sleep(1000)
TestThread.Abort()

Thread Methods
The following table shows some of the methods you can use to control individual threads.
Meth Action
od
Start Causes a thread to start running.

Sleep Pauses a thread for a specified time.

Suspe Pauses a thread when it reaches a safe point.


nd

Abort Stops a thread when it reaches a safe point.

Resu Restarts a suspended thread


me

Join Causes the current thread to wait for another thread to finish. If used with a time-out value, this method returns True if
the thread finishes in the allotted time.
Safe Points
Most of these methods are self-explanatory, but the concept of safe points may be new to you. Safe points are places in code
where it is safe for the common language runtime to perform automatic garbage collection, the process of releasing unused
variables and reclaiming memory. When you call the Abort or Suspend method of a thread, the common language runtime
analyzes the code and determines the location of an appropriate place for the thread to stop running.
Thread Properties
Threads also contain a number of useful properties, as shown in the following table:
Property Value
IsAlive Contains the value True if a thread is active.

IsBackground Gets or sets a Boolean that indicates if a thread is or should be a background thread. Background threads are l
ike foreground threads, but a background thread does not prevent a process from terminating. Once all foregr
ound threads belonging to a process have terminated, the common language runtime ends the process by call
ing the Abort method on background threads that are still alive.

Name Gets or sets the name of a thread. Most commonly used to discover individual threads when debugging.

Priority Gets or sets a value used by the operating system to prioritize thread scheduling.

ApartmentState Gets or sets the threading model used for a particular thread. Threading models are important when a thread
calls unmanaged code.

ThreadState Contains a value that describes a thread's state or states.

See Thread States for more information on thread states and methods.
Thread Priorities
Every thread has a priority property that determines how big or small a slice of processor time it gets to execute. The operating
system allocates longer time slices to high-priority threads and shorter time slices to low-priority threads. New threads are
created with the value of Normal, but you can change the Priority property to any value in the ThreadPriority enumeration.
See ThreadPriority for a detailed description of the various thread priorities.
Foreground and Background Threads
A foreground thread runs indefinitely, while a background thread terminates once the last foreground thread has stopped. You
can use the IsBackground property to determine or change the background status of a thread.
See Also
Concepts
Thread States
Parameters and Return Values for Multithreaded Procedures
Thread Synchronization
Multithreading with Forms and Controls
Other Resources
Multithreading in Components
Visual Basic Language Concepts

Thread States
The ThreadState property provides information about the status of a thread. Because threads can be in more than one state at
any given time, the value stored in ThreadState can be a combination of the values in the ThreadState enumeration. For
example, if a thread is blocked on a call to Wait, and another thread calls the Abort method on that same thread, the thread is
in both the WaitSleepJoin and the AbortRequested state at the same time.
Changing Thread States
Once a thread has started, you can call its methods to change its state. For example, you can cause a thread to pause for a fixed
number of milliseconds by calling System.Threading.Thread.Sleep(System.Int32). The Sleep method takes as a parameter a
time-out, which is the number of milliseconds that the thread remains blocked.
Calling Sleep with the argument Infinite causes a thread to sleep until it is interrupted by another thread that calls Interrupt.
The Interrupt method wakes the destination thread out of any wait state it may be in and causes an exception to be raised.
You can also pause a thread by calling Suspend. When a thread calls Suspend on itself, the call blocks until another thread
resumes it by calling Resume. When a thread calls Suspend on another thread, the call is non-blocking and causes the other
thread to pause. Calling Resume breaks another thread out of its suspended state and causes it to resume execution. Unlike
Sleep, Suspend does not immediately stop a thread; the suspended thread does not pause until the common language
runtime determines that it has reached a safe point.
The Abort method stops a running thread by raising a ThreadAbortException exception that causes the thread to die.
See Thread for detailed information about these methods.
See Also
Reference
SyncLock Statement
System.Threading
Concepts
Multithreaded Applications
Thread Synchronization
Parameters and Return Values for Multithreaded Procedures
Multithreading with Forms and Controls
Delegates and the AddressOf Operator
Other Resources
Multithreading in Components
Visual Basic Language Concepts

Parameters and Return Values for Multithreaded Procedures


Supplying and returning values in a multithreaded application is complicated because the constructor for the thread class must
be passed a reference to a procedure that takes no arguments and returns no value. The following sections show some simple
ways to supply parameters and return values from procedures on separate threads.
Supplying Parameters for Multithreaded Procedures
The best way to supply parameters for a multithreaded method call is to wrap the target method in a class and define fields for
that class that will serve as parameters for the new thread. The advantage of this approach is that you can create a new
instance of the class, with its own parameters, every time you want to start a new thread. For example, suppose you have a
function that calculates the area of a triangle, as in the following code:
VB
Function CalcArea(ByVal Base As Double, ByVal Height As Double) As Double
CalcArea = 0.5 * Base * Height
End Function

You can write a class that wraps the CalcArea function and creates fields to store input parameters, as follows:
VB
Class AreaClass
Public Base As Double
Public Height As Double
Public Area As Double
Sub CalcArea()
Area = 0.5 * Base * Height
MsgBox("The area is: " & Area)
End Sub
End Class

To use the AreaClass, you can create an AreaClass object, and set the Base and Height properties as shown in the following
code:
VB
Protected Sub TestArea()
Dim AreaObject As New AreaClass
Dim Thread As New System.Threading.Thread _
(AddressOf AreaObject.CalcArea)
AreaObject.Base = 30
AreaObject.Height = 40
Thread.Start()
End Sub

Notice that the TestArea procedure does not check the value of the Area field after calling the CalcArea method. Because
CalcArea runs on a separate thread, the Area field is not guaranteed to be set if you check it immediately after calling
Thread.Start. The next section discusses a better way to return values from multithreaded procedures.

Returning Values from Multithreaded Procedures


Returning values from procedures that run on separate threads is complicated by the fact that the procedures cannot be
functions and cannot use ByRef arguments. The easiest way to return values is to use the BackgroundWorker component to
manage your threads and raise an event when the task is done, and process the results with an event handler.
The following example returns a value by raising an event from a procedure running on a separate thread:
VB
Private Class AreaClass2
Public Base As Double
Public Height As Double
Function CalcArea() As Double
' Calculate the area of a triangle.
Return 0.5 * Base * Height
End Function
End Class

Private WithEvents BackgroundWorker1 As New System.ComponentModel.BackgroundWorker


Private Sub TestArea2()
Dim AreaObject2 As New AreaClass2
AreaObject2.Base = 30
AreaObject2.Height = 40

' Start the asynchronous operation.


BackgroundWorker1.RunWorkerAsync(AreaObject2)
End Sub
' This method runs on the background thread when it starts.
Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, _
ByVal e As System.ComponentModel.DoWorkEventArgs) _
Handles BackgroundWorker1.DoWork

Dim AreaObject2 As AreaClass2 = CType(e.Argument, AreaClass2)


' Return the value through the Result property.
e.Result = AreaObject2.CalcArea()
End Sub
' This method runs on the main thread when the background thread finishes.
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, _
ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
Handles BackgroundWorker1.RunWorkerCompleted

' Access the result through the Result property.


Dim Area As Double = CDbl(e.Result)
MsgBox("The area is: " & Area)
End Sub

You can provide parameters and return values to thread-pool threads by using the optional ByVal state-object variable of the
QueueUserWorkItem method. Thread-timer threads also support a state object for this purpose. For information on thread
pooling and thread timers, see Thread Pooling and Thread Timers.
See Also
Concepts
Thread States
Thread Pooling
Thread Synchronization
Events and Event Handlers
Multithreaded Applications
Multithreading with Forms and Controls
Delegates and the AddressOf Operator
Other Resources
Multithreading in Components
Visual Basic Language Concepts

Multithreading with Forms and Controls


While multithreading is best suited to running procedures and class methods, you can also use it with forms and controls. If
you do so, be aware of the following points:
Whenever possible, execute the methods of a control only on the thread with which it was created. If you must call a
method of a control from another thread, you must use the Invoke to call the method.
Do not use the SyncLock statement to lock threads that manipulate controls or forms. Because the methods of controls
and forms sometimes call back to a calling procedure, you can end up inadvertently creating a deadlock—a situation in
which two threads wait for each other to release the lock, causing the application to halt.
See Also
Reference
Invoke
InvokeRequired
Concepts
Thread States
Parameters and Return Values for Multithreaded Procedures
Multithreaded Applications
Other Resources
Multithreading in Components
Visual Basic Language Concepts

Walkthrough: Multithreading
This walkthrough demonstrates how to create a multithreaded application that searches a text file for occurrences of a word. It
demonstrates:
Defining a class with a method that can be called by the BackgroundWorker component.
Handling events raised by the BackgroundWorker component.
Starting a BackgroundWorker component to run a method.
Implementing a Cancel button that stops the BackgroundWorker component.

To build the code example for this topic


1. Open a new Visual Basic Windows Application project, and create a form named Form1.
2. Add two buttons and four text boxes to Form1.
3. Name the objects as shown in the following table.
Object Property Setting
First button Name, Text Start, Start

Second button Name, Text Cancel, Cancel

First text box Name, Text SourceFile, ""

Second text box Name, Text CompareString, ""

Third text box Name, Text WordsCounted, "0"

Fourth text box Name, Text LinesCounted, "0"

4. Add a label next to each text box. Set the Text property for each label as shown in the following table.
Object Property Setting
First label Text Source File

Second label Text Compare String

Third label Text Matching Words

Fourth label Text Lines Counted

5. Add a BackgroundWorker component from the Components section of the ToolBox to your form. It will appear in the
form's component tray.
6. Set the following properties for the BackgroundWorker1 object.
Property Setting
WorkerReportsProgress True

WorkerSupportsCancellation True
7.
To define the method that will run on a separate thread
1. From the Project menu, choose Add Class to add a class to the project. The Add New Item dialog box is displayed.
2. Select Class from the templates window and type Words.vb in the name field.
3. Click Add. The Words class is displayed.
4. Add an Option Compare statement to the top of the Words class, above the Class statement:
VB
Option Compare Text ' Case insensitive search.
' Use Option Compare Binary for case sensitive search.

5. Add the following code to the Words class:


VB
Public Class Words
' Object to store the current state, for passing to the caller.
Public Class CurrentState
Public LinesCounted As Integer
Public WordsMatched As Integer
End Class

Public SourceFile As String


Public CompareString As String
Private WordCount As Integer = 0
Private LinesCounted As Integer = 0

Public Sub CountWords( _


ByVal worker As System.ComponentModel.BackgroundWorker, _
ByVal e As System.ComponentModel.DoWorkEventArgs _
)
' Initialize the variables.
Dim mystream As System.IO.StreamReader = Nothing
Dim line As String = ""

If CompareString Is Nothing Or _
CompareString = System.String.Empty Then
Throw New Exception("CompareString not specified.")
End If

Try
' Open a new stream.
mystream = My.Computer.FileSystem.OpenTextFileReader(SourceFile)
' Do until the stream returns Nothing at end of file.
Do Until line Is Nothing
If worker.CancellationPending Then
e.Cancel = True
Exit Do
Else
line = mystream.ReadLine
WordCount += CountInString(line, CompareString)
LinesCounted += 1 ' Increment line count.

' Raise an event so the form can monitor progress.


Dim state As New CurrentState
state.LinesCounted = LinesCounted
state.WordsMatched = WordCount
worker.ReportProgress(0, state)
End If
Loop
Finally
If mystream IsNot Nothing Then
' Close the file.
mystream.Close()
End If
End Try
End Sub

Private Function CountInString( _


ByVal SourceString As String, _
ByVal CompareString As String _
) As Integer
' This function counts the number of times
' a word is found in a line.
If SourceString Is Nothing Then
Return 0
End If

Dim regex As New System.Text.RegularExpressions.Regex( _


System.Text.RegularExpressions.Regex.Escape(CompareString))
Dim matches As System.Text.RegularExpressions.MatchCollection
matches = regex.Matches(SourceString)
Return matches.Count
End Function
End Class

To handle events from the thread


Add the following event handlers to your main form:
VB
Private Sub BackgroundWorker1_RunWorkerCompleted( _
ByVal sender As Object, _
ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
Handles BackgroundWorker1.RunWorkerCompleted

' This event handler is called when the background thread finishes.
' This method runs on the main thread.

If e.Error IsNot Nothing Then


MsgBox("Error: " & e.Error.Message)
ElseIf e.Cancelled Then
MsgBox("Word counting canceled.")
Else
MsgBox("Finished counting words.")
End If
End Sub

Private Sub BackgroundWorker1_ProgressChanged( _


ByVal sender As Object, _
ByVal e As System.ComponentModel.ProgressChangedEventArgs) _
Handles BackgroundWorker1.ProgressChanged

' This event handler is called after the background thread


' reads a line from the source file.
' This method runs on the main thread.

Dim state As Words.CurrentState = _


CType(e.UserState, Words.CurrentState)
Me.LinesCounted.Text = state.LinesCounted.ToString
Me.WordsCounted.Text = state.WordsMatched.ToString
End Sub

To start and call a new thread that runs the WordCount method
1. Add the following procedures to your program:
VB
Private Sub BackgroundWorker1_DoWork( _
ByVal sender As Object, _
ByVal e As System.ComponentModel.DoWorkEventArgs) _
Handles BackgroundWorker1.DoWork

' This event handler is where the actual work is done.


' This method runs on the background thread.

' Get the BackgroundWorker object that raised this event.


Dim worker As System.ComponentModel.BackgroundWorker
worker = CType(sender, System.ComponentModel.BackgroundWorker)

' Get the Works object and call the main method.
Dim WC As Words = CType(e.Argument, Words)
WC.CountWords(worker, e)
End Sub

Sub StartThread()
' This method runs on the main thread.

Me.WordsCounted.Text = "0"

' Initialize the object that the background worker calls.


Dim WC As New Words
WC.CompareString = Me.CompareString.Text
WC.SourceFile = Me.SourceFile.Text

' Start the asynchronous operation.


BackgroundWorker1.RunWorkerAsync(WC)
End Sub

2. Call the StartThread method from the Start button on your form:
VB
Private Sub Start_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Start.Click

StartThread()
End Sub
To implement a Cancel button that stops the thread
Call the StopThread procedure from the Click event handler for the Cancel button.
VB
Private Sub Cancel_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Cancel.Click

' Cancel the asynchronous operation.


Me.BackgroundWorker1.CancelAsync()
End Sub

Testing
You can now test the application to make sure it works correctly.
To test the application
1. Press F5 to run the application.
2. When the form is displayed, enter the file path for the file you want to test in the sourceFile box. For example, assuming
your test file is named Test.txt, enter C:\Test.txt.
3. In the second text box, enter a word or phrase for the application to search for in the text file.
4. Click the Start button. The LinesCounted button should begin incrementing immediately. The application displays the
message "Finished Counting" when it is done.

To test the Cancel button


1. Press F5 to start the application, and enter the file name and search word as described in the previous procedure. Make
sure that the file you choose is large enough to ensure you will have time to cancel the procedure before it is finished.
2. Click the Start button to start the application.
3. Click the Cancel button. The application should stop counting immediately.
Next Steps
This application contains some basic error handling. It detects blank search strings. You can make this program more robust by
handling other errors, such as exceeding the maximum number of words or lines that can be counted.
See Also
Tasks
Walkthrough: Authoring a Simple Multithreaded Component with Visual Basic
Other Resources
Multithreading in Visual Basic
Visual Basic Language Reference

Reference (Visual Basic)


This section links you to reference information on various aspects of Visual Basic programming.
In This Section
Visual Basic Reference
Provides reference information for various aspects of the Visual Basic language.
Visual Basic Command-Line Tools
Covers the Visual Basic command-line compiler, the compiler options, and the Keyword Upgrade tool.
Upgrading Reference for Visual Basic
Provides links to information on upgrading your applications from previous versions of Visual Basic to the current version.
.NET Framework Reference Information
Provides links to information on working with the .NET Framework class library.
Visual Basic Language Specification
Provides links to the complete Visual Basic language specification, which contains detailed information on all aspects of the
language.
Related Sections
General User Interface Elements (Visual Studio)
Contains topics for dialog boxes and windows used in Visual Studio.
XML Schema References
Provides links to topics on various XML schemas available in Visual Studio.
Language Equivalents
Compares keywords, programming concepts, data types, operators, controls, and programmable objects in several
programming languages.
Automation and Extensibility Reference
Provides links to topics covering automation and extensibility in Visual Studio, for both shared and language-specific
components.
Visual Basic Language Reference

Visual Basic Reference


This section provides reference information for various aspects of the Visual Basic language.
In This Section
Typographic and Code Conventions
Summarizes the way that keywords, placeholders, and other elements of the language are formatted in the Visual Basic
documentation.
Visual Basic Language Keywords
Documents the reserved and unreserved keywords of the Visual Basic language.
Visual Basic Run-Time Library Members
Lists the classes and modules of the Microsoft.VisualBasic namespace, with links to their member functions, methods,
properties, constants, and enumerations.
Keywords and Members by Task
Summarizes Visual Basic language keywords and run-time library members by purpose and use.
Visual Basic Attributes
Documents the attributes available in Visual Basic.
Constants and Enumerations (Visual Basic)
Documents the constants and enumerations available in Visual Basic.
Data Type Summary (Visual Basic)
Documents the data types available in Visual Basic.
Directives (Visual Basic)
Documents the compiler directives available in Visual Basic.
Functions (Visual Basic)
Documents the run-time functions available in Visual Basic.
Keywords (Visual Basic)
Documents the language keywords available in Visual Basic.
Modules (Visual Basic)
Documents the modules available in Visual Basic and their members.
Objects (Visual Basic)
Documents the objects available in Visual Basic and their members.
Operators (Visual Basic)
Documents the operators available in Visual Basic.
Properties (Visual Basic)
Documents the properties available in Visual Basic.
Statements (Visual Basic)
Documents the declaration and executable statements available in Visual Basic.
Recommended XML Tags for Documentation Comments (Visual Basic)
Describes the documentation comments for which IntelliSenseTM is provided in the Visual Basic code editor.
Error Messages (Visual Basic)
Provides a listing of Visual Basic compiler and run-time error messages and help on how to handle them.
Related Sections
Visual Basic
Provides comprehensive help on all areas of the Visual Basic language.
Visual Basic Compiler
Describes how to use the command-line compiler as an alternative to compiling programs from within the Visual Studio
integrated development environment (IDE).
Visual Basic Language Reference

Typographic and Code Conventions


Visual Basic documentation uses the following typographic and code conventions.
Typographic Conventions
Convention Description
Sub, If, ChDir, Print, True, Words in bold with initial letter capitalized indicate language-specific keywords or runtime mem
Debug bers.

Module Statement Words and phrases in an underlined, colored font are hyperlinks you can click to go immediately
to a relevant Help page.

object, variablename, argum Italic letters indicate placeholders for information that you supply.
entlist

[ Shadows ], [ expressionlist ] In syntax, items inside brackets are optional.

{ Public | Friend | Private } In syntax, curly braces and vertical bars indicate a mandatory choice between two or more items.
You must choose one, and only one, of the items.

[ Protected | Friend ] In syntax, square brackets and vertical bars indicate two or more independent options. You can c
hoose any combination, or none, of the items.

[{ ByVal | ByRef }] In syntax, square brackets surrounding curly braces and vertical bars indicate that you can choos
e no more than one item, but you can also omit the items entirely.

membername 1, memberna Subscripts differentiate multiple instances of the same placeholder.


me2, membername3

memerbname1 In syntax, ellipses indicate an indefinite number of items of the kind immediately preceding the el
lipses.
...
In code, ellipses signify code omitted for the sake of clarity.
membernamen

ESC, ENTER Words in capital letters indicate key names and key sequences on your keyboard.

ALT+F1, CTRL+R A plus sign (+) between key names indicates a combination of keys. For example, ALT+F1 means
hold down the ALT key while pressing the F1 key.
Code Conventions
Sample code Description
sampleString = "Hello, world!" A fixed pitch font is used for code samples, as well as for code element
The preceding statement sets the value of sampleStrin s in explanatory text.
g to "Hello, world!".

' This is a comment. An apostrophe (') or the REM keyword introduces code comments.
REM This is also a comment.

sampleVar = "This is an " _ A space followed by an underscore ( _) at the end of a line continues th
& "example" _ e source code statement.
& " of how to continue code."

See Also
Tasks
How to: Break and Combine Statements in Code
Reference
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Concepts
Visual Basic Naming Conventions
Comments in Code
Other Resources
Visual Basic Reference
Visual Basic Language Reference

Visual Basic Language Keywords


The following tables list all the Visual Basic language keywords.
Reserved Keywords
The following keywords are reserved, which means you cannot use them as names for your programming elements such as
variables or procedures. You can bypass this restriction by enclosing the name in brackets ([ ]). For more information, see
"Escaped Names" in Declared Element Names.
Note
Using escaped names is not recommended, because it can make your code hard to read, and can lead to subtle errors that ca
n be difficult to find.

AddHandler AddressOf Alias And

AndAlso As Boolean ByRef

Byte ByVal Call Case

Catch CBool CByte CChar

CDate CDec CDbl Char

CInt Class CLng CObj

Const Continue CSByte CShort

CSng CStr CType CUInt

CULng CUShort Date Decimal

Declare Default Delegate Dim

DirectCast Do Double Each

Else ElseIf End EndIf

Enum Erase Error Event

Exit False Finally For

Friend Function Get GetType

Global GoSub GoTo Handles

If Implements Imports In

Inherits Integer Interface Is

IsNot Let Lib Like

Long Loop Me Mod


Module MustInherit MustOverride MyBase

MyClass Namespace Narrowing New

Next Not Nothing NotInheritable

NotOverridable Object Of On

Operator Option Optional Or

OrElse Overloads Overridable Overrides

ParamArray Partial Private Property

Protected Public RaiseEvent ReadOnly

ReDim REM RemoveHandler Resume

Return SByte Select Set

Shadows Shared Short Single

Static Step Stop String

Structure Sub SyncLock Then

Throw To True Try

TryCast TypeOf Variant Wend

UInteger ULong UShort Using

When While Widening With

WithEvents WriteOnly Xor #Const

#Else #ElseIf #End #If

- & &= *

*= / /= \

\= ^ ^= +

+= = -=
Note
EndIf, GoSub, Let, Variant, and Wend are retained as reserved keywords, although they are no longer used in Visual Basic.

Unreserved Keywords
The following keywords are not reserved, which means you can use them as names for your programming elements. However,
doing this is not recommended, because it can make your code hard to read and can lead to subtle errors that can be difficult
to find.
Ansi Assembly Auto Binary

Compare Custom Explicit IsFalse

IsTrue Mid Off Preserve

Strict Text Unicode Until

#ExternalSource #Region
See Also
Reference
Visual Basic Run-Time Library Members
Keywords and Members by Task
Keywords Compared in Different Languages
Visual Basic Language Reference

Visual Basic Run-Time Library Members


The Microsoft.VisualBasic namespace contains the classes, modules, constants, and enumerations that constitute the Visual
Basic run-time library. These library members provide procedures, properties, and constant values you can use in your code.
Each module and class represents a particular category of functionality.
Microsoft.VisualBasic.Collection Class
Add Clear Contains Count

GetEnumerator Item Remove


Microsoft.VisualBasic.ComClassAttribute Class
ClassID EventID InterfaceID InterfaceShadows
Microsoft.VisualBasic.ControlChars Class
Back Cr CrLf FormFeed

Lf NewLine NullChar Quote

Tab VerticalTab
Microsoft.VisualBasic.Conversion Module
ErrorToString Fix Hex Int

Oct Str Val


Microsoft.VisualBasic.DateAndTime Module
DateAdd DateDiff DatePart DateSerial

DateString DateValue Day Hour

Minute Month MonthName Now

Second TimeOfDay Timer TimeSerial

TimeString TimeValue Today WeekDay

WeekDayName Year
Microsoft.VisualBasic.ErrObject Class
Clear Description Erl GetException

HelpContext HelpFile LastDLLError Number

Raise Source
Microsoft.VisualBasic.FileSystem Module
ChDir ChDrive CurDir Dir

EOF FileAttr FileClose FileCopy

FileDateTime FileGet FileGetObject FileLen


FileOpen FilePut FilePutObject FileWidth

FreeFile GetAttr Input InputString

Kill LineInput Loc Lock

LOF MkDir Print PrintLine

Rename Reset RmDir Seek

SetAttr SPC TAB Unlock

Write WriteLine
Microsoft.VisualBasic.Financial Module
DDB FV IPmt IRR

MIRR NPer NPV Pmt

PPmt PV Rate SLN

SYD
Microsoft.VisualBasic.Globals Module
ScriptEngine ScriptEngineBuildVersion ScriptEngineMajorVersion ScriptEngineMinorVersion
Microsoft.VisualBasic.Information Module
Err IsArray IsDate IsDBNull

IsError IsNothing IsNumeric IsReference

LBound QBColor RGB SystemTypeName

TypeName UBound VarType VbTypeName


Microsoft.VisualBasic.Interaction Module
AppActivate Beep CallByName Choose

Command CreateObject DeleteSetting Environ

GetAllSettings GetObject GetSetting IIf

InputBox MsgBox Partition SaveSetting

Shell Switch
Microsoft.VisualBasic.Strings Module
Asc AscW Chr ChrW

Filter Format FormatCurrency FormatDateTime

FormatNumber FormatPercent GetChar InStr


InStrRev Join LCase Left

Len LSet LTrim Mid

Replace Right RSet RTrim

Space Split StrComp StrConv

StrDup StrReverse Trim UCase


Microsoft.VisualBasic.VBFixedArrayAttribute Class
Bounds Length
Microsoft.VisualBasic.VBFixedStringAttribute Class
Length
Microsoft.VisualBasic.VbMath Module
Randomize Rnd
Microsoft.VisualBasic Constants and Enumerations
The Microsoft.VisualBasic namespace provides constants and enumerations as part of the Visual Basic run-time library. You
can use these constant values in your code. Each enumeration represents a particular category of functionality. For more
information, see Constants and Enumerations (Visual Basic).
See Also
Reference
Visual Basic Language Keywords
Keywords and Members by Task
Other Resources
Visual Basic Runtime Namespace in Visual Studio
Constants and Enumerations (Visual Basic)
Visual Basic Language Reference

Keywords and Members by Task


Visual Basic language keywords and run-time library members are organized by purpose and use.
Category Description
Arrays Summary Creating, defining, and using arrays.

Collection Object Summary Using collections.

Compiler Directive Summary Controlling compiler behavior.

Control Flow Summary Looping and controlling procedure flow.

Conversion Summary Converting numbers and data types.

Data Types Summary Data types and object subtypes.

Dates and Times Summary Converting and using date and time expressions.

Declarations and Constants Summary Declaring programming elements and defining constants.

Directories and Files Summary Controlling the file system and processing files.

Errors Summary Trapping and returning error values.

Financial Summary Performing financial calculations.

Input and Output Summary Receiving input and displaying or printing output.

Information and Interaction Summary Starting other applications and processing events.

Math Summary Performing trigonometric and other mathematical calculations.

My Reference Documents My, a feature that allows easy and rapid application development by provid
ing intuitive access to commonly used methods, properties, and events used for progra
mming against the computer on which the application is running, the current applicatio
n, the application's resources, the application's settings, and so on

Operators Summary Comparing expressions and other operations.

Registry Summary Deleting, reading, and saving program settings.

String Manipulation Summary Manipulating strings and string type data.


See Also
Reference
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Arrays Summary
Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Verify an array. IsArray

Declare and initialize an array. Dim, Private, Public, ReDim

Find the limits of an array. LBound, UBound

Reinitialize an array Erase, ReDim


See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Collection Object Summary


Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Create a Collection object. Collection

Add an item to a collection. Add

Remove an object from a collection. Remove

Reference an item in a collection. Item

Return a reference to an IEnumerator interface. GetEnumerator


See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Compiler Directive Summary


Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Define a compiler constant. #Const Directive

Compile selected blocks of code. #If...Then...#Else Directives

Collapse and hide sections of code. #Region Directive

Indicate a mapping between source lines and text external to the source. #ExternalSource Directive
See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Control Flow Summary


Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Branch. GoTo, On Error

Exit or pause the program. End, Exit, Stop

Loop. Do...Loop, For...Next, For Each...Next, While...End While, With

Make decisions. Choose, If...Then...Else, Select Case, Switch

Use procedures. Call, Function, Property, Sub


See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Conversion Summary
Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Convert ANSI value to string. Chr, ChrW

Convert string to lowercase or uppercase. Format, LCase,UCase

Convert date to serial number. DateSerial, DateValue

Convert decimal number to other bases. Hex, Oct

Convert number to string. Format, Str

Convert one data type to another. CBool, CByte, CDate, CDbl, CDec, CInt, CLng, CSng, CShort, CStr, CType, Fix, Int

Convert date to day, month, weekday, or year. Day, Month, Weekday, Year

Convert time to hour, minute, or second. Hour, Minute, Second

Convert string to ASCII value. Asc, AscW

Convert string to number. Val

Convert time to serial number. TimeSerial, TimeValue


See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Data Types Summary


Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Convert between data types CBool, CByte, CChar, CDate, CDbl, CDec, CInt, CLng, CObj, CShort, CSng, CStr, Fix, Int

Set intrinsic data types Boolean, Byte, Char, Date, Decimal, Double, Integer, Long, Object, Short, Single, String

Verify data types IsArray, IsDate, IsDbNull, IsError, IsNothing, IsNumeric, IsReference
See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Dates and Times Summary


Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Get the current date or time. Now, Today, TimeOfDay

Perform date calculations. DateAdd, DateDiff, DatePart

Return a date. DateSerial, DateValue, MonthName, WeekDayName

Return a time. TimeSerial, TimeValue

Set the date or time. DateString, TimeOfDay, TimeString, Today

Time a process. Timer


See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Declarations and Constants Summary


Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Assign a value. Get, Property

Declare variables or constants. Const, Dim, Private, Protected, Public, Shadows, Shared, Static

Declare a class, delegate, enumeration, mod Class, Delegate, Enum, Module, Namespace, Structure
ule, namespace, or structure.

Create objects. CreateObject, GetObject, New

Get information about an object. GetType, IsArray, IsDate, IsDbNull, IsError, IsNothing, IsNumeric, IsReference,
SystemTypeName, TypeName, VarType, VbTypeName

Refer to the current object. Me

Require explicit variable declarations. Option Explicit, Option Strict

Handle events. AddHandler, Event, RaiseEvent, RemoveHandler

Implement inheritance. Inherits, MustInherit, MustOverride, MyBase, MyClass, New, NotInheritable,


NotOverridable, Overloads, Overridable, Overrides
See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Directories and Files Summary


Visual Basic language keywords and run-time library members are organized by purpose and use.
Using the My feature gives you greater productivity and performance in file I/O operations than using these members. For
more information, see My.Computer.FileSystem Object.
Action Language element
Change a directory or folder. ChDir

Change the drive. ChDrive

Copy a file. FileCopy

Make a directory or folder. MkDir

Remove a directory or folder. RmDir

Rename a file, directory, or folder. Rename

Return the current path. CurDir

Return a file's date/time stamp. FileDateTime

Return file, directory, or label attributes. GetAttr

Return a file's length. FileLen

Return a file's name or volume label. Dir

Set attribute information for a file. SetAttr


See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Concepts
Parsing Text Files with the TextFieldParser Object
Other Resources
Reading from Files in Visual Basic
Writing to Files in Visual Basic
Creating, Deleting, and Moving Files and Directories in Visual Basic
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference

Errors Summary
Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Generate run-time errors. Clear, Error, Raise

Get exceptions. GetException

Provide error information. Err

Trap errors during run time. On Error, Resume, Try...Catch...Finally

Provide line number of error. Erl

Provide system error code. LastDLLError


See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Financial Summary
Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Calculate depreciation. DDB, SLN, SYD

Calculate future value. FV

Calculate interest rate. Rate

Calculate internal rate of return. IRR, MIRR

Calculate number of periods. NPer

Calculate payments. IPmt, Pmt, PPmt

Calculate present value. NPV, PV


See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Information and Interaction Summary


Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Run other programs. AppActivate, Shell

Call a method or property. CallByName

Sound a beep from computer. Beep

Provide a command-line string. Command

Manipulate COM objects. CreateObject, GetObject

Retrieve color information. QBColor, RGB

Control dialog boxes InputBox, MsgBox


See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Input and Output Summary


Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Access or create a file. FileOpen

Close files. FileClose, Reset

Control output appearance. Format, Print, SPC, TAB, FileWidth

Copy a file. FileCopy

Get information about a file. EOF, FileAttr, FileDateTime, FileLen, FreeFile, GetAttr, Loc, LOF,
Seek

Get or provide information from/to the user by means of a c InputBox, MsgBox


ontrol dialog box.

Manage files. Dir, Kill, Lock, Unlock

Read from a file. FileGet, FileGetObject, Input, InputString, LineInput

Return length of a file. FileLen

Set or get file attributes. FileAttr, GetAttr, SetAttr

Set read-write position in a file. Seek

Write to a file. FilePut, FilePutObject, Print, Write, WriteLine Functions,


Write, WriteLine Functions
See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Math Summary
Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Derive trigonometric functions. Atn, Cos, Sin, Tan

General calculations. Exp, Log, Sqr

Generate random numbers. Randomize, Rnd

Get absolute value. Abs

Get the sign of an expression. Sgn

Perform numeric conversions. Fix, Int


See Also
Reference
Derived Math Functions (Visual Basic)
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Derived Math Functions (Visual Basic)


The following is a list of non-intrinsic math functions that can be derived from the intrinsic math functions:
Function Derived equivalents
Secant (Sec(x)) 1 / Cos(x)

Cosecant (Csc(x)) 1 / Sin(x)

Cotangent (Ctan(x)) 1 / Tan(x)

Inverse sine (Asin(x)) Atan(x / Sqrt(-x * x + 1))

Inverse cosine (Acos(x)) Atan(-x / Sqrt(-x * x + 1)) + 2 * Atan(1)

Inverse secant (Asec(x)) 2 * Atan(1) – Atan(Sign(x) / Sqrt(x * x – 1))

Inverse cosecant (Acsc(x)) Atan(Sign(x) / Sqrt(x * x – 1))

Inverse cotangent (Acot(x)) 2 * Atan(1) - Atan(x)

Hyperbolic sine (Sinh(x)) (Exp(x) – Exp(-x)) / 2

Hyperbolic cosine (Cosh(x)) (Exp(x) + Exp(-x)) / 2

Hyperbolic tangent (Tanh(x)) (Exp(x) – Exp(-x)) / (Exp(x) + Exp(-x))

Hyperbolic secant (Sech(x)) 2 / (Exp(x) + Exp(-x))

Hyperbolic cosecant (Csch(x)) 2 / (Exp(x) – Exp(-x))

Hyperbolic cotangent (Coth(x)) (Exp(x) + Exp(-x)) / (Exp(x) – Exp(-x))

Inverse hyperbolic sine (Asinh(x)) Log(x + Sqrt(x * x + 1))

Inverse hyperbolic cosine (Acosh(x)) Log(x + Sqrt(x * x – 1))

Inverse hyperbolic tangent (Atanh(x)) Log((1 + x) / (1 – x)) / 2

Inverse hyperbolic secant (AsecH(x)) Log((Sqrt(-x * x + 1) + 1) / x)

Inverse hyperbolic cosecant (Acsch(x)) Log((Sign(x) * Sqrt(x * x + 1) + 1) / x)

Inverse hyperbolic cotangent (Acoth(x)) Log((x + 1) / (x – 1)) / 2


Requirements
Namespace: Math
Assembly: mscorlib (in mscorlib.dll)
See Also
Reference
Math Functions (Visual Basic)
Visual Basic Language Reference

My Reference
The My feature makes programming faster and easier by giving you intuitive access to commonly used methods, properties,
and events. This table lists the objects contained in My, and the actions that can be performed with each.
Action Object
Accessing application information and services. My.Application Object

Accessing the host computer and its resources, services, and data. My.Computer Object

Accessing the forms in the current project. My.Forms Object

Accessing the application log. My.Log Object

Accessing the current web request. My.Request Object

Accessing resource elements. My.Resources Object

Accessing the current web response. My.Response Object

Accessing user and application level settings. My.Settings Object

Accessing the current user's security context. My.User Object

Accessing XML Web services referenced by the current project. My.WebServices Object
See Also
Concepts
What's New in Visual Basic
Overview of the Visual Basic Application Model
Development with My
Visual Basic Language Reference

Operators Summary
Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Arithmetic ^, –, *, /, \, Mod, +, =

Assignment =, ^=, *=, /=, \=, +=, -=, &=

Comparison =, <>, <, >, <=, >=, Like, Is

Concatenation &, +

Logical/bitwise operations Not, And, Or, Xor, AndAlso, OrElse

Miscellaneous operations AddressOf, GetType


See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Registry Summary
Visual Studio language keywords and run-time library members are organized by purpose and use.
Using the My feature provides you with greater productivity and performance in registry operations than these elements. For
more information, see My.Computer.Registry Object.
Action Language element
Delete program settings. DeleteSetting

Read program settings. GetSetting, GetAllSettings

Save program settings. SaveSetting


See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Concepts
Common Registry Tasks
Visual Basic Language Reference

String Manipulation Summary


Visual Basic language keywords and run-time library members are organized by purpose and use.
Action Language element
Compare two strings. StrComp

Convert strings. StrConv

Reverse a string. InStrRev, StrReverse

Convert to lowercase or uppercase. Format, LCase, UCase

Create a string of repeating characters. Space, StrDup

Find the length of a string. Len

Format a string. Format, FormatCurrency, FormatDateTime, FormatNumber, FormatPercent

Manipulate strings. InStr, Left, LTrim, Mid, Right, RTrim, Trim

Set string comparison rules. Option Compare

Work with ASCII and ANSI values. Asc, AscW, Chr, ChrW

Replace a specified substring. Replace

Return a filter-based string array. Filter

Return a specified number of substrings. Split, Join


See Also
Reference
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Visual Basic Attributes


Visual Basic provides several attributes that allow objects interoperate with unmanaged code, and one attribute that enables
module members to be accessed without the module name.
In This Section
ComClassAttribute Class
HideModuleNameAttribute Class
VBFixedArrayAttribute Class
VBFixedStringAttribute Class
Related Sections
Attributes in Visual Basic
Visual Basic Language Reference

ComClassAttribute Class
The ComClassAttribute attribute instructs the compiler to add metadata that allows a class to be exposed as a COM object.

<System.AttributeUsage(System.AttributeTargets.Class, _
Inherited := False, AllowMultiple := False)> _
Public NotInheritable Class ComClassAttribute
Inherits System.Attribute

Remarks
Use ComClassAttribute to simplify the process of exposing COM components from Visual Basic. COM objects are very
different from .NET Framework assemblies; without the ComClassAttribute, you need to follow a number of steps to generate
a COM object from Visual Basic. For classes marked with ComClassAttribute, the compiler performs many of these steps
automatically.
Note
This attribute simplifies the creation of COM objects. To expose a class as a COM object, you must compile the project with th
e Register for COM Interop option selected in the Build section of the Configuration Properties dialog box.

Note
Although you can also expose a class created with Visual Basic as a COM object for unmanaged code to use, it is not a true C
OM object. For details, see COM Interoperability in .NET Framework Applications.

Example
To run this example, create a new Class Library application and add the following code to a class module.
VB
<ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> _
Public Class ComClass1
' Use the Region directive to define a section named COM Guids.
#Region "COM GUIDs"
' These GUIDs provide the COM identity for this class
' and its COM interfaces. You can generate
' these guids using guidgen.exe
Public Const ClassId As String = "7666AC25-855F-4534-BC55-27BF09D49D46"
Public Const InterfaceId As String = "54388137-8A76-491e-AA3A-853E23AC1217"
Public Const EventsId As String = "EA329A13-16A0-478d-B41F-47583A761FF2"
#End Region
Public Sub New()
MyBase.New()
End Sub
Function AddNumbers(ByVal X As Integer, ByVal Y As Integer)
AddNumbers = X + Y
End Function
End Class

Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
Walkthrough: Creating COM Objects with Visual Basic 2005
Reference
ComClassAttribute Class Members
VBFixedArrayAttribute Class
VBFixedStringAttribute Class
System.Runtime.InteropServices
Concepts
Applying Interop Attributes
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

ComClassAttribute Class Members


The ComClassAttribute Class provides properties that identify the object and indicate if the name shadows another member.
Properties
ClassID Property Contains a class ID used to uniquely identify the class.

EventID Property Contains an event ID used to uniquely identify the event.

InterfaceID Property Contains an interface ID used to uniquely identify the interface.

InterfaceShadows Property Indicates that a generated COM interface name shadows another member of the class or base clas
s.
Constructor
ComClassAttribute Constructor Initializes a new instance of the ComClassAttribute class.
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
Walkthrough: Creating COM Objects with Visual Basic 2005
Reference
VBFixedArrayAttribute Class
VBFixedStringAttribute Class
ComClassAttribute Class
Shadows
System.Runtime.InteropServices
Concepts
Applying Interop Attributes
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

ComClassAttribute Constructor
Initializes a new instance of the ComClassAttribute class.

Public Sub New()


' -or-
Public Sub New( _
ByVal _ClassID As String _
)
' -or-
Public Sub New( _
ByVal _ClassID As String, _
ByVal _InterfaceID As String _
)
' -or-
Public Sub New( _
ByVal _ClassID As String, _
ByVal _InterfaceID As String, _
ByVal _EventId As String _
)

Parameters
_ClassID
Initializes the value of the ClassID property that is used to uniquely identify a class.
_InterfaceID
Initializes the value of the InterfaceID property that is used to uniquely identify an interface.
_EventId
Initializes the value of the EventID property that is used to uniquely identify an event.
Remarks
Use the constructor for the ComClassAttribute class to set the ClassID, InterfaceID, or EventID properties when applying
the ComClassAttribute to a class.
Requirements
Namespace: Microsoft.VisualBasic
Class: ComClassAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
Walkthrough: Creating COM Objects with Visual Basic 2005
Reference
ComClassAttribute Class
System.Runtime.InteropServices
Concepts
Attributes Used in Visual Basic
Object Lifetime: How Objects Are Created and Destroyed
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

ComClassAttribute.ClassID Property
Gets a class ID used to uniquely identify a class.

Public ReadOnly Property ClassID As String

Return Value
Read-only. A string that can be used by the compiler to uniquely identify the class when a COM object is created.
Remarks
The constructor sets this property when the ComClassAttribute is applied to a class.
Requirements
Namespace: Microsoft.VisualBasic
Class: ComClassAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
ComClassAttribute Class
System.Runtime.InteropServices
Concepts
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

ComClassAttribute.EventID Property
Gets an event ID used to uniquely identify an event.

Public ReadOnly Property EventID As String

Return Value
Read only. A string that can be used by the compiler to uniquely identify an event for the class when a COM object is created.
Remarks
The constructor sets this property when the ComClassAttribute is applied to a class.
Requirements
Namespace: Microsoft.VisualBasic
Class: ComClassAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
ComClassAttribute Class
System.Runtime.InteropServices
Concepts
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

ComClassAttribute.InterfaceID Property
Gets an interface ID used to uniquely identify an interface.

Public ReadOnly Property InterfaceID As String

Return Value
Read-only. A string that can be used by the compiler to uniquely identify an interface for the class when a COM object is
created.
Remarks
The constructor sets this property when the ComClassAttribute is applied to a class.
Requirements
Namespace: Microsoft.VisualBasic
Class: ComClassAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
ComClassAttribute Class
System.Runtime.InteropServices
Concepts
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

ComClassAttribute.InterfaceShadows Property
Indicates that the COM interface name shadows another member of the class or base class.

Public Property InterfaceShadows As Boolean

Return Value
A Boolean value that indicates that the COM interface name shadows another member of the class or base class.
Remarks
Shadowing is when a member uses the same name as another member.
Requirements
Namespace: Microsoft.VisualBasic
Class: ComClassAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
ComClassAttribute Class
System.Runtime.InteropServices
Concepts
Shadowing in Visual Basic
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

HideModuleNameAttribute Class
The HideModuleNameAttribute attribute, when applied to a module, allows the module members to be accessed using only
the qualification needed for the module.

' Usage
<HideModuleName> Module moduleName
' Declaration
<System.AttributeUsage(System.AttributeTargets.Class, _
Inherited := False, AllowMultiple := False)> _
Public NotInheritable Class HideModuleNameAttribute
Inherits System.Attribute

Remarks
This attribute is useful for exposing module members without showing the module itself. When using IntelliSense in the Visual
Studio Integrated Development Environment (IDE) for Visual Basic, the module does not show in the statement completion list.
Instead, IntelliSense shows the module members.
Even when the module name is hidden, the module members are still accessible through the module.
If a member name conflicts with another identifier or with a member of another module with the
HideModuleNameAttribute attribute, then the member does not show in IntelliSense at the level of the module.
Example
This example shows how to use the HideModuleNameAttribute attribute to add a Database object to My, which can be
accessed through My.Database.
VB
Namespace My
<HideModuleName()> Module CustomMyDatabase
Public ReadOnly Property Database() As MyDatabase
Get
Return databaseValue
End Get
End Property
Private ReadOnly databaseValue As MyDatabase = New MyDatabase
End Module
End Namespace

Class MyDatabase
' The members of the My.Database object go here.
End Class

The Namespace statement must appear outside of any classes or modules.


Requirements
Namespace: Microsoft.VisualBasic
Class: HideModuleNameAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
VBFixedArrayAttribute Class
VBFixedStringAttribute Class
Concepts
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

VBFixedArrayAttribute Class
Indicates that an array in a structure or non-local variable should be treated as a fixed-length array.

<System.AttributeUsage(System.AttributeTargets.Field, _
Inherited := False, AllowMultiple := False)> _
Public NotInheritable Class VBFixedArrayAttribute
Inherits System.Attribute

Remarks
Visual Basic arrays are of variable length by default. This attribute is useful when using Visual Basic file input and output
functions, such as FileGet and FilePut, and API calls that require fixed-length arrays.
Example
VB
Structure Book
<VBFixedArray(4)> Public Chapter() As Integer
End Structure

Sub WriteData()
Dim FileNum As Integer = FreeFile()
Dim MyBook As Book
ReDim MyBook.Chapter(4)
' Add code to populate the array.
MyBook.Chapter(0) = 1
MyBook.Chapter(1) = 2
MyBook.Chapter(2) = 3
MyBook.Chapter(3) = 4
MyBook.Chapter(4) = 5
' Write the array to a file.
FileOpen(FileNum, "C:\testfile", OpenMode.Binary, _
OpenAccess.Write, OpenShare.Default)
FilePut(FileNum, MyBook) ' Write data.
FileClose(FileNum)
End Sub

Note
The VBFixedArrayAttribute is informational and does not allocate any storage. The purpose of this attribute is to modify ho
w arrays in structures and non-local variables are used by methods or API calls that recognize the VBFixedArrayAttribute.
Keep in mind that this attribute does not convert a variable length array to a fixed array and that you must still allocate array
storage using Dim or ReDim statements.

Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
VBFixedArrayAttribute Class Members
VBFixedStringAttribute Class
ComClassAttribute Class
FileGet Function
FilePut Function
FileOpen Function
MarshalAsAttribute
Other Resources
Attributes in Visual Basic
XML and SOAP Serialization
Visual Basic Language Reference

VBFixedArrayAttribute Class Members


The VBFixedArrayAttribute Class provides properties that identify the size and bounds of the array.
Properties
Bounds Returns the bounds of the array.

Length Returns the size of the array.


Constructor
VBFixedArrayAttribute Constructor Initializes the bounds of a fixed-sized array.
Requirements
Namespace: Microsoft.VisualBasic
Class: VBFixedArrayAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
VBFixedStringAttribute Class
ComClassAttribute Class
MarshalAsAttribute
Concepts
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

VBFixedArrayAttribute Constructor
Initializes the value of the Bounds property.

Public Sub New( _


ByVal UpperBound1 As Integer, _
)
' -or-
Public Sub New( _
ByVal UpperBound1 As Integer, _
ByVal UpperBound2 As Integer, _
)

Parameters
UpperBound1
Initializes the value of upper field, which represents the size of the first dimension of the array.
UpperBound2
Initializes the value of upper field, which represents the size of the second dimension of the array.
Remarks
The constructor runs when the VBFixedArrayAttribute attribute is applied to an array.
Requirements
Namespace: Microsoft.VisualBasic
Class: VBFixedArrayAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
VBFixedStringAttribute Class
ComClassAttribute Class
MarshalAsAttribute Class
Concepts
Attributes Used in Visual Basic
Object Lifetime: How Objects Are Created and Destroyed
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

VBFixedArrayAttribute.Bounds Property
Returns the bounds of the array.

Public ReadOnly Property Bounds() As Integer()

Return Value
Contains an integer array that represents the bounds of the array.
Remarks
The constructor sets this property when the VBFixedArrayAttribute is applied to an array.
Requirements
Namespace: Microsoft.VisualBasic
Class: VBFixedArrayAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
VBFixedStringAttribute Class
ComClassAttribute Class
MarshalAsAttribute
Concepts
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

VBFixedArrayAttribute.Length Property
Returns the size of the array.

Public ReadOnly Property Length As Integer

Return Value
Contains an integer that represents the number of elements in the array.
Remarks
The constructor sets this property when the VBFixedArrayAttribute is applied to an array.
Requirements
Namespace: Microsoft.VisualBasic
Class: VBFixedArrayAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
VBFixedStringAttribute Class
ComClassAttribute Class
MarshalAsAttribute Class
Concepts
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

VBFixedStringAttribute Class
Indicates that a string should be treated as if it were fixed length.

<System.AttributeUsage(System.AttributeTargets.Field, _
Inherited := False, AllowMultiple := False)> _
Public NotInheritable Class VBFixedStringAttribute
Inherits System.Attribute

Remarks
Visual Basic strings are of variable length by default. This attribute is useful when using Visual Basic file input and output
functions such as FileGet and FilePut that require fixed length strings.
Note
The VBFixedStringAttribute attribute specifies the length of a string in bytes, not characters.

Example
VB
Structure Person
Public ID As Integer
Public MonthlySalary As Decimal
Public LastReviewDate As Long
<VBFixedString(15)> Public FirstName As String
<VBFixedString(15)> Public LastName As String
<VBFixedString(15)> Public Title As String
<VBFixedString(150)> Public ReviewComments As String
End Structure

Note
The VBFixedStringAttribute is informational and cannot be used to convert a variable length string to a fixed string. The pu
rpose of this attribute is to modify how strings in structures and non-local variables are used by methods or API calls that rec
ognize the VBFixedStringAttribute, such as the Len and FilePut functions. Keep in mind that this attribute does not change
the actual length of the string itself.

Smart Device Developer Notes


This class is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
VBFixedStringAttribute Class Members
VBFixedArrayAttribute Class
ComClassAttribute Class
Len Function (Visual Basic)
FileGet Function
FilePut Function
FileOpen Function
StringBuilder
MarshalAsAttribute
Concepts
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

VBFixedStringAttribute Class Members


The VBFixedStringAttribute Class provides a property that identifies the string length.
Fields
VBFixedStringAttribute.Length Gets the length of the string.
Constructor
VBFixedStringAttribute Constructor Initializes the value of the SizeConst field.
Smart Device Developer Notes
This class is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
VBFixedArrayAttribute Class
VBFixedStringAttribute Class
ComClassAttribute Class
StringBuilder
MarshalAsAttribute
Concepts
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

VBFixedStringAttribute Constructor
Initializes the value of the SizeConst field.

Public Sub New( _


ByVal Length As Integer _
)

Parameters
Length
The length of the fixed string.
Remarks
The constructor runs when the VBFixedStringAttribute attribute is applied to a string.
Smart Device Developer Notes
This constructor is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Class: VBFixedStringAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
VBFixedStringAttribute Class
StringBuilder Class
MarshalAsAttribute Class
Concepts
Attributes Used in Visual Basic
Object Lifetime: How Objects Are Created and Destroyed
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

VBFixedStringAttribute.Length Property
Gets the length of the string.

Public ReadOnly Property Length As Integer

Return Value
Returns the length of the string.
Remarks
The constructor for this attribute sets this property when the VBFixedStringAttribute is applied to a string.
Smart Device Developer Notes
This property is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Class: VBFixedStringAttribute
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
VBFixedStringAttribute Class
Concepts
Attributes Used in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

Constants and Enumerations (Visual Basic)


Visual Basic supplies a number of predefined constants and enumerations for developers. Constants store values that remain
constant throughout the execution of an application. Enumerations provide a convenient way to work with sets of related
constants, and to associate constant values with names.
In This Section
AppWinStyle Enumeration
Indicates the window style to use for the invoked program when calling the Shell function.
AudioPlayMode Enumeration
Indicates how to play sounds when calling audio methods.
BuiltInRole Enumeration
Indicates the type of role to check when calling the My.User.IsInRole Method.
CallType Enumeration
Indicates the type of procedure being invoked when calling the CallByName function.
CompareMethod Enumeration
Indicates how to compare strings when calling comparison functions.
Conditional Compilation Constants
Lists predefined constants available for conditional compilation.
DateFormat Enumeration
Indicates how to display dates when calling the FormatDateTime function.
DateInterval Enumeration
Indicates how to determine and format date intervals when calling date-related functions.
DeleteDirectoryOption Enumeration
Specifies what should be done when a directory that is to be deleted contains files or directories.
DueDate Enumeration
Indicates when payments are due when calling financial methods.
FieldType Enumeration
Indicates whether text fields are delimited or fixed-width.
FileAttribute Enumeration
Indicates the file attributes to use when calling file-access functions.
FirstDayOfWeek Enumeration
Indicates the first day of the week to use when calling date-related functions.
FirstWeekOfYear Enumeration
Indicates the first week of the year to use when calling date-related functions.
MsgBoxResult Enumeration
Indicates which button was pressed on a message box, returned by the MsgBox function.
MsgBoxStyle Enumeration
Indicates which buttons to display when calling the MsgBox function.
OpenAccess Enumeration
Indicates how to open a file when calling file-access functions.
OpenMode Enumeration
Indicates how to open a file when calling file-access functions.
OpenShare Enumeration
Indicates how to open a file when calling file-access functions.
Print and Display Constants
Lists predefined constants available when calling print and display functions.
RecycleOption Enumeration
Specifies whether a file should be deleted permanently or placed in the Recycle Bin.
SearchOption Enumeration
Specifies whether to search all or only top-level directories.
TriState Enumeration
Indicates a Boolean value or whether the default should be used when calling number-formatting functions.
UICancelOption Enumeration
Specifies what should be done if the user clicks Cancel during an operation.
UIOption Enumeration
Specifies whether or not to show a progress dialog when copying, deleting, or moving files or directories.
VariantType Enumeration
Indicates the type of a variant object, returned by the VarType function.
VbStrConv Enumeration
Indicates which type of conversion to perform when calling the StrConv function.
Related Sections
Visual Basic Reference
Visual Basic
Constants in Visual Basic
Enumerations Overview
Visual Basic Language Reference

AppWinStyle Enumeration
Indicates the window style to use for the invoked program when calling the Shell function.
Remarks
When you issue Shell commands, you can use the following enumeration members in your code in place of the actual values.
The Style argument takes the AppWinStyle enumeration members.
Members
Member Constant Description
Hide vbHide Window is hidden and focus is passed to the hidden window.

NormalFocus vbNormalFocus Window has focus and is restored to its original size and position.

MinimizedFocus vbMinimizedFocus Window is displayed as an icon with focus.

MaximizedFocu vbMaximizedFocu Window is maximized with focus.


s s

NormalNoFocus vbNormalNoFocus Window is restored to its most recent size and position. The currently active window r
emains active.

MinimizedNoFo vbMinimizedNoFo Window is displayed as an icon. The currently active window remains active.
cus cus
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
Shell Function
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Visual Basic Language Reference

AudioPlayMode Enumeration
Indicates how to play sounds when calling audio methods.
Remarks
You can use the AudioPlayMode enumeration members to control how the My.Computer.Audio.Play Method plays sounds.
Members
Member Description
WaitToCo Causes the My.Computer.Audio.Play method to play the sound, and waits until it completes before calling code
mplete continues.

Backgroun Causes the My.Computer.Audio.Play method to play the sound in the background. The calling code continues t
d o execute.

Backgroun Causes the My.Computer.Audio.Play method to play the sound in the background until the
dLoop My.Computer.Audio.Stop Method is called. The calling code continues to execute.
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer.Audio.Play Method
AudioPlayMode
Concepts
Intrinsic Constants and Enumerations
Visual Basic Language Reference

BuiltInRole Enumeration
Indicates the type of role to check when calling the My.User.IsInRole Method.
Remarks
This enumeration provides functionality similar to the WindowsBuiltInRole enumeration.
These roles represent the local Windows groups common to most installations of Windows NT, Windows 2000, and Windows
XP.
Members
Member Description
AccountOp Account operators manage the user accounts on a computer or domain.
erator

Administrat Administrators have complete and unrestricted access to the computer or domain.
or

BackupOpe Backup operators can override security restrictions for the sole purpose of backing up or restoring files.
rator

Guest Guests are more restricted than users.

PowerUser Power users possess most administrative permissions with some restrictions. Thus, power users can run legacy a
pplications, in addition to certified applications.

PrintOperat Print operators can take control of a printer.


or

Replicator Replicators support file replication in a domain.

SystemOpe System operators manage a particular computer.


rator

User Users are prevented from making accidental or intentional system-wide changes. Thus, users can run certified ap
plications, but not most legacy applications.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.User.IsInRole Method
Microsoft.VisualBasic.ApplicationServices.BuiltInRole
Concepts
Intrinsic Constants and Enumerations
Visual Basic Language Reference

CallType Enumeration
Indicates the type of procedure being invoked when calling the CallByName function.
Remarks
When you call the CallByName function, you can use the following CallType enumeration members in your code in place of
the actual values. The UseCallType argument takes the CallType enumeration members.
Members
Member Constant Description
Method vbMethod A method is being invoked.

Get vbGet A property value is being retrieved.

Set vbSet A property value is being determined.

Let vbLet An Object property value is being determined.


Smart Device Developer Notes
This enumeration is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
CallByName Function
CallType Constants for Visual Basic 6.0 Users
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Visual Basic Language Reference

CompareMethod Enumeration
Indicates how to compare strings when calling comparison functions.
Remarks
When you call comparison functions, you can use the CompareMethod enumeration in your code in place of the actual
values. The Compare argument takes the CompareMethod enumeration members.
Members
Member Constant Description
Binary vbBinaryCompare Performs a binary comparison.

Text vbTextCompare Performs a textual comparison.


Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
Filter Function (Visual Basic)
InStr Function (Visual Basic)
InStrRev Function (Visual Basic)
Replace Function (Visual Basic)
Split Function (Visual Basic)
StrComp Function (Visual Basic)
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Visual Basic Language Reference

Conditional Compilation Constants


Conditional compilation allows you to easily control at compile time what code to include in your program.
The following table lists the predefined constants available for conditional compilation.
Co Description
ns
ta
nt
C A string that corresponds to the current setting of the Active Solution Configuration box in the Configuration Manage
O r.
N
FI
G

D A Boolean value that can be set in the Project Properties dialog box. By default, the Debug configuration for a project def
EB ines DEBUG. When DEBUG is defined, Debug class methods generate output to the Output window. When it is not define
U d, Debug class methods are not compiled and no Debug output is generated.
G

TA A string representing the output type for the project or the setting of the command-line /target option. The possible value
R s of TARGET are: "winexe" for a Windows application, "exe" for a console application, "library" for a class library, and "modu
GE le" for a module. The /target option can be set in the Visual Studio integrated development environment. For more inform
T ation, see /target.

TR A Boolean value that can be set in the Project Properties dialog box. By default, all configurations for a project define TR
A ACE. When TRACE is defined, Trace class methods generate output to the Output window. When it is not defined, Trace cl
CE ass methods are not compiled and no Trace output is generated.

V A number representing the Visual Basic version, in major.minor format. The version number for Visual Basic 2005 is 8.0.
BC
_V
ER

_ A string representing the type of project being built. This controls which My objects are available in code. For more inform
M ation, see How My Depends on Project Type.
YT
YP
E

You can use these constants only for conditional compilation; they cannot be used in executable code.
Example
This example uses the TARGET conditional compilation constant to determine whether to compile certain statements.
VB
#If TARGET = "winexe" Then
' Insert code to be compiled for a Windows application.
#ElseIf TARGET = "exe" Then
' Insert code to be compiled for a console application.
#End If

Requirements
The Visual Studio integrated development environment defines the CONFIG, DEBUG, TRACE, and _MYTYPE conditional
compilation constants.
The Visual Basic compiler defines the TARGET and VBC_VER conditional compilation constants. The TARGET, VBC_VER, and
_MYTYPE constants are not available in compiler versions before Visual Basic 2005.
See Also
Tasks
How to: Declare Conditional Compilation Constants
Reference
#If...Then...#Else Directives
#Const Directive
/target (Visual Basic)
Concepts
Conditional Compilation Overview
How My Depends on Project Type
Visual Basic Language Reference

DateFormat Enumeration
Indicates how to display dates when calling the FormatDateTime function.
Remarks
When you call the FormatDateTime function, you can use the following enumeration members in your code in place of the
actual values.
Note
You can access your computer's regional settings by double-clicking the Regional Options icon, found in Control Panel.

Members
Mem Consta Description
ber nt
Gene vbGen For real numbers, displays a date and time. If the number has no fractional part, displays only a date. If the num
ralDa eralDa ber has no integer part, displays time only. Date and time display is determined by your computer's regional se
te te ttings.

Long vbLon Displays a date using the long-date format specified in your computer's regional settings.
Date gDate

Short vbShor Displays a date using the short-date format specified in your computer's regional settings.
Date tDate

Long vbLon Displays a time using the long-time format specified in your computer's regional settings.
Time gTime

Short vbShor Displays a time using the short-time format specified in your computer's regional settings.
Time tTime
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
FormatDateTime Function (Visual Basic)
Concepts
Custom DateTime Format Strings
When to Use an Enumeration
Visual Basic Language Reference

DateInterval Enumeration
Indicates how to determine and format date intervals when calling date-related functions.
Remarks
When you call date-related functions, you can use enumeration members in your code in place of the actual values.
The DateInterval enumeration defines constants used with date-related functions to identify how date intervals are
determined and formatted. The following table lists the DateInterval enumeration members.
Members
Member Description
Day Day of month (1 through 31)

DayOfYear Day of year (1 through 366)

Hour Hour (1 through 24)

Minute Minute (1 through 60)

Month Month (1 through 12)

Quarter Quarter of year (1 through 4)

Second Second (1 through 60)

Weekday Day of week (1 through 7)

WeekOfYear Week of year (1 through 53)

Year Year
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
DateFormat Enumeration
DueDate Enumeration
DatePart Function (Visual Basic)
DateAdd Function (Visual Basic)
DateDiff Function (Visual Basic)
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Visual Basic Language Reference

DeleteDirectoryOption Enumeration
Specifies what should be done when a directory that is to be deleted contains files or directories.
Remarks
This enumeration is used with the My.Computer.FileSystem.DeleteDirectory Method.
Members
Member Description
DeleteAllContents Delete the contents of the directory along with the directory. Default.

ThrowIfDirectoryNon Throw an IOException if the directory is not empty. The Data property of the exception lists the file(s)
Empty that could not be deleted.
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: DeleteDirectoryOption
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Delete a Directory in Visual Basic
Reference
My.Computer.FileSystem.DeleteDirectory Method
Microsoft.VisualBasic.FileIO.DeleteDirectoryOption
Visual Basic Language Reference

DueDate Enumeration
Indicates when payments are due when calling financial methods.
Remarks
When you call financial functions, you can use enumeration members in your code in place of the actual values.
The DueDate enumeration defines constants used to identify when payments are due.
Members
Member Description
BegOfPeriod Falls at the beginning of the date interval

EndOfPeriod Falls at the end of the date interval


Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
DateInterval Enumeration
Financial Summary
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Visual Basic Language Reference

FieldType Enumeration
Indicates whether text fields are delimited or fixed width.
Remarks
This enumeration is used with the TextFieldParser Object.
Members
Member Name Description
Delimited Indicates that the fields are delimited.

FixedWidth Indicates that the fields are fixed width.


Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
Reference
TextFieldParser.TextFieldType Property
TextFieldParser
OpenTextFieldParser
Visual Basic Language Reference

FileAttribute Enumeration
Indicates the file attributes to use when calling file-access functions.
Remarks
When you call the Dir, GetAttr, or SetAttr functions, you can use the FileAttribute enumeration in your code in place of the
actual values.
The Attributes argument takes the FileAttribute enumeration members.
When performing file I/O operations, the My.Computer.FileSystem object provides greater performance and ease of use
than legacy file I/O methods. For more information, see My.Computer.FileSystem Object.
Members
Member Constant Description
Normal vbNormal Normal (default for Dir and SetAttr). No special characteristics apply to this file.

ReadOnly vbReadOnly Read only.

Hidden vbHidden Hidden.

System vbSystem System file.

Volume vbVolume Volume label. This attribute is not valid when used with SetAttr.

Directory vbDirectory Directory or folder.

Archive vbArchive File has changed since last backup.


Smart Device Developer Notes
This enumeration is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
Dir Function
GetAttr Function
SetAttr Function
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Visual Basic Language Reference

FirstDayOfWeek Enumeration
Indicates the first day of the week to use when calling date-related functions.
Remarks
When you call date-related functions, you can use the following enumeration members in your code in place of the actual
values.
Some date-related functions take a DayOfWeek argument, a WeekOfYear argument, or both. The FirstDayOfWeek
enumeration specifies the valid values for the DayOfWeek arguments, as well as the possible return values from the functions.
The DayOfWeek argument takes the FirstDayOfWeek enumeration members.
Date-related functions also return FirstDayOfWeek values (except System).
Members
Member Constant Description
System vbUseSystemDayOfWeek The first day of the week as specified in your system settings

Sunday vbSunday Sunday (default)

Monday vbMonday Monday

Tuesday vbTuesday Tuesday

Wednesday vbWednesday Wednesday

Thursday vbThursday Thursday

Friday vbFriday Friday

Saturday vbSaturday Saturday


Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
FirstWeekOfYear Enumeration
DateFormat Enumeration
DateDiff Function (Visual Basic)
DatePart Function (Visual Basic)
Format Function
Weekday Function (Visual Basic)
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Visual Basic Language Reference

FirstWeekOfYear Enumeration
Indicates the first week of the year to use when calling date-related functions.
Remarks
When you call date-related functions, you can use the following enumeration members in your code in place of the actual
values.
Some date-related functions take a DayOfWeek argument, a WeekOfYear argument, or both. The FirstWeekOfYear
enumeration specifies the valid values for the WeekOfYear arguments, as well as the possible return values from the functions.
The WeekOfYear argument takes the FirstWeekOfYear enumeration members.
Members
Member Constant Description
System vbUseSystem The day of the week specified in your system settings as the first day of the week

Jan1 vbFirstJan1 The week in which January 1 occurs (default)

FirstFourDays vbFirstFourDays The first week that has at least four days in the new year

FirstFullWeek vbFirstFullWeek The first full week of the year


Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
FirstDayOfWeek Enumeration
DateFormat Enumeration
DateDiff Function (Visual Basic)
DatePart Function (Visual Basic)
Format Function
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Visual Basic Language Reference

MsgBoxResult Enumeration
Indicates which button was pressed on a message box, returned by the MsgBox function.
Remarks
When you call the MsgBox function, you can use the MsgBoxResult enumeration in your code in place of the actual values.
The MsgBox function returns a MsgBoxResult enumeration value.
Members
Member Constant Description
OK vbOK OK button was pressed.

Cancel vbCancel Cancel button was pressed.

Abort vbAbort Abort button was pressed.

Retry vbRetry Retry button was pressed.

Ignore vbIgnore Ignore button was pressed.

Yes vbYes Yes button was pressed.

No vbNo No button was pressed.


Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
MsgBoxStyle Enumeration
MsgBox Function (Visual Basic)
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Visual Basic Language Reference

MsgBoxStyle Enumeration
Indicates which buttons to display when calling the MsgBox function.
Remarks
When you call the MsgBox function, you can use the MsgBoxStyle enumeration in your code in place of the actual values.
The Buttons argument takes the MsgBoxStyle enumeration members.
Members
Member Constant Description
OKOnly vbOKOnly OK button only (default).

OKCancel vbOKCancel OK and Cancel buttons.

AbortRetryIgnore vbAbortRetryIgnore Abort, Retry, and Ignore buttons.

YesNoCancel vbYesNoCancel Yes, No, and Cancel buttons.

YesNo vbYesNo Yes and No buttons.

RetryCancel vbRetryCancel Retry and Cancel buttons.

Critical vbCritical Critical message.

Question vbQuestion Warning query.

Exclamation vbExclamation Warning message.

Information vbInformation Information message.

DefaultButton1 vbDefaultButton1 First button is default.

DefaultButton2 vbDefaultButton2 Second button is default.

DefaultButton3 vbDefaultButton3 Third button is default.

ApplicationModal vbApplicationModal Application modal message box.

SystemModal vbSystemModal System modal message box.

MsgBoxSetForeground vbMsgBoxSetForeground Foreground message box window.

MsgBoxRight vbMsgBoxRight Right-aligned text.

MsgBoxRtlReading vbMsgBoxRtlReading Right-to-left reading text (Hebrew and Arabic systems).

MsgBoxHelp vbMsgBoxHelp Help text.


Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
MsgBoxResult Enumeration
MsgBox Function (Visual Basic)
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Visual Basic Language Reference

OpenAccess Enumeration
Indicates how to open a file when calling file-access functions.
Remarks
When you call file access-related functions, you can use enumeration members in your code in place of the actual values.
The OpenAccess enumeration defines constants used to identify whether a file can be read from (Read), written to (Write), or
both (ReadWrite). A file opened for Read access cannot be modified, only read from. The following table lists the
OpenAccess enumeration members.
When performing file I/O operations, the My.Computer.FileSystem object provides greater performance and ease of use
than legacy file I/O methods. For more information, see My.Computer.FileSystem Object.
Members
Member Description
Default Read and write access permitted. This is the default.

Read Read access permitted.

ReadWrite Read and write access permitted.

Write Write access permitted.


Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
OpenMode Enumeration
OpenShare Enumeration
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Visual Basic Language Reference

OpenMode Enumeration
Indicates how to open a file when calling file-access functions.
Remarks
When you call file access–related functions, you can use enumeration members in your code in place of the actual values.
The OpenMode enumeration defines constants used to set file access modes. The following table lists the OpenMode
enumeration members.
Input, Output, and Append are used when sequentially accessing files, such as text files, while Binary is used for binary file
access and Random for random file access.
When sequentially accessing a file, you cannot change its data. You can read the data, append to it, or overwrite it with new
data. If you open it for input, the contents of the file will be overwritten, even if you do not directly write to the file.
When performing file I/O operations, the My.Computer.FileSystem object provides greater performance and ease of use
than legacy file I/O methods. For more information, see My.Computer.FileSystem Object.
Members
Member Description
Append File opened to append to it. Default.

Binary File opened for binary access.

Input File opened for read access.

Output File opened for write access.

Random File opened for random access.


Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
OpenShare Enumeration
OpenAccess Enumeration
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Visual Basic Language Reference

OpenShare Enumeration
Indicates how to open a file when calling file-access functions.
Remarks
When you call file access–related functions, you can use enumeration members in your code in place of the actual values.
The OpenShare enumeration defines constants that specify whether or not other processes can access the file while your
application has it open. The following table lists the OpenShare enumeration members.
When performing file I/O operations, the My.Computer.FileSystem object provides greater performance and ease of use
than legacy file I/O methods. For more information, see My.Computer.FileSystem Object.
Members
Member Description
Default LockReadWrite. This is the default.

LockRead Other processes cannot read the file.

LockReadWrite Other processes cannot read or write to the file.

LockWrite Other processes cannot write to the file.

Shared Any process can read or write to the file.


Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
OpenAccess Enumeration
OpenMode Enumeration
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Visual Basic Language Reference

Print and Display Constants


When you call print and display functions, you can use the following constants in your code in place of the actual values.
ControlChars Module Members
Member Constant Equivalent Description
CrLf vbCrLf Chr(13) + Chr(10) Carriage-return/linefeed character combination.

Cr vbCr Chr(13) Carriage-return character.

Lf vbLf Chr(10) Linefeed character.

NewLine vbNewLine Chr(13) + Chr(10) Newline character.

NullChar vbNullChar Chr(0) Character having value 0.

n/a vbNullStrin String having valu Not the same as a zero-length string (""); used for calling external procedures.
g e0

n/a vbObjectErr -2147221504 Error number. User-defined error numbers should be greater than this value. For
or example:
Err.Raise(Number) = vbObjectError + 1000

Tab vbTab Chr(9) Tab character.

Back vbBack Chr(8) Backspace character.

FormFeed vbFormFeed Chr(12) Not useful in Microsoft Windows.

VerticalTa vbVerticalT Chr(11) Not useful in Microsoft Windows.


b ab

Quote n/a Chr(34) Quotation mark character (" or ') used to enclose values.
Requirements
Namespace: Microsoft.VisualBasic
Module: Constants
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Print, PrintLine Functions
Write, WriteLine Functions
Concepts
Intrinsic Constants and Enumerations
Constants Overview
Constants Declared by Visual Basic
Visual Basic Language Reference

RecycleOption Enumeration
Specifies whether a file should be deleted permanently or placed in the Recycle Bin.
Remarks
This enumeration is used with the My.Computer.FileSystem.DeleteDirectory Method and the
My.Computer.FileSystem.DeleteFile Method.
To protect users against accidental deletion of important files, the Recycle Bin collects deleted files and provides a method for
restoring those files. You must explicitly delete the files from the Recycle Bin to make the deletion permanent. Until the files
are deleted from the Recycle Bin, the disk space occupied by those files is unavailable for other uses.
Sometimes it is beneficial to bypass the Recycle Bin, especially if you are deleting a large number of files (or a smaller number
of very large files) that you are sure are no longer needed, and you want to reclaim the disk space.
Members
Member Description
DeletePermanently Delete the file or directory permanently. Default.

SendToRecycleBin Send the file or directory to the Recycle Bin.


Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: RecycleOption
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Delete a File in Visual Basic
How to: Delete a Directory in Visual Basic
Reference
My.Computer.FileSystem.DeleteDirectory Method
My.Computer.FileSystem.DeleteFile Method
Microsoft.VisualBasic.FileIO.RecycleOption
Visual Basic Language Reference

SearchOption Enumeration
Specifies whether to search all or only top-level directories.
Remarks
This enumeration is used with the My.Computer.FileSystem.GetFiles Method, My.Computer.FileSystem.GetDirectories Method,
and My.Computer.FileSystem.FindInFiles Method.
Members
Member Description
SearchAllSubDirectories Search the specified directory and all subdirectories within it. Default.

SearchTopLevelOnly Search only the specified directory and exclude subdirectories.


Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: SearchOption
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer.FileSystem.FindInFiles Method
My.Computer.FileSystem.GetDirectories Method
My.Computer.FileSystem.GetFiles Method
Microsoft.VisualBasic.FileIO.SearchOption
Visual Basic Language Reference

TriState Enumeration
Indicates a Boolean value or whether the default should be used when calling number-formatting functions.
Remarks
When you call number-formatting functions, you can use the following enumeration members in your code in place of the
actual values.
Members
Member Description
True True. The numeric value of this member is -1.

False False. The numeric value of this member is 0.

UseDefault Default setting. The numeric value of this member is -2.


Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
FormatNumber Function (Visual Basic)
FormatCurrency Function (Visual Basic)
FormatPercent Function (Visual Basic)
Concepts
When to Use an Enumeration
Visual Basic Language Reference

UICancelOption Enumeration
Specifies whether an exception is thrown if the user clicks Cancel during an operation.
Remarks
This enumeration determines whether an IOException is thrown when a user clicks Cancel during an operation. In either case,
the operation is canceled.
Members
Member Name Description
DoNothing Do nothing when the user clicks Cancel.

ThrowException Throw an exception when the user clicks Cancel.


Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: UICancelOption
Platforms: Windows 95, Windows 98, Windows 98 Second Edition, Windows Millennium Edition, Windows NT 4.0, Windows
NT Workstation 4.0, Windows NT Server 4.0, Windows 2000, Windows 2000 Server, Windows 2000 Advanced Server,
Windows XP Home Edition, Windows XP Professional, Windows Server 2003, .NET Compact Framework - Mobile Phone, .NET
Compact Framework, Common Language Infrastructure (CLI) Standard
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer.FileSystem.CopyDirectory Method
My.Computer.FileSystem.CopyFile Method
My.Computer.FileSystem.DeleteDirectory Method
My.Computer.FileSystem.DeleteFile Method
My.Computer.Network.DownloadFile Method
My.Computer.FileSystem.MoveDirectory Method
My.Computer.FileSystem.MoveFile Method
My.Computer.Network.UploadFile Method
UICancelOption
Visual Basic Language Reference

UIOption Enumeration
Specifies which dialog boxes to show when copying, deleting, or moving files or directories.
Remarks
This enumeration is used with My.Computer.FileSystem.CopyDirectory Method, My.Computer.FileSystem.CopyFile Method,
My.Computer.FileSystem.DeleteDirectory Method, My.Computer.FileSystem.DeleteFile Method,
My.Computer.FileSystem.MoveDirectory Method, and My.Computer.FileSystem.MoveFile Method.
Members
Member Description
OnlyErrorDialogs Only show error dialog boxes and hide progress dialog boxes. Default.

AllDialogs Show progress dialog box and any error dialog boxes.
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: UIOption
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer.FileSystem.CopyDirectory Method
My.Computer.FileSystem.CopyFile Method
My.Computer.FileSystem.DeleteDirectory Method
My.Computer.FileSystem.DeleteFile Method
My.Computer.FileSystem.MoveDirectory Method
My.Computer.FileSystem.MoveFile Method
Microsoft.VisualBasic.FileIO.UIOption
Visual Basic Language Reference

VariantType Enumeration
Indicates the type of a variant object, returned by the VarType function.
Remarks
When you call the VarType function, you can use enumeration members in your code in place of the actual values.
The VariantType enumeration defines constants used to identify possible Variant types. The following table lists the
VariantType enumeration members.
Members
Memb Constan Description
er t
Array vbArray Array.

Boolea vbBool Boolean. (True or False.)


n ean

Byte vbByte Byte. (0 through 255.)

Char vbChar Char. (0 through 65535.)

Curren vbCurre Currency.


cy ncy

DataO DataObject.
bject

Date vbDate Date. (0:00:00 on January 1, 0001 through 11:59:59 PM on December 31, 9999.)

Decim vbDeci Decimal. (0 through +/-79,228,162,514,264,337,593,543,950,335 with no decimal point; 0 through +/-7.92
al mal 28162514264337593543950335 with 28 places to the right of the decimal; smallest non-zero number is +/
-0.0000000000000000000000000001.)

Doubl vbDoub Double. (-1.79769313486231E+308 through -4.94065645841247E-324 for negative values; 4.940656458
e le 41247E-324 through 1.79769313486231E+308 for positive values.)

Empty vbEmpt Null reference.


y

Error System.Exception

Intege vbInteg Integer. (-2,147,483,648 through 2,147,483,647.)


r er

Long vbLong Long. (-9,223,372,036,854,775,808 through 9,223,372,036,854,775,807.)

Null vbNull Null object.

Object vbObje Any type can be stored in a variable of type Object.


ct

Short Short. (-32,768 through 32,767.)


Single vbSingl Single. (-3.402823E+38 through -1.401298E-45 for negative values; 1.401298E-45 through 3.402823E+38
e for positive values.)

String vbStrin String. (0 to approximately 2 billion Unicode characters.)


g

UserD vbUser User-defined type. Each member of the structure has a range determined by its data type and independent o
efined Defined f the ranges of the other members.
Type Type

Varian vbVaria Variant.


t nt
Smart Device Developer Notes
This enumeration is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
VarType Function (Visual Basic)
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Visual Basic Language Reference

VbStrConv Enumeration
Indicates which type of conversion to perform when calling the StrConv function.
Remarks
When you call the StrConv function, you can use the following enumeration members in your code in place of the actual
values. The Conversion argument takes the VbStrConv enumeration members.
Members
Member Constant Description
UpperCase vbUpperCase Converts the string to uppercase characters.

LowerCase vbLowerCase Converts the string to lowercase characters.

ProperCase vbProperCase Converts the first letter of every word in the string to uppercase.

Wide vbWide Converts narrow (single-byte) characters in the string to wide (double-byte) characters. A
pplies to Asian locales.

Narrow vbNarrow Converts wide (double-byte) characters in the string to narrow (single-byte) characters. A
pplies to Asian locales.

None Performs no conversion.

Katakana vbKatakana Converts Hiragana characters in the string to Katakana characters. Applies to Japanese loc
ale only.

Hiragana vbHiragana Converts Katakana characters in the string to Hiragana characters. Applies to Japanese loc
ale only.

SimplifiedChin vbSimplifiedChi Converts the string to Simplified Chinese characters.


ese nese

TraditionalChi vbTraditionalChi Converts the string to Traditional Chinese characters.


nese nese

LinguisticCasin vbLinguisticCasi Converts the string from file system rules for casing to linguistic rules.
g ng
Smart Device Developer Notes
This enumeration is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Refer to an Enumeration Member
Reference
StrConv Function
Concepts
Intrinsic Constants and Enumerations
When to Use an Enumeration
Other Resources
Introduction to Strings in Visual Basic
Visual Basic Language Reference

Data Type Summary (Visual Basic)


The following table shows the Visual Basic data types, their supporting common language runtime types, their nominal storage
allocation, and their value ranges.
Visual Basic ty Common langua Nominal sto Value range
pe ge runtime type rage allocati
structure on
Boolean Boolean Depends on i True or False
mplementing
platform

Byte Byte 1 byte 0 through 255 (unsigned)

Char (single cha Char 2 bytes 0 through 65535 (unsigned)


racter)

Date DateTime 8 bytes 0:00:00 (midnight) on January 1, 0001 through 11:59:59 PM on December 3
1, 9999

Decimal Decimal 16 bytes 0 through +/-79,228,162,514,264,337,593,543,950,335 (+/-7.9...E+28) † wit


h no decimal point; 0 through +/-7.9228162514264337593543950335 wit
h 28 places to the right of the decimal;
smallest nonzero number is +/-0.0000000000000000000000000001 (+/-1
E-28) †

Double (double Double 8 bytes -1.79769313486231570E+308 through -4.94065645841246544E-324 † for


-precision floati negative values;
ng-point)
4.94065645841246544E-324 through 1.79769313486231570E+308 † for p
ositive values

Integer Int32 4 bytes -2,147,483,648 through 2,147,483,647 (signed)

Long (long inte Int64 8 bytes -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807 (9.2...E+18


ger) †) (signed)

Object Object (class) 4 bytes on 32 Any type can be stored in a variable of type Object
-bit platform
8 bytes on 64
-bit platform

SByte SByte 1 byte -128 through 127 (signed)

Short (short int Int16 2 bytes -32,768 through 32,767 (signed)


eger)

Single (single-p Single 4 bytes -3.4028235E+38 through -1.401298E-45 † for negative values;
recision floating
-point) 1.401298E-45 through 3.4028235E+38 † for positive values

String (variable String (class) Depends on i 0 to approximately 2 billion Unicode characters


-length) mplementing
platform
UInteger UInt32 4 bytes 0 through 4,294,967,295 (unsigned)

ULong UInt64 8 bytes 0 through 18,446,744,073,709,551,615 (1.8...E+19 †) (unsigned)

User-Defined (s (inherits from Depends on i Each member of the structure has a range determined by its data type and i
tructure) ValueType) mplementing ndependent of the ranges of the other members
platform

UShort UInt16 2 bytes 0 through 65,535 (unsigned)

† In scientific notation, "E" refers to a power of 10. So 3.56E+2 signifies 3.56 x 10 2 or 356, and 3.56E-2 signifies 3.56 / 10 2 or
0.0356.
Note
For strings containing text, use the StrConv function to convert from one text format to another.

Memory Consumption
When you declare an elementary data type, it is not safe to assume that its memory consumption is the same as its nominal
storage allocation. This is due to the following considerations:
Storage Assignment. The common language runtime can assign storage based on the current characteristics of the
platform on which your application is executing. If memory is nearly full, it might pack your declared elements as closely
together as possible. In other cases it might align their memory addresses to natural hardware boundaries to optimize
performance.
Platform Width. Storage assignment on a 64-bit platform is different from assignment on a 32-bit platform.
Composite Data Types
The same considerations apply to each member of a composite data type, such as a structure or an array. You cannot rely on
simply adding together the nominal storage allocations of the type's members. Furthermore, there are other considerations,
such as the following:
Overhead. Some composite types have additional memory requirements. For example, an array uses extra memory for
the array itself and also for each dimension. On a 32-bit platform, this overhead is currently 12 bytes plus 8 bytes for
each dimension. On a 64-bit platform this requirement is doubled.
Storage Layout. You cannot safely assume that the order of storage in memory is the same as your order of declaration.
You cannot even make assumptions about byte alignment, such as a 2-byte or 4-byte boundary. If you are defining a
class or structure and you need to control the storage layout of its members, you can apply the StructLayoutAttribute
attribute to the class or structure.
Object Overhead
An Object referring to any elementary or composite data type uses 4 bytes in addition to the data contained in the data type.
See Also
Reference
Type Conversion Functions
Conversion Summary
StrConv Function
StructLayoutAttribute Class
Concepts
Type Characters
Efficient Use of Data Types
Visual Basic Language Reference

Boolean Data Type (Visual Basic)


Holds values that can be only True or False. The keywords True and False correspond to the two states of Boolean variables.
Remarks
Use the Boolean data type to contain two-state values such as true/false, yes/no, or on/off.
The default value of Boolean is False.
Type Conversions
When Visual Basic converts numeric data type values to Boolean, 0 becomes False and all other values become True. When
Visual Basic converts Boolean values to numeric types, False becomes 0 and True becomes -1.
When you convert between Boolean values and numeric data types, keep in mind that the .NET Framework conversion
methods do not always produce the same results as the Visual Basic conversion keywords. This is because the Visual Basic
conversion retains behavior compatible with previous versions. For more information, see Troubleshooting Data Types.
Programming Tips
Negative Numbers. Boolean is not a numeric type and cannot represent a negative value. In any case, you should not
use Boolean to hold numeric values.
Type Characters. Boolean has no literal type character or identifier type character.
Framework Type. The corresponding type in the .NET Framework is the System.Boolean structure.
Example
In the following example, runningVB is a Boolean variable, which stores a simple yes/no setting.

Dim runningVB As Boolean


' Check to see if program is running on Visual Basic engine.
If scriptEngine = "VB" Then
runningVB = True
End If

See Also
Tasks
Troubleshooting Data Types
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Conversion Summary
CType Function
System.Boolean
Concepts
Efficient Use of Data Types
Visual Basic Language Reference

Byte Data Type (Visual Basic)


Holds unsigned 8-bit (1-byte) integers ranging in value from 0 through 255.
Remarks
Use the Byte data type to contain binary data.
The default value of Byte is 0.
Programming Tips
Negative Numbers. Because Byte is an unsigned type, it cannot represent a negative number. If you use the unary
minus (-) operator on an expression that evaluates to type Byte, Visual Basic converts the expression to Short first.
Format Conversions. When Visual Basic reads or writes files, or when it calls DLLs, methods, and properties, it can
automatically convert between data formats. Binary data stored in Byte variables and arrays is preserved during such
format conversions. You should not use a String variable for binary data, because its contents can be corrupted during
conversion between ANSI and Unicode formats.
Widening. The Byte data type widens to Short, UShort, Integer, UInteger, Long, ULong, Decimal, Single, or
Double. This means you can convert Byte to any of these types without encountering a System.OverflowException error.
Type Characters. Byte has no literal type character or identifier type character.
Framework Type. The corresponding type in the .NET Framework is the System.Byte structure.
See Also
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Conversion Summary
System.Byte
Concepts
Efficient Use of Data Types
Visual Basic Language Reference

Char Data Type (Visual Basic)


Holds unsigned 16-bit (2-byte) code points ranging in value from 0 through 65535. Each code point, or character code,
represents a single Unicode character.
Remarks
Use the Char data type when you need to hold only a single character and do not need the overhead of String. In some cases
you can use Char(), an array of Char elements, to hold multiple characters.
The default value of Char is the character with a code point of 0.
Unicode Characters
The first 128 code points (0–127) of Unicode correspond to the letters and symbols on a standard U.S. keyboard. These first
128 code points are the same as those the ASCII character set defines. The second 128 code points (128–255) represent special
characters, such as Latin-based alphabet letters, accents, currency symbols, and fractions. Unicode uses the remaining code
points (256-65535) for a wide variety of symbols, including worldwide textual characters, diacritics, and mathematical and
technical symbols.
You can use methods like IsDigit and IsPunctuation on a Char variable to determine its Unicode classification.
Type Conversions
Visual Basic does not convert directly between Char and the numeric types. You can use the Asc, AscW Functions to convert a
Char value to an Integer representing its code point. You can use the Chr, ChrW Functions to convert an Integer value to a
Char having that code point.
If the type checking switch (Option Strict Statement) is on, you must append the literal type character to a single-character
string literal to identify it as the Char data type. The following example illustrates this.

Option Strict On
Dim charVar As Char
' The following statement attempts to convert a String literal to Char.
' Because Option Strict is On, it generates a compiler error.
charVar = "Z"
' The following statement succeeds because it specifies a Char literal.
charVar = "Z"C

Programming Tips
Negative Numbers. Char is an unsigned type and cannot represent a negative value. In any case, you should not use
Char to hold numeric values.
Interop Considerations. If you are interfacing with components not written for the .NET Framework, for example
Automation or COM objects, keep in mind that character types have a different data width (8 bits) in other environments.
If you are passing an 8-bit argument to such a component, declare it as Byte instead of Char in your new Visual Basic
code.
Widening. The Char data type widens to String. This means you can convert Char to String without encountering a
System.OverflowException error.
Type Characters. Appending the literal type character C to a single-character string literal forces it to the Char data type.
Char has no identifier type character.
Framework Type. The corresponding type in the .NET Framework is the System.Char structure.
See Also
Tasks
How to: Optimize Storage of Positive Integers With Unsigned Types
How to: Call a Windows Function that Takes Unsigned Types
Reference
Data Type Summary (Visual Basic)
String Data Type (Visual Basic)
Type Conversion Functions
Conversion Summary
Asc, AscW Functions
Chr, ChrW Functions
System.Char
Concepts
Efficient Use of Data Types
Visual Basic Language Reference

Date Data Type (Visual Basic)


Holds IEEE 64-bit (8-byte) values that represent dates ranging from January 1 of the year 0001 through December 31 of the
year 9999, and times from 12:00:00 AM (midnight) through 11:59:59.9999999 PM. Each increment represents 100
nanoseconds of elapsed time since the beginning of January 1 of the year 1 in the Gregorian calendar. The maximum value
represents 100 nanoseconds before the beginning of January 1 of the year 10000.
Remarks
Use the Date data type to contain date values, time values, or date and time values.
The default value of Date is 0:00:00 (midnight) on January 1, 0001.
Format Requirements
You must enclose a Date literal within number signs (# #). You must specify the date value in the format M/d/yyyy, for
example #5/31/1993#. This requirement is independent of your locale and your computer's date and time format settings.
The reason for this restriction is that the meaning of your code should never change depending on the locale in which your
application is running. Suppose you hard-code a Date literal of #3/4/1998# and intend it to mean March 4, 1998. In a locale
that uses mm/dd/yyyy, 3/4/1998 compiles as you intend. But suppose you deploy your application in many countries. In a
locale that uses dd/mm/yyyy, your hard-coded literal would compile to April 3, 1998. In a locale that uses yyyy/mm/dd, the
literal would be invalid (April 1998, 0003) and cause a compiler error.
Workarounds
To convert a Date literal to the format of your locale, or to a custom format, supply the literal to the Format Function,
specifying either Predefined Date/Time Formats (Format Function) or User-Defined Date/Time Formats (Format Function). The
following example demonstrates this.

MsgBox("The formatted date is " & Format(#5/31/1993#, "dddd, d MMM yyyy"))

Alternatively, you can use one of the overloaded constructors of the DateTime structure to assemble a date and time value. The
following example creates a value to represent May 31, 1993 at 12:14 in the afternoon.

Dim dateInMay As New System.DateTime(1993, 5, 31, 12, 14, 0)

Hour Format
You can specify the time value in either 12-hour or 24-hour format, for example #1:15:30 PM# or #13:15:30#. However, if you
do not specify either the minutes or the seconds, you must specify AM or PM.
Date and Time Defaults
If you do not include a date in a date/time literal, Visual Basic sets the date part of the value to January 1, 0001. If you do not
include a time in a date/time literal, Visual Basic sets the time part of the value to the start of the day, that is, midnight (0:00:00).
Type Conversions
If you convert a Date value to the String type, Visual Basic renders the date according to the short date format specified by the
run-time locale, and it renders the time according to the time format (either 12-hour or 24-hour) specified by the run-time
locale.
Programming Tips
Interop Considerations. If you are interfacing with components not written for the .NET Framework, for example
Automation or COM objects, keep in mind that date/time types in other environments are not compatible with the Visual
Basic Date type. If you are passing a date/time argument to such a component, declare it as Double instead of Date in
your new Visual Basic code, and use the conversion methods System.DateTime.FromOADate(System.Double) and
System.DateTime.ToOADate.
Type Characters. Date has no literal type character or identifier type character. However, the compiler treats literals
enclosed within number signs (# #) as Date.
Framework Type. The corresponding type in the .NET Framework is the System.DateTime structure.
Example
A variable or constant of the Date data type holds both the date and the time. The following example illustrates this.

Dim someDateAndTime As Date = #8/13/2002 12:14 PM#

See Also
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Conversion Summary
System.DateTime
Concepts
Efficient Use of Data Types
Data Type Changes for Visual Basic 6.0 Users
Visual Basic Language Reference

Decimal Data Type (Visual Basic)


Holds signed 128-bit (16-byte) values representing 96-bit (12-byte) integer numbers scaled by a variable power of 10. The
scaling factor specifies the number of digits to the right of the decimal point; it ranges from 0 through 28. With a scale of 0 (no
decimal places), the largest possible value is +/-79,228,162,514,264,337,593,543,950,335 (+/-
7.9228162514264337593543950335E+28). With 28 decimal places, the largest value is +/-
7.9228162514264337593543950335, and the smallest nonzero value is +/-0.0000000000000000000000000001 (+/-1E-28).
Remarks
The Decimal data type provides the greatest number of significant digits for a number. It supports up to 29 significant digits
and can represent values in excess of 7.9228 x 10^28. It is particularly suitable for calculations, such as financial, that require a
large number of digits but cannot tolerate rounding errors.
The default value of Decimal is 0.
Programming Tips
Precision. Decimal is not a floating-point data type. The Decimal structure holds a binary integer value, together with a
sign bit and an integer scaling factor that specifies what portion of the value is a decimal fraction. Because of this,
Decimal numbers have a more precise representation in memory than floating-point types (Single and Double).
Performance. The Decimal data type is the slowest of all the numeric types. You should weigh the importance of
precision against performance before choosing a data type.
Widening. The Decimal data type widens to Single or Double. This means you can convert Decimal to either of these
types without encountering a System.OverflowException error.
Trailing Zeros. Visual Basic does not store trailing zeros in a Decimal literal. However, a Decimal variable preserves
any trailing zeros acquired computationally. The following example illustrates this.

Dim d1, d2, d3, d4 As Decimal


d1 = 2.375D
d2 = 1.625D
d3 = d1 + d2
d4 = 4.000D
MsgBox("d1 = " & CStr(d1) & ", d2 = " & CStr(d2) _
& ", d3 = " & CStr(d3) & ", d4 = " & CStr(d4))

The output of MsgBox in the preceding example is as follows:


d1 = 2.375, d2 = 1.625, d3 = 4.000, d4 = 4
Type Characters. Appending the literal type character D to a literal forces it to the Decimal data type. Appending the
identifier type character @ to any identifier forces it to Decimal.
Framework Type. The corresponding type in the .NET Framework is the System.Decimal structure.
Range
You might need to use the D type character to assign a large value to a Decimal variable or constant. The following example
illustrates this.

Dim bigDec1 As Decimal = 9223372036854775807 ' No overflow.


Dim bigDec2 As Decimal = 9223372036854775808 ' Overflow.
Dim bigDec3 As Decimal = 9223372036854775808D ' No overflow.

The compiler interprets a literal as Long unless it is followed by a literal type character. The declaration for bigDec1 does not
produce an overflow because its value is within the range for Long. However, the value for bigDec2 is too large for Long, so
the compiler generates an error. The literal type character D solves the problem for bigDec3 by forcing the compiler to
interpret the literal as Decimal.
See Also
Reference
Data Type Summary (Visual Basic)
Single Data Type (Visual Basic)
Double Data Type (Visual Basic)
Type Conversion Functions
Conversion Summary
System.Decimal
System.Decimal.#ctor(System.Int32[])
Concepts
Efficient Use of Data Types
Visual Basic Language Reference

Double Data Type (Visual Basic)


Holds signed IEEE 64-bit (8-byte) double-precision floating-point numbers ranging in value from -
1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and from 4.94065645841246544E-
324 through 1.79769313486231570E+308 for positive values. Double-precision numbers store an approximation of a real
number.
Remarks
The Double data type provides the greatest and smallest possible magnitudes for a number.
The default value of Double is 0.
Programming Tips
Precision. When you work with floating-point numbers, keep in mind that they do not always have a precise
representation in memory. This could lead to unexpected results from certain operations, such as value comparison and
the Mod operator. For more information, see Troubleshooting Data Types.
Trailing Zeros. The floating-point data types do not have any internal representation of trailing 0 characters. For
example, they do not distinguish between 4.2000 and 4.2. Consequently, trailing 0 characters do not appear when you
display or print floating-point values.
Type Characters. Appending the literal type character R to a literal forces it to the Double data type. Appending the
identifier type character # to any identifier forces it to Double.
Framework Type. The corresponding type in the .NET Framework is the System.Double structure.
See Also
Tasks
Troubleshooting Data Types
Reference
Data Type Summary (Visual Basic)
Decimal Data Type (Visual Basic)
Single Data Type (Visual Basic)
Type Conversion Functions
Conversion Summary
System.Double
Concepts
Efficient Use of Data Types
Visual Basic Language Reference

Integer Data Type (Visual Basic)


Holds signed 32-bit (4-byte) integers ranging in value from -2,147,483,648 through 2,147,483,647.
Remarks
The Integer data type provides optimal performance on a 32-bit processor. The other integral types are slower to load and
store from and to memory.
The default value of Integer is 0.
Programming Tips
Interop Considerations. If you are interfacing with components not written for the .NET Framework, for example
Automation or COM objects, keep in mind that Integer has a different data width (16 bits) in other environments. If you
are passing a 16-bit argument to such a component, declare it as Short instead of Integer in your new Visual Basic code.
Widening. The Integer data type widens to Long, Decimal, Single, or Double. This means you can convert Integer to
any of these types without encountering a System.OverflowException error.
Type Characters. Appending the literal type character I to a literal forces it to the Integer data type. Appending the
identifier type character % to any identifier forces it to Integer.
Framework Type. The corresponding type in the .NET Framework is the System.Int32 structure.
Range
If you try to set a variable of an integral type to a number outside the range for that type, an error occurs. If you try to set it to a
fraction, the number is rounded. The following example shows this.

' The valid range of an Integer variable is -2147483648 through +2147483647.


Dim k As Integer
' The following statement causes an error because the value is too large.
k = 2147483648
' The following statement sets k to 6.
k = CInt(5.9)

See Also
Reference
Data Type Summary (Visual Basic)
Long Data Type (Visual Basic)
Short Data Type (Visual Basic)
Type Conversion Functions
Conversion Summary
System.Int32
Concepts
Integer Data Type for Visual Basic 6.0 Users
Efficient Use of Data Types
Visual Basic Language Reference

Long Data Type (Visual Basic)


Holds signed 64-bit (8-byte) integers ranging in value from -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807
(9.2...E+18).
Remarks
Use the Long data type to contain integer numbers that are too large to fit in the Integer data type.
The default value of Long is 0.
Programming Tips
Interop Considerations. If you are interfacing with components not written for the .NET Framework, for example
Automation or COM objects, keep in mind that Long has a different data width (32 bits) in other environments. If you are
passing a 32-bit argument to such a component, declare it as Integer instead of Long in your new Visual Basic code.
Furthermore, Automation does not support 64-bit integers on Windows 95, Windows 98, Windows ME, or Windows
2000. You cannot pass a Visual Basic Long argument to an Automation component on these platforms.
Widening. The Long data type widens to Decimal, Single, or Double. This means you can convert Byte to any of these
types without encountering a System.OverflowException error.
Type Characters. Appending the literal type character L to a literal forces it to the Long data type. Appending the
identifier type character & to any identifier forces it to Long.
Framework Type. The corresponding type in the .NET Framework is the System.Int64 structure.
See Also
Reference
Data Type Summary (Visual Basic)
Int64 Structure
Integer Data Type (Visual Basic)
Short Data Type (Visual Basic)
Type Conversion Functions
Conversion Summary
Concepts
Integer Data Type for Visual Basic 6.0 Users
Efficient Use of Data Types
Visual Basic Language Reference

Object Data Type


Holds 32-bit (4-byte) addresses that refer to objects. You can assign any reference type (string, array, class, or interface) to an
Object variable. An Object variable can also refer to data of any value type (numeric, Boolean, Char, Date, structure, or
enumeration).
Remarks
The Object data type can point to data of any data type, including any object instance your application recognizes. Use Object
when you do not know at compile time what data type the variable might point to.
The default value of Object is Nothing (a null reference).
Data Types
You can assign a variable, constant, or expression of any data type to an Object variable. To determine the data type an Object
variable currently refers to, you can use the GetTypeCode method of the System.Type class. The following example illustrates
this.

Dim myObject As Object


' Suppose myObject has now had something assigned to it.
Dim datTyp As Integer
datTyp = Type.GetTypeCode(myObject.GetType())

The Object data type is a reference type. However, Visual Basic treats an Object variable as a value type when it refers to data
of a value type.
Storage
Whatever data type it refers to, an Object variable does not contain the data value itself, but rather a pointer to the value. It
always uses four bytes in computer memory, but this does not include the storage for the data representing the value of the
variable. Because of the code that uses the pointer to locate the data, Object variables holding value types are slightly slower
to access than explicitly typed variables.
Programming Tips
Interop Considerations. If you are interfacing with components not written for the .NET Framework, for example
Automation or COM objects, keep in mind that pointer types in other environments are not compatible with the Visual
Basic Object type.
Performance. A variable you declare with the Object type is flexible enough to contain a reference to any object.
However, when you invoke a method or property on such a variable, you always incur late binding (at run time). To force
early binding (at compile time) and better performance, declare the variable with a specific class name, or cast it to the
specific data type.
When you declare an object variable, try to use a specific class type, for example OperatingSystem, instead of the
generalized Object type. You should also use the most specific class available, such as TextBox instead of Control, so that
you can access its properties and methods. You can usually use the Classes list in the Object Browser to find available
class names.
Widening. All data types and all reference types widen to the Object data type. This means you can convert any type to
Object without encountering a System.OverflowException error.
However, if you convert between value types and Object, Visual Basic performs operations called boxing and unboxing,
which make execution slower.
Type Characters. Object has no literal type character or identifier type character.
Framework Type. The corresponding type in the .NET Framework is the System.Object class.
Example
The following example illustrates an Object variable pointing to an object instance.

Dim objDb As Object


Dim myCollection As New Collection()
' Suppose myCollection has now been populated.
objDb = myCollection.Item(1)

See Also
Tasks
How to: Determine Whether Two Objects Are Related
How to: Determine Whether Two Objects Are Identical
Reference
Data Type Summary (Visual Basic)
Object Class
Type Conversion Functions
Conversion Summary
Concepts
Efficient Use of Data Types
Object as the Universal Data Type
Visual Basic Language Reference

SByte Data Type (Visual Basic)


Holds signed 8-bit (1-byte) integers ranging in value from -128 through 127.
Remarks
Use the SByte data type to contain integer values that do not require the full data width of Integer or even the half data width
of Short. In some cases the common language runtime might be able to pack your SByte variables closely together and save
memory consumption.
The default value of SByte is 0.
Programming Tips
CLS Compliance. The SByte data type is not part of the Common Language Specification (CLS), so CLS-compliant code
cannot consume a component that uses it.
Widening. The SByte data type widens to Short, Integer, Long, Decimal, Single, and Double. This means you can
convert SByte to any of these types without encountering a System.OverflowException error.
Type Characters. SByte has no literal type character or identifier type character.
Framework Type. The corresponding type in the .NET Framework is the System.SByte structure.
See Also
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Conversion Summary
Short Data Type (Visual Basic)
Integer Data Type (Visual Basic)
Long Data Type (Visual Basic)
System.SByte
Concepts
Integer Data Type for Visual Basic 6.0 Users
Efficient Use of Data Types
Visual Basic Language Reference

Short Data Type (Visual Basic)


Holds signed 16-bit (2-byte) integers ranging in value from -32,768 through 32,767.
Remarks
Use the Short data type to contain integer values that do not require the full data width of Integer. In some cases the common
language runtime might be able to pack your Short variables closely together and save memory consumption.
The default value of Short is 0.
Programming Tips
Widening. The Short data type widens to Integer, Long, Decimal, Single, or Double. This means you can convert
Short to any of these types without encountering a System.OverflowException error.
Type Characters. Appending the literal type character S to a literal forces it to the Short data type. Short has no
identifier type character.
Framework Type. The corresponding type in the .NET Framework is the System.Int16 structure.
See Also
Reference
Data Type Summary (Visual Basic)
Type Conversion Functions
Conversion Summary
Integer Data Type (Visual Basic)
Long Data Type (Visual Basic)
System.Int16
Concepts
Integer Data Type for Visual Basic 6.0 Users
Efficient Use of Data Types
Visual Basic Language Reference

Single Data Type (Visual Basic)


Holds signed IEEE 32-bit (4-byte) single-precision floating-point numbers ranging in value from -3.4028235E+38 through -
1.401298E-45 for negative values and from 1.401298E-45 through 3.4028235E+38 for positive values. Single-precision
numbers store an approximation of a real number.
Remarks
Use the Single data type to contain floating-point values that do not require the full data width of Double. In some cases the
common language runtime might be able to pack your Single variables closely together and save memory consumption.
The default value of Single is 0.
Programming Tips
Precision. When you work with floating-point numbers, keep in mind that they do not always have a precise
representation in memory. This could lead to unexpected results from certain operations, such as value comparison and
the Mod operator. For more information, see Troubleshooting Data Types.
Widening. The Single data type widens to Double. This means you can convert Single to Double without
encountering a System.OverflowException error.
Trailing Zeros. The floating-point data types do not have any internal representation of trailing 0 characters. For
example, they do not distinguish between 4.2000 and 4.2. Consequently, trailing 0 characters do not appear when you
display or print floating-point values.
Type Characters. Appending the literal type character F to a literal forces it to the Single data type. Appending the
identifier type character ! to any identifier forces it to Single.
Framework Type. The corresponding type in the .NET Framework is the System.Single structure.
See Also
Tasks
Troubleshooting Data Types
Reference
Data Type Summary (Visual Basic)
Decimal Data Type (Visual Basic)
Double Data Type (Visual Basic)
Type Conversion Functions
Conversion Summary
System.Single
Concepts
Efficient Use of Data Types
Visual Basic Language Reference

String Data Type (Visual Basic)


Holds sequences of unsigned 16-bit (2-byte) code points ranging in value from 0 through 65535. Each code point, or character
code, represents a single Unicode character. A string can contain from 0 to approximately 2 billion (2 ^ 31) Unicode characters.
Remarks
Use the String data type to hold multiple characters without the array management overhead of Char(), an array of Char
elements.
The default value of String is Nothing (a null reference). Note that this is not the same as the empty string (value "").
Unicode Characters
The first 128 code points (0–127) of Unicode correspond to the letters and symbols on a standard U.S. keyboard. These first
128 code points are the same as those the ASCII character set defines. The second 128 code points (128–255) represent special
characters, such as Latin-based alphabet letters, accents, currency symbols, and fractions. Unicode uses the remaining code
points (256-65535) for a wide variety of symbols, including worldwide textual characters, diacritics, and mathematical and
technical symbols.
You can use methods like IsDigit and IsPunctuation on an individual character in a String variable to determine its Unicode
classification.
Format Requirements
You must enclose a String literal within quotation marks (" "). If you need to include a quotation mark as one of the characters
in the string, you use two contiguous quotation marks (""). The following example illustrates this.

Dim j As String = "Joe said ""Hello"" to me."


Dim h As String = "Hello"
' The following messages all display the same thing:
' "Joe said "Hello" to me."
MsgBox(j)
MsgBox("Joe said " & """" & h & """" & " to me.")
MsgBox("Joe said """ & h & """ to me.")

Note that the contiguous quotation marks representing a quotation mark in the string are independent of the quotation marks
that begin and end the String literal.
String Manipulations
Once you assign a string to a String variable, that string is immutable, meaning you cannot change its length or contents.
When you alter a string in any way, Visual Basic creates a new string and abandons the previous one. The String variable then
points to the new string.
You can manipulate the contents of a String variable using a variety of string functions. The following example illustrates the
Left Function (Visual Basic).

Dim S As String = "Database"


' The following statement sets S to a new string containing "Data".
S = Microsoft.VisualBasic.Left(S, 4)

A string created by another component might be padded with leading or trailing spaces. If you receive such a string, you can
use the Trim, LTrim, and RTrim Functions to remove these spaces.
For more information on string manipulations, see Strings in Visual Basic.
Programming Tips
Negative Numbers. Keep in mind that the characters held by String are unsigned and cannot represent negative
values. In any case, you should not use String to hold numeric values.
Interop Considerations. If you are interfacing with components not written for the .NET Framework, for example
Automation or COM objects, keep in mind that string characters have a different data width (8 bits) in other
environments. If you are passing a string argument of 8-bit characters to such a component, declare it as Byte(), an array
of Byte elements, instead of String in your new Visual Basic code.
Type Characters. Appending the identifier type character $ to any identifier forces it to the String data type. String has
no literal type character. However, the compiler treats literals enclosed within quotation marks (" ") as String.
Framework Type. The corresponding type in the .NET Framework is the System.String class.
See Also
Tasks
How to: Optimize Storage of Positive Integers With Unsigned Types
How to: Call a Windows Function that Takes Unsigned Types
Reference
Data Type Summary (Visual Basic)
Char Data Type (Visual Basic)
Type Conversion Functions
Conversion Summary
System.String
Concepts
Efficient Use of Data Types
Visual Basic Language Reference

UInteger Data Type


Holds unsigned 32-bit (4-byte) integers ranging in value from 0 through 4,294,967,295.
Remarks
The UInteger data type provides the largest unsigned value in the most efficient data width.
The default value of UInteger is 0.
Programming Tips
The UInteger and Integer data types provide optimal performance on a 32-bit processor, because the smaller integer types
(UShort, Short, Byte, and SByte), even though they use fewer bits, take more time to load, store, and fetch.
See Also
Tasks
How to: Optimize Storage of Positive Integers With Unsigned Types
How to: Call a Windows Function that Takes Unsigned Types
Reference
Data Type Summary (Visual Basic)
UInt32 Structure
Type Conversion Functions
Conversion Summary
Concepts
Efficient Use of Data Types
Visual Basic Language Reference

ULong Data Type (Visual Basic)


Holds unsigned 64-bit (8-byte) integers ranging in value from 0 through 18,446,744,073,709,551,615 (more than 1.84 times
10 ^ 18).
Remarks
Use the ULong data type to contain binary data too large for UInteger, or the largest possible unsigned integer values.
The default value of ULong is 0.
Programming Tips
Negative Numbers. Because ULong is an unsigned type, it cannot represent a negative number. If you use the unary
minus (-) operator on an expression that evaluates to type ULong, Visual Basic converts the expression to Decimal first.
CLS Compliance. The ULong data type is not part of the Common Language Specification (CLS), so CLS-compliant code
cannot consume a component that uses it.
Interop Considerations. If you are interfacing with components not written for the .NET Framework, for example
Automation or COM objects, keep in mind that types such as ulong can have a different data width (32 bits) in other
environments. If you are passing a 32-bit argument to such a component, declare it as UInteger instead of ULong in
your managed Visual Basic code.
Furthermore, Automation does not support 64-bit integers on Windows 95, Windows 98, Windows ME, or Windows
2000. You cannot pass a Visual Basic ULong argument to an Automation component on these platforms.
Widening. The ULong data type widens to Decimal, Single, and Double. This means you can convert ULong to any of
these types without encountering a System.OverflowException error.
Type Characters. Appending the literal type characters UL to a literal forces it to the ULong data type. ULong has no
identifier type character.
Framework Type. The corresponding type in the .NET Framework is the System.UInt64 structure.
See Also
Tasks
How to: Call a Windows Function that Takes Unsigned Types
Reference
Data Type Summary (Visual Basic)
UInt64 Structure
Type Conversion Functions
Conversion Summary
Concepts
Efficient Use of Data Types
Visual Basic Language Reference

User-Defined Data Type


Holds data in a format you define. The Structure statement defines the format.
Previous versions of Visual Basic support the user-defined type (UDT). The current version expands the UDT to a structure. A
structure is a concatenation of one or more members of various data types. Visual Basic treats a structure as a single unit,
although you can also access its members individually.
Remarks
Define and use a structure data type when you need to combine various data types into a single unit, or when none of the
elementary data types serve your needs.
The default value of a structure data type consists of the combination of the default values of each of its members.
Declaration Format
A structure declaration starts with the Structure Statement and ends with the End Structure statement. The Structure
statement supplies the name of the structure, which is also the identifier of the data type the structure is defining. Other parts
of the code can use this identifier to declare variables, parameters, and function return values to be of this structure's data type.
The declarations between the Structure and End Structure statements define the members of the structure.
Member Access Levels
You must declare every member using a Dim Statement (Visual Basic) or a statement that specifies access level, such as
Public (Visual Basic), Friend (Visual Basic), or Private (Visual Basic). If you use a Dim statement, the access level defaults to
public.
Programming Tips
Memory Consumption. As with all composite data types, you cannot safely calculate the total memory consumption of
a structure by adding together the nominal storage allocations of its members. Furthermore, you cannot safely assume
that the order of storage in memory is the same as your order of declaration. If you need to control the storage layout of
a structure, you can apply the StructLayoutAttribute attribute to the Structure statement.
Interop Considerations. If you are interfacing with components not written for the .NET Framework, for example
Automation or COM objects, keep in mind that user-defined types in other environments are not compatible with Visual
Basic structure types.
Widening. There is no automatic conversion to or from any structure data type. You can define conversion operators on
your structure using the Operator Statement, and you can declare each conversion operator to be Widening or
Narrowing.
Type Characters. Structure data types have no literal type character or identifier type character.
Framework Type. There is no corresponding type in the .NET Framework. All structures inherit from the .NET
Framework class System.ValueType, but no individual structure corresponds to System.ValueType.
Example
The following paradigm shows the outline of the declaration of a structure.

[Public | Protected | Friend | Protected Friend | Private] Structure structname


{Dim | Public | Friend | Private} member1 As datatype1
' ...
{Dim | Public | Friend | Private} memberN As datatypeN
End Structure

See Also
Reference
Data Type Summary (Visual Basic)
ValueType Class
Type Conversion Functions
Conversion Summary
Structure Statement
Widening
Narrowing
StructLayoutAttribute
Concepts
Efficient Use of Data Types
Other Resources
Structures: Your Own Data Types
Visual Basic Language Reference

UShort Data Type (Visual Basic)


Holds unsigned 16-bit (2-byte) integers ranging in value from 0 through 65,535.
Remarks
Use the UShort data type to contain binary data too large for Byte.
The default value of UShort is 0.
Programming Tips
Negative Numbers. Because UShort is an unsigned type, it cannot represent a negative number. If you use the unary
minus (-) operator on an expression that evaluates to type UShort, Visual Basic converts the expression to Integer first.
CLS Compliance. The UShort data type is not part of the Common Language Specification (CLS), so CLS-compliant
code cannot consume a component that uses it.
Widening. The UShort data type widens to Integer, UInteger, Long, ULong, Decimal, Single, and Double. This
means you can convert UShort to any of these types without encountering a System.OverflowException error.
Type Characters. Appending the literal type characters US to a literal forces it to the UShort data type. UShort has no
identifier type character.
Framework Type. The corresponding type in the .NET Framework is the System.UInt16 structure.
See Also
Tasks
How to: Call a Windows Function that Takes Unsigned Types
Reference
Data Type Summary (Visual Basic)
UInt16 Structure
Type Conversion Functions
Conversion Summary
Concepts
Efficient Use of Data Types
Visual Basic Language Reference

Directives (Visual Basic)


The topics in this section document the Visual Basic source code compiler directives.
In This Section
#Const Directive
#ExternalSource Directive
#If...Then...#Else Directives
#Region Directive
Related Sections
Visual Basic Reference
Visual Basic
Visual Basic Language Reference

#Const Directive
Defines conditional compiler constants for Visual Basic.

#Const constname = expression

Parts
constname
Required. String. Name of the constant being defined.
expression
Required. Literal, other conditional compiler constant, or any combination that includes any or all arithmetic or logical
operators except Is.
Remarks
Conditional compiler constants are always private to the file in which they appear. You cannot create public compiler constants
using the #Const directive; you can create them only in the user interface or with the /define compiler option.
You can use only conditional compiler constants and literals in expression. Using a standard constant defined with Const
causes an error. Conversely, you can use constants defined with the #Const keyword only for conditional compilation.
Constants can also be undefined, in which case they have a value of Nothing.
Example
This example uses the #Const directive.
VB
#Const MyLocation = "USA"
#Const Version = "8.0.0012"
#Const CustomerNumber = 36

See Also
Tasks
How to: Declare Conditional Compilation Constants
Reference
/define (Visual Basic)
#If...Then...#Else Directives
Const Statement (Visual Basic)
If...Then...Else Statement (Visual Basic)
Concepts
Conditional Compilation Overview
Visual Basic Language Reference

#ExternalSource Directive
Indicates a mapping between specific lines of source code and text external to the source.

#ExternalSource( StringLiteral , IntLiteral )


[ LogicalLine+ ]
#End ExternalSource

Parts
StringLiteral
The path to the external source.
IntLiteral
The line number of the first line of the external source.
LogicalLine
The line where the error occurs in the external source.
#End ExternalSource
Terminates the #ExternalSource block.
Remarks
This directive is used only by the compiler and the debugger.
A source file may include external source directives, which indicate a mapping between specific lines of code in the source file
and text external to the source, such as an .aspx file. If errors are encountered in the designated source code during
compilation, they are identified as coming from the external source.
External source directives have no effect on compilation and cannot be nested. They are intended for internal use by the
application only.
See Also
Other Resources
Conditional Compilation (Visual Basic)
Visual Basic Language Reference

#If...Then...#Else Directives
Conditionally compiles selected blocks of Visual Basic code.

#If expression Then


statements
[ #ElseIf expression Then
[ statements ]
...
#ElseIf expression Then
[ statements ] ]
[ #Else
[ statements ] ]
#End If

Parts
expression
Required for #If and #ElseIf statements, optional elsewhere. Any expression, consisting exclusively of one or more
conditional compiler constants, literals, and operators, that evaluates to True or False.
statements
Required for #If statement block, optional elsewhere. Visual Basic program lines or compiler directives that are compiled if
the associated expression evaluates to True.
#End If
Terminates the #If statement block.
Remarks
On the surface, the behavior of the #If...Then...#Else directives appears the same as that of the If...Then...Else statements.
However, the #If...Then...#Else directives evaluate what is compiled by the compiler, whereas the If...Then...Else statements
evaluate conditions at run time.
Conditional compilation is typically used to compile the same program for different platforms. It is also used to prevent
debugging code from appearing in an executable file. Code excluded during conditional compilation is completely omitted
from the final executable file, so it has no effect on size or performance.
Regardless of the outcome of any evaluation, all expressions are evaluated using Option Compare Binary. The Option
Compare statement does not affect expressions in #If and #ElseIf statements.
Note
No single-line form of the #If, #Else, #ElseIf, and #End If directives exists. No other code can appear on the same line as any
of the directives.

Example
This example uses the #If...Then...#Else construct to determine whether to compile certain statements.
VB
#Const CustomerNumber = 36
#If CustomerNumber = 35 Then
' Insert code to be compiled for customer # 35.
#ElseIf CustomerNumber = 36 Then
' Insert code to be compiled for customer # 36.
#Else
' Insert code to be compiled for all other customers.
#End If

See Also
Reference
#Const Directive
If...Then...Else Statement (Visual Basic)
Conditional Compilation Constants
Concepts
Conditional Compilation Overview
Visual Basic Language Reference

#Region Directive
Collapses and hides sections of code in Visual Basic files.

#Region "identifier_string"
#End Region

Parts
identifier_string
Required. String that acts as the title of a region when it is collapsed. Regions are collapsed by default.
#End Region
Terminates the #Region block.
Remarks
Use the #Region directive to specify a block of code to expand or collapse when using the outlining feature of the Visual
Studio Code Editor. #Region statements support block semantics (such as #If...#End If), meaning that the start and end must
be in the same code block.
Example
This example uses the #Region directive.
VB
#Region "MathFunctions"
' Insert code for the Math functions here.
#End Region

See Also
Tasks
How to: Outline and Hide Code
How to: Collapse and Hide Sections of Code
Reference
#If...Then...#Else Directives
Visual Basic Language Reference

Functions (Visual Basic)


The topics in this section contain tables of the Visual Basic run-time member functions.
In This Section
Conversion Functions (Visual Basic)
Math Functions (Visual Basic)
Type Conversion Functions
A-C Functions
D-G Functions
H-L Functions
M-R Functions
S-Z Functions
Related Sections
Visual Basic Reference
Visual Basic
Visual Basic Language Reference

Conversion Functions (Visual Basic)


Asc Function
AscW Function
CBool Function
CByte Function
CChar Function
CDate Function
CDbl Function
CDec Function
Chr Function
ChrW Function
CInt Function
CLng Function
CObj Function
CSByte Function
CShort Function
CSng Function
CStr Function
CType Function
CUInt Function
CULng Function
CUShort Function
Format Function
Hex Function
Oct Function
Str Function
Val Function
See Also
Reference
Type Conversion Functions
Visual Basic Language Reference

Math Functions (Visual Basic)


The math functions in Visual Basic 6 have been replaced by equivalent methods in the System.Math class of the .NET
Framework.
Remarks
The .NET Framework math methods are functionally identical to their Visual Basic 6 counterparts, although some have slightly
different names. For example, the .NET Framework equivalent of the Visual Basic 6 Atn function is Atan. The following table
lists the Visual Basic 6 math function names and the equivalent .NET Framework methods.
Visual Ba .NET Fram Description
sic 6 func ework met
tion hod
Abs Abs Returns the absolute value of a specified number.

Atn Atan Returns a Double value containing the angle whose tangent is the specified number.

Cos Cos Returns a Double value containing the cosine of the specified angle.

Exp Exp Returns a Double value containing e (the base of natural logarithms) raised to the specified power.

Log Log Returns a Double value containing the logarithm of a specified number. This method is overloaded an
d can return either the natural (base e) logarithm of a specified number or the logarithm of a specified
number in a specified base.

Round Round Returns a Double value containing the number nearest the specified value. Additional round functions
are available as methods of the intrinsic types such as Round.

Sgn Sign Returns an Integer value indicating the sign of a number.

Sin Sin Returns a Double value specifying the sine of an angle.

Sqr Sqrt Returns a Double value specifying the square root of a number.

Tan Tan Returns a Double value containing the tangent of an angle.

In addition, the .NET Framework math class provides constants and other static methods for trigonometric, logarithmic, and
other common mathematical functions. All of these can be used in a Visual Basic program.
To use these functions without qualification, import the System.Math namespace into your project by adding the following
code to the top of the source code:

'Imports System.Math

Example
This example uses the Abs method of the Math class to compute the absolute value of a number.

' Returns 50.3.


Dim MyNumber1 As Double = Math.Abs(50.3)
' Returns 50.3.
Dim MyNumber2 As Double = Math.Abs(-50.3)

This example uses the Atan method of the Math class to calculate the value of pi.

Public Function GetPi() As Double


' Calculate the value of pi.
Return 4.0 * Math.Atan(1.0)
End Function

This example uses the Cos method of the Math class to return the cosine of an angle.

Public Function Sec(ByVal angle As Double) As Double


' Calculate the secant of angle, in radians.
Return 1.0 / Math.Cos(angle)
End Function

This example uses the Exp method of the Math class to return e raised to a power.

Public Function Sinh(ByVal angle As Double) As Double


' Calculate hyperbolic sine of an angle, in radians.
Return (Math.Exp(angle) - Math.Exp(-angle)) / 2.0
End Function

This example uses the Log method of the Math class to return the natural logarithm of a number.

Public Function Asinh(ByVal value As Double) As Double


' Calculate inverse hyperbolic sine, in radians.
Return Math.Log(value + Math.Sqrt(value * value + 1.0))
End Function

This example uses the Round method of the Math class to round a number to the nearest integer.

' Returns 3.
Dim MyVar2 As Double = Math.Round(2.8)

This example uses the Sign method of the Math class to determine the sign of a number.

' Returns 1.
Dim MySign1 As Integer = Math.Sign(12)
' Returns -1.
Dim MySign2 As Integer = Math.Sign(-2.4)
' Returns 0.
Dim MySign3 As Integer = Math.Sign(0)

This example uses the Sin method of the Math class to return the sine of an angle.

Public Function Csc(ByVal angle As Double) As Double


' Calculate cosecant of an angle, in radians.
Return 1.0 / Math.Sin(angle)
End Function

This example uses the Sqrt method of the Math class to calculate the square root of a number.

' Returns 2.
Dim MySqr1 As Double = Math.Sqrt(4)
' Returns 4.79583152331272.
Dim MySqr2 As Double = Math.Sqrt(23)
' Returns 0.
Dim MySqr3 As Double = Math.Sqrt(0)
' Returns NaN (not a number).
Dim MySqr4 As Double = Math.Sqrt(-4)

This example uses the Tan method of the Math class to return the tangent of an angle.

Public Function Ctan(ByVal angle As Double) As Double


' Calculate cotangent of an angle, in radians.
Return 1.0 / Math.Tan(angle)
End Function

Requirements
Class: Math
Namespace: System
Assembly: mscorlib (in mscorlib.dll)
See Also
Reference
Rnd Function (Visual Basic)
Randomize Function (Visual Basic)
Derived Math Functions (Visual Basic)
NaN
Visual Basic Language Reference

Type Conversion Functions


These functions are compiled inline, meaning the conversion code is part of the code that evaluates the expression. Sometimes
there is no call to a procedure to accomplish the conversion, which improves performance. Each function coerces an expression
to a specific data type.

CBool(expression)
CByte(expression)
CChar(expression)
CDate(expression)
CDbl(expression)
CDec(expression)
CInt(expression)
CLng(expression)
CObj(expression)
CSByte(expression)
CShort(expression)
CSng(expression)
CStr(expression)
CUInt(expression)
CULng(expression)
CUShort(expression)

Part
expression
Required. Any expression of the source data type.
Return Value Data Type
The function name determines the data type of the value it returns, as shown in the following table.
Func Return data type Range for expression argument
tion
nam
e
CBo Boolean Data Type (Visual Basic) Any valid Char or String or numeric expression.
ol

CByt Byte Data Type (Visual Basic) 0 through 255 (unsigned); fractional parts are rounded.1
e

CCha Char Data Type (Visual Basic) Any valid Char or String expression; only first character of a String is converted; value
r can be 0 through 65535 (unsigned).

CDat Date Data Type (Visual Basic) Any valid representation of a date and time.
e

CDbl Double Data Type (Visual Basic) -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative va
lues; 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive
values.

CDec Decimal Data Type (Visual Basic) +/-79,228,162,514,264,337,593,543,950,335 for zero-scaled numbers, that is, numbers
with no decimal places. For numbers with 28 decimal places, the range is +/-7.922816
2514264337593543950335. The smallest possible non-zero number is 0.0000000000
000000000000000001 (+/-1E-28).

CInt Integer Data Type (Visual Basic) -2,147,483,648 through 2,147,483,647; fractional parts are rounded.1
CLng Long Data Type (Visual Basic) -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807; fractional parts are r
ounded.1

CObj Object Data Type Any valid expression.

CSBy SByte Data Type (Visual Basic) -128 through 127; fractional parts are rounded.1
te

CSho Short Data Type (Visual Basic) -32,768 through 32,767; fractional parts are rounded.1
rt

CSng Single Data Type (Visual Basic) -3.402823E+38 through -1.401298E-45 for negative values; 1.401298E-45 through 3.4
02823E+38 for positive values.

CStr String Data Type (Visual Basic) Returns for CStr depend on the expression argument. See
Return Values for the CStr Function.

CUIn UInteger Data Type 0 through 4,294,967,295 (unsigned); fractional parts are rounded.1
t

CUL ULong Data Type (Visual Basic) 0 through 18,446,744,073,709,551,615 (unsigned); fractional parts are rounded.1
ng

CUS UShort Data Type (Visual Basic) 0 through 65,535 (unsigned); fractional parts are rounded.1
hort

1 Fractional parts can be subject to a special type of rounding called banker's rounding. See "Remarks" for more information.

Remarks
As a rule, you should use the Visual Basic type conversion functions in preference to the .NET Framework methods such as
ToString(), either on the Convert class or on an individual type structure or class. The Visual Basic functions are designed for
optimal interaction with Visual Basic code, and they also make your source code shorter and easier to read. In addition, the
.NET Framework conversion methods do not always produce the same results as the Visual Basic functions, for example when
converting Boolean to Integer. For more information, see Troubleshooting Data Types.
Behavior
Coercion. In general, you can use the data type conversion functions to coerce the result of an operation to a particular
data type rather than the default data type. For example, use CDec to force decimal arithmetic in cases where single-
precision, double-precision, or integer arithmetic would normally take place.
Failed Conversions. If the expression passed to the function is outside the range of the data type to which it is to be
converted, an OverflowException occurs.
Fractional Parts. When you convert a nonintegral value to an integral type, the integer conversion functions (CByte,
CInt, CLng, CSByte, CShort, CUInt, CULng, and CUShort) remove the fractional part and round the value to the closest
integer.
If the fractional part is exactly 0.5, the integer conversion functions round it to the nearest even integer. For example, 0.5
rounds to 0, and 1.5 and 2.5 both round to 2. This is sometimes called banker's rounding, and its purpose is to
compensate for a bias that could accumulate when adding many such numbers together.
CInt and CLng differ from the Int, Fix Functions (Visual Basic), which truncate, rather than round, the fractional part of a
number. Also, Fix and Int always return a value of the same data type as you pass in.
Date/Time Conversions. Use the IsDate Function (Visual Basic) to determine if a value can be converted to a date and
time. CDate recognizes date literals and time literals but not numeric values. To convert a Visual Basic 6.0 Date value to
a Visual Basic 2005 Date value, you can use the System.DateTime.FromOADate(System.Double) method.
Neutral Date/Time Values. The Date Data Type (Visual Basic) always contains both date and time information. For
purposes of type conversion, Visual Basic considers 1/1/0001 (January 1 of the year 1) to be a neutral value for the date,
and 00:00:00 (midnight) to be a neutral value for the time. If you convert a Date value to a string, CStr does not include
neutral values in the resulting string. For example, if you convert #January 1, 0001 9:30:00# to a string, the result is
"9:30:00 AM"; the date information is suppressed. However, the date information is still present in the original Date value
and can be recovered with functions such as DatePart Function (Visual Basic).
Culture Sensitivity. The type conversion functions involving strings perform conversions based on the current culture
settings for the application. For example, CDate recognizes date formats according to the locale setting of your system.
You must provide the day, month, and year in the correct order for your locale, or the date might not be interpreted
correctly. A long date format is not recognized if it contains a day-of-the-week string, such as "Wednesday".
If you need to convert to or from a string representation of a value in a format other than the one specified by your
locale, you cannot use the Visual Basic type conversion functions. To do this, use the ToString(IFormatProvider) and
Parse(String, IFormatProvider) methods of that value's type. For example, use
System.Double.Parse(System.String,System.IFormatProvider) when converting a string to a Double, and use
System.Double.ToString(System.IFormatProvider) when converting a value of type Double to a string.
CType Function
The CType Function takes a second argument, typename, and coerces expression to typename, where typename can be any
data type, structure, class, or interface to which there exists a valid conversion.
For a comparison of CType with the other type conversion keywords, see DirectCast and TryCast.
CBool Example
The following example uses the CBool function to convert expressions to Boolean values. If an expression evaluates to a
nonzero value, CBool returns True; otherwise, it returns False.
VB
Dim a, b, c As Integer
Dim check As Boolean
a = 5
b = 5
' The following line of code sets check to True.
check = CBool(a = b)
c = 0
' The following line of code sets check to False.
check = CBool(c)

CByte Example
The following example uses the CByte function to convert an expression to a Byte.
VB
Dim aDouble As Double
Dim aByte As Byte
aDouble = 125.5678
' The following line of code sets aByte to 126.
aByte = CByte(aDouble)

CChar Example
The following example uses the CChar function to convert the first character of a String expression to a Char type.
VB
Dim aString As String
Dim aChar As Char
' CChar converts only the first character of the string.
aString = "BCD"
' The following line of code sets aChar to "B".
aChar = CChar(aString)
The input argument to CChar must be of data type Char or String. You cannot use CChar to convert a number to a character,
because CChar cannot accept a numeric data type. The following example obtains a number representing a code point
(character code) and converts it to the corresponding character. It uses the InputBox Function (Visual Basic) to obtain the string
of digits, CInt to convert the string to type Integer, and ChrW to convert the number to type Char.
VB
Dim someDigits As String
Dim codePoint As Integer
Dim thisChar As Char
someDigits = InputBox("Enter code point of character:")
codePoint = CInt(someDigits)
' The following line of code sets thisChar to the Char value of codePoint.
thisChar = ChrW(codePoint)

CDate Example
The following example uses the CDate function to convert strings to Date values. In general, hard-coding dates and times as
strings (as shown in this example) is not recommended. Use date literals and time literals, such as #Feb 12, 1969# and
#4:45:23 PM#, instead.
VB
Dim aDateString, aTimeString As String
Dim aDate, aTime As Date
aDateString = "February 12, 1969"
aTimeString = "4:35:47 PM"
' The following line of code sets aDate to a Date value.
aDate = CDate(aDateString)
' The following line of code sets aTime to Date value.
aTime = CDate(aTimeString)

CDbl Example
VB
Dim aDec As Decimal
Dim aDbl As Double
' The following line of code uses the literal type character D to make aDec a Decimal.
aDec = 234.456784D
' The following line of code sets aDbl to 1.9225456288E+1.
aDbl = CDbl(aDec * 8.2D * 0.01D)

CDec Example
The following example uses the CDec function to convert a numeric value to Decimal.
VB
Dim aDouble As Double
Dim aDecimal As Decimal
aDouble = 10000000.0587
' The following line of code sets aDecimal to 10000000.0587.
aDecimal = CDec(aDouble)

CInt Example
The following example uses the CInt function to convert a value to Integer.
VB
Dim aDbl As Double
Dim anInt As Integer
aDbl = 2345.5678
' The following line of code sets anInt to 2346.
anInt = CInt(aDbl)

CLng Example
The following example uses the CLng function to convert values to Long.
VB
Dim aDbl1, aDbl2 As Double
Dim aLng1, aLng2 As Long
aDbl1 = 25427.45
aDbl2 = 25427.55
' The following line of code sets aLng1 to 25427.
aLng1 = CLng(aDbl1)
' The following line of code sets aLng2 to 25428.
aLng2 = CLng(aDbl2)

CObj Example
The following example uses the CObj function to convert a numeric value to Object. The Object variable itself contains only a
four-byte pointer, which points to the Double value assigned to it.
VB
Dim aDouble As Double
Dim anObject As Object
aDouble = 2.7182818284
' The following line of code sets anObject to a pointer to aDouble.
anObject = CObj(aDouble)

CSByte Example
The following example uses the CSByte function to convert a numeric value to SByte.
VB
Dim aDouble As Double
Dim anSByte As SByte
aDouble = 39.501
' The following line of code sets anSByte to 40.
anSByte = CSByte(aDouble)

CShort Example
The following example uses the CShort function to convert a numeric value to Short.
VB
Dim aByte As Byte
Dim aShort As Short
aByte = 100
' The following line of code sets aShort to 100.
aShort = CShort(aByte)

CSng Example
The following example uses the CSng function to convert values to Single.
VB
Dim aDouble1, aDouble2 As Double
Dim aSingle1, aSingle2 As Single
aDouble1 = 75.3421105
aDouble2 = 75.3421567
' The following line of code sets aSingle1 to 75.34211.
aSingle1 = CSng(aDouble1)
' The following line of code sets aSingle2 to 75.34216.
aSingle2 = CSng(aDouble2)

CStr Example
The following example uses the CStr function to convert a numeric value to String.
VB
Dim aDouble As Double
Dim aString As String
aDouble = 437.324
' The following line of code sets aString to "437.324".
aString = CStr(aDouble)

The following example uses the CStr function to convert Date values to String values.
VB
Dim aDate As Date
Dim aString As String
' The following line of code generates a COMPILER ERROR because of invalid format.
' aDate = #February 12, 1969 00:00:00#
' Date literals must be in the format #m/d/yyyy# or they are invalid.
' The following line of code sets the time component of aDate to midnight.
aDate = #2/12/1969#
' The following conversion suppresses the neutral time value of 00:00:00.
' The following line of code sets aString to "2/12/1969".
aString = CStr(aDate)
' The following line of code sets the time component of aDate to one second past midnight.
aDate = #2/12/1969 12:00:01 AM#
' The time component becomes part of the converted value.
' The following line of code sets aString to "2/12/1969 12:00:01 AM".
aString = CStr(aDate)

CStr always renders a Date value in the standard short format for the current locale, for example, "6/15/2003 4:35:47 PM".
However, CStr suppresses the neutral values of 1/1/0001 for the date and 00:00:00 for the time.
For more detail on the values returned by CStr, see Return Values for the CStr Function.
CUInt Example
The following example uses the CUInt function to convert a numeric value to UInteger.
VB
Dim aDouble As Double
Dim aUInteger As UInteger
aDouble = 39.501
' The following line of code sets aUInteger to 40.
aUInteger = CUInt(aDouble)

CULng Example
The following example uses the CULng function to convert a numeric value to ULong.
VB
Dim aDouble As Double
Dim aULong As ULong
aDouble = 39.501
' The following line of code sets aULong to 40.
aULong = CULng(aDouble)
CUShort Example
The following example uses the CUShort function to convert a numeric value to UShort.
VB
Dim aDouble As Double
Dim aUShort As UShort
aDouble = 39.501
' The following line of code sets aUShort to 40.
aUShort = CUShort(aDouble)

See Also
Reference
Conversion Functions (Visual Basic)
Asc, AscW Functions
Chr, ChrW Functions
Int, Fix Functions (Visual Basic)
Format Function
Hex Function (Visual Basic)
Oct Function
Str Function
Val Function
Other Resources
Type Conversions in Visual Basic
Visual Basic Language Reference

Return Values for the CStr Function


The following table describes the return values for CStr for different data types of expression.
If expression type is CStr returns
Boolean Data Type (Visual Basic) A string containing "True" or "False".

Date Data Type (Visual Basic) A string containing a Date value (date and time) in the short date format of your system.

Numeric Data Types A string representing the number.


CStr and Date
The Date type always contains both date and time information. For purposes of type conversion, Visual Basic considers
1/1/0001 (January 1 of the year 1) to be a neutral value for the date, and 00:00:00 (midnight) to be a neutral value for the time.
CStr does not include neutral values in the resulting string. For example, if you convert #January 1, 0001 9:30:00# to a
string, the result is "9:30:00 AM"; the date information is suppressed. However, the date information is still present in the
original Date value and can be recovered with functions such as DatePart Function (Visual Basic).
Note
The CStr function performs its conversion based on the current culture settings for the application. To get the string represen
tation of a number in a particular culture, use the number's ToString(IFormatProvider) method. For example, use
System.Double.ToString(System.IFormatProvider) when converting a value of type Double to a String.

See Also
Reference
Type Conversion Functions
Boolean Data Type (Visual Basic)
Date Data Type (Visual Basic)
DatePart Function (Visual Basic)
Visual Basic Language Reference

A-C Functions
The following table contains a listing of the Visual Basic run-time member functions.

AppActivate Asc AscW Beep

CallByName CBool CByte CChar

CDate CDbl CDec ChDir

ChDrive Choose Chr ChrW

CInt CLng CObj Command

CreateObject CShort CSng CStr

CType CurDir

The math functions Abs, Atn, and Cos that were available as Visual Basic run-time member functions in version 6.0 and earlier
have been replaced by methods (Abs, Atan, Cos) in the Math class of the .NET Framework class library. For more information,
see Math Functions (Visual Basic).
Smart Device Developer Notes
The following functions are not supported in smart device applications: AppActivate, Beep, CallByName, ChDir, ChDrive,
CreateObject, and CurDir.
See Also
Reference
D-G Functions
H-L Functions
M-R Functions
S-Z Functions
Other Resources
Visual Basic Reference
Visual Basic Language Reference

AppActivate Function
Activates an application that is already running.

Public Overloads Sub AppActivate( _


ByVal { Title As String | ProcessId As Integer } _
)

Parameters
Title
String expression specifying the title in the title bar of the application you want to activate. You can use the title assigned to
the application when it was launched.
ProcessId
Integer specifying the Win32 process ID number assigned to this process. You can use the ID returned by the Shell Function,
provided it is not zero.
Exceptions
Exception type Error number Condition
ArgumentException 5 Title or ProcessId cannot be found.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
You use AppActivate to bring an application's active window into focus. You might not have a handle or a reference to the
active window, or even know which window is active at a given moment. In such a case, you cannot use the Focus method.
The AppActivate function changes the focus to the named application or window but does not affect whether it is maximized
or minimized. Focus moves away from the activated application window when the user takes some action to change the focus
or close the window. You can use the Shell function to start an application and set the window style.
If you use the Title parameter, AppActivate uses a case-insensitive comparison but otherwise requires an exact match with the
contents of the title bar. It first looks through the top-level windows and then through the child windows. If it cannot find a
match, it throws an ArgumentException.
You can use AppActivate only with processes that own windows. Most console applications do not own windows, which
means that they do not appear in the list of processes that AppActivate searches. When running from a console application,
the system creates a separate process to run the application and returns the output to the console process. Consequently,
when you request the current process ID, you get the process ID of this separate process, rather than the console application's
process ID.
At run time, the AppActivate function activates any running application with a title that matches Title or with a process ID that
matches ProcessId. If there is no exact match, it activates any application whose title string ends with Title. If there is more than
one application named Title, the AppActivate function arbitrarily chooses one to activate.
Note
The AppActivate function requires UIPermission at the SafeTopLevelWindows level, which may affect its execution in parti
al-trust situations. For more information, see Requesting Permissions and UIPermission Class.

Example
This example illustrates various uses of the AppActivate function to activate an application window. If a Notepad process is
not running, the example throws an ArgumentException. The Shell procedure assumes the applications are in the paths
specified.
VB
Dim notepadID As Integer
' Activate a running Notepad process.
AppActivate("Untitled - Notepad")
' AppActivate can also use the return value of the Shell function.
' Shell runs a new instance of Notepad.
notepadID = Shell("C:\WINNT\NOTEPAD.EXE", AppWinStyle.NormalFocus)
' Activate the new instance of Notepad.
AppActivate(notepadID)

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Shell Function
Focus
ArgumentException
Visual Basic Language Reference

Asc, AscW Functions


Returns an Integer value representing the character code corresponding to a character.

Public Overloads Function Asc(ByVal String As Char) As Integer


Public Overloads Function AscW(ByVal String As Char) As Integer
' -or-
Public Overloads Function Asc(ByVal String As String) As Integer
Public Overloads Function AscW(ByVal String As String) As Integer

Parameters
String
Required. Any valid Char or String expression. If String is a String expression, only the first character of the string is used for
input. If String is Nothing or contains no characters, an ArgumentException error occurs.
Exceptions
Exception type Error number Condition
ArgumentException 5 String is empty or is zero length.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Asc returns the code point, or character code, for the input character. This can be 0 through 255 for single-byte character set
(SBCS) values and -32768 through 32767 for double-byte character set (DBCS) values. For charts of the single-byte ASCII
characters, see ASCII Character Codes.
The returned value depends on the code page for the current thread, which is contained in the ANSICodePage property of the
TextInfo class in the System.Globalization namespace. You can obtain ANSICodePage by specifying
System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage.

AscW returns the Unicode code point for the input character. This can be 0 through 65535. The returned value is independent
of the culture and code page settings for the current thread.
Note
The AscB function of earlier versions of Visual Basic returns a code for a byte, rather than a character. It is used primarily for
converting strings in double-byte character set (DBCS) applications. All Visual Basic 2005 strings are in Unicode, and AscB is
no longer supported.

Example
The following example uses the Asc function to return Integer Data Type (Visual Basic) character codes corresponding to the
first letter in each string.
VB
Dim codeInt As Integer
' The following line of code sets myInt to 65.
codeInt = Asc("A")
' The following line of code sets myInt to 97.
codeInt = Asc("a")
' The following line of code sets myInt to 65.
codeInt = Asc("Apple")

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Chr, ChrW Functions
Conversion Functions (Visual Basic)
Type Conversion Functions
Integer Data Type (Visual Basic)
System.Globalization
CultureInfo
ANSICodePage
ArgumentException
Other Resources
ASCII Character Codes
Visual Basic Language Reference

Beep Function
Sounds a tone through the computer's speaker.

Public Sub Beep()

Remarks
The pitch and duration of the beep depend on your hardware and system software and therefore vary among computers.
Note
The Beep function requires UIPermission at the SafeTopLevelWindows level, which may affect its execution in partial-trust s
ituations. For more information, see Requesting Permissions and UIPermission Class.

Example
This example uses the Beep function to sound a long, uninterrupted tone through the computer's speaker.
VB
Dim I As Integer
For I = 1 To 100 ' Loop 100 times.
Beep ' Sound a tone.
Next I

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Visual Basic Run-Time Library Members
Other Resources
Playing Sounds
Visual Basic Language Reference

CallByName Function
Executes a method on an object, or sets or returns a property on an object.

Public Function CallByName( _


ByVal ObjectRef As System.Object, _
ByVal ProcName As String, _
ByVal UseCallType As CallType, _
ByVal Args() As Object _
) As Object

Parameters
ObjectRef
Required. Object. A pointer to the object exposing the property or method.
ProcName
Required. String. A string expression containing the name of the property or method on the object.
UseCallType
Required. An enumeration member of type CallType Enumeration representing the type of procedure being called. The value
of CallType can be Method, Get, or Set.
Args
Optional. ParamArray. A parameter array containing the arguments to be passed to the property or method being called.
Exceptions
Exception type Error number Condition
ArgumentException 5 Invalid UseCallType value; must be Method, Get, or Set.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The CallByName function is used at runtime to get a property, set a property, or invoke a method.
Example
In the following example, the first line uses CallByName to set the Text property of a text box, the second line retrieves the
value of the Text property, and the third line invokes the Move method to move the text box.
VB
' Imports statements must be at the top of a module.
Imports Microsoft.VisualBasic.CallType

VB
Sub TestCallByName1()
'Set a property.
CallByName(TextBox1, "Text", CallType.Set, "New Text")
'Retrieve the value of a property.
MsgBox(CallByName(TextBox1, "Text", CallType.Get))
'Call a method.
CallByName(TextBox1, "Hide", CallType.Method)
End Sub
The next example uses the CallByName function to invoke the Add and Item methods of a collection object.
VB
Public Sub TestCallByName2()
Dim col As New Collection()
'Store the string "Item One" in a collection by
'calling the Add method.
CallByName(col, "Add", CallType.Method, "Item One")
'Retrieve the first entry from the collection using the
'Item property and display it using MsgBox().
MsgBox(CallByName(col, "Item", CallType.Get, 1))
End Sub

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
CallType Enumeration
ArgumentException Class
Concepts
Parameter Arrays
Calling a Property or Method Using a String Name
Visual Basic Language Reference

ChDir Function
Changes the current directory or folder.
The My feature provides you with greater productivity and performance in file I/O operations than the ChDir function. For
more information, see My.Computer.FileSystem.CurrentDirectory Property

Public Sub ChDir(ByVal Path As String)

Parameters
Path
Required. A String expression that identifies which directory or folder becomes the new default directory or folder. Path may
include the drive. If no drive is specified, ChDir changes the default directory or folder on the current drive.
Exceptions
Exception type Error number Condition
ArgumentException 52 Path is empty.

FileNotFoundException 76 Invalid drive is specified, or drive is unavailable.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The ChDir function changes the default directory, but not the default drive. For example, if the default drive is C, the following
statement changes the default directory on drive D, but C remains the default drive:
VB
ChDir("D:\TMP")

Making relative directory changes is accomplished by typing two periods, as follows:


VB
ChDir("..") ' Moves up one directory.

Security Note
The ChDir function requires unmanaged code permission, which may affect its execution in partial-trust situations. For more
information, see SecurityPermission Class and Code Access Permissions.

Example
This example uses the ChDir function to change the current directory or folder.
VB
' Change current directory or folder to "MYDIR".
ChDir("MYDIR")

' Assume "C:" is the current drive. The following statement changes
' the default directory on drive "D:". "C:" remains the current drive.
ChDir("D:\WINDOWS\SYSTEM")

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Parse File Paths in Visual Basic
Reference
ChDrive Function
CurDir Function
Dir Function
MkDir Function
RmDir Function
ArgumentException Class
FileNotFoundException Class
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Reference

ChDrive Function
Changes the current drive.

Public Overloads Sub ChDrive(ByVal Drive As { Char | String })

Parameters
Drive
Required. String expression that specifies an existing drive. If you supply a zero-length string (""), the current drive doesn't
change. If the Drive argument is a multiple-character string, ChDrive uses only the first letter.
Exceptions
Exception type Error number Condition
IOException 68 Invalid drive is specified, or drive is unavailable.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The ChDrive function requires unmanaged-code permission, which may affect its execution in partial-trust situations. For
more information, see SecurityPermission Class and Code Access Permissions.
Example
This example uses the ChDrive function to change the current drive. The function throws an exception if the drive does not
exist.
VB
ChDrive("D") ' Make "D" the current drive.

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
ChDir Function
CurDir Function
MkDir Function
RmDir Function
IOException Class
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference

Choose Function
Selects and returns a value from a list of arguments.

Public Function Choose( _


ByVal Index As Double, _
ByVal ParamArray Choice() As Object _
) As Object

Parameters
Index
Required. Double. Numeric expression that results in a value between 1 and the number of elements passed in the Choice
argument.
Choice
Required. Object parameter array. You can supply either a single variable or an expression that evaluates to the Object data
type, to a list of Object variables or expressions separated by commas, or to a single-dimensional array of Object elements.
Remarks
The Choose function returns a member of the list passed in Choice(), based on the value of Index. The first member of the list
is selected when Index is 1. The last member of the list is selected when Index is UBound(Choice()). If Index is outside these
limits, Choose returns Nothing.
If Index is not a whole number, it is rounded to the nearest whole number before being evaluated.
You can use Choose to look up a value in a list of possibilities.
Note
The expressions in the argument list can include function calls. As part of preparing the argument list for the call to Choose, t
he Visual Basic compiler calls every function in every expression. This means that you cannot rely on a particular function not
being called if a different expression is selected by Index.

Example
This example uses the Choose function to display a name in response to an index passed into the procedure in the Ind
parameter.
VB
Function GetChoice(ByVal Ind As Integer) As String
GetChoice = CStr(Choose(Ind, "Speedy", "United", "Federal"))
End Function

Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IIf Function
Select...Case Statement (Visual Basic)
Switch Function
Visual Basic Language Reference

Chr, ChrW Functions


Returns the character associated with the specified character code.

Public Function Chr(ByVal CharCode As Integer) As Char


Public Function ChrW(ByVal CharCode As Integer) As Char

Parameters
CharCode
Required. An Integer expression representing the code point, or character code, for the character. If CharCode is outside the
valid range, an ArgumentException error occurs. The valid range for Chr is 0 through 255, and the valid range for ChrW is -
32768 through 65535.
Exceptions
Exception type Error number Condition
ArgumentException 5 CharCode < -32768 or > 65535 for ChrW.

ArgumentException 5 CharCode < 0 or > 255 for Chr.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The asymmetric range accepted for CharCode compensates for the storage differences between the
Short Data Type (Visual Basic) and the Integer Data Type (Visual Basic). For example, -29183 is a Short but +36353 is an
Integer. This also facilitates compatibility with Visual Basic 6.0.
Chr uses the Encoding class in the System.Text namespace to determine if the current thread is using a single-byte character
set (SBCS) or a double-byte character set (DBCS). It then takes CharCode as a code point in the appropriate set. The range can
be 0 through 255 for SBCS characters and -32768 through 65535 for DBCS characters. For charts of the single-byte ASCII
characters, see ASCII Character Codes.
The returned value depends on the code page for the current thread, which is contained in the ANSICodePage property of the
TextInfo class in the System.Globalization namespace. You can obtain ANSICodePage by specifying
System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage.

ChrW takes CharCode as a Unicode code point. The range is independent of the culture and code page settings for the current
thread. Values from -32768 through -1 are treated the same as values in the range +32768 through +65535.
Numbers from 0 through 31 are the same as standard nonprintable ASCII codes. For example, Chr(10) returns a line feed
character.
Note
The ChrB function in earlier versions of Visual Basic returns a single byte. It is used primarily for converting strings in double
-byte character set (DBCS) applications. All strings in Visual Basic and the .NET Framework are in Unicode, and ChrB is no lon
ger supported.

Example
The following example uses the Chr function to return the character associated with the specified character code.
VB
Dim associatedChar As Char
' Returns "A".
associatedChar = Chr(65)
' Returns "a".
associatedChar = Chr(97)
' Returns ">".
associatedChar = Chr(62)
' Returns "%".
associatedChar = Chr(37)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Asc, AscW Functions
Str Function
Conversion Functions (Visual Basic)
Type Conversion Functions
CultureInfo
ArgumentException
Other Resources
ASCII Character Codes
Visual Basic Language Reference

Command Function
Returns the argument portion of the command line used to start Visual Basic or an executable program developed with Visual
Basic.
The My feature provides greater productivity and performance than the Command function. For more information, see
My.Application.CommandLineArgs Property.

Public Function Command() As String

Remarks
After the arguments are returned, you can search for common delimiters, such as spaces, backward or forward slashes,
hyphens, or quotation marks, to split or search the string for individual parameters.
For applications developed with Visual Basic and compiled to an .exe file, the Command function returns any arguments that
appear after the name of the application on the command line, in this form: MyApp(cmdlineargs).
Example
This example uses the Command function to return the command-line arguments in an object that contains an array.
VB
Function GetCommandLineArgs() As String()
' Declare variables.
Dim separators As String = " "
Dim commands As String = Microsoft.VisualBasic.Interaction.Command()
Dim args() As String = commands.Split(separators.ToCharArray)
Return args
End Function

Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Visual Basic Run-Time Library Members
Structure of a Visual Basic Program
Environment.GetCommandLineArgs Method
My.Application.CommandLineArgs Property
Concepts
Visual Basic Version of Hello, World
Other Resources
Visual Basic Compiler
Visual Basic Language Reference

CreateObject Function (Visual Basic)


Creates and returns a reference to a COM object. CreateObject cannot be used to create instances of classes in Visual Basic
unless those classes are explicitly exposed as COM components.

Public Shared Function CreateObject( _


ByVal ProgId As String, _
Optional ByVal ServerName As String = "" _
) As Object

Parameters
ProgId
Required. String. The program ID of the object to create.
ServerName
Optional. String. The name of the network server where the object will be created. If ServerName is an empty string (""), the
local computer is used.
Exceptions
Exception type Error nu Condition
mber
Exception 429 ProgId not found or not supplied
-or-
ServerName fails the DnsValidateName function, most likely because it is longer than 63 ch
aracters or contains an invalid character.

Exception 462 Server is unavailable

FileNotFoundException 53 No object of the specified type exists

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
To create an instance of a COM component, assign the object returned by CreateObject to an object variable:

Sub CreateADODB()
Dim adoApp As Object
adoApp = CreateObject("ADODB.Connection")
End Sub

The type of object variable you use to store the returned object can affect your application's performance. Declaring an object
variable with the As Object clause creates a variable that can contain a reference to any type of object. However, access to the
object through that variable is late-bound, that is, the binding occurs when your program runs. There are many reasons you
should avoid late binding, including slower application performance.
You can create an object variable that results in early binding—that is, binding when the program is compiled. To do so, add a
reference to the type library for your object from the COM tab of the Add Reference dialog box on the Project menu. Then
declare the object variable of the specific type of your object. In most cases, it is more efficient to use the Dim statement and a
primary interop assembly to create objects than it is to use the CreateObject function.
Interacting with Unmanaged Code
Another issue is that COM objects use unmanaged code — code without the benefit of the common language runtime. There is
a fair degree of complexity involved in mixing the managed code of Visual Basic with unmanaged code from COM. When you
add a reference to a COM object, Visual Basic searches for a primary interop assembly (PIA) for that library; if it finds one, then
it uses it. If it does not find a PIA, then it creates an interoperability assembly that contains local interoperability classes for each
class in the COM library. For more information, see COM Interoperability in .NET Framework Applications.
You should generally use strongly bound objects and primary interop assemblies whenever possible. The examples below use
the CreateObject function with Microsoft Office objects for demonstration purposes only. However, these objects are easier to
use and more reliable when used with the appropriate primary interop assembly.
Creating an Object on a Remote Computer
You can create an object on a remote networked computer by passing the name of the computer to the ServerName argument
of the CreateObject function. That name is the same as the Machine Name portion of a share name: for a share named
"\\MyServer\Public," ServerName is "MyServer."
Note
Refer to COM documentation (see Microsoft Developer Network) for additional information on making an application access
ible on a remote networked computer. You may need to add a registry key for your application.

The following code returns the version number of an instance of Excel running on a remote computer named MyServer:

Sub CreateRemoteExcelObj()
Dim xlApp As Object
' Replace string "\\MyServer" with name of the remote computer.
xlApp = CreateObject("Excel.Application", "\\MyServer")
MsgBox(xlApp.Version)
End Sub

If the remote server name is incorrect, or if it is unavailable, a run-time error occurs.


Note
Use CreateObject when there is no current instance of the object. If an instance of the object is already running, a new insta
nce is started, and an object of the specified type is created. To use the current instance, or to start the application and have it
load a file, use the GetObject function. If an object has registered itself as a single-instance object, only one instance of the o
bject is created, no matter how many times CreateObject is executed.

Creating Framework Objects


You can use the CreateObject function only to create a COM object. While there is no exact equivalent mechanism for creating
a .NET Framework object, the Activator in the System namespace contains methods to create local or remote objects. In
particular, the CreateInstance method or the CreateInstanceFrom method might be useful.
Security Note
The CreateObject function requires unmanaged code permission, which might affect its execution in partial-trust situations.
For more information, see SecurityPermission and Code Access Permissions.

Example
The following example uses the CreateObject function to create a Microsoft Excel worksheet and saves the worksheet to a file.
To use this example, Excel must be installed on the computer where this program runs. Also, you must add a reference to the
type library from the COM tab of the Add Reference dialog box on the Project menu. The name of the type library varies
depending on the version of Excel installed on your computer. For example, the type library for Microsoft Excel 2002 is named
Microsoft Excel 10.0 Object Library.
VB
Sub TestExcel()
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet

xlApp = CType(CreateObject("Excel.Application"), _
Microsoft.Office.Interop.Excel.Application)
xlBook = CType(xlApp.Workbooks.Add, _
Microsoft.Office.Interop.Excel.Workbook)
xlSheet = CType(xlBook.Worksheets(1), _
Microsoft.Office.Interop.Excel.Worksheet)

' The following statement puts text in the second row of the sheet.
xlSheet.Cells(2, 2) = "This is column B row 2"
' The following statement shows the sheet.
xlSheet.Application.Visible = True
' The following statement saves the sheet to the C:\Test.xls directory.
xlSheet.SaveAs("C:\Test.xls")
' Optionally, you can call xlApp.Quit to close the workbook.
End Sub

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
GetObject Function (Visual Basic)
Dim Statement (Visual Basic)
Declare Statement
Exception
FileNotFoundException
Activator
CreateInstance
CreateInstanceFrom
Other Resources
COM Interoperability in .NET Framework Applications
Interoperating with Unmanaged Code
Visual Basic Language Reference

CType Function
Returns the result of explicitly converting an expression to a specified data type, object, structure, class, or interface.

CType(expression, typename)

Parts
expression
Any valid expression. If the value of expression is outside the range allowed by typename, Visual Basic throws an exception.
typename
Any expression that is legal within an As clause in a Dim statement, that is, the name of any data type, object, structure, class,
or interface.
Remarks
CType is compiled inline, which means that the conversion code is part of the code that evaluates the expression. In some
cases there is no call to a procedure to accomplish the conversion, which makes execution faster.
If no conversion is defined from expression to typename, for example from Integer to Date, Visual Basic displays a compile-
time error message.
If a conversion fails at run time, the appropriate exception occurs. If a narrowing conversion fails, an OverflowException is the
most common result. If the conversion is undefined, an InvalidCastException occurs. This can happen, for example, if expression
is of type Object and its run-time type has no conversion to typename.
If the data type of expression or typename is a class or structure you have defined, you can define CType on that class or
structure as a conversion operator. This makes CType act as an overloaded operator. If you do this, you can control the
behavior of conversions to and from your class or structure, including what exceptions can be thrown.
Overloading
The CType operator can also be overloaded on a class or structure defined outside your code. If your code converts to or from
such a class or structure, be sure you understand the behavior of its CType operator. For more information, see
Operator Procedures.
Example
The following example uses the CType function to convert an expression to the specified data type.
VB
Dim testNumber As Long = 1000
' The following line of code sets testNewType to 1000.0.
Dim testNewType As Single = CType(testNumber, Single)

See Also
Tasks
How to: Define a Conversion Operator
Reference
Type Conversion Functions
Conversion Functions (Visual Basic)
Operator Statement
OverflowException
InvalidCastException
Visual Basic Language Reference

CurDir Function
Returns a string representing the current path.
The My.Computer.FileSystem Object gives you greater productivity and performance in file I/O operations than CurDir. For
more information, see My.Computer.FileSystem.CurrentDirectory Property.

Public Overloads Function CurDir([ ByVal Drive As Char ]) As String

Parameters
Drive
Optional. Char expression that specifies an existing drive. If no drive is specified, or if Drive is a zero-length string (""), CurDir
returns the path for the current drive.
Exceptions
Exception type Error number Condition
IOException 68 Drive is not found.

ArgumentException 68 Invalid Drive is specified.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
This function returns a string representing the current path.
Example
This example uses the CurDir function to return the current path.
VB
' Assume current path on C drive is "C:\WINDOWS\SYSTEM".
' Assume current path on D drive is "D:\EXCEL".
' Assume C is the current drive.
Dim MyPath As String
MyPath = CurDir() ' Returns "C:\WINDOWS\SYSTEM".
MyPath = CurDir("C"c) ' Returns "C:\WINDOWS\SYSTEM".
MyPath = CurDir("D"c) ' Returns "D:\EXCEL".

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
ChDir Function
ChDrive Function
MkDir Function
RmDir Function
IOException Class
ArgumentException Class
Visual Basic Language Reference

D-G Functions
The following table contains a listing of the Visual Basic run-time member functions.

DateAdd DateDiff DatePart DateSerial

DateValue Day DDB DeleteSetting

Derived Math Dir Environ EOF

ErrorToString FileAttr FileClose FileCopy

FileDateTime FileGet FileGetObject FileLen

FileOpen FilePut FilePutObject FileWidth

Filter Fix Format FormatCurrency

FormatDateTime FormatNumber FormatPercent FreeFile

FV GetAllSettings GetAttr GetChar

GetException GetObject GetSetting

The math function Exp that was available as a Visual Basic run-time member function in version 6.0 and earlier has been
replaced by a method (Exp) in the Math class of the .NET Framework class library. For more information, see
Math Functions (Visual Basic).
Smart Device Developer Notes
The following are not supported in smart device applications: DeleteSetting, Dir, Environ, EOF, FileAttr, FileClose, FileCopy,
FileDateTime, FileGet, FileGetObject, FileLen, FileOpen, FilePut, FilePutObject, FileWidth, FreeFile, GetAllSettings,
GetAttr, GetObject, and GetSetting.
See Also
Reference
A-C Functions
H-L Functions
M-R Functions
S-Z Functions
Other Resources
Visual Basic Reference
Visual Basic Language Reference

DateAdd Function (Visual Basic)


Returns a Date value containing a date and time value to which a specified time interval has been added.

Public Overloads Function DateAdd( _


ByVal Interval As DateInterval, _
ByVal Number As Double, _
ByVal DateValue As DateTime _
) As DateTime
' -or-
Public Overloads Function DateAdd( _
ByVal Interval As String, _
ByVal Number As Double, _
ByVal DateValue As Object _
) As DateTime

Parameters
Interval
Required. DateInterval enumeration value or String expression representing the time interval you want to add.
Number
Required. Double. Floating-point expression representing the number of intervals you want to add. Number can be positive
(to get date/time values in the future) or negative (to get date/time values in the past). Any fractional part of Number is
ignored.
DateValue
Required. Date. An expression representing the date and time to which the interval is to be added. DateValue itself is not
changed in the calling program.
Settings
The Interval argument can have one of the following settings.
Enumeration value String Unit of time interval to add
DateInterval.Day d Day; truncated to integral value

DateInterval.DayOfYear y Day; truncated to integral value

DateInterval.Hour h Hour; truncated to integral value

DateInterval.Minute n Minute; truncated to integral value

DateInterval.Month m Month; truncated to integral value

DateInterval.Quarter q Quarter; truncated to integral value

DateInterval.Second s Second; truncated to integral value

DateInterval.Weekday w Day; truncated to integral value

DateInterval.WeekOfYear ww Week; truncated to integral value

DateInterval.Year yyyy Year; truncated to integral value


Exceptions
Exception type Error num Condition
ber
InvalidCastException 13 DateValue is not coercible to Date.

ArgumentException 5 Interval is invalid.

ArgumentOutOfRangeException 9 Calculated date is before 00:00:00 on January 1 of the year 1, or later than 23:59:5
9 on December 31, 9999.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
You can use the DateAdd function to add or subtract a specified time interval from a date. For example, you can calculate a
date 30 days from today or a time 45 minutes before now.
To add days to DateValue, you can use DateInterval.Day, DateInterval.DayOfYear, or DateInterval.Weekday. These are
treated as equivalent because DayOfYear and Weekday are not meaningful time intervals.
The DateAdd function never returns an invalid date. If necessary, the day part of the resulting date is adjusted downward to
the last day of the resulting month in the resulting year. The following example adds one month to January 31:

Dim NextMonth As Date = DateAdd(DateInterval.Month, 1, #1/31/1995#)

In this example, DateAdd returns #2/28/1995#, not #2/31/1995#. If DateValue is #1/31/1996#, it returns #2/29/1996# because
1996 is a leap year.
Note
DateAdd uses the current calendar setting from the CurrentCulture property of the CultureInfo class in the
System.Globalization namespace. The default CurrentCulture values are determined by Control Panel settings.

Since every Date value is supported by a DateTime structure, its methods give you additional options in adding time intervals.
For example, you can add a fractional number of days, rounded to the nearest millisecond, to a Date variable as follows:

Dim NextTime As Date = Now ' Current date and time.


NextTime = NextTime.AddDays(3.4) ' Increment by 3 2/5 days.

Example
This example takes a date and, using the DateAdd function, displays a corresponding date a specified number of months in
the future.
VB
Dim Msg, Number, StartDate As String 'Declare variables.
Dim Months As Double
Dim SecondDate As Date
Dim IntervalType As DateInterval
IntervalType = DateInterval.Month ' Specifies months as interval.
StartDate = InputBox("Enter a date")
SecondDate = CDate(StartDate)
Number = InputBox("Enter number of months to add")
Months = Val(Number)
Msg = "New date: " & DateAdd(IntervalType, Months, SecondDate)
MsgBox(Msg)

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DateDiff Function (Visual Basic)
DatePart Function (Visual Basic)
Day Function (Visual Basic)
Format Function
Now Property
Weekday Function (Visual Basic)
Year Function (Visual Basic)
Date Data Type (Visual Basic)
System
Visual Basic Language Reference

DateDiff Function (Visual Basic)


Returns a Long value specifying the number of time intervals between two Date values.

Public Overloads Function DateDiff( _


ByVal Interval As [ DateInterval | String ], _
ByVal Date1 As DateTime, _
ByVal Date2 As DateTime, _
Optional ByVal DayOfWeek As FirstDayOfWeek = FirstDayOfWeek.Sunday, _
Optional ByVal WeekOfYear As FirstWeekOfYear = FirstWeekOfYear.Jan1 _
) As Long

Parameters
Interval
Required. DateInterval enumeration value or String expression representing the time interval you want to use as the unit
of difference between Date1 and Date2.
Date1
Required. Date. The first date/time value you want to use in the calculation.
Date2
Required. Date. The second date/time value you want to use in the calculation.
DayOfWeek
Optional. A value chosen from the FirstDayOfWeek enumeration that specifies the first day of the week. If not specified,
FirstDayOfWeek.Sunday is used.
WeekOfYear
Optional. A value chosen from the FirstWeekOfYear enumeration that specifies the first week of the year. If not specified,
FirstWeekOfYear.Jan1 is used.
Settings
The Interval argument can have one of the following settings.
Enumeration value String value Unit of time difference
DateInterval.Day "d" Day

DateInterval.DayOfYear "y" Day

DateInterval.Hour "h" Hour

DateInterval.Minute "n" Minute

DateInterval.Month "m" Month

DateInterval.Quarter "q" Quarter

DateInterval.Second "s" Second

DateInterval.Weekday "w" Week

DateInterval.WeekOfYear "ww" Calendar week

DateInterval.Year "yyyy" Year


The DayOfWeek argument can have one of the following settings.
Enumeration value Value Description
FirstDayOfWeek.System 0 First day of week specified in system settings

FirstDayOfWeek.Sunday 1 Sunday (default)

FirstDayOfWeek.Monday 2 Monday (complies with ISO standard 8601, section 3.17)

FirstDayOfWeek.Tuesday 3 Tuesday

FirstDayOfWeek.Wednesday 4 Wednesday

FirstDayOfWeek.Thursday 5 Thursday

FirstDayOfWeek.Friday 6 Friday

FirstDayOfWeek.Saturday 7 Saturday

The WeekOfYear argument can have one of the following settings.


Enumeration value Valu Description
e
FirstWeekOfYear.System 0 First week of year specified in system settings

FirstWeekOfYear.Jan1 1 Week in which January 1 occurs (default)

FirstWeekOfYear.FirstFourD 2 Week that has at least four days in the new year (complies with ISO standard 8601, secti
ays on 3.17)

FirstWeekOfYear.FirstFullW 3 First full week in the new year


eek
Exceptions
Exception type Error number Condition
ArgumentException 5 Invalid Interval.

ArgumentException 5 Date1, Date2, or DayofWeek is out of range.

InvalidCastException 13 Date1 or Date2 is of an invalid type.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
You can use the DateDiff function to determine how many specified time intervals exist between two date/time values. For
example, you might use DateDiff to calculate the number of days between two dates, or the number of weeks between today
and the end of the year.
Behavior
Treatment of Parameters. DateDiff subtracts the value of Date1 from the value of Date2 to produce the difference.
Neither value is changed in the calling program.
Return Values. Because Date1 and Date2 are of the Date data type, they hold date and time values accurate to 100-
nanosecond ticks on the system timer. However, DateDiff always returns the number of time intervals as a Long value.
If Date1 represents a later date and time than Date2, DateDiff returns a negative number.
Day Intervals. If Interval is set to DateInterval.DayOfYear, it is treated the same as DateInterval.Day, because
DayOfYear is not a meaningful unit for a time interval.
Week Intervals. If Interval is set to DateInterval.WeekOfYear, the return value represents the number of weeks
between the first day of the week containing Date1 and the first day of the week containing Date2. The following
example shows how this produces different results from DateInterval.Weekday.
VB
' The following statements set datTim1 to a Thursday
' and datTim2 to the following Tuesday.
Dim datTim1 As Date = #1/4/2001#
Dim datTim2 As Date = #1/9/2001#
' Assume Sunday is specified as first day of the week.
Dim wD As Long = DateDiff(DateInterval.Weekday, datTim1, datTim2)
Dim wY As Long = DateDiff(DateInterval.WeekOfYear, datTim1, datTim2)

In the preceding example, DateDiff returns 0 to wD because the difference between the two dates is less than seven days,
but it returns 1 to wY because there is a seven-day difference between the first days of the respective calendar weeks.
Caution
When the time part of Date1 is greater than that of Date2 and Interval is set to DateInterval.WeekOfYear, the DateD
iff function returns a value that is one less than the correct value.

Larger Intervals. If Interval is set to DateInterval.Year, the return value is calculated purely from the year parts of
Date1 and Date2. Similarly, the return value for DateInterval.Month is calculated purely from the year and month parts
of the arguments, and for DateInterval.Quarter from the quarters containing the two dates.
For example, when comparing December 31 to January 1 of the following year, DateDiff returns 1 for
DateInterval.Year, DateInterval.Quarter, or DateInterval.Month, even though at most only one day has elapsed.
Other Intervals. Since every Date value is supported by a DateTime structure, its methods give you additional options
in finding time intervals. For example, you can use the Subtract method in either of its overloaded forms:
System.DateTime.Subtract(System.TimeSpan) subtracts a TimeSpan from a Date variable to return another Date value,
and System.DateTime.Subtract(System.DateTime) subtracts a Date value to return a TimeSpan. You can time a process
to find out how many milliseconds it takes, as the following example shows.
VB
Dim startTime As Date = Now
' Run the process that is to be timed.
Dim runLength As Global.System.TimeSpan = Now.Subtract(startTime)
Dim millisecs As Integer = runLength.Milliseconds

Example
This example uses the DateDiff function to display the number of days between a given date and today.
VB
Dim firstDate, msg As String
Dim secondDate As Date
firstDate = InputBox("Enter a date")
secondDate = CDate(firstDate)
msg = "Days from today: " & DateDiff(DateInterval.Day, Now, secondDate)
MsgBox(msg)
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DateAdd Function (Visual Basic)
DatePart Function (Visual Basic)
Day Function (Visual Basic)
Format Function
Now Property
Weekday Function (Visual Basic)
Year Function (Visual Basic)
Date Data Type (Visual Basic)
DateTime
TimeSpan
Visual Basic Language Reference

DatePart Function (Visual Basic)


Returns an Integer value containing the specified component of a given Date value.

Public Overloads Function DatePart( _


ByVal Interval As DateInterval, _
ByVal DateValue As DateTime, _
Optional ByVal FirstDayOfWeekValue As FirstDayOfWeek = VbSunday, _
Optional ByVal FirstWeekOfYearValue As FirstWeekOfYear = VbFirstJan1 _
) As Integer
' -or-
Public Overloads Function DatePart( _
ByVal Interval As String, _
ByVal DateValue As Object, _
Optional ByVal DayOfWeek As FirstDayOfWeek = FirstDayOfWeek.Sunday, _
Optional ByVal WeekOfYear As FirstWeekOfYear = FirstWeekOfYear.Jan1 _
) As Integer

Parameters
Interval
Required. DateInterval enumeration value or String expression representing the part of the date/time value you want to
return.
DateValue
Required. Date value that you want to evaluate.
FirstDayOfWeekValue, DayOfWeek
Optional. A value chosen from the FirstDayOfWeek enumeration that specifies the first day of the week. If not specified,
FirstDayOfWeek.Sunday is used.
FirstWeekOfYearValue, WeekOfYear
Optional. A value chosen from the FirstWeekOfYear enumeration that specifies the first week of the year. If not specified,
FirstWeekOfYear.Jan1 is used.
Settings
The Interval argument can have one of the following settings.
Enumeration value String Part of date/time value to return
DateInterval.Day d Day of month (1 through 31)

DateInterval.DayOfYear y Day of year (1 through 366)

DateInterval.Hour h Hour

DateInterval.Minute n Minute

DateInterval.Month m Month

DateInterval.Quarter q Quarter

DateInterval.Second s Second

DateInterval.Weekday w Day of week (1 through 7)

DateInterval.WeekOfYear ww Week of year (1 through 53)


DateInterval.Year yyyy Year

The FirstDayOfWeekValue argument can have one of the following settings.


Enumeration value Value Description
FirstDayOfWeek.System 0 First day of week specified in system settings

FirstDayOfWeek.Sunday 1 Sunday (default)

FirstDayOfWeek.Monday 2 Monday (complies with ISO standard 8601, section 3.17)

FirstDayOfWeek.Tuesday 3 Tuesday

FirstDayOfWeek.Wednesday 4 Wednesday

FirstDayOfWeek.Thursday 5 Thursday

FirstDayOfWeek.Friday 6 Friday

FirstDayOfWeek.Saturday 7 Saturday

The FirstWeekOfYearValue argument can have one of the following settings.


Enumeration value Valu Description
e
FirstWeekOfYear.System 0 First week of year specified in system settings

FirstWeekOfYear.Jan1 1 Week in which January 1 occurs (default)

FirstWeekOfYear.FirstFourD 2 Week that has at least four days in the new year (complies with ISO standard 8601, secti
ays on 3.17)

FirstWeekOfYear.FirstFullW 3 First full week in new year


eek
Exceptions
Exception type Error number Condition
ArgumentException 5 Interval is invalid.

InvalidCastException 13 DateValue is not coercible to Date.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
You can use the DatePart function to evaluate a date/time value and return a specific component. For example, you might use
DatePart to calculate the day of the week or the current hour.
If you choose DateInterval.Weekday for the Interval argument, the returned value is consistent with the values of the
FirstDayOfWeek enumeration. If you choose DateInterval.WeekOfYear, DatePart uses the Calendar and CultureInfo
classes of the System.Globalization namespace to determine your current settings.
The FirstDayOfWeekValue argument affects calculations that use the DateInterval.Weekday and
DateInterval.WeekOfYear Interval settings. The FirstWeekOfYearValue argument affects calculations that specify
DateInterval.WeekOfYear for Interval.
Since every Date value is supported by a DateTime structure, its methods give you additional options in retrieving date/time
parts. For example, you can obtain the entire date value of a Date variable, with the time value set to midnight, as follows:

Dim CurrDatTim As Date = Now ' Current date and time.


Dim LastMidnight As Date = CurrDatTim.Date ' At midnight.

Example
This example takes a date and, using the DatePart function, displays the quarter of the year in which it occurs.
VB
Dim FirstDate, Msg As String 'Declare variables.
Dim SecondDate As Date
FirstDate = InputBox("Enter a date:")
SecondDate = CDate(FirstDate)
Msg = "Quarter: " & DatePart(DateInterval.Quarter, SecondDate)
MsgBox(Msg)

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DateAdd Function (Visual Basic)
DateDiff Function (Visual Basic)
Day Function (Visual Basic)
Format Function
Now Property
Weekday Function (Visual Basic)
Year Function (Visual Basic)
Date Data Type (Visual Basic)
System
Visual Basic Language Reference

DateSerial Function (Visual Basic)


Returns a Date value representing a specified year, month, and day, with the time information set to midnight (00:00:00).

Public Function DateSerial( _


ByVal [Year] As Integer, _
ByVal [Month] As Integer, _
ByVal [Day] As Integer _
) As DateTime

Parameters
Year
Required. Integer expression from 1 through 9999. However, values below this range are also accepted. If Year is 0 through
99, it is interpreted as being between 1930 and 2029, as explained in the "Remarks" section below. If Year is less than 1, it is
subtracted from the current year.
Month
Required. Integer expression from 1 through 12. However, values outside this range are also accepted. The value of Month is
offset by 1 and applied to January of the calculated year. In other words, (Month - 1) is added to January. The year is
recalculated if necessary. The following results illustrate this effect:
If Month is 1, the result is January of the calculated year.
If Month is 0, the result is December of the previous year.
If Month is -1, the result is November of the previous year.
If Month is 13, the result is January of the following year.
Day
Required. Integer expression from 1 through 31. However, values outside this range are also accepted. The value of Day is
offset by 1 and applied to the first day of the calculated month. In other words, (Day - 1) is added to the first of the month.
The month and year are recalculated if necessary. The following results illustrate this effect:
If Day is 1, the result is the first day of the calculated month.
If Day is 0, the result is the last day of the previous month.
If Day is -1, the result is the penultimate day of the previous month.
If Day is past the end of the current month, the result is the appropriate day of the following month. For example, if
Month is 4 and Day is 31, the result is May 1.
Remarks
Under Windows 98 or Windows 2000, two-digit years for the Year argument are interpreted based on user-defined computer
settings. The default settings are that values from 0 through 29 are interpreted as the years 2000–2029, and values from 30
through 99 are interpreted as the years 1930–1999. For all other Year arguments, use a four-digit year; for example, 1924.
Earlier versions of Windows interpret two-digit years based on the defaults described previously. To be sure the function
returns the proper value, use a four-digit Year.
The following example demonstrates negative, zero, and positive argument values. Here, the DateSerial function returns a
Date representing the day before the first day of March in the year 10 years before the current year; in other words, the last
day of February ten years ago.

Dim EndFeb As Date = DateSerial(-10, 3, 0)

If either Month or Day exceeds its normal range, it is applied to the next larger unit as appropriate. For example, if you specify
32 days, it is evaluated as one month and from one to four days, depending on the value of Month. If Year is greater than 9999,
or if any argument is outside the range -2,147,483,648 through 2,147,483,647, an ArgumentException error occurs. If the date
specified by the three arguments is earlier than 00:00:00 on January 1 of the year 1, or later than 23:59:59 on December 31,
9999, an ArgumentOutOfRangeException error occurs.
The Date data type includes time components. DateSerial sets all of these to 0, so the returned value represents the
beginning of the calculated day.
Since every Date value is supported by a DateTime structure, its methods give you additional options in assembling a Date
value. For example, you can use one of the overloaded DateTime constructors to populate a Date variable using the desired
combination of components. The following example sets NewDateTime to May 6, 1978 at one tenth of a second before 8:30 in
the morning:

Dim NewDateTime As Date = New Date(1978, 5, 6, 8, 29, 59, 900)

Example
This example uses the DateSerial function to return the date for the specified year, month, and day.
VB
Dim MyDate As Date
' MyDate contains the date for February 12, 1969.
MyDate = DateSerial(1969, 2, 12) ' Return a date.

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DateValue Function (Visual Basic)
Day Function (Visual Basic)
Month Function (Visual Basic)
Now Property
TimeSerial Function (Visual Basic)
TimeValue Function (Visual Basic)
Weekday Function (Visual Basic)
Year Function (Visual Basic)
Date Data Type (Visual Basic)
System
Visual Basic Language Reference

DateValue Function (Visual Basic)


Returns a Date value containing the date information represented by a string, with the time information set to midnight
(00:00:00).

Public Function DateValue(ByVal StringDate As String) As DateTime

Parameters
StringDate
Required. String expression representing a date/time value from 00:00:00 on January 1 of the year 1 through 23:59:59 on
December 31, 9999.
Exceptions
Exception type Error number Condition
InvalidCastException 13 StringDate includes invalid time information.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If StringDate includes only numbers from 1 through 12 separated by valid date separators, DateValue recognizes the order
for month, day, and year according to the Short Date format specified for your system. DateValue uses the current calendar
setting from the CurrentCulture property of the CultureInfo class in the System.Globalization namespace. The default
CurrentCulture values are determined by Control Panel settings. You can override the Short Date format by setting the
ShortDatePattern property of the DateTimeFormatInfo class in the System.Globalization namespace.
DateValue recognizes month names in long, abbreviated, and numeric form. For example, in addition to recognizing
12/30/1991 and 12/30/91, DateValue also recognizes December 30, 1991 and Dec 30, 1991.
If the year part of StringDate is omitted, DateValue uses the current year from your computer's system date.
If the StringDate argument includes time information, DateValue does not include it in the returned value. However, if
StringDate includes invalid time information, such as "89:98", an InvalidCastException error occurs.
Example
This example uses the DateValue function to convert a string to a date. You can also use date literals to directly assign a date
to an Object or Date variable, for example, oldDate = #2/12/69#.
VB
Dim oldDate As Date
oldDate = DateValue("February 12, 1969")

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DateSerial Function (Visual Basic)
Day Function (Visual Basic)
Month Function (Visual Basic)
Now Property
TimeSerial Function (Visual Basic)
TimeValue Function (Visual Basic)
Weekday Function (Visual Basic)
Year Function (Visual Basic)
Date Data Type (Visual Basic)
DateTime
Visual Basic Language Reference

Day Function (Visual Basic)


Returns an Integer value from 1 through 31 representing the day of the month.

Public Function Day(ByVal DateValue As DateTime) As Integer

Parameters
DateValue
Required. Date value from which you want to extract the day.
Remarks
If you use the Day function, you might have to qualify it with the Microsoft.VisualBasic namespace, because the
System.Windows.Forms namespace defines Day as an enumeration. The following example shows how qualifying Day resolves
this ambiguity:

Dim thisDay As Integer = Microsoft.VisualBasic.DateAndTime.Day(Now)

You can also obtain the day of the month by calling DatePart and specifying DateInterval.Day for the Interval argument.
Example
The following example uses the Day function to obtain the day of the month from a specified date. In the development
environment, the date literal is displayed in standard short format (such as "02/12/1969") using the locale settings of your
code.
VB
Dim oldDate As Date
Dim oldDay As Integer
' Assign a date using standard short format.
oldDate = #2/12/1969#
oldDay = Microsoft.VisualBasic.DateAndTime.Day(oldDate)
' oldDay now contains 12.

Day is qualified to distinguish it from the System.Windows.Forms.Day enumeration.

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DatePart Function (Visual Basic)
Month Function (Visual Basic)
Now Property
Weekday Function (Visual Basic)
Year Function (Visual Basic)
DateTime
ArgumentException
ArgumentOutOfRangeException
Visual Basic Language Reference

DDB Function
Returns a Double specifying the depreciation of an asset for a specific time period using the double-declining balance method
or some other method you specify.

Function DDB( _
ByVal Cost As Double, _
ByVal Salvage As Double, _
ByVal Life As Double, _
ByVal Period As Double, _
Optional ByVal Factor As Double = 2.0 _
) As Double

Parameters
Cost
Required. Double specifying initial cost of the asset.
Salvage
Required. Double specifying value of the asset at the end of its useful life.
Life
Required. Double specifying length of useful life of the asset.
Period
Required. Double specifying period for which asset depreciation is calculated.
Factor
Optional. Double specifying rate at which the balance declines. If omitted, 2 (double-declining method) is assumed.
Exceptions
Exception type Error number Condition
ArgumentException 5 Factor <= 0, Salvage < 0, Period <= 0, or Period > Life.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The double-declining balance method computes depreciation at an accelerated rate. Depreciation is highest in the first period
and decreases in successive periods.
The Life and Period arguments must be expressed in the same units. For example, if Life is given in months, Period must also
be given in months. All arguments must be positive numbers.
The DDB function uses the following formula to calculate depreciation for a given period:
Depreciation / Period = ((Cost – Salvage) * Factor) / Life
Example
This example uses the DDB function to return the depreciation of an asset for a specified period given the initial cost
(InitCost), the salvage value at the end of the asset's useful life (SalvageVal), the total life of the asset in years (LifeTime), and
the period in years for which the depreciation is calculated (Depr).
VB
Dim InitCost, SalvageVal, LifeTime, DepYear As Double
Dim Fmt As String = "###,##0.00"

InitCost = CDbl(InputBox("What's the initial cost of the asset?"))


SalvageVal = CDbl(InputBox("Enter the asset's value at end of its life."))
LifeTime = CDbl(InputBox("What's the asset's useful life in years?"))

' Use the SLN function to calculate the deprecation per year.
Dim SlnDepr As Double = SLN(InitCost, SalvageVal, LifeTime)
Dim msg As String = "The depreciation per year: " & Format(SlnDepr, Fmt)
msg &= vbCrLf & "Year" & vbTab & "Linear" & vbTab & "Doubling" & vbCrLf

' Use the SYD and DDB functions to calculate the deprecation for each year.
For DepYear = 1 To LifeTime
msg &= DepYear & vbTab & _
Format(SYD(InitCost, SalvageVal, LifeTime, DepYear), Fmt) & vbTab & _
Format(DDB(InitCost, SalvageVal, LifeTime, DepYear), Fmt) & vbCrLf
Next
MsgBox(msg)

Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
SLN Function
SYD Function
Financial Summary
ArgumentException
Visual Basic Language Reference

DeleteSetting Function
Deletes a section or key setting from an application's entry in the Windows registry.
The My feature gives you greater productivity and performance in registry operations than the DeleteSetting function. For
more information, see My.Computer.Registry Object.

Public Sub DeleteSetting( _


ByVal AppName As String, _
Optional ByVal Section As String = Nothing, _
Optional ByVal Key As String = Nothing _
)

Parameters
AppName
Required. String expression containing the name of the application or project to which the section or key setting applies.
Section
Required. String expression containing the name of the section from which the key setting is being deleted. If only
AppName and Section are provided, the specified section is deleted along with all related key settings.
Key
Optional. String expression containing the name of the key setting being deleted.
Exceptions
Exception type Error number Condition
ArgumentException 5 Section, AppName, or Key setting does not exist.

ArgumentException 5 User is not logged in.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If all arguments are provided, the specified setting is deleted. A run-time error occurs if you attempt to use DeleteSetting on a
nonexistent section or key setting.
DeleteSetting requires that a user be logged on since it operates under the HKEY_LOCAL_USER registry key, which is not
active until a user logs on interactively.
Registry settings that are to be accessed from a non-interactive process (such as Mtx.exe) should be stored under either the
HKEY_LOCAL_MACHINE\Software\ or the HKEY_USER\DEFAULT\Software registry keys.
Example
The following example first uses the SaveSetting procedure to make entries in the Windows registry for the MyApp application,
and then uses the DeleteSetting function to remove them. Because no Key argument is specified, the whole Startup section
is deleted, including the section name and all of its keys.
VB
' Place some settings in the registry.
SaveSetting("MyApp", "Startup", "Top", "75")
SaveSetting("MyApp","Startup", "Left", "50")
' Remove section and all its settings from registry.
DeleteSetting ("MyApp", "Startup")
' Remove MyApp from the registry.
DeleteSetting ("MyApp")
Smart Device Developer Notes
This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
GetAllSettings Function
GetSetting Function
SaveSetting Function
ArgumentException Class
Visual Basic Language Reference

Dir Function
Returns a string representing the name of a file, directory, or folder that matches a specified pattern or file attribute, or the
volume label of a drive.
The My.Computer.FileSystem Object gives you greater productivity and performance in file I/O operations than the Dir
function. See My.Computer.FileSystem.GetDirectoryInfo Method for more information.

Public Overloads Function Dir() As String


' -or-
Public Overloads Function Dir( _
ByVal PathName As String, _
Optional ByVal Attributes As FileAttribute = FileAttribute.Normal _
) As String

Parameters
PathName
Optional. String expression that specifies a file name, directory or folder name, or drive volume label. A zero-length string
("") is returned if PathName is not found.
Attributes
Optional. Enumeration or numeric expression whose value specifies file attributes. If omitted, Dir returns files that match
PathName but have no attributes.
Settings
The Attributes argument enumeration values are as follows:
Value Constant Description
Normal vbnormal Default. Specifies files with no attributes.

ReadOnly vbReadOnly Specifies read-only files, in addition to files with no attributes.

Hidden vbHidden Specifies hidden files, in addition to files with no attributes.

System vbSystem Specifies system files, in addition to files with no attributes.

Volume vbVolume Specifies volume label; if any other attribute is specified, vbVolume is ignored.

Directory vbDirectory Specifies directories or folders, in addition to files with no attributes.

Archive vbArchive File has changed since last backup.

Alias vbAlias File has a different name.


Note
These enumerations are specified by the Visual Basic language and can be used anywhere in your code in place of the actual
values.

Remarks
The Dir function supports the use of multiple-character (*) and single-character (?) wildcards to specify multiple files.
VbVolume returns the volume label for the drive instead of a specific file name.
You must supply a PathName the first time you call the Dir function. To retrieve the next item, you can make subsequent calls
to the Dir function with no parameters.
Security Note
To run correctly, the Dir function requires the Read and PathDiscovery flags of FileIOPermission to be granted to the executi
ng code. For more information, see FileIOPermission, SecurityException, and Code Access Permissions.

Example
This example uses the Dir function to check if certain files and directories exist.
VB
Dim MyFile, MyPath, MyName As String
' Returns "WIN.INI" if it exists.
MyFile = Dir("C:\WINDOWS\WIN.INI")

' Returns filename with specified extension. If more than one *.INI
' file exists, the first file found is returned.
MyFile = Dir("C:\WINDOWS\*.INI")
' Call Dir again without arguments to return the next *.INI file in the
' same directory.
MyFile = Dir()

' Return first *.TXT file, including files with a set hidden attribute.
MyFile = Dir("*.TXT", vbHidden)

' Display the names in C:\ that represent directories.


MyPath = "c:\" ' Set the path.
MyName = Dir(MyPath, vbDirectory) ' Retrieve the first entry.
Do While MyName <> "" ' Start the loop.
' Use bitwise comparison to make sure MyName is a directory.
If (GetAttr(MyPath & MyName) And vbDirectory) = vbDirectory Then
' Display entry only if it's a directory.
MsgBox(MyName)
End If
MyName = Dir() ' Get next entry.
Loop

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
ChDir Function
CurDir Function
FileAttribute Enumeration
Visual Basic Language Reference

Environ Function
Returns the string associated with an operating-system environment variable.

Overloads Function Environ(ByVal Expression As Integer) As String


' -or-
Overloads Function Environ(ByVal Expression As String) As String

Parameters
Expression
Required. Expression that evaluates either a string containing the name of an environment variable, or an integer
corresponding to the numeric order of an environment string in the environment-string table.
Exceptions
Exception type Error number Condition
ArgumentException 5 Expression is missing.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If Expression contains a string, the Environ function returns the text assigned to the specified environment string—that is, the
text following the equal sign (=) in the environment-string table for that environment variable. If the string in Expression
cannot be found in the environment-string table, a zero-length string ("") is returned.
If Expression contains an integer, the string occupying that numeric position in the environment-string table is returned. In this
case, Environ returns all of the text, including the name of the environment variable. If there is no environment string in the
specified position, Environ returns a zero-length string.
Security Note
The Environ function requires environment permission, which might affect its execution in partial-trust situations. For more i
nformation, see SecurityPermission and Code Access Permissions.

Example
This example uses the Environ function to supply the entry number and length of the PATH statement from the environment-
string table.
VB
Sub tenv()
Dim envString As String
Dim found As Boolean = False
Dim index As Integer = 1
Dim pathLength As Integer
Dim message As String

envString = Environ(index)
While Not found And (envString <> "")
If (envString.Substring(0, 5) = "Path=") Then
found = True
Else
index += 1
envString = Environ(index)
End If
End While
If found Then
pathLength = Environ("PATH").Length
message = "PATH entry = " & index & " and length = " & pathLength
Else
message = "No PATH environment variable exists."
End If
MsgBox(message)
End Sub

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Visual Basic Run-Time Library Members
ArgumentException
Visual Basic Language Reference

EOF Function
Returns a Boolean value True when the end of a file opened for Random or sequential Input has been reached.

Public Function EOF(ByVal FileNumber As Integer) As Boolean

Parameters
FileNumber
Required. An Integer containing any valid file number.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.

IOException 54 File mode is invalid.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Use EOF to avoid the error generated by attempting to get input past the end of a file.
The EOF function returns False until the end of the file has been reached. With files opened for Random or Binary access, EOF
returns False until the last executed FileGet function is unable to read an entire record.
With files opened for Binary access, an attempt to read through the file using the Input function until EOF returns True
generates an error. Use the LOF and Loc functions instead of EOF when reading binary files with Input, or use Get when using
the EOF function. With files opened for Output, EOF always returns True.
Example
This example uses the EOF function to detect the end of a file. This example assumes that Testfile is a text file with a few lines
of text.
VB
Dim TextLine As String
' Open file.
FileOpen(1, "TESTFILE", OpenMode.Input)
' Loop until end of file.
Do While Not EOF(1)
' Read line into variable.
TextLine = LineInput(1)
' Display result in a message box.
MsgBox("End of file reached at " & TextLine)
Loop
FileClose(1)

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
FileGet Function
Loc Function
LOF Function
FileOpen Function
IOException
Visual Basic Language Reference

ErrorToString Function
Returns the error message that corresponds to a given error number.

Public Shared Function ErrorToString(ByVal ErrorNumber As Integer) As String

Parameters
ErrorNumber
Optional. Any valid error number.
Exceptions
Exception type Error number Condition
ArgumentException 5 ErrorNumber is out of range.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The ErrorToString function examines the property settings of the Err object to identify the most recent run-time error. The
return value of the ErrorToString function corresponds to the Description property of the Err object. If ErrorNumber is a
valid error number but is not defined, ErrorToString returns the string "Application-defined or object-defined error." If
ErrorNumber is not valid, an error occurs. If ErrorNumber is omitted, the message corresponding to the most recent run-time
error is returned. If no run-time error has occurred or ErrorNumber is 0, ErrorToString returns a zero-length string ("").
In Visual Basic version 6.0 and earlier, this functionality was provided by the Error function.
Example
The following code uses the ErrorToString function to display error messages that correspond to the specified error numbers.
VB
Dim ErrorNumber As Integer
For ErrorNumber = 61 To 64 ' Loop through values 61 - 64.
MsgBox(ErrorToString(ErrorNumber)) ' Display error names in message box.
Next ErrorNumber

Requirements
Namespace: Microsoft.VisualBasic
Module: Conversion
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Err Object (Visual Basic)
Description Property (Err Object)
ArgumentException
Concepts
Structured Exception Handling Overview for Visual Basic
Unstructured Exception Handling Overview
Visual Basic Language Reference

FileAttr Function
Returns an enumeration representing the file mode for files opened using the FileOpen function.
The My.Computer.FileSystem Object gives you greater productivity and performance in file I/O operations than the FileAttr
function. See My.Computer.FileSystem.GetFileInfo Method for more information.

Public Function FileAttr(ByVal FileNumber As Integer) As OpenMode

Parameters
FileNumber
Required. Integer. Any valid file number.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.

IOException 54 File mode is invalid.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Return Value
The following enumeration values indicate the file access mode:
Value Mode
1 OpenMode.Input

2 OpenMode.Output

4 OpenMode.Random

8 OpenMode.Append

32 OpenMode.Binary
Remarks
This function returns an enumeration representing the file mode for files opened using the FileOpen function.
Example
This example uses the FileAttr function to return the file mode of an open file.
VB
Dim mode As OpenMode
FileOpen(1, "c:\TESTFILE.TXT", OpenMode.Input)
mode = FileAttr(1)
MsgBox("The file mode is " & mode.ToString())
FileClose(1)

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
GetAttr Function
FileOpen Function
SetAttr Function
IOException Class
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference

FileClose Function
Concludes input/output (I/O) to a file opened using the FileOpen function.
Using My gives you greater productivity and performance in file I/O operations. See My.Computer.FileSystem Object for more
information.

Public Sub FileClose(ParamArray FileNumbers() As Integer)

Parameters
FileNumbers
Optional. Parameter array of 0 or more channels to be closed.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The FileClose function is provided for backward compatibility and may affect performance. For non-legacy applications, the
My.Computer.FileSystem object provides better performance. For more information, see File Access with Visual Basic.
If you omit FileNumbers, all active files opened by the FileOpen function are closed.
When you close files that were opened for Output or Append, the final buffer of output is written to the operating system
buffer for that file. All buffer space associated with the closed file is released.
When the FileClose function is executed, the association of a file with its file number ends.
Example
This example uses the FileClose function to close a file opened for Input.
VB
Dim TextLine As String
FileOpen(1, "TESTFILE", OpenMode.Input) ' Open file.
Do While Not EOF(1) ' Loop until end of file.
TextLine = LineInput(1) ' Read line into variable.
MsgBox(TextLine) ' Display the line
Loop
FileClose(1) ' Close file.

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
End Statement
FileOpen Function
Reset Function
Stop Statement (Visual Basic)
Other Resources
File Access with Visual Basic
Visual Basic Language Reference

FileCopy Function
Copies a file.
The My.Computer.FileSystem Object gives you greater productivity and performance in file I/O operations than FileCopy. See
My.Computer.FileSystem.CopyFile Method for more information.

Public Sub FileCopy( _


ByVal Source As String, _
ByVal Destination As String _
)

Parameters
Source
Required. String expression that specifies the name of the file to be copied. Source may include the directory or folder, and
drive, of the source file.
Destination
Required. String expression that specifies the target file name. Destination may include the directory or folder, and drive, of
the destination file.
Exceptions
Exception type Error number Condition
ArgumentException 52 Source or Destination is invalid or not specified.

IOException 55 File is already open.

FileNotFoundException 53 File does not exist.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If you try to use the FileCopy function on a currently open file, an error occurs.
FileCopy requires full trust to work on the local drive.
Example
This example uses the FileCopy function to copy one file to another. For purposes of this example, assume that SrcFile is a
file containing some data.
VB
Dim SourceFile, DestinationFile As String
SourceFile = "SRCFILE" ' Define source file name.
DestinationFile = "DESTFILE" ' Define target file name.
FileCopy(SourceFile, DestinationFile) ' Copy source to target.

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Create a Copy of a File in a Different Directory in Visual Basic
How to: Create a Copy of a File in the Same Directory in Visual Basic
How to: Copy a Directory to Another Directory in Visual Basic
Reference
Kill Function
IOException Class
FileNotFoundException Class
ArgumentException
Visual Basic Language Reference

FileDateTime Function
Returns a Date value that indicates the date and time a file was created or last modified.
The My feature gives you greater productivity and performance in file I/O operations than FileDateTime. For more
information, see My.Computer.FileSystem.GetFileInfo Method.

Public Function FileDateTime(ByVal PathName As String) As DateTime

Parameters
PathName
Required. String expression that specifies a file name. PathName may include the directory or folder, and the drive.
Exceptions
Exception type Error number Condition
ArgumentException 52 PathName is invalid or contains wildcards.

FileNotFoundException 53 Target file does not exist.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
This function returns a Date value that indicates the date and time a file was created or last modified.
Example
This example uses the FileDateTime function to determine the date and time a file was created or last modified. The format of
the date and time displayed is based on the locale settings of your system.
VB
Dim MyStamp As Date
' Assume TESTFILE was last modified on October 12, 2001 at 4:35:47 PM.
' Assume English/U.S. locale settings.
' Returns "10/12/2001 4:35:47 PM".
MyStamp = FileDateTime("C:\TESTFILE.txt")

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
FileLen Function
GetAttr Function
ArgumentException Class
FileNotFoundException Class
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference

FileGet Function
Reads data from an open disk file into a variable.
The My feature gives you greater productivity and performance in file I/O operations than FileGet. For more information, see
My.Computer.FileSystem Object.

Public Overloads Sub FileGet( _


ByVal FileNumber As Integer, _
ByRef Value As Object, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Public Overloads Sub FileGet( _
ByVal FileNumber As Integer, _
ByRef Value As Short, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Public Overloads Sub FileGet( _
ByVal FileNumber As Integer, _
ByRef Value As Integer, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Public Overloads Sub FileGet( _
ByVal FileNumber As Integer, _
ByRef Value As Single, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Public Overloads Sub FileGet( _
ByVal FileNumber As Integer, _
ByRef Value As Double, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Public Overloads Sub FileGet( _
ByVal FileNumber As Integer, _
ByRef Value As Decimal, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Public Overloads Sub FileGet( _
ByVal FileNumber As Integer, _
ByRef Value As Byte, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Public Overloads Sub FileGet( _
ByVal FileNumber As Integer, _
ByRef Value As Boolean, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Public Overloads Sub FileGet( _
ByVal FileNumber As Integer, _
ByRef Value As Date, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Public Overloads Sub FileGet( _
ByVal FileNumber As Integer, _
ByRef Value As System.Array, _
Optional RecordNumber As Integer = -1, _
Optional ArrayIsDynamic As Boolean = False _
)
' -or-
Public Overloads Sub FileGet(
ByVal FileNumber As Integer, _
ByRef Value As String, _
Optional RecordNumber As Integer = -1, _
Optional StringIsFixedLength As Boolean = False _
)

Parameters
FileNumber
Required. Any valid file number.
Value
Required. Valid variable name into which data is read.
RecordNumber
Optional. Record number (Random mode files) or byte number (Binary mode files) at which reading begins.
ArrayIsDynamic
Optional. Applies only when writing an array. Specifies whether the array is to be treated as dynamic and whether an array
descriptor describing the size and bounds of the array is necessary.
StringIsFixedLength
Optional. Applies only when writing a string. Specifies whether to write a two-byte descriptor for the string describing the
length. The default is False.
Exceptions
Exception type Error number Condition
ArgumentException 63 RecordNumber < 1 and not equal to -1.

IOException 52 FileNumber does not exist.

IOException 54 File mode is invalid.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
FileGet is valid only in Random and Binary mode.
Data read with FileGet is usually written to a file with FilePut.
The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you omit RecordNumber,
the next record or byte following the last FileGet or FilePut function (or pointed to by the last Seek function) is read.
Security Note
When reading from files, do not make decisions about the contents of a file based on the file name extension. For example, a
file named Form1.vb may not be a Visual Basic source file.

Random Mode
For files opened in Random mode, the following rules apply:
If the length of the data being read is less than the length specified in the RecordLength clause of the FileOpen function,
FileGet reads subsequent records on record-length boundaries. The space between the end of one record and the
beginning of the next record is padded with the existing contents of the file buffer. Because the amount of padding data
cannot be determined with any certainty, it is generally a good idea to have the record length match the length of the
data being read.
If the variable being read into is a string, by default FileGet reads a two-byte descriptor containing the string length and
then reads the data that goes into the variable. Therefore, the record length specified by the RecordLength clause of the
FileOpen function must be at least two bytes greater than the actual length of the string. Visual Basic 6.0 and earlier
versions support fixed-length strings; when put to a file, the length descriptor is not written. If you want to read a string
without the descriptor, you should pass True to the StringIsFixedLength parameter, and the string you read into should
be the correct length.
If the variable being read into is an array, you can choose whether to read a descriptor for the size and dimension of the
array. To write the descriptor, set the ArrayIsDynamic parameter to True. When reading the array, you need to match the
way the array was written. If it was written with the descriptor, you need to read the descriptor. If the descriptor is not
used, then the size and bounds of the array passed into FileGet determine what to read.
The descriptor specifies the rank of the array, the size, and the lower bounds for each rank. Its length equals 2 plus 8
times the number of dimensions: (2 + 8 * NumberOfDimensions). The record length specified by the RecordLength
parameter in the FileOpen function must be greater than or equal to the sum of all the bytes required to write the array
data and the array descriptor. For example, the following array declaration requires 118 bytes when the array is written
to disk.
VB
Dim MyArray(4,9) As Integer

The 118 bytes are distributed as follows:


18 bytes for the descriptor: (2 + 8 * 2)
100 bytes for the data: (5 * 10 * 2).
If the variable being read into is any other type of variable (not a variable-length string or an object), FileGet reads only
the variable data. The record length specified by the RecordLength clause in the FileOpen function must be greater than
or equal to the length of the data being read.
FileGet reads elements of structures as if each were being read individually, except that there is no padding between
elements. On disk, a dynamic array in a user-defined type (written with FilePut) is prefixed by a descriptor whose length
equals 2 plus 8 times the number of dimensions: (2 + 8 * NumberOfDimensions). The record length specified by the
RecordLength clause in the FileOpen function must be greater than or equal to the sum of all the bytes required to read
the individual elements, including any arrays and their descriptors. The VBFixedString attribute can be applied to string
fields in the structures to indicate the size of a string when written to disk.
Binary Mode
For files opened in Binary mode, most of the Random mode rules apply, with a few exceptions. The following rules for files
opened in Binary mode differ from the rules for Random mode:
The RecordLength clause in the FileOpen function has no effect. FileGet reads all variables from disk contiguously; that
is, with no padding between records.
For any array other than an array in a structure, FileGet reads only the data. No descriptor is read.
FileGet reads variable-length strings that are not elements of structures without expecting the two-byte length
descriptor. The number of bytes read equals the number of characters already in the string.
Security Note
Reading from a file with the FileGet function requires Read access from the FileIOPermissionAccess enumeration.

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
FileOpen Function
FilePut Function
Seek Function
FileGetObject Function
Other Resources
Reading from Files in Visual Basic
Writing to Files in Visual Basic
Visual Basic Language Reference

FileGetObject Function
Reads data from an open disk file into a variable.
The My feature gives you greater productivity and performance in file I/O operations than FileGetObject. For more
information, see My.Computer.FileSystem Object.

Public Sub FileGetObject( _


ByVal FileNumber As Integer, _
ByRef Value As Object, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FileGetObject( _
ByVal FileNumber As Integer, _
ByRef Value As Short, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FileGetObject( _
ByVal FileNumber As Integer, _
ByRef Value As Integer, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FileGetObject( _
ByVal FileNumber As Integer, _
ByRef Value As Single, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FileGetObject( _
ByVal FileNumber As Integer, _
ByRef Value As Double, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FileGetObject( _
ByVal FileNumber As Integer, _
ByRef Value As Decimal, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FileGetObject( _
ByVal FileNumber As Integer, _
ByRef Value As Byte, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FileGetObject( _
ByVal FileNumber As Integer, _
ByRef Value As Boolean, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FileGetObject( _
ByVal FileNumber As Integer, _
ByRef Value As Date, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FileGetObject( _
ByVal FileNumber As Integer, _
ByRef Value As System.Array, _
Optional RecordNumber As Integer = -1, _
Optional ArrayIsDynamic As Boolean = False _
)
' -or-
Overloads Public Sub FileGetObject( _
ByVal FileNumber As Integer, _
ByRef Value As String, _
Optional RecordNumber As Integer = -1, _
Optional StringIsFixedLength As Boolean = False _
)

Parameters
FileNumber
Required. Any valid file number.
Value
Required. Valid variable name into which data is read.
RecordNumber
Optional. Record number (Random mode files) or byte number (Binary mode files) at which reading begins.
ArrayIsDynamic
Optional. Applies only when writing an array. Specifies whether the array is to be treated as dynamic and so whether to write
an array descriptor describing the size and bounds of the array.
StringIsFixedLength
Optional. Applies only when writing a string. Specifies whether to write a two-byte descriptor for the string describing the
length. The default is False.
Remarks
The FileGetObject function is used in place of FileGet to avoid ambiguities at compile time if type Object is returned rather
than another type, such as Integer, Long, Short, and so forth.
If you intend to write out the Variant type, FileGetObject is required. When in doubt, if you are using an object for the second
parameter, it is always suggested that you use FilePutObject and FileGetObject.
FileGetObject is valid only in Random and Binary mode.
Data read with FileGetObject is usually written with FilePutObject.
The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you omit RecordNumber,
FileGetObject reads the record or byte after the last FileGetObject or FilePutObject function (or pointed to by the last Seek
function).
Random Mode
For files opened in Random mode, the following rules apply:
If the length of the data being read is less than the length specified in the RecordLength clause of the FileOpen function,
FileGetObject reads subsequent records on record-length boundaries. The space between the end of one record and the
beginning of the next record is padded with the existing contents of the file buffer. Because the amount of padding data
cannot be precisely determined, it is a good idea to have the record length match the length of the data being read.
If the variable being read into is a string, by default FileGetObject reads a two-byte descriptor containing the string
length and then reads the data that goes into the variable. Therefore, the record length specified by the RecordLength
clause of the FileOpen function must be at least two bytes greater than the actual length of the string. Visual Basic 6.0
and earlier versions support fixed-length strings and when read to a file, the length descriptor is not written. If you want
to read a string without the descriptor, you should pass True to the StringIsFixedLength parameter, and the string you
read into should be the correct length.
If the variable being read into is an array, then you can choose to read a descriptor for the size and dimension of the
array. To read the descriptor, set the ArrayIsDynamic parameter to True. When reading the array, you need to match the
way the array was written. If it was written with the descriptor, you need to read the descriptor. If the descriptor is not
used, the size and bounds of the array passed into FileGetObject are used to determine what to read.
The descriptor specifies the rank of the array, the size, and the lower bounds for each rank. Its length equals 2 plus 8
times the number of dimensions: 2 + 8 * NumberOfDimensions. The record length specified by the RecordLength
parameter in the FileOpen function must be greater than or equal to the sum of all the bytes required to write the array
data and the array descriptor. For example, the following array declaration requires 118 bytes when the array is written
to disk:
VB
Dim MyArray(4,9) As Integer

The 118 bytes are distributed as follows: 18 bytes for the descriptor (2 + 8 * 2), and 100 bytes for the data (5 * 10 * 2).
FileGetObject reads elements of structures as if each were being read individually, except that there is no padding
between elements. On disk, a dynamic array in a user-defined type (written with FilePutObject) is prefixed by a
descriptor whose length equals 2 plus 8 times the number of dimensions: 2 + 8 * NumberOfDimensions. The record
length specified by the RecordLength clause in the FileOpen function must be greater than or equal to the sum of all the
bytes required to read the individual elements, including any arrays and their descriptors. The
VBFixedStringAttribute Class can be applied to string fields in the structures to indicate the size of string when written to
disk.
Binary Mode
For files opened in Binary mode, all of the Random rules apply, with these exceptions:
The RecordLength clause in the FileOpen function has no effect. FileGetObject reads all variables from disk
contiguously, that is, with no padding between records.
For any array other than an array in a structure, FileGetObject reads only the data. No descriptor is read.
FileGetObject reads variable-length strings that are not elements of structures without expecting the two-byte length
descriptor. The number of bytes read equals the number of characters already in the string.
Security Note
When reading from files, do not make decisions about the contents of a file based on the file name extension. For example, a
file named Form1.vb may not be a Visual Basic source file.

Example
The following example reads a record into a test file and then retrieves it.
VB
Dim c As Object = "test"
FileSystem.FileOpen(1, "test.dat", OpenMode.Binary)
FileSystem.FilePutObject(1, "ABCDEF")
FileSystem.Seek(1, 1)
FileSystem.FileGetObject(1, c)
MsgBox(c)
FileSystem.FileClose(1)

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
FilePut Function
FileOpen Function
Seek Function
FileGet Function
Other Resources
Reading from Files in Visual Basic
Writing to Files in Visual Basic
Visual Basic Language Reference

FileLen Function
Returns a Long value specifying the length of a file in bytes.
The My feature gives you greater productivity and performance in file I/O operations than FileLen. For more information, see
My.Computer.FileSystem.GetFileInfo Method.

Public Function FileLen(ByVal PathName As String) As Long

Parameters
PathName
Required. String expression that specifies a file. PathName may include the directory or folder, and the drive.
Exceptions
Exception type Error number Condition
FileNotFoundException 53 File does not exist.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If the specified file is open when the FileLen function is called, the value returned represents the size of the file at the time it
was opened.
Note
To obtain the current length of an open file, use the LOF function.

Example
This example uses the FileLen function to return the length of a file in bytes. For purposes of this example, assume that
TestFile is a file containing some data.

VB
Dim MySize As Long
' Returns file length (bytes).
MySize = FileLen("TESTFILE")

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
FileDateTime Function
GetAttr Function
LOF Function
FileNotFoundException Class
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference

FileOpen Function
Opens a file for input or output.
The My feature gives you greater productivity and performance in file I/O operations than FileOpen. For more information,
see My.Computer.FileSystem Object.

Public Sub FileOpen( _


ByVal FileNumber As Integer, _
ByVal FileName As String, _
ByVal Mode As OpenMode, _
Optional ByVal Access As OpenAccess = OpenAccess.Default, _
Optional ByVal Share As OpenShare = OpenShare.Default, _
Optional ByVal RecordLength As Integer = -1 _
)

Parameters
FileNumber
Required. Any valid file number. Use the FreeFile function to obtain the next available file number.
FileName
Required. String expression that specifies a file name—may include directory or folder, and drive.
Mode
Required. Enumeration specifying the file mode: Append, Binary, Input, Output, or Random. (For more information, see
OpenMode Enumeration.)
Access
Optional. Enumeration specifying the operations permitted on the open file: Read, Write, or ReadWrite. Defaults to
ReadWrite. (For more information, see OpenAccess Enumeration.)
Share
Optional. Enumeration specifying the operations not permitted on the open file by other processes: Shared, Lock Read,
Lock Write, and Lock Read Write. Defaults to Lock Read Write. (For more information, see OpenShare Enumeration.)
RecordLength
Optional. Number less than or equal to 32,767 (bytes). For files opened for random access, this value is the record length. For
sequential files, this value is the number of characters buffered.
Exceptions
Exception type Error number Condition
ArgumentException 5 Invalid Access, Share, or Mode.

ArgumentException 5 WriteOnly file is opened for Input.

ArgumentException 5 ReadOnly file is opened for Output.

ArgumentException 5 ReadOnly file is opened for Append.

ArgumentException 5 Record length is negative (and not equal to -1).

IOException 52 FileNumber is invalid (<-1 or >255), or FileNumber is already in use.

IOException 55 FileName is already open, or FileName is invalid.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The FileOpen function is provided for backward compatibility and may affect performance. For non-legacy applications, the
My.Computer.FileSystem object provides better performance. For more information, see File Access with Visual Basic.
You must open a file before any I/O operation can be performed on it. FileOpen allocates a buffer for I/O to the file and
determines the mode of access to use with the buffer.
Security Note
When writing to a file, an application may need to create a file, if the file to which it is trying to write does not exist. To do so, i
t needs permission for the directory in which the file is to be created. However, if the file specified by FileName does exist, th
e application needs Write permission only to the file itself. Wherever possible, to help improve security, create the file during
deployment and grant Write permission to that file only, rather than to the entire directory. To help improve security, write d
ata to user directories rather than to the root directory or the Program Files directory.

The channel to open can be found using the FreeFile() function.


Security Note
The FileOpen function requires Read access from the FileIOPermissionAccess enumeration, which may affect its execution
in partial trust situations. For more information, see FileIOPermissionAccess enumeration and Requesting Permissions.

Example
This example illustrates various uses of the FileOpen function to enable input and output to a file.
The following code opens the file TestFile in Input mode.
VB
FileOpen(1, "TESTFILE", OpenMode.Input)
' Close before reopening in another mode.
FileClose(1)

This example opens the file in Binary mode for writing operations only.
VB
FileOpen(1, "TESTFILE", OpenMode.Binary,OpenAccess.Write)
' Close before reopening in another mode.
FileClose(1)

The following example opens the file in Random mode. The file contains records of the structure Person.
VB
Structure Person
<VBFixedString(30)> Dim Name As String
Dim ID As Integer
End Structure
Public Sub ExampleMethod()
' Count 30 for the string, plus 4 for the integer.
FileOpen(1, "TESTFILE", OpenMode.Random, , , 34)
' Close before reopening in another mode.
FileClose(1)
End Sub

This code example opens the file in Output mode; any process can read or write to file.
VB
FileOpen(1, "TESTFILE", OpenMode.Output, OpenAccess.Default, OpenShare.Shared)
' Close before reopening in another mode.
FileClose(1)

This code example opens the file in Binary mode for reading; other processes cannot read file.
VB
FileOpen(1, "TESTFILE", OpenMode.Binary, OpenAccess.Read, _
OpenShare.LockRead)

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
FileClose Function
FreeFile Function
Other Resources
Reading from Files in Visual Basic
Writing to Files in Visual Basic
Visual Basic Language Reference

FilePut Function
Writes data from a variable to a disk file.
The My feature gives you greater productivity and performance in file I/O operations than FilePut. For more information, see
My.Computer.FileSystem Object.

Public Overloads Sub FilePut( _


FileNumber As Integer, _
Value As Short, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Public Overloads Sub FilePut( _
FileNumber As Integer, _
Value As Integer, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Public Overloads Sub FilePut( _
FileNumber As Integer, _
Value As Single, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Public Overloads Sub FilePut( _
FileNumber As Integer, _
Value As Double, _
RecordNumber As Integer = -1 _
)
' -or-
Public Overloads Sub FilePut( _
FileNumber As Integer, _
Value As Decimal, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Public Overloads Sub FilePut( _
FileNumber As Integer, _
Value As Byte, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Public Overloads Sub FilePut( _
FileNumber As Integer, _
Value As Boolean, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Public Overloads Sub FilePut( _
FileNumber As Integer, _
Value As Date, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Public Overloads Sub FilePut( _
FileNumber As Integer, _
Value As System.Array, _
Optional RecordNumber As Integer = -1, _
Optional ArrayIsDynamic As Boolean = False _
)
' -or-
Public Overloads Sub FilePut (
FileNumber As Integer,
Value As String, _
Optional RecordNumber As Integer = -1,
Optional StringIsFixedLength As Boolean = False
)

Parameters
FileNumber
Required. Any valid file number.
Value
Required. Valid variable name containing data written to disk.
RecordNumber
Optional. Record number (Random mode files) or byte number (Binary mode files) at which writing begins.
ArrayIsDynamic
Optional. Applies only when writing an array. Specifies whether the array is to be treated as dynamic, and whether to write
an array descriptor for the string describing the length.
StringIsFixedLength
Optional. Applies only when writing a string. Specifies whether to write a two-byte string length descriptor for the string to
the file. The default is False.
Exceptions
Exception type Error number Condition
ArgumentException 63 RecordNumber < 1 and not equal to -1.

IOExceptio 52 FileNumber does not exist.

IOException 54 File mode is invalid.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
FilePut is valid only in Random and Binary mode.
Data written with FilePut is usually read from a file with FileGet.
The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you omit RecordNumber,
the next record or byte after the last FileGet or FilePut function or pointed to by the last Seek function is written.
The StringIsFixedLength argument controls whether the function interprets strings as variable or fixed length. FilePut does not
write the length descriptor when the argument is True. If you use StringIsFixedLength = True with FilePut, you need to do the
same with FileGet, and you need to make sure the string is initialized to the length expected.
Random Mode
For files opened in Random mode, the following rules apply:
If the length of the data being written is less than the length specified in the RecordLength clause of the FileOpen
function, FilePut writes subsequent records on record-length boundaries. The space between the end of one record and
the beginning of the next record is padded with the existing contents of the file buffer. Because the amount of padding
data cannot be determined with any certainty, it is generally a good idea to have the record length match the length of
the data being written. If the length of the data being written is greater than the length specified in the RecordLength
clause of the FileOpen function, an exception will be thrown.
If the variable being written is a string, FilePut writes a two-byte descriptor containing the string length, and then writes
the data that goes into the variable. Therefore, the record length specified by the RecordLength clause in the FileOpen
function must be at least two bytes greater than the actual length of the string.
If the variable being written is an object containing a numeric type, FilePut writes two bytes identifying the VarType of
the object and then writes the variable. For example, when writing an object containing an integer, FilePut writes six
bytes: two bytes identifying the object as VarType(3) (Integer) and four bytes containing the data. The record length
specified by the RecordLength parameter in the FileOpen function must be at least two bytes greater than the actual
number of bytes required to store the variable.
If the variable being written is an object containing a string, FilePut writes a two byte descriptor identifying the
VarType(8) of the object, a two-byte descriptor indicating the length of the string, and then writes the string data. The
record length specified by the RecordLength parameter in the FileOpen function must be at least four bytes greater than
the actual length of the string. If you wish to put a string without the descriptor, then you should pass True to the
StringIsFixedLength parameter, and the string you read into should be the correct length.
If the variable being written is an array, then you have a choice as to whether or not to write a descriptor for the size and
dimensions of the array. Visual Basic 6.0 and earlier versions write the file descriptor for a dynamic array but not for a
fixed-size array. Visual Basic 2005 defaults to not writing the descriptor. To write the descriptor, set the ArrayIsDynamic
parameter to True. When writing the array, you need to match the way the array will be read; if it will be read with the
descriptor, then you need to write the descriptor. The descriptor specifies the rank of the array, the size, and the lower
bounds for each rank. Its length equals 2 plus 8 times the number of dimensions: (2 + 8 * NumberOfDimensions). The
record length specified by the RecordLength clause in the FileOpen function must be greater than or equal to the sum of
all the bytes required to write the array data and the array descriptor. For example, the following array declaration
requires 118 bytes when the array is written to disk.
VB
Dim MyArray(4,9) As Integer

If the variable being written is any other type of variable (not a variable-length string or an object), FilePut writes only
the variable data. The record length specified by the RecordLength clause in the FileOpen function must be greater than
or equal to the length of the data being written.
FilePut writes elements of structures as if each were written individually, except there is no padding between elements.
The VBFixedString attribute can be applied to string fields in the structures to indicate the size of the string when
written to disk.
Note
String fields that have more bytes than specified by the VBFixedString attribute are truncated when written to disk,

Binary Mode
For files opened in Binary mode, most of the Random mode rules apply, with a few exceptions. The following rules for files
opened in Binary mode differ from the rules for Random mode:
The RecordLength clause in the FileOpen function has no effect. FilePut writes all variables to disk contiguously, that is,
with no padding between records.
For any array other than an array in a structure, FilePut writes only the data. No descriptor is written.
FilePut writes variable-length strings that are not elements of structures without the two-byte length descriptor. The
number of bytes written equals the number of characters in the string. For example, the following statements write 11
bytes to file number 1:
VB
Dim hellow As String = "Hello World"
FilePut(1,hellow)

Writing to a file with the FilePut function requires Write access from the FileIOPermissionAccess enumeration.
Example
This example uses the FilePut function to write data to a file. Five records of the structure Person are written to the file.
VB
Structure Person
Public ID As Integer
Public Name As String
End Structure

Sub WriteData()
Dim PatientRecord As Person
Dim recordNumber As Integer
' Open file for random access.
FileOpen(1, "C:\TESTFILE.txt", OpenMode.Binary)
' Loop 5 times.
For recordNumber = 1 To 5
' Define ID.
PatientRecord.ID = recordNumber
' Create a string.
PatientRecord.Name = "Name " & recordNumber
' Write record to file.
FilePut(1, PatientRecord)
Next recordNumber
FileClose(1)
End Sub

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
FileGet Function
FileOpen Function
Seek Function
FileGetObject Function
VBFixedStringAttribute Class
Len Function (Visual Basic)
ArgumentException
IOException
Other Resources
Writing to Files in Visual Basic
Visual Basic Language Reference

FilePutObject Function
Writes data from a variable to a disk file.
The My feature gives you greater productivity and performance in file I/O operations than FilePutObject. For more
information, see My.Computer.FileSystem Object.

Public Sub FilePutObject( _


FileNumber As Integer, _
Value As Object, _
RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FilePutObject( _
FileNumber As Integer, _
Value As Short, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FilePutObject( _
FileNumber As Integer, _
Value As Integer, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FilePutObject( _
FileNumber As Integer, _
Value As Single, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FilePutObject( _
FileNumber As Integer, _
Value As Double, _
RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FilePutObject( _
FileNumber As Integer, _
Value As Decimal, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FilePutObject( _
FileNumber As Integer, _
Value As Byte, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FilePutObject( _
FileNumber As Integer, _
Value As Boolean, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FilePutObject( _
FileNumber As Integer, _
Value As Date, _
Optional RecordNumber As Integer = -1 _
)
' -or-
Overloads Public Sub FilePutObject( _
FileNumber As Integer, _
Value As System.Array, _
Optional RecordNumber As Integer = -1, _
Optional ArrayIsDynamic As Boolean = False _
)
' -or-
Overloads Public Sub FilePutObject( _
FileNumber As Integer, _
Value As String, _
Optional RecordNumber As Integer = -1, _
Optional StringIsFixedLength As Boolean = False _
)

Parameters
FileNumber
Required. Any valid file number.
Value
Required. Valid variable name containing data written to disk.
RecordNumber
Optional. Record number (Random mode files) or byte number (Binary mode files) at which writing begins.
ArrayIsDynamic
Optional. Applies only when writing an array. Specifies whether the array is to be treated as dynamic, and whether to write
an array descriptor for the string describing the length.
StringIsFixedLength
Optional. Applies only when writing a string. Specifies whether to write a descriptor for the string describing the length. The
default is False.
Remarks
The FilePutObject function is used in place of FilePut to avoid ambiguities at compile time if type Object is passed rather
than another type, such as Integer, Long, Short, and so forth.
FilePutObject writes and reads descriptors that describe the object. If you intend to write out the Variant type, FilePutObject
is required. When in doubt, if you are using an object for the second parameter, it is suggested that you always use
FilePutObject and FileGetObject.
FilePutObject is valid only in Random and Binary mode.
Data written with FilePutObject is usually read from a file with FileGetObject.
The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you omit RecordNumber,
FilePutObject writes the next record or byte after the last FileGetObject or FilePutObject function (or the record or byte
pointed to by the last Seek function).
The StringIsFixedLength argument controls whether the function interprets strings as variable or fixed length. FilePutObject
does not write the length descriptor when the argument is True. If you use StringIsFixedLength = True with FilePutObject,
you need to do the same with FileGetObject, and you must also make sure that the string is initialized to the length expected.
Random Mode
For files opened in Random mode, the following rules apply:
If the length of the data being written is less than the length specified in the RecordLength clause of the FileOpen
function, FilePutObject writes subsequent records on record-length boundaries. The space between the end of one
record and the beginning of the next record is padded with the existing contents of the file buffer. Because the amount of
padding data cannot be precisely determined, it is generally a good idea to have the record length match the length of
the data being written. If the length of the data being written is greater than the length specified in the RecordLength
clause of the FileOpen function, an exception is thrown.
If the variable being written is an object containing a numeric type, FilePutObject writes two bytes identifying the
VarType of the object and then writes the variable. For example, when writing an object containing an integer,
FilePutObject writes six bytes: two bytes identifying the object as VarType(3) (Integer) and four bytes containing the
data. The record length specified by the RecordLength parameter in the FileOpen function must be at least two bytes
greater than the actual number of bytes required to store the variable.
If the variable being written is an object containing a string, FilePutObject writes a two-byte descriptor identifying the
VarType(8) of the object, a two-byte descriptor indicating the length of the string, and then writes the string data. The
record length specified by the RecordLength parameter in the FileOpen function must be at least four bytes greater than
the actual length of the string. If you wish to put a string without the descriptor, then you should pass True to the
StringIsFixedLength parameter, and the string you read into should be the correct length.
If the variable being written is an array, you can choose to write a descriptor for the size and dimensions of the array.
Visual Basic 6.0 and earlier versions would write the file descriptor for a dynamic array, but not for a fixed-size array;
Visual Basic defaults to not writing the descriptor. To write the descriptor, set the ArrayIsDynamic parameter to True.
When writing the array, you need to match the way the array is read; if it is read with the descriptor, you need to write
the descriptor. The descriptor specifies the rank of the array, the size, and the lower bounds for each rank. Its length
equals 2 plus 8 times the number of dimensions: (2 + 8 * NumberOfDimensions). The record length specified by the
RecordLength clause in the FileOpen function must be greater than or equal to the sum of all the bytes required to write
the array data and the array descriptor.
Binary Mode
For files opened in Binary mode, all of the Random mode rules apply, except:
The RecordLength clause in the FileOpen function has no effect. FilePutObject writes all variables to disk contiguously,
that is, with no padding between records.
Example
This example uses the FilePutObject function to write a string to a file.
VB
Sub WriteData()
Dim text As String = "test"
FileOpen(1, "test.bin", OpenMode.Binary)
FilePutObject(1, text)
FileClose(1)
End Sub

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
FileGet Function
FileOpen Function
Seek Function
FilePut Function
My.Computer.FileSystem Object
Other Resources
Writing to Files in Visual Basic
Visual Basic Language Reference

FileWidth Function
Assigns an output line width to a file opened using the FileOpen function.

Public Sub FileWidth( _


FileNumber As Integer, _
RecordWidth As Integer _
)

Parameters
FileNumber
Required. Any valid file number.
RecordWidth
Required. Numeric expression in the range 0–255, inclusive, which indicates how many characters appear on a line before a
new line is started. If RecordWidth equals 0, there is no limit to the length of a line. The default value for RecordWidth is 0.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.

IOException 54 File mode is invalid.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
This function assigns an output line width to a file opened using the FileOpen function.
Example
This example uses the FileWidth function to set the output line width for a file.
VB
Dim i As Integer
FileOpen(1, "TESTFILE", OpenMode.Output) ' Open file for output.
FileWidth(1, 5) ' Set output line width to 5.
For i = 0 To 9 ' Loop 10 times.
Print(1, Chr(48 + I)) ' Prints five characters per line.
Next
FileClose(1) ' Close file.

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
FileOpen Function
Print, PrintLine Functions
IOException Class
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference

Filter Function (Visual Basic)


Returns a zero-based array containing a subset of a String array based on specified filter criteria.

Function Filter(
ByVal Source() As { Object | String },
ByVal Match As String,
Optional ByVal Include As Boolean = True,
Optional ByVal Compare As CompareMethod = CompareMethod.Binary
) As String()

Parameters
Source
Required. One-dimensional array of strings to be searched.
Match
Required. String to search for.
Include
Optional. Boolean value indicating whether to return substrings that include or exclude Match. If Include is True, the Filter
function returns the subset of the array that contains Match as a substring. If Include is False, the Filter function returns the
subset of the array that does not contain Match as a substring.
Compare
Optional. Numeric value indicating the kind of string comparison to use. See "Settings" for values.
Settings
The Compare argument can have the following values.
Constant Description
CompareMethod.Binary Performs a binary comparison

CompareMethod.Text Performs a textual comparison


Exceptions
Exception type Error number Condition
ArgumentException 9 Source is Nothing or is not a one-dimensional array.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If no matches of Match are found within Source, the Filter function returns an empty array. An error occurs if Source is set to
Nothing or is not a one-dimensional array.
The array returned by the Filter function contains only enough elements to contain the number of matched items.
Example
This example demonstrates the use of the Filter function.
VB
Dim TestStrings(2) As String
TestStrings(0) = "This"
TestStrings(1) = "Is"
TestStrings(2) = "It"
Dim subStrings() As String
' Returns ["This", "Is"].
subStrings = Filter(TestStrings, "is", True, CompareMethod.Text)
' Returns ["This"].
subStrings = Filter(TestStrings, "is", True, CompareMethod.Binary)
' Returns ["Is", "It"].
subStrings = Filter(TestStrings, "is", False, CompareMethod.Binary)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Replace Function (Visual Basic)
ArgumentException
Visual Basic Language Reference

Int, Fix Functions (Visual Basic)


Return the integer portion of a number.

Public Shared Function Int( _


ByVal Number As { Double | Integer | Long | Object | Short | Single | Decimal }) _
As { Double | Integer | Long | Object | Short | Single | Decimal }
Public Shared Function Fix( _
ByVal Number As { Double | Integer | Long | Object | Short | Single | Decimal }) _
As { Double | Integer | Long | Object | Short | Single | Decimal }

Parameters
Number
Required. A number of type Double or any valid numeric expression. If Number contains Nothing, Nothing is returned.
Exceptions
Exception type Error number Condition
ArgumentNullException 5 Number is not specified.

ArgumentException 5 Number is not a numeric type.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Both the Int and Fix functions remove the fractional part of Number and return the resulting integer value.
The difference between Int and Fix functions is that if Number is negative, Int returns the first negative integer less than or
equal to Number, whereas Fix returns the first negative integer greater than or equal to Number. For example, Int converts -
8.4 to -9, and Fix converts -8.4 to -8.
Fix(number) is equivalent to Sign(number) * Int(Abs(number)).

Example
This example illustrates how the Int and Fix functions return integer portions of numbers. In the case of a negative number
argument, the Int function returns the first negative integer less than or equal to the number; the Fix function returns the first
negative integer greater than or equal to the number. The following example requires you to specify Option Strict Off
because implicit conversions from type Double to type Integer are not allowed under Option Strict On:
VB
' This code requires Option Strict Off
Dim MyNumber As Integer
MyNumber = Int(99.8) ' Returns 99.
MyNumber = Fix(99.8) ' Returns 99.

MyNumber = Int(-99.8) ' Returns -100.


MyNumber = Fix(-99.8) ' Returns -99.
MyNumber = Int(-99.2) ' Returns -100.
MyNumber = Fix(-99.2) ' Returns -99.

You can use the CInt function to explicitly convert other data types to type Integer with Option Strict Off. However, CInt
rounds to the nearest integer instead of truncating the fractional part of numbers. For example:
VB
MyNumber = CInt(99.8) ' Returns 100.
MyNumber = CInt(-99.8) ' Returns -100.
MyNumber = CInt(-99.2) ' Returns -99.

You can use the CInt function on the result of a call to Fix or Int to perform explicit conversion to integer without rounding.
For example:
VB
MyNumber = CInt(Fix(99.8)) ' Returns 99.
MyNumber = CInt(Int(99.8)) ' Returns 99.

For more information on CInt, see Type Conversion Functions.


Requirements
Namespace: Microsoft.VisualBasic
Module: Conversion
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Type Conversion Functions
Integer Data Type (Visual Basic)
Math Summary
Math Functions (Visual Basic)
Conversion Summary
ArgumentNullException
Visual Basic Language Reference

Format Function
Returns a string formatted according to instructions contained in a format String expression.

Public Shared Function Format( _


ByVal Expression As Object, _
Optional ByVal Style As String = "" _
) As String

Parameters
Expression
Required. Any valid expression.
Style
Optional. A valid named or user-defined format String expression.
Settings
For information on how to create the Style argument, see the appropriate topic listed below:
To format Do this
Numbers Use predefined numeric formats or create user-defined numeric formats.

Dates and times Use predefined date/time formats or create user-defined date/time formats.

Date and time serial numbers Use date and time formats or numeric formats.

If you try to format a number without specifying Style, the Format function provides functionality similar to the Str function,
although it is internationally aware. However, positive numbers formatted as strings using the Format function don't include a
leading space reserved for the sign of the value; those converted using the Str function retain the leading space.
Remarks
If you are formatting a nonlocalized numeric string, you should use a user-defined numeric format to ensure that you get the
look you want.
The System.String.Format method also provides similar functionality.
Example
This example shows various uses of the Format function to format values using both String formats and user-defined
formats. For the date separator (/), time separator (:), and the AM/PM indicators (t and tt), the actual formatted output
displayed by your system depends on the locale settings the code is using. When times and dates are displayed in the
development environment, the short time format and short date format of the code locale are used.
Note
For locales that use a 24-hour clock, the AM/PM indicators (t and tt) display nothing.

VB
Dim TestDateTime As Date = #1/27/2001 5:04:23 PM#
Dim TestStr As String
' Returns current system time in the system-defined long time format.
TestStr = Format(Now(), "Long Time")
' Returns current system date in the system-defined long date format.
TestStr = Format(Now(), "Long Date")
' Also returns current system date in the system-defined long date
' format, using the single letter code for the format.
TestStr = Format(Now(), "D")
' Returns the value of TestDateTime in user-defined date/time formats.
' Returns "5:4:23".
TestStr = Format(TestDateTime, "h:m:s")
' Returns "05:04:23 PM".
TestStr = Format(TestDateTime, "hh:mm:ss tt")
' Returns "Saturday, Jan 27 2001".
TestStr = Format(TestDateTime, "dddd, MMM d yyyy")
' Returns "17:04:23".
TestStr = Format(TestDateTime, "HH:mm:ss")
' Returns "23".
TestStr = Format(23)

' User-defined numeric formats.


' Returns "5,459.40".
TestStr = Format(5459.4, "##,##0.00")
' Returns "334.90".
TestStr = Format(334.9, "###0.00")
' Returns "500.00%".
TestStr = Format(5, "0.00%")

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Different Formats for Different Numeric Values (Format Function)
Predefined Date/Time Formats (Format Function)
Predefined Numeric Formats (Format Function)
Str Function
Type Conversion Functions
User-Defined Date/Time Formats (Format Function)
User-Defined Numeric Formats (Format Function)
Format
Visual Basic Language Reference

Different Formats for Different Numeric Values (Format


Function)
A user-defined format expression for numbers can have from one to three sections separated by semicolons. If the Style
argument of the Format function contains one of the predefined numeric formats, only one section is allowed.
If you use This is the result
One section onl The format expression applies to all values.
y

Two sections The first section applies to positive values and zeros; the second applies to negative values.

Three sections The first section applies to positive values, the second applies to negative values, and the third applies to zero
s.

The following example has two sections: the first defines the format for positive values and zeros; the second section defines
the format for negative values. Since the Style argument of the Format function takes a string, it is enclosed by quotation
marks.
VB
Dim Style1 As String = "$#,##0;($#,##0)"

If you include semicolons with nothing between them, the missing section is printed using the format of the positive value. For
example, the following format displays positive and negative values using the format in the first section and displays Zero if
the value is zero.
VB
Dim Style2 As String = "$#,##0;;\Z\e\r\o"

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Predefined Numeric Formats (Format Function)
Format Function
String Manipulation Summary
Visual Basic Language Reference

Predefined Numeric Formats (Format Function)


The following table identifies the predefined numeric format names. These may be used by name as the style argument for the
Format function:
Format nam Description
e
General Nu Displays number with no thousand separator.
mber, G, or g

Currency, C, Displays number with thousand separator, if appropriate; displays two digits to the right of the decimal separato
or c r. Output is based on system locale settings.

Fixed, F, or f Displays at least one digit to the left and two digits to the right of the decimal separator.

Standard, N, Displays number with thousand separator, at least one digit to the left and two digits to the right of the decimal
or n separator.

Percent Displays number multiplied by 100 with a percent sign (%) appended immediately to the right; always displays t
wo digits to the right of the decimal separator.

P, or p Displays number with thousandths separator multiplied by 100 with a percent sign (%) appended to the right a
nd separated by a single space; always displays two digits to the right of the decimal separator.

Scientific Uses standard scientific notation, providing two significant digits.

E, or e Uses standard scientific notation, providing six significant digits.

D, or d Displays number as a string that contains the value of the number in Decimal (base 10) format. This option is su
pported for integral types (Byte, Short, Integer, Long) only.

X, or x Displays number as a string that contains the value of the number in Hexadecimal (base 16) format. This option
is supported for integral types (Byte, Short, Integer, Long) only.

Yes/No Displays No if number is 0; otherwise, displays Yes.

True/False Displays False if number is 0; otherwise, displays True.

On/Off Displays Off if number is 0; otherwise, displays On.


Smart Device Developer Notes
The Yes/No, True/False, and On/Off formats are not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Conversion Summary
Format Function
Predefined Date/Time Formats (Format Function)
User-Defined Numeric Formats (Format Function)
Visual Basic Language Reference

Predefined Date/Time Formats (Format Function)


The following table identifies the predefined date and time format names. These may be used by name as the style argument
for the Format function:
Format Name Description
General Date, or G Displays a date and/or time. For example, 4/3/93 05:34 PM. Date display is determined by your appl
ication's current culture value.

Long Date, Medium Da Displays a date according to your current culture's long date format.
te, or D

Short Date, or d Displays a date using your current culture's short date format.

Long Time, Medium Ti Displays a time using your current culture's long time format; typically includes hours, minutes, seco
me, or T nds.

Short Time, or t Displays a time using your current culture's short time format.

f Displays the long date and short time according to your current culture's format.

F Displays the long date and long time according to your current culture's format.

g Displays the short date and short time according to your current culture's format.

M, m Displays the month and the day of a date.

R, r Formats the date and time as Greenwich Mean Time (GMT).

s Formats the date and time as a sortable index.

u Formats the date and time as a GMT sortable index.

U Formats the date and time with the long date and long time as GMT.

Y, y Formats the date as the year and month.

For more information about the application's current culture information, see How Culture Affects Strings in Visual Basic.
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Conversion Summary
Format Function
Predefined Numeric Formats (Format Function)
User-Defined Date/Time Formats (Format Function)
Visual Basic Language Reference

User-Defined Date/Time Formats (Format Function)


The following table shows characters you can use to create user-defined date/time formats. Unlike in previous versions of
Visual Basic, these format characters are case-sensitive.
Ch Description
ara
cte
r
(:) Time separator. In some locales, other characters may be used to represent the time separator. The time separator separat
es hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in format
ted output is determined by your application's current culture value.

(/) Date separator. In some locales, other characters may be used to represent the date separator. The date separator separate
s the day, month, and year when date values are formatted. The actual character used as the date separator in formatted o
utput is determined by your application's current culture.

(%) Used to indicate that the following character should be read as a single-letter format without regard to any trailing letters.
Also used to indicate that a single-letter format is read as a user-defined format. See below for further details.

d Displays the day as a number without a leading zero (for example, 1). Use %d if this is the only character in your user-defi
ned numeric format.

dd Displays the day as a number with a leading zero (for example, 01).

dd Displays the day as an abbreviation (for example, Sun).


d

dd Displays the day as a full name (for example, Sunday).


dd

M Displays the month as a number without a leading zero (for example, January is represented as 1). Use %M if this is the on
ly character in your user-defined numeric format.

M Displays the month as a number with a leading zero (for example, 01/12/01).
M

M Displays the month as an abbreviation (for example, Jan).


M
M

M Displays the month as a full month name (for example, January).


M
M
M

gg Displays the period/era string (for example, A.D.)

h Displays the hour as a number without leading zeros using the 12-hour clock (for example, 1:15:15 PM). Use %h if this is t
he only character in your user-defined numeric format.

hh Displays the hour as a number with leading zeros using the 12-hour clock (for example, 01:15:15 PM).

H Displays the hour as a number without leading zeros using the 24-hour clock (for example, 1:15:15). Use %H if this is the
only character in your user-defined numeric format.
HH Displays the hour as a number with leading zeros using the 24-hour clock (for example, 01:15:15).

m Displays the minute as a number without leading zeros (for example, 12:1:15). Use %m if this is the only character in your
user-defined numeric format.

m Displays the minute as a number with leading zeros (for example, 12:01:15).
m

s Displays the second as a number without leading zeros (for example, 12:15:5). Use %s if this is the only character in your
user-defined numeric format.

ss Displays the second as a number with leading zeros (for example, 12:15:05).

f Displays fractions of seconds. For example ff will display hundredths of seconds, whereas ffff will display ten-thousandths
of seconds. You may use up to seven f symbols in your user-defined format. Use %f if this is the only character in your us
er-defined numeric format.

t Uses the 12-hour clock and displays an uppercase A for any hour before noon; displays an uppercase P for any hour betwe
en noon and 11:59 P.M. Use %t if this is the only character in your user-defined numeric format.

tt For locales that use a 12-hour clock, displays an uppercase AM with any hour before noon; displays an uppercase PM with a
ny hour between noon and 11:59 P.M.
For locales that use a 24-hour clock, displays nothing.

y Displays the year number (0-9) without leading zeros. Use %y if this is the only character in your user-defined numeric for
mat.

yy Displays the year in two-digit numeric format with a leading zero, if applicable.

yy Displays the year in four-digit numeric format.


y

yy Displays the year in four-digit numeric format.


yy

z Displays the timezone offset without a leading zero (for example, -8). Use %z if this is the only character in your user-defi
ned numeric format.

zz Displays the timezone offset with a leading zero (for example, -08)

zzz Displays the full timezone offset (for example, -08:00)

For more information about the application's current culture information, see How Culture Affects Strings in Visual Basic.
Example
The following are examples of user-defined date and time formats for December 7, 1958, 8:50 PM, 35 seconds:

Format Displays
M/d/yy 12/7/58

d-MMM 7-Dec

d-MMMM-yy 7-December-58

d MMMM 7 December
MMMM yy December 58

hh:mm tt 08:50 PM

h:mm:ss t 8:50:35 P

H:mm 20:50

H:mm:ss 20:50:35

M/d/yyyy H:mm 12/7/1958 20:50

Smart Device Developer Notes


The minimum time resolution for a device is determined by the manufacturer of the device. If the time resolution for the device
is coarse enough, the f format character returns 0 when run on that device.
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Conversion Summary
Format Function
Predefined Date/Time Formats (Format Function)
User-Defined Numeric Formats (Format Function)
Visual Basic Language Reference

User-Defined Numeric Formats (Format Function)


The following table identifies characters you can use to create user-defined number formats. These may be used to build the
Style argument for the Format function:
C Description
h
a
r
a
ct
e
r
N Displays the number with no formatting.
o
n
e

(0 Digit placeholder. Displays a digit or a zero. If the expression has a digit in the position where the zero appears in the format
) string, display it; otherwise, displays a zero in that position.
If the number has fewer digits than there are zeros (on either side of the decimal) in the format expression, displays leading
or trailing zeros. If the number has more digits to the right of the decimal separator than there are zeros to the right of the d
ecimal separator in the format expression, rounds the number to as many decimal places as there are zeros. If the number h
as more digits to the left of the decimal separator than there are zeros to the left of the decimal separator in the format expr
ession, displays the extra digits without modification.

(# Digit placeholder. Displays a digit or nothing. If the expression has a digit in the position where the # character appears in th
) e format string, displays it; otherwise, displays nothing in that position.
This symbol works like the 0 digit placeholder, except that leading and trailing zeros aren't displayed if the number has fewe
r digits than there are # characters on either side of the decimal separator in the format expression.

(.) Decimal placeholder. The decimal placeholder determines how many digits are displayed to the left and right of the decimal
separator. If the format expression contains only # characters to the left of this symbol; numbers smaller than 1 begin with a
decimal separator. To display a leading zero displayed with fractional numbers, use zero as the first digit placeholder to the l
eft of the decimal separator. In some locales, a comma is used as the decimal separator. The actual character used as a deci
mal placeholder in the formatted output depends on the number format recognized by your system. Thus, you should use t
he period as the decimal placeholder in your formats even if you are in a locale that uses a comma as a decimal placeholder.
The formatted string will appear in the format correct for the locale.

( Percent placeholder. Multiplies the expression by 100. The percent character (%) is inserted in the position where it appears
% in the format string.
)
(,) Thousand separator. The thousand separator separates thousands from hundreds within a number that has four or more pl
aces to the left of the decimal separator. Standard use of the thousand separator is specified if the format contains a thousa
nd separator surrounded by digit placeholders (0 or #).
A thousand separator immediately to the left of the decimal separator (whether or not a decimal is specified) or as the right
most character in the string means "scale the number by dividing it by 1,000, rounding as needed." Numbers smaller than 1
,000 but greater or equal to 500 are displayed as 1, and numbers smaller than 500 are displayed as 0. Two adjacent thousan
d separators in this position scale by a factor of 1 million, and an additional factor of 1,000 for each additional separator.
Multiple separators in any position other than immediately to the left of the decimal separator or the rightmost position in t
he string are treated simply as specifying the use of a thousand separator. In some locales, a period is used as a thousand se
parator. The actual character used as the thousand separator in the formatted output depends on the Number Format recog
nized by your system. Thus, you should use the comma as the thousand separator in your formats even if you are in a locale
that uses a period as a thousand separator. The formatted string will appear in the format correct for the locale.
For example, consider the three following format strings:
"#,0.", which uses the thousands separator to format the number 100 million as the string "100,000,000".

"#0,.", which uses scaling by a factor of one thousand to format the number 100 million as the string "100000".

"#,0,.", which uses the thousands separator and scaling by one thousand to format the number 100 million as the st
ring "100,000".
(:) Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates
hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted o
utput is determined by your system settings.

(/ Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates
) the day, month, and year when date values are formatted. The actual character used as the date separator in formatted outp
ut is determined by your system settings.

(E Scientific format. If the format expression contains at least one digit placeholder (0 or #) to the left of E-, E+, e-, or e+, the n
- umber is displayed in scientific format and E or e is inserted between the number and its exponent. The number of digit plac
E eholders to the left determines the number of digits in the exponent. Use E- or e- to place a minus sign next to negative exp
+ onents. Use E+ or e+ to place a minus sign next to negative exponents and a plus sign next to positive exponents. You must
e also include digit placeholders to the right of this symbol to get correct formatting.
-
e
+
)

- Literal characters. These characters are displayed exactly as typed in the format string. To display a character other than one
+ of those listed, precede it with a backslash (\) or enclose it in double quotation marks (" ").
$
()

(\ Displays the next character in the format string. To display a character that has special meaning as a literal character, preced
) e it with a backslash (\). The backslash itself isn't displayed. Using a backslash is the same as enclosing the next character in
double quotation marks. To display a backslash, use two backslashes (\\).
Examples of characters that can't be displayed as literal characters are the date-formatting and time-formatting characters (
a, c, d, h, m, n, p, q, s, t, w, y, /, and :), the numeric-formatting characters (#, 0, %, E, e, comma, and period), and the string-fo
rmatting characters (@, &, <, >, and !).

(" Displays the string inside the double quotation marks (" "). To include a string in the style argument from within code, you
A must use Chr(34) to enclose the text (34 is the character code for a quotation mark (")).
B
C
")
Example
The following table contains some sample format expressions for numbers. (These examples all assume that your system's
locale setting is English-U.S.) The first column contains the format strings for the Style argument of the Format function; the
other columns contain the resulting output if the formatted data has the value given in the column headings.
Format (Style) "5" formatted as "-5" formatted as "0.5" formatted as
Zero-length string ("") 5 -5 0.5

0 5 -5 1

0.00 5.00 -5.00 0.50

#,##0 5 -5 1

$#,##0;($#,##0) $5 ($5) $1

$#,##0.00;($#,##0.00) $5.00 ($5.00) $0.50

0% 500% -500% 50%

0.00% 500.00% -500.00% 50.00%

0.00E+00 5.00E+00 -5.00E+00 5.00E-01

0.00E-00 5.00E00 -5.00E00 5.00E-01

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Conversion Summary
Different Formats for Different Numeric Values (Format Function)
Format Function
Predefined Numeric Formats (Format Function)
User-Defined Date/Time Formats (Format Function)
Visual Basic Language Reference

FormatCurrency Function (Visual Basic)


Returns an expression formatted as a currency value using the currency symbol defined in the system control panel.

Function FormatCurrency(
ByVal Expression As Object,
Optional ByVal NumDigitsAfterDecimal As Integer = -1,
Optional ByVal IncludeLeadingDigit As TriState = TriState.UseDefault,
Optional ByVal UseParensForNegativeNumbers As TriState = TriState.UseDefault,
Optional ByVal GroupDigits As TriState = TriState.UseDefault
) As String

Parameters
Expression
Required. Expression to be formatted.
NumDigitsAfterDecimal
Optional. Numeric value indicating how many places are displayed to the right of the decimal. Default value is –1, which
indicates that the computer's regional settings are used.
IncludeLeadingDigit
Optional. TriState enumeration that indicates whether or not a leading zero is displayed for fractional values. See "Settings"
for values.
UseParensForNegativeNumbers
Optional. TriState enumeration that indicates whether or not to place negative values within parentheses. See "Settings" for
values.
GroupDigits
Optional. TriState enumeration that indicates whether or not numbers are grouped using the group delimiter specified in the
computer's regional settings. See "Settings" for values.
Settings
The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments take the following TriState enumeration
values.
Value Description
TriState.True True

TriState.False False

TriState.UseDefault The computer's regional settings


Exceptions
Exception type Error number Condition
ArgumentException 5 Number of digits after decimal point is greater than 99.

InvalidCastException 13 Type is not numeric.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
When one or more optional arguments are omitted, the computer's matching regional-settings values are used instead.
The position of the currency symbol relative to the currency value is determined by the system's regional settings.
Note
All settings information comes from the locale of the application. By default, that will be the locale set in the control panel. Ho
wever, it may be changed programmatically by using the .NET Framework, except leading zero, which comes from the Num
ber tab.

Example
The following example illustrates the use of the FormatCurrency function.
VB
Dim TestDebt As Double = -4456.43
Dim TestString As String
' Returns "($4,456.43)".
TestString = FormatCurrency(TestDebt, , , TriState.True, TriState.True)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
FormatDateTime Function (Visual Basic)
FormatNumber Function (Visual Basic)
FormatPercent Function (Visual Basic)
TriState Enumeration
ArgumentException
InvalidCastException
Visual Basic Language Reference

FormatDateTime Function (Visual Basic)


Returns a string expression representing a date/time value.

Function FormatDateTime(
ByVal Expression As DateTime,
Optional ByVal NamedFormat As DateFormat = DateFormat.GeneralDate
) As String

Parameters
Expression
Required. Date expression to be formatted.
NamedFormat
Optional. Numeric value that indicates the date/time format used. If omitted, DateFormat.GeneralDate is used.
Settings
The NamedFormat argument has the following settings.
Constant Description
DateFormat.Gener Display a date and/or time. Display a date part as a short date. If there is a time part, display it as a long ti
alDate me. If present, both parts display.

DateFormat.Long Display a date using the long date format specified in your computer's regional settings.
Date

DateFormat.Short Display a date using the short date format specified in your computer's regional settings.
Date

DateFormat.LongT Display a time using the time format specified in your computer's regional settings.
ime

DateFormat.Short Display a time using the 24-hour format (hh:mm).


Time
Exceptions
Exception type Error number Condition
ArgumentException 5 NamedFormat setting is not valid.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Date data type always contains both date and time information. For purposes of type conversion, Visual Basic considers
1/1/1 (January 1 of the year 1) to be a neutral value for the date, and 00:00:00 (midnight) to be a neutral value for the time. If
you format a Date value as a date/time string, FormatDateTime does not include neutral values in the resulting string. For
example, if you convert #1/1/0001 9:30:00# to a string, the result is "9:30:00 AM"; the date information is suppressed.
However, the date information is still present in the original Date value and can be recovered with functions such as DatePart.
Note
If you pass the Expression argument as a String literal, FormatDateTime interprets it according to the CurrentCulture settin
g of your application. However, if you pass it as a Date literal, use the format #mm/dd/yyyy#, because FormatDateTime al
ways interprets a Date literal according to the English (US) culture. This is necessary because, if an application is developed a
nd coded using Date literals from one culture, but is then executed on a platform with a different culture, the Date literals co
uld be parsed incorrectly.

Example
This example demonstrates the use of the FormatDateTime function.
VB
' English (US) format.
Dim TestDate As DateTime = #3/12/1999#

' FormatDateTime returns "Friday, March 12, 1999".


' The time information is neutral (00:00:00) and therefore suppressed.
Dim TestString As String = FormatDateTime(TestDate, DateFormat.LongDate)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
FormatCurrency Function (Visual Basic)
FormatNumber Function (Visual Basic)
FormatPercent Function (Visual Basic)
DatePart Function (Visual Basic)
String Manipulation Summary
ArgumentException
Visual Basic Language Reference

FormatNumber Function (Visual Basic)


Returns an expression formatted as a number.

Function FormatNumber(
ByVal Expression As Object,
Optional ByVal NumDigitsAfterDecimal As Integer = -1,
Optional ByVal IncludeLeadingDigit As TriState = TriState.UseDefault,
Optional ByVal UseParensForNegativeNumbers As TriState = TriState.UseDefault,
Optional ByVal GroupDigits As TriState = TriState.UseDefault
) As String

Parameters
Expression
Required. Expression to be formatted.
NumDigitsAfterDecimal
Optional. Numeric value indicating how many places are displayed to the right of the decimal. The default value is –1, which
indicates that the computer's regional settings are used.
IncludeLeadingDigit
Optional. TriState constant that indicates whether a leading 0 is displayed for fractional values. See "Settings" for values.
UseParensForNegativeNumbers
Optional. TriState constant that indicates whether to place negative values within parentheses. See "Settings" for values.
GroupDigits
Optional. TriState constant that indicates whether or not numbers are grouped using the group delimiter specified in the
locale settings. See "Settings" for values.
Settings
The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings.
Constant Description
TriState.True True

TriState.False False

TriState.UseDefault The computer's regional settings


Exceptions
Exception type Error number Condition
InvalidCastException 13 Type is not numeric.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
When one or more optional arguments are omitted the values for omitted arguments are provided by the locale settings.
Note
All settings information comes from the locale of the application. By default, that will be the locale set in the control panel. Ho
wever, it may be changed programmatically by using the .NET Framework.
Example
This example demonstrates the FormatNumber function.
VB
Dim TestNumber As Integer = 45600
' Returns "45,600.00".
Dim TestString As String = FormatNumber(TestNumber, 2, , , TriState.True)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
FormatCurrency Function (Visual Basic)
FormatDateTime Function (Visual Basic)
FormatPercent Function (Visual Basic)
TriState Enumeration
InvalidCastException
Visual Basic Language Reference

FormatPercent Function (Visual Basic)


Returns an expression formatted as a percentage (that is, multiplied by 100) with a trailing % character.

Function FormatPercent(
ByVal Expression As Object,
Optional ByVal NumDigitsAfterDecimal As Integer = -1,
Optional ByVal IncludeLeadingDigit As TriState = TriState.UseDefault,
Optional ByVal UseParensForNegativeNumbers As TriState = TriState.UseDefault,
Optional ByVal GroupDigits As TriState = TriState.UseDefault
) As String

Parameters
Expression
Required. Expression to be formatted.
NumDigitsAfterDecimal
Optional. Numeric value indicating how many places to the right of the decimal are displayed. Default value is –1, which
indicates that the locale settings are used.
IncludeLeadingDigit
Optional. TriState constant that indicates whether or not a leading zero displays for fractional values. See "Settings" for
values.
UseParensForNegativeNumbers
Optional. TriState constant that indicates whether or not to place negative values within parentheses. See "Settings" for
values.
GroupDigits
Optional. TriState constant that indicates whether or not numbers are grouped using the group delimiter specified in the
locale settings. See "Settings" for values.
Settings
The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings.
Constant Description
TriState.True True

TriState.False False

TriState.Default The computer's regional settings


Exceptions
Exception type Error number Condition
InvalidCastException 13 Type is not numeric.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
When one or more optional arguments are omitted, the values for omitted arguments are provided by the locale settings.
Note
All settings information comes from the locale of the application. By default, that will be the locale set in the control panel. Ho
wever, it may be changed programmatically by using the .NET Framework.

Example
This example illustrates the use of the FormatPercent function.
VB
Dim TestNumber As Single = 0.76
' Returns "76.00%".
Dim TestString As String = FormatPercent(TestNumber)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
FormatCurrency Function (Visual Basic)
FormatDateTime Function (Visual Basic)
FormatNumber Function (Visual Basic)
TriState Enumeration
InvalidCastException
Visual Basic Language Reference

FreeFile Function
Returns an Integer value representing the next file number available for use by the FileOpen function.

Public Function FreeFile() As Integer

Exceptions
Exception type Error number Condition
IOException 67 More than 255 files are in use.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Use FreeFile to supply a file number that is not already in use.
Example
This example uses the FreeFile function to return the next available file number. Five files are opened for output within the
loop, and some sample data is written to each.
VB
Dim count As Integer
Dim fileNumber As Integer
For count = 1 To 5
fileNumber = FreeFile()
FileOpen(fileNumber, "TEST" & count & ".TXT", OpenMode.Output)
PrintLine(fileNumber, "This is a sample.")
FileClose(fileNumber)
Next

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
FileOpen Function
IOException Class
Other Resources
Writing to Files in Visual Basic
Visual Basic Language Reference

FV Function
Returns a Double specifying the future value of an annuity based on periodic, fixed payments and a fixed interest rate.

Function FV( _
ByVal Rate As Double, _
ByVal NPer As Double, _
ByVal Pmt As Double, _
Optional ByVal PV As Double = 0, _
Optional ByVal Due As DueDate = DueDate.EndOfPeriod _
) As Double

Parameters
Rate
Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of
10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
NPer
Required. Double specifying total number of payment periods in the annuity. For example, if you make monthly payments
on a four-year car loan, your loan has a total of 4 x 12 (or 48) payment periods.
Pmt
Required. Double specifying payment to be made each period. Payments usually contain principal and interest that doesn't
change over the life of the annuity.
PV
Optional. Double specifying present value (or lump sum) of a series of future payments. For example, when you borrow
money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make. If
omitted, 0 is assumed.
Due
Optional. Object of type DueDate Enumeration that specifies when payments are due. This argument must be either
DueDate.EndOfPeriod if payments are due at the end of the payment period, or DueDate.BegOfPeriod if payments are
due at the beginning of the period. If omitted, DueDate.EndOfPeriod is assumed.
Remarks
An annuity is a series of fixed cash payments made over time. An annuity can be a loan (such as a home mortgage) or an
investment (such as a monthly savings plan).
The Rate and NPer arguments must be calculated using payment periods expressed in the same units. For example, if Rate is
calculated using months, NPer must also be calculated using months.
For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as
dividend checks) is represented by positive numbers.
Example
This example uses the FV function to return the future value of an investment given the percentage rate that accrues per period
(APR / 12), the total number of payments (TotPmts), the payment (Payment), the current value of the investment (PVal), and a
number that indicates whether the payment is made at the beginning or end of the payment period (PayType). Note that
because Payment represents cash paid out, it is a negative number.
VB
Sub TestFV()
Dim TotPmts As Integer
Dim Payment, APR, PVal, Fval As Double
Dim PayType As DueDate
Dim Response As MsgBoxResult
' Define money format.
Dim Fmt As String = "###,###,##0.00"
Payment = CDbl(InputBox("How much do you plan to save each month?"))
APR = CDbl(InputBox("Enter the expected interest annual percentage rate."))
' Ensure proper form.
If APR > 1 Then APR = APR / 100
TotPmts = CInt(InputBox("For how many months do you expect to save?"))
Response = MsgBox("Do you make payments at the end of month?", MsgBoxStyle.YesNo)
If Response = MsgBoxResult.No Then
PayType = DueDate.BegOfPeriod
Else
PayType = DueDate.EndOfPeriod
End If
PVal = CDbl(InputBox("How much is in this savings account now?"))
Fval = FV(APR / 12, TotPmts, -Payment, -PVal, PayType)
MsgBox("Your savings will be worth " & Format(Fval, Fmt) & ".")
End Sub

Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Financial Summary
Visual Basic Language Reference

GetAllSettings Function
Returns a list of key settings and their respective values (originally created with SaveSetting) from an application's entry in
the Windows registry.
Using the My feature gives you greater productivity and performance in registry operations than GetAllSettings. For more
information, see My.Computer.Registry Object.

Public Function GetAllSettings( _


ByVal AppName As String, _
ByVal Section As String _
) As String(,)

Parameters
AppName
Required. String expression containing the name of the application or project whose key settings are requested.
Section
Required. String expression containing the name of the section whose key settings are requested. GetAllSettings returns an
object that contains a two-dimensional array of strings. The strings contain all the key settings in the specified section, plus
their corresponding values.
Exceptions
Exception type Error number Condition
ArgumentException 5 User is not logged in.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
GetAllSettings returns an uninitialized Object if either AppName or Section does not exist.
Because it operates under the HKEY_LOCAL_USER registry key, which is not active until a user logs on interactively,
GetAllSettings requires that a user be logged on.
Registry settings that are to be accessed from a non-interactive process (such as Mtx.exe) should be stored under either the
HKEY_LOCAL_MACHINE\Software\ or the HKEY_USER\DEFAULT\Software registry keys.
Example
This example first uses the SaveSetting function to make entries in the Windows registry for the application specified as
AppName, then uses the GetAllSettings function to display the settings. Note that application names and Section names
cannot be retrieved with GetAllSettings. Finally, the DeleteSetting function removes the application's entries.
VB
' Object to hold 2-dimensional array returned by GetAllSettings.
' Integer to hold counter.
Dim MySettings(,) As String
Dim intSettings As Integer
' Place some settings in the registry.
SaveSetting("MyApp", "Startup", "Top", "75")
SaveSetting("MyApp", "Startup", "Left", "50")
' Retrieve the settings.
MySettings = GetAllSettings("MyApp", "Startup")
For intSettings = LBound(MySettings, 1) To UBound(MySettings, 1)
WriteLine(1, MySettings(intSettings, 0))
WriteLine(1, MySettings(intSettings, 1))
Next intSettings
DeleteSetting("MyApp")
Smart Device Developer Notes
This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DeleteSetting Function
GetSetting Function
SaveSetting Function
ArgumentException Class
Concepts
Common Registry Tasks
Visual Basic Language Reference

GetAttr Function
Returns a FileAttribute value representing the attributes of a file, directory, or folder.
The My feature gives you greater productivity and performance in file I/O operations than FileAttribute. For more
information, see My.Computer.FileSystem Object.

Public Function GetAttr(ByVal PathName As String) As FileAttribute

Parameters
PathName
Required. String expression that specifies a file, directory, or folder name. PathName can include the directory or folder, and
the drive.
Return Value
The value returned by GetAttr is the sum of the following enumeration values:
Value Constant Description
Normal vbNormal Normal.

ReadOnly vbReadOnly Read-only.

Hidden vbHidden Hidden.

System vbSystem System file.

Directory vbDirectory Directory or folder.

Archive vbArchive File has changed since last backup.

Alias vbAlias File has a different name.


Note
These enumerations are specified by the Visual Basic language. The names can be used anywhere in your code in place of the
actual values.

Exceptions
Exception type Error number Condition
IOException 52 Pathname is invalid or contains wildcards.

FileNotFoundException 53 Target file does not exist.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
To determine which attributes are set, use the And operator to perform a bitwise comparison of the value returned by the
GetAttr function and the value of the individual file attribute you want. If the result is not zero, that attribute is set for the
named file. For example, the return value of the following And expression is zero if the Archive attribute is not set:

Result = GetAttr(FName) And vbArchive


A nonzero value is returned if the Archive attribute is set.
Example
This example uses the GetAttr function to determine the attributes of a file and directory or folder.
VB
Dim MyAttr As FileAttribute
' Assume file TESTFILE is normal and readonly.
MyAttr = GetAttr("C:\TESTFILE.txt") ' Returns vbNormal.

' Test for normal.


If (MyAttr And FileAttribute.Normal) = FileAttribute.Normal Then
MsgBox("This file is normal.")
End If

' Test for normal and readonly.


Dim normalReadonly As FileAttribute
normalReadonly = FileAttribute.Normal Or FileAttribute.ReadOnly
If (MyAttr And normalReadonly) = normalReadonly Then
MsgBox("This file is normal and readonly.")
End If

' Assume MYDIR is a directory or folder.


MyAttr = GetAttr("C:\MYDIR")
If (MyAttr And FileAttribute.Directory) = FileAttribute.Directory Then
MsgBox("MYDIR is a directory")
End If

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
And Operator (Visual Basic)
FileAttr Function
SetAttr Function
IOException Class
FileNotFoundException Class
FileAttribute Enumeration
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference

GetChar Function
Returns a Char value representing the character from the specified index in the supplied string.

Public Shared Function GetChar( _


ByVal str As String, _
ByVal Index As Integer _
) As Char

Parameters
str
Required. Any valid String expression.
Index
Required. Integer expression. The (1-based) index of the character in str to be returned.
Exceptions
Exception type Error number Condition
ArgumentException 5 str is Nothing, Index < 1, or Index is greater than index of last character of str.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If Index is less than 1 or greater than the index of the last character in str, an ArgumentException is thrown.
Example
This example shows how to use the GetChar function to return a character from a specified index in a String.
VB
Dim TestString As String = "ABCDE"
Dim TestChar As Char
' Returns "D"
TestChar = GetChar(TestString, 4)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Mid Function (Visual Basic)
ArgumentException
Visual Basic Language Reference

GetException Function
Returns the exception representing the error that occurred.

Overridable Public Function GetException() As Exception

Remarks
The GetException function is available only from the Err object class. It works with the Exception property of the Err object
to display the error that has occurred.
Example
The following code displays the message assigned to the exception in the Err object:
VB
On Error Resume Next
Dim myError As System.Exception
' Generate an overflow exception.
Err.Raise(6)
' Assigns the exception from the Err object to myError.
myError = Err.GetException()
' Displays the message associated with the exception.
MsgBox(myError.Message)

Requirements
Namespace: Microsoft.VisualBasic
Class: Err Object
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Retrieve Information from an Error Object
Reference
Err Object (Visual Basic)
Concepts
Structured Exception Handling Overview for Visual Basic
Unstructured Exception Handling Overview
Visual Basic Language Reference

GetObject Function (Visual Basic)


Returns a reference to an object provided by a COM component.

Public Function GetObject( _


Optional ByVal PathName As String = Nothing, _
Optional ByVal [Class] As String = Nothing _
) As Object

Parameters
Parame Description
ter
PathNa Optional. String. The full path and name of the file containing the object to retrieve. If PathName is omitted or is a ze
me ro-length string (""), Class is required.

Class Required if PathName is not supplied. String. A string representing the class of the object. The Class argument has th
e following syntax and parts:
appname . objecttype
Parameter Description
appname Required. String. The name of the application providing the object.

objecttype Required. String. The type or class of object to create.


Exceptions
Exception type Error number Condition
Exception 429 No object of the specified class type exists.

FileNotFoundException 432 No object with the specified path and file name exists.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Use the GetObject function to load an instance of a COM component from a file. The following example illustrates this.

Dim CADObject As Object


CADObject = GetObject("C:\CAD\schema.cad")

When this code runs, the application associated with the specified PathName is started and the object in the specified file is
activated.
Default Cases
If PathName is a zero-length string (""), GetObject returns a new object instance of the specified class type. If the PathName
argument is omitted, GetObject returns a currently active object of the class type specified in Class. If no object of the specified
type exists, an error occurs.
Accessing a Subobject
Some applications allow you to activate a subobject associated with a file. To do this, add an exclamation point (!) to the end of
the file name and follow it with a string that identifies the part of the file you want to activate. For information on how to create
this string, see the documentation for the application that created the object.
For example, in a drawing application you might have multiple layers to a drawing stored in a file. You could use the following
code to activate a layer within a drawing called schema.cad.
layerObject = GetObject("C:\CAD\schema.cad!Layer3")

Specifying a Class
If you do not specify the object's Class, Automation determines the application to start and the object to activate, based on the
file name you provide. Some files, however, can support more than one class of object. For example, a drawing might support
three different types of objects: an Application object, a Drawing object, and a Toolbar object, all of which are part of the same
file. To specify which object in a file you want to activate, use the optional Class argument. The following example illustrates
this.

Dim drawObj As Object


drawObj = GetObject("C:\Drawings\sample.drw", "Figment.Drawing")

In the preceding example, Figment is the name of a drawing application and Drawing is one of the object types it supports.
Using the Object
Once an object is activated, you refer to it in code using the object variable you declared. In the preceding example, you access
properties and methods of the new object using the object variable drawObj. The following example illustrates this.

drawObj.Line(9, 90)
drawObj.InsertText(9, 100, "Hello, world.")
drawObj.SaveAs("C:\Drawings\sample.drw")

Note
Use the GetObject function when there is a current instance of the object or if you want to create the object with a file loade
d. If there is no current instance, and you do not want the object started with a file loaded, use the
CreateObject Function (Visual Basic).
If an object has registered itself as an ActiveX single-instance object, only one instance of the object is created, no matter how
many times CreateObject is called. With a single-instance object, GetObject always returns the same instance when called
with the zero-length string ("") syntax, and it causes an error if the PathName argument is omitted. You cannot use GetObje
ct to obtain a reference to a class created with Visual Basic.

Security Note
The GetObject function requires unmanaged code permission, which might affect its execution in partial-trust situations. For
more information, see SecurityPermission and Code Access Permissions.

When you are finished using the object, set all references to the object to Nothing. This allows the runtime to dispose of the
COM component.
Example
The following example uses the GetObject function to determine whether Excel is running.
VB
' Test to see if a copy of Excel is already running.
Private Sub testExcelRunning()
On Error Resume Next
' GetObject called without the first argument returns a
' reference to an instance of the application. If the
' application is not already running, an error occurs.
Dim excelObj As Object = GetObject(, "Excel.Application")
If Err.Number = 0 Then
MsgBox("Excel is running")
Else
MsgBox("Excel is not running")
End If
Err.Clear()
excelObj = Nothing
End Sub
The following example uses the GetObject function to obtain a reference to a specific Microsoft Excel worksheet (excelObj).
The call to GetObject returns a reference to the worksheet represented by the specified file, test.xls. Next, the example code
makes both Excel and the window containing the specified worksheet visible.
This example requires Option Strict Off because it uses late binding, where objects are assigned to variables of type Object.
You can specify Option Strict On and declare objects of specific object types if you add a project reference to the Excel type
library. To do so, open the Add Reference dialog box from the Project menu in Visual Studio and select the Excel type library
on the COM tab.
VB
' Add Option Strict Off to the top of your program.
Option Strict Off

VB
Private Sub getExcel()
Dim fileName As String = "c:\vb\test.xls"

If Not My.Computer.FileSystem.FileExists(fileName) Then


MsgBox(fileName & " does not exist")
Exit Sub
End If
' Set the object variable to refer to the file you want to use.
Dim excelObj As Object = GetObject(fileName)
' Show Excel through its Application property.
excelObj.Application.Visible = True
' Show the window containing the file.
Dim winCount As Integer = excelObj.Parent.Windows.Count()
excelObj.Parent.Windows(winCount).Visible = True
' Insert additional code to manipulate the test.xls file here.
' ...

excelObj = Nothing
End Sub

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
CreateObject Function (Visual Basic)
Declare Statement
Option Strict Statement
Exception
FileNotFoundException
Visual Basic Language Reference

GetSetting Function
Returns a key setting value from an application's entry in the Windows registry.
The My feature gives you greater productivity and performance in registry operations than GetAllSettings. For more
information, see My.Computer.Registry Object.

Public Function GetSetting( _


ByVal AppName As String, _
ByVal Section As String, _
ByVal Key As String, _
Optional ByVal Default As String = "" _
) As String

Parameters
AppName
Required. String expression containing the name of the application or project whose key setting is requested.
Section
Required. String expression containing the name of the section in which the key setting is found.
Key
Required. String expression containing the name of the key setting to return.
Default
Optional. Expression containing the value to return if no value is set in the Key setting. If omitted, Default is assumed to be a
zero-length string ("").
Exceptions
Exception type Error number Condition
ArgumentException 5 One or more arguments are not String expressions, or user is not logged in.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If any of the items named in the GetSetting arguments do not exist, GetSetting returns a value of Default.
Because it operates under the HKEY_LOCAL_USER registry key, which is not active until a user logs on interactively,
GetSetting requires that a user be logged on.
Registry settings that are to be accessed from a non-interactive process (such as Mtx.exe) should be stored under either the
HKEY_LOCAL_MACHINE\Software\ or the HKEY_USER\DEFAULT\Software registry keys.
GetSetting requires Read Registry Permission.
Example
This example first uses the SaveSetting function to make entries in the Windows registry for the application specified as
AppName, and then uses the GetSetting function to display one of the settings. Because the Default argument is specified,
some value is guaranteed to be returned. Notice that Section names cannot be retrieved with GetSetting. Finally, the
DeleteSetting function removes all the application's entries.
VB
' Place some settings in the registry.
SaveSetting("MyApp", "Startup", "Top", "75")
SaveSetting("MyApp", "Startup", "Left", "50")
Console.WriteLine(GetSetting("MyApp", "Startup", "Left", "25"))
DeleteSetting("MyApp")
Smart Device Developer Notes
This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DeleteSetting Function
GetAllSettings Function
SaveSetting Function
ArgumentException Class
RegistryPermission Class
Concepts
Common Registry Tasks
Visual Basic Language Reference

H-L Functions
The following table contains a listing of the Visual Basic run-time member functions.

Hex Hour IIf Input

InputBox InputString InStr InStrRev

Int IPmt IRR IsArray

IsDate IsDBNull IsError IsNothing

IsNumeric IsReference Join Kill

LBound LCase Left Len

LineInput Loc Lock LOF

LSet LTrim

The math function Log that was available as a Visual Basic run-time member function in version 6.0 and earlier has been
replaced by a method (Log) in the Math class of the .NET Framework class library. For more information, see
Math Functions (Visual Basic).
Smart Device Developer Notes
The following are not supported in smart device applications: Input, InputString, Kill, LineInput, Loc, Lock, and LOF.
See Also
Reference
A-C Functions
D-G Functions
M-R Functions
S-Z Functions
Other Resources
Visual Basic Reference
Visual Basic Language Reference

Hex Function (Visual Basic)


Returns a string representing the hexadecimal value of a number.

Public Shared Function Hex( _


ByVal Number As { Byte | SByte | Short | UShort |
Integer | UInteger | Long | ULong | Object } _
) As String

Parameters
Number
Required. Any valid numeric expression or String expression.
Exceptions
Exception type Error number Condition
ArgumentNullException 5 Number is not specified.

ArgumentException 5 Number is not a numeric type.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If Number is not already a whole number, it is rounded to the nearest whole number before being evaluated.
If Number is Hex returns
Empty Zero (0)

Any numeric value Up to sixteen hexadecimal characters

You can represent hexadecimal numbers directly by preceding numbers in the proper range with &H. For example, &H10
represents decimal 16 in hexadecimal notation.
Example
This example uses the Hex function to return the hexadecimal value of a number.
VB
Dim TestHex As String
' Returns 5.
TestHex = Hex(5)
' Returns A.
TestHex = Hex(10)
' Returns 1CB.
TestHex = Hex(459)

Requirements
Namespace: Microsoft.VisualBasic
Module: Conversion
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Convert Hexadecimal Strings to Numbers
Reference
Oct Function
Type Conversion Functions
ArgumentNullException
Visual Basic Language Reference

Hour Function (Visual Basic)


Returns an Integer value from 0 through 23 representing the hour of the day.

Public Function Hour(ByVal TimeValue As DateTime) As Integer

Parameters
TimeValue
Required. Date value from which you want to extract the hour.
Remarks
You can also obtain the hour of the day by calling DatePart and specifying DateInterval.Hour for the Interval argument.
Example
This example uses the Hour function to obtain the hour from a specified time. In the development environment, the time literal
is displayed in short time format using the locale settings of your code.
VB
Dim someTime As Date
Dim someHour As Integer
someTime = #4:35:17 PM#
someHour = Hour(someTime)
' someHour now contains 16.

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Day Function (Visual Basic)
Minute Function
Now Property
Second Function (Visual Basic)
TimeOfDay Property
DatePart Function (Visual Basic)
System
DateTime
ArgumentException
ArgumentOutOfRangeException
Visual Basic Language Reference

IIf Function
Returns one of two objects, depending on the evaluation of an expression.

Public Function IIf( _


ByVal Expression As Boolean, _
ByVal TruePart As Object, _
ByVal FalsePart As Object _
) As Object

Parameters
Expression
Required. Boolean. The expression you want to evaluate.
TruePart
Required. Object. Returned if Expression evaluates to True.
FalsePart
Required. Object. Returned if Expression evaluates to False.
Remarks
The IIf function provides a counterpart for the ternary Conditional Operator: ? : in Visual C++.
Example
This example uses the IIf function to evaluate the testMe parameter of the checkIt procedure and returns the word "Large" if
the amount is greater than 1000; otherwise, it returns the word "Small".
VB
Function checkIt(ByVal testMe As Integer) As String
Return CStr(IIf(testMe > 1000, "Large", "Small"))
End Function

Note that if Option Strict is On, you must use the CStr keyword to explicitly convert the return from Object to String.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Option Strict Statement
Type Conversion Functions
Choose Function
If...Then...Else Statement (Visual Basic)
Select...Case Statement (Visual Basic)
Switch Function
Visual Basic Language Reference

Input Function
Reads data from an open sequential file and assigns the data to variables.

Public Sub Input( _


FileNumber As Integer, _
ByRef Value As Object _
)

Parameters
FileNumber
Required. Any valid file number.
Value
Required. Variable that is assigned the values read from the file—cannot be an array or object variable.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.

IOException 54 File mode is invalid.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Input function is provided for backward compatibility and may have an impact on performance. For non-legacy
applications, the My.Computer.FileSystem object provides better performance. For more information, see
File Access with Visual Basic.
Data read with Input is usually written to a file with Write. Use this function only with files opened in Input or Binary mode.
Security Note
When reading from files, do not make decisions about the contents of the file based on the file name extension. For example,
a file named Form1.vb may not be a Visual Basic 2005 source file.

When read, standard string or numeric data is assigned to variables without modification. The following table illustrates how
other input data is treated.
Data Value assigned to variable
Delimiting comma or blank line Empty

#NULL# DBNull

#TRUE# or #FALSE# True or False

#yyyy-mm-dd hh:mm:ss# The date and/or time represented by the expression

#ERROR errornumber# errornumber (variable is an object tagged as an error)

If you reach the end of the file while you are inputting a data item, the input is terminated and an error occurs.
Note
The Input function is not localized. For example, in the German version, if you input 3,14159, it returns only 3, since the com
ma is treated as a variable separator rather than a decimal point.

Security Note
Reading from a file with the Input function requires Read access from the FileIOPermissionAccess enumeration. For more
information, see FileIOPermissionAccess Enumeration.

Example
This example uses the Input function to read data from a file into two variables. This example assumes that TestFile is a file
with a few lines of data written to it using the Write function, each line containing a string in quotations and a number
separated by a comma, for example: ("Hello", 234).
VB
FileOpen(1, "TESTFILE", OpenMode.Output)
Write(1, "hello")
Write(1, 14)
FileClose(1)
Dim s As String = "teststring"
Dim i As Integer
FileOpen(1, "TESTFILE", OpenMode.Input)
Input(1, s)
MsgBox(s)
Input(1, i)
MsgBox(i)
FileClose(1)

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Write Text to Files in Visual Basic
How to: Write Text to Files with a StreamWriter in Visual Basic
Reference
InputString Function
FileOpen Function
Print, PrintLine Functions
Write, WriteLine Functions
Other Resources
File Access with Visual Basic
Visual Basic Language Reference

InputBox Function (Visual Basic)


Displays a prompt in a dialog box, waits for the user to input text or click a button, and then returns a string containing the
contents of the text box.

Public Function InputBox( _


ByVal Prompt As String, _
Optional ByVal Title As String = "", _
Optional ByVal DefaultResponse As String = "", _
Optional ByVal Xpos As Integer = -1, _
Optional ByVal YPos As Integer = -1 _
) As String

Parameters
Prompt
Required String expression displayed as the message in the dialog box. The maximum length of Prompt is approximately
1024 characters, depending on the width of the characters used. If Prompt consists of more than one line, you can separate
the lines using a carriage return character (Chr(13)), a line feed character (Chr(10)), or a carriage return/line feed
combination (Chr(13) & Chr(10)) between each line.
Title
Optional. String expression displayed in the title bar of the dialog box. If you omit Title, the application name is placed in the
title bar.
DefaultResponse
Optional. String expression displayed in the text box as the default response if no other input is provided. If you omit
DefaultResponse, the displayed text box is empty.
XPos
Optional. Numeric expression that specifies, in pixels, the distance of the left edge of the dialog box from the left edge of the
screen. If you omit XPos and YPos, the dialog box is centered on the screen.
YPos
Optional. Numeric expression that specifies, in pixels, the distance of the upper edge of the dialog box from the top of the
screen. If you omit XPos and YPos, the dialog box is centered on the screen.
Remarks
If the user clicks Cancel, a zero-length string is returned.
To specify more than the first argument, you must use the InputBox function in an expression. If you omit any positional
arguments, you must retain the corresponding comma delimiter.
Note
The InputBox function requires UIPermission at the SafeTopLevelWindows level, which may affect its execution in partial-tr
ust situations. For more information, see Requesting Permissions and UIPermission Class.

Example
This example shows various ways to use the InputBox function to prompt the user to enter a value. If the x and y positions are
omitted, the dialog box is automatically centered for the respective axes. The variable MyValue contains the value entered by
the user if the user clicks OK or presses the ENTER key.
VB
Dim message, title, defaultValue As String
Dim myValue As Object
' Set prompt.
message = "Enter a value between 1 and 3"
' Set title.
title = "InputBox Demo"
defaultValue = "1" ' Set default value.

' Display message, title, and default value.


myValue = InputBox(message, title, defaultValue)
' If user has clicked Cancel, set myValue to defaultValue
If myValue Is "" Then myValue = defaultValue

' Display dialog box at position 100, 100.


myValue = InputBox(message, title, defaultValue, 100, 100)
' If user has clicked Cancel, set myValue to defaultValue
If myValue Is "" Then myValue = defaultValue

Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
MsgBox Function (Visual Basic)
Chr, ChrW Functions
Visual Basic Language Reference

InputString Function
Returns String value containing characters from a file opened in Input or Binary mode.
The My feature gives you greater productivity and performance in file I/O operations than InputString. For more information,
see My.Computer.FileSystem Object.

InputString(_
ByVal FileNumber As Integer, _
ByVal CharCount As Integer _
) As String

Parameters
FileNumber
Required. Any valid file number.
CharCount
Required. Any valid numeric expression specifying the number of characters to read.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.

ArgumentException 5 CharCount < 0 or > 214.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The InputString function is provided for backward compatibility and may have an impact on performance. For non-legacy
applications, the My.Computer.FileSystem object provides better performance. For more information, see
File Access with Visual Basic.
Data read with the InputString function is usually written to a file with Print or FilePut. Use this function only with files
opened in Input or Binary mode.
Unlike the Input function, the InputString function returns all of the characters it reads, including commas, carriage returns,
line feeds, quotation marks, and leading spaces.
With files opened for Binary access, an attempt to read through the file using the InputString function until EOF returns True
generates an error. Use the LOF and Loc functions instead of EOF when reading binary files with InputString, or use FileGet
when using the EOF function.
Security Note
When reading from files, do not make decisions about the contents of the file based on the file name extension. For example,
a file named Form1.vb may not be a Visual Basic source file.

Example
This example uses the InputString function to read one character at a time from a file and print it to the Output window. This
example assumes that MyFile is a text file with a few lines of sample data.
VB
Dim oneChar As String
' Open file.
FileOpen(1, "MYFILE.TXT", OpenMode.Input)
' Loop until end of file.
While Not EOF(1)
' Get one character.
oneChar = (InputString(1, 1))
' Print to the output window.
System.Console.Out.WriteLine(oneChar)
End While
FileClose(1)

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Write Text to Files with a StreamWriter in Visual Basic
How to: Write Text to Files in Visual Basic
Reference
Input Function
Other Resources
File Access with Visual Basic
Visual Basic Language Reference

InStr Function (Visual Basic)


Returns an integer specifying the start position of the first occurrence of one string within another.

Public Shared Function InStr(_


ByVal String1 As String, _
ByVal String2 As String, _
Optional ByVal Compare As CompareMethod _
) As Integer
' -or-
Public Shared Function InStr(_
ByVal Start As Integer, _
ByVal String1 As String, _
ByVal String2 As String, _
Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod _
) As Integer

Parameters
Start
Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the first character
position. The start index is 1-based.
String1
Required. String expression being searched.
String2
Required. String expression sought.
Compare
Optional. Specifies the type of string comparison. If Compare is omitted, the Option Compare setting determines the type
of comparison.
Settings
The Compare argument settings are:
Constant Value Description
Binary 0 Performs a binary comparison

Text 1 Performs a text comparison


Return Value
If InStr returns
String1 is zero length or Nothing 0

String2 is zero length or Nothing start

String2 is not found 0

String2 is found within String1 Position where match begins

Start > String2 0


Exceptions
Exception type Error number Condition
ArgumentException 5 Start < 1.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Typically, the InStr function is used when parsing strings.
Note
The InStrB function in previous versions of Visual Basic returns a number of bytes rather than a character position. It is used
primarily for converting strings in double-byte character set (DBCS) applications. All Visual Basic 2005 strings are in Unicode,
and InStrB is no longer supported.

Example
This example uses the InStr function to return the position of the first occurrence of one string within another.
VB
' String to search in.
Dim SearchString As String = "XXpXXpXXPXXP"
' Search for "P".
Dim SearchChar As String = "P"
Dim TestPos As Integer
' A textual comparison starting at position 4. Returns 6.
TestPos = InStr(4, SearchString, SearchChar, CompareMethod.Text)

' A binary comparison starting at position 1. Returns 9.


TestPos = InStr(1, SearchString, SearchChar, CompareMethod.Binary)
' If Option Compare is not set, or set to Binary, return 9.
' If Option Compare is set to Text, returns 3.
TestPos = InStr(SearchString, SearchChar)

' Returns 0.
TestPos = InStr(1, SearchString, "W")

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
InStrRev Function (Visual Basic)
Option Compare Statement
StrComp Function (Visual Basic)
ArgumentException
Concepts
Programming Element Support Changes Summary
Other Resources
Strings in Visual Basic
Introduction to Strings in Visual Basic
Visual Basic Language Reference

InStrRev Function (Visual Basic)


Returns the position of the first occurrence of one string within another, starting from the right side of the string.

Public Function InStrRev(


ByVal StringCheck As String,
ByVal StringMatch As String,
Optional ByVal Start As Integer = -1,
Optional ByVal Compare As CompareMethod = CompareMethod.Binary
) As Integer

Parameters
StringCheck
Required. String expression being searched.
StringMatch
Required. String expression being searched for.
Start
Optional. Numeric expression setting the one-based starting position for each search, starting from the left side of the string.
If Start is omitted then –1 is used, meaning the search begins at the last character position. Search then proceeds from right
to left.
Compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. If omitted, a binary
comparison is performed. See Settings for values.
Settings
The Compare argument can have the following values.
Constant Description
Binary Performs a binary comparison.

Text Performs a textual comparison.


Return Value
InStrRev returns the following values.
If InStrRev returns
StringCheck is zero-length 0

StringMatch is zero-length Start

StringMatch is not found 0

StringMatch is found within StringCheck Position at which the first match is found, starting with the right side of the string.

Start is greater than length of StringMatch 0


Exceptions
Exception type Error number Condition
ArgumentException 5 Start = 0 or Start < -1.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Note that the syntax for the InStrRev function is not the same as the syntax for the InStr function.
Example
This example demonstrates the use of the InStrRev function.
VB
Dim TestString As String = "the quick brown fox jumps over the lazy dog"
Dim TestNumber As Integer
' Returns 32.
TestNumber = InStrRev(TestString, "the")
' Returns 1.
TestNumber = InStrRev(TestString, "the", 16)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
InStr Function (Visual Basic)
Other Resources
Strings in Visual Basic
Introduction to Strings in Visual Basic
Visual Basic Language Reference

Int, Fix Functions (Visual Basic)


Return the integer portion of a number.

Public Shared Function Int( _


ByVal Number As { Double | Integer | Long | Object | Short | Single | Decimal }) _
As { Double | Integer | Long | Object | Short | Single | Decimal }
Public Shared Function Fix( _
ByVal Number As { Double | Integer | Long | Object | Short | Single | Decimal }) _
As { Double | Integer | Long | Object | Short | Single | Decimal }

Parameters
Number
Required. A number of type Double or any valid numeric expression. If Number contains Nothing, Nothing is returned.
Exceptions
Exception type Error number Condition
ArgumentNullException 5 Number is not specified.

ArgumentException 5 Number is not a numeric type.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Both the Int and Fix functions remove the fractional part of Number and return the resulting integer value.
The difference between Int and Fix functions is that if Number is negative, Int returns the first negative integer less than or
equal to Number, whereas Fix returns the first negative integer greater than or equal to Number. For example, Int converts -
8.4 to -9, and Fix converts -8.4 to -8.
Fix(number) is equivalent to Sign(number) * Int(Abs(number)).

Example
This example illustrates how the Int and Fix functions return integer portions of numbers. In the case of a negative number
argument, the Int function returns the first negative integer less than or equal to the number; the Fix function returns the first
negative integer greater than or equal to the number. The following example requires you to specify Option Strict Off
because implicit conversions from type Double to type Integer are not allowed under Option Strict On:
VB
' This code requires Option Strict Off
Dim MyNumber As Integer
MyNumber = Int(99.8) ' Returns 99.
MyNumber = Fix(99.8) ' Returns 99.

MyNumber = Int(-99.8) ' Returns -100.


MyNumber = Fix(-99.8) ' Returns -99.
MyNumber = Int(-99.2) ' Returns -100.
MyNumber = Fix(-99.2) ' Returns -99.

You can use the CInt function to explicitly convert other data types to type Integer with Option Strict Off. However, CInt
rounds to the nearest integer instead of truncating the fractional part of numbers. For example:
VB
MyNumber = CInt(99.8) ' Returns 100.
MyNumber = CInt(-99.8) ' Returns -100.
MyNumber = CInt(-99.2) ' Returns -99.

You can use the CInt function on the result of a call to Fix or Int to perform explicit conversion to integer without rounding.
For example:
VB
MyNumber = CInt(Fix(99.8)) ' Returns 99.
MyNumber = CInt(Int(99.8)) ' Returns 99.

For more information on CInt, see Type Conversion Functions.


Requirements
Namespace: Microsoft.VisualBasic
Module: Conversion
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Type Conversion Functions
Integer Data Type (Visual Basic)
Math Summary
Math Functions (Visual Basic)
Conversion Summary
ArgumentNullException
Visual Basic Language Reference

IPmt Function
Returns a Double specifying the interest payment for a given period of an annuity based on periodic, fixed payments and a
fixed interest rate.

Function IPmt( _
ByVal Rate As Double, _
ByVal Per As Double, _
ByVal NPer As Double, _
ByVal PV As Double, _
Optional ByVal FV As Double = 0, _
Optional ByVal Due As DueDate = DueDate.EndOfPeriod _
) As Double

Parameters
Rate
Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of
10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
Per
Required. Double specifying payment period in the range 1 through NPer.
NPer
Required. Double specifying total number of payment periods in the annuity. For example, if you make monthly payments
on a four-year car loan, your loan has a total of 4 x 12 (or 48) payment periods.
PV
Required. Double specifying present value, or value today, of a series of future payments or receipts. For example, when you
borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.
FV
Optional. Double specifying future value or cash balance you want after you've made the final payment. For example, the
future value of a loan is $0 because that's its value after the final payment. However, if you want to save $50,000 over 18
years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
Due
Optional. Object of type DueDate Enumeration that specifies when payments are due. This argument must be either
DueDate.EndOfPeriod if payments are due at the end of the payment period, or DueDate.BegOfPeriod if payments are due at
the beginning of the period. If omitted, DueDate.EndOfPeriod is assumed.
Exceptions
Exception type Error number Condition
ArgumentException 5 Per <= 0 or Per > NPer

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
An annuity is a series of fixed cash payments made over time. An annuity can be a loan (such as a home mortgage) or an
investment (such as a monthly savings plan).
The Rate and NPer arguments must be calculated using payment periods expressed in the same units. For example, if Rate is
calculated using months, NPer must also be calculated using months.
For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as
dividend checks) is represented by positive numbers.
Example
This example uses the IPmt function to calculate how much of a payment is interest when all the payments are of equal value.
Given are the interest percentage rate per period (APR / 12), the payment period for which the interest portion is desired
(Period), the total number of payments (TotPmts), the present value or principal of the loan (PVal), the future value of the loan
(FVal), and a number that indicates whether the payment is due at the beginning or end of the payment period (PayType).
VB
Sub TestIPMT()
Dim APR, PVal, Period, IntPmt, TotInt, TotPmts As Double
Dim PayType As DueDate
Dim Response As MsgBoxResult

' Usually 0 for a loan.


Dim Fval As Double = 0
' Define money format.
Dim Fmt As String = "###,###,##0.00"
PVal = CDbl(InputBox("How much do you want to borrow?"))
APR = CDbl(InputBox("What is the annual percentage rate of your loan?"))
If APR > 1 Then APR = APR / 100 ' Ensure proper form.
TotPmts = CInt(InputBox("How many monthly payments?"))
Response = MsgBox("Do you make payments at end of the month?", MsgBoxStyle.YesNo)
If Response = MsgBoxResult.No Then
PayType = DueDate.BegOfPeriod
Else
PayType = DueDate.EndOfPeriod
End If
For Period = 1 To TotPmts ' Total all interest.
IntPmt = IPmt(APR / 12, Period, TotPmts, -PVal, Fval, PayType)
TotInt = TotInt + IntPmt
Next Period

' Display results.


MsgBox("You will pay a total of " & Format(TotInt, Fmt) & _
" in interest for this loan.")
End Sub

Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Financial Summary
ArgumentException
Visual Basic Language Reference

IRR Function
Returns a Double specifying the internal rate of return for a series of periodic cash flows (payments and receipts).

Function IRR( _
ByRef ValueArray() As Double, _
Optional ByVal Guess As Double = 0.1 _
) As Double

Parameters
ValueArray
Required. Array of Double specifying cash flow values. The array must contain at least one negative value (a payment) and
one positive value (a receipt).
Guess
Optional. Object specifying value you estimate will be returned by IRR. If omitted, Guess is 0.1 (10 percent).
Exceptions
Exception type Error number Condition
ArgumentException 5 Array argument values are invalid or Guess <= -1.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The internal rate of return is the interest rate received for an investment consisting of payments and receipts that occur at
regular intervals.
The IRR function uses the order of values within the array to interpret the order of payments and receipts. Be sure to enter
your payment and receipt values in the correct sequence. The cash flow for each period does not need to be fixed, as it is for an
annuity.
IRR is calculated by iteration. Starting with the value of Guess, IRR cycles through the calculation until the result is accurate to
within 0.00001 percent. If IRR cannot find a result after 20 tries, it fails.
Example
In this example, the IRR function returns the internal rate of return for a series of five cash flows contained in the array
Values(). The first array element is a negative cash flow representing business start-up costs. The remaining four cash flows
represent positive cash flows for the subsequent four years. Guess is the estimated internal rate of return.
VB
' Define money format.
Dim MoneyFmt As String = "###,##0.00"
' Define percentage format.
Dim PercentFmt As String = "#0.00"
Dim values(4) As Double
' Business start-up costs.
values(0) = -70000
' Positive cash flows reflecting income for four successive years.
values(1) = 22000
values(2) = 25000
values(3) = 28000
values(4) = 31000
' Use the IRR function to calculate the rate of return.
' Guess starts at 10 percent.
Dim Guess As Double = 0.1
' Calculate internal rate.
Dim CalcRetRate As Double = IRR(values, Guess) * 100
' Display internal return rate.
MsgBox("The internal rate of return for these cash flows is " & _
Format(CalcRetRate, CStr(PercentFmt)) & " percent.")

Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
NPV Function
MIRR Function
Financial Summary
ArgumentException
Visual Basic Language Reference

IsArray Function (Visual Basic)


Returns a Boolean value indicating whether a variable points to an array.

Public Function IsArray(ByVal VarName As Object) As Boolean

Parameters
VarName
Required. Object variable.
Remarks
IsArray returns True if the variable points to an array; otherwise, it returns False. IsArray is especially useful with objects that
might contain arrays.
Example
This example uses the IsArray function to check if several variables refer to an array.
VB
Dim firstArray(4), secondArray(3) As Integer
Dim thisString As String = "Test"
Dim arrayCheck As Boolean
arrayCheck = IsArray(firstArray)
arrayCheck = IsArray(secondArray)
arrayCheck = IsArray(thisString)
' The first two calls to IsArray return True; the third returns False.

Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Declare an Array Variable
Reference
IsDate Function (Visual Basic)
IsDBNull Function
IsError Function
IsNothing Function
IsNumeric Function (Visual Basic)
IsReference Function
Object Data Type
TypeName Function (Visual Basic)
Visual Basic Language Reference

IsDate Function (Visual Basic)


Returns a Boolean value indicating whether an expression represents a valid Date value.

Public Function IsDate(ByVal Expression As Object) As Boolean

Parameters
Expression
Required. Object expression.
Remarks
IsDate returns True if Expression is of the Date Data Type or can be converted to Date; otherwise, it returns False.
The Date data type holds both a date value and a time value. IsDate returns True if Expression represents a valid date, a valid
time, or a valid date and time.
Example
The following example uses the IsDate function to determine if several variables represent valid Date values.
VB
Dim firstDate, secondDate As Date
Dim timeOnly, dateAndTime, noDate As String
Dim dateCheck As Boolean
firstDate = CDate("February 12, 1969")
secondDate = #2/12/1969#
timeOnly = "3:45 PM"
dateAndTime = "March 15, 1981 10:22 AM"
noDate = "Hello"
dateCheck = IsDate(firstDate)
dateCheck = IsDate(secondDate)
dateCheck = IsDate(timeOnly)
dateCheck = IsDate(dateAndTime)
dateCheck = IsDate(noDate)

In the preceding example, IsDate returns True for the first four calls and False for the last call.
Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IsArray Function (Visual Basic)
IsDBNull Function
IsError Function
IsNothing Function
IsNumeric Function (Visual Basic)
IsReference Function
Object Data Type
Date Data Type (Visual Basic)
TypeName Function (Visual Basic)
Visual Basic Language Reference

IsDBNull Function
Returns a Boolean value indicating whether an expression evaluates to the System.DBNull class.

Public Function IsDBNull(ByVal Expression As Object) As Boolean

Parameters
Expression
Required. Object expression.
Remarks
IsDBNull returns True if the data type of Expression evaluates to the DBNull type; otherwise, IsDBNull returns False.
The System.DBNull value indicates that the Object represents missing or nonexistent data. DBNull is not the same as
Nothing, which indicates that a variable has not yet been initialized. DBNull is also not the same as a zero-length string (""),
which is sometimes referred to as a null string.
Example
This example uses the IsDBNull function to determine if a variable evaluates to DBNull.
VB
Dim testVar As Object
Dim nullCheck As Boolean
nullCheck = IsDBNull(testVar)
testVar = ""
nullCheck = IsDBNull(testVar)
testVar = System.DBNull.Value
nullCheck = IsDBNull(testVar)
' The first two calls to IsDBNull return False; the third returns True.

Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IsArray Function (Visual Basic)
IsDate Function (Visual Basic)
IsError Function
IsNothing Function
IsNumeric Function (Visual Basic)
IsReference Function
Object Data Type
TypeName Function (Visual Basic)
DBNull
Visual Basic Language Reference

IsError Function
Returns a Boolean value indicating whether an expression is an exception type.

Public Function IsError(ByVal Expression As Object) As Boolean

Parameters
Expression
Required. Object expression.
Remarks
IsError returns True if the expression represents an Object variable that derives from the Exception class in the System
namespace.
An exception that derives from System.Exception can be caught with the Try...Catch...Finally statements.
Example
The following example uses the IsError function to check if an expression represents a system exception.
VB
Sub demonstrateIsError(ByVal firstArg As Integer)
Dim returnVal As New Object
Dim badArg As String = "Bad argument value"
Dim errorCheck As Boolean
If firstArg > 10000 Then
returnVal = New System.ArgumentOutOfRangeException(badArg)
End If
errorCheck = IsError(returnVal)
End Sub

Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IsArray Function (Visual Basic)
IsDate Function (Visual Basic)
IsDBNull Function
IsNothing Function
IsNumeric Function (Visual Basic)
IsReference Function
Object Data Type
TypeName Function (Visual Basic)
Visual Basic Language Reference

IsNothing Function
Returns a Boolean value indicating whether an expression has no object assigned to it.

Public Function IsNothing(ByVal Expression As Object) As Boolean

Parameters
Expression
Required. Object expression.
Remarks
IsNothing returns True if the expression represents an object variable that currently has no object assigned to it; otherwise, it
returns False.
IsNothing is intended to work on reference types. A value type cannot hold a value of Nothing and reverts to its default value
if you assign Nothing to it. If you supply a value type in Expression, IsNothing always returns False.
Example
The following example uses the IsNothing function to determine if an object variable is associated with any object instance.
VB
Dim testVar As Object
' No instance has been assigned to variable testVar yet.
Dim testCheck As Boolean
' The following call returns True.
testCheck = IsNothing(testVar)
' Assign a string instance to variable testVar.
testVar = "ABCDEF"
' The following call returns False.
testCheck = IsNothing(testVar)
' Disassociate variable testVar from any instance.
testVar = Nothing
' The following call returns True.
testCheck = IsNothing(testVar)

Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IsArray Function (Visual Basic)
IsDate Function (Visual Basic)
IsDBNull Function
IsError Function
IsNumeric Function (Visual Basic)
IsReference Function
Object Data Type
TypeName Function (Visual Basic)
Concepts
Value Types and Reference Types
Visual Basic Language Reference

IsNumeric Function (Visual Basic)


Returns a Boolean value indicating whether an expression can be evaluated as a number.

Public Function IsNumeric(ByVal Expression As Object) As Boolean

Parameters
Expression
Required. Object expression.
Remarks
IsNumeric returns True if the data type of Expression is Boolean, Byte, Decimal, Double, Integer, Long, SByte, Short,
Single, UInteger, ULong, or UShort, or an Object that contains one of those numeric types. It also returns True if Expression
is a Char or String that can be successfully converted to a number.
IsNumeric returns False if Expression is of data type Date or of data type Object and it does not contain a numeric type.
IsNumeric returns False if Expression is a Char or String that cannot be converted to a number.
Example
The following example uses the IsNumeric function to determine if the contents of a variable can be evaluated as a number.
VB
Dim testVar As Object
Dim numericCheck As Boolean
testVar = "53"
' The following call to IsNumeric returns True.
numericCheck = IsNumeric(testVar)
testVar = "459.95"
' The following call to IsNumeric returns True.
numericCheck = IsNumeric(testVar)
testVar = "45 Help"
' The following call to IsNumeric returns False.
numericCheck = IsNumeric(testVar)

Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IsArray Function (Visual Basic)
IsDate Function (Visual Basic)
IsDBNull Function
IsError Function
IsNothing Function
IsReference Function
Object Data Type
TypeName Function (Visual Basic)
Visual Basic Language Reference

IsReference Function
Returns a Boolean value indicating whether an expression evaluates to a reference type.

Public Function IsReference(ByVal Expression As Object) As Boolean

Parameters
Expression
Required. Object expression.
Remarks
IsReference returns True if Expression represents a reference type, such as a class instance, a String type, or an array of any
type; otherwise, it returns False.
A reference type contains a pointer to data stored elsewhere in memory. A value type contains its own data.
Example
This example uses the IsReference function to check if several variables refer to reference types.
VB
Dim testArray(3) As Boolean
Dim testString As String = "Test string"
Dim testObject As Object = New Object()
Dim testNumber As Integer = 12
testArray(0) = IsReference(testArray)
testArray(1) = IsReference(testString)
testArray(2) = IsReference(testObject)
testArray(3) = IsReference(testNumber)

In the preceding example, the first three calls to IsReference return True. The last call returns False, because Integer is a value
type, not a reference type.
Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IsArray Function (Visual Basic)
IsDate Function (Visual Basic)
IsDBNull Function
IsError Function
IsNothing Function
IsNumeric Function (Visual Basic)
Object Data Type
TypeName Function (Visual Basic)
Concepts
Value Types and Reference Types
Visual Basic Language Reference

Join Function (Visual Basic)


Returns a string created by joining a number of substrings contained in an array.

Function Join(
ByVal SourceArray() As { Object | String },
Optional ByVal Delimiter As String = " "
) As String

Parameters
SourceArray
Required. One-dimensional array containing substrings to be joined.
Delimiter
Optional. Any string, used to separate the substrings in the returned string. If omitted, the space character (" ") is used. If
Delimiter is a zero-length string ("") or Nothing, all items in the list are concatenated with no delimiters.
Exceptions
Exception type Error number Condition
ArgumentException 5 SourceArray is not one dimensional.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
There is a parity between the Join and Split functions. The Join function takes an array of strings and joins them using a
delimiter string, to return a single string. The Split function takes a string and separates it at the delimiter, to return an array of
strings. However, a key difference is that Join can concatenate strings with any delimiter string, Split can only separate strings
using a single character delimiter.
Example
The following example demonstrates how to use the Join function to create a list from several strings.
VB
Dim TestItem() As String = {"Pickle", "Pineapple", "Papaya"}
' Returns "Pickle, Pineapple, Papaya"
Dim TestShoppingList As String = Join(TestItem, ", ")

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Split Function (Visual Basic)
ArgumentException
Visual Basic Language Reference

Kill Function
Deletes files from a disk.
The My feature gives you greater productivity and performance in file I/O operations than Kill. For more information, see
My.Computer.FileSystem Object.

Public Sub Kill(ByVal PathName As String)

Parameters
PathName
Required. String expression that specifies one or more file names to be deleted. PathName can include the directory or
folder, and the drive.
Exceptions
Exception type Error number Condition
IOException 55 Target file(s) open.

FileNotFoundException 53 Target file(s) not found.

SecurityException Permission denied (Visual Basic) Permission denied.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Kill supports the use of multiple-character (*) and single-character (?) wildcards to specify multiple files.
Security Note In order to execute, the Kill function requires Read and PathDiscovery flags of FileIOPermission to be
granted to the executing code. For more information, see SecurityException, and Code Access Permissions
Example
This example uses the Kill function to delete a file from a disk.
VB
' Assume TESTFILE is a file containing some data.
Kill("TestFile") ' Delete file.

' Delete all *.TXT files in current directory.


Kill("*.TXT")

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
RmDir Function
IOException Class
FileNotFoundException Class
Visual Basic Language Reference

LBound Function (Visual Basic)


Returns the lowest available subscript for the indicated dimension of an array.

Public Function LBound( _


ByVal Array As System.Array, _
Optional ByVal Rank As Integer = 1 _
) As Integer

Parameters
Array
Required. Array of any data type. The array in which you want to find the lowest possible subscript of a dimension.
Rank
Optional. Integer. The dimension for which the lowest possible subscript is to be returned. Use 1 for the first dimension, 2
for the second, and so on. If Rank is omitted, 1 is assumed.
Return Value
Integer. The lowest value the subscript for the specified dimension can contain. LBound always returns 0 as long as Array has
been initialized, even if it has no elements, for example if it is a zero-length string. If Array is Nothing, LBound throws an
ArgumentNullException.
Exceptions
Exception type Error number Condition
ArgumentNullException 9 Array is Nothing.

RankException 9 Rank < 1 or Rank is greater than the rank of Array.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Since array subscripts start at 0, the lowest available subscript for every dimension is always 0.
For an array with the following dimensions, LBound returns the values in the following table:

Dim a(100, 5, 4) As Byte

Call to LBound Return value


LBound(a, 1) 0

LBound(a, 2) 0

LBound(a, 3) 0
Example
The following example uses the LBound function to determine the lowest available subscript for the indicated dimension of an
array.
VB
Dim lowest, bigArray(10, 15, 20), littleArray(6) As Integer
lowest = LBound(bigArray, 1)
lowest = LBound(bigArray, 3)
lowest = LBound(littleArray)
' All three calls to LBound return 0.

Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
UBound Function (Visual Basic)
Dim Statement (Visual Basic)
ReDim Statement (Visual Basic)
ArgumentException
RankException
Visual Basic Language Reference

LCase Function (Visual Basic)


Returns a string or character converted to lowercase.

Public Shared Function LCase(ByVal Value As Char) As Char


' -or-
Public Shared Function LCase(ByVal Value As String) As String

Parameters
Value
Required. Any valid String or Char expression.
Remarks
Only uppercase letters are converted to lowercase; all lowercase letters and nonletter characters remain unchanged.
This function uses the application's culture information when manipulating the string so that the case changes are appropriate
for the locale in which the application is being used.
Security Note
If your application makes security decisions based on the result of a comparison or case-change operation, then the operatio
n should use the System.String.Compare(System.String,System.String,System.StringComparison) method, and pass Ordinal
or OrdinalIgnoreCase for the comparisonType argument. For more information, see
How Culture Affects Strings in Visual Basic.

Example
This example uses the LCase function to return a lowercase version of a string.
VB
' String to convert.
Dim UpperCase As String = "Hello World 1234"
' Returns "hello world 1234".
Dim LowerCase As String = LCase(UpperCase)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
UCase Function (Visual Basic)
Other Resources
Strings in Visual Basic
Introduction to Strings in Visual Basic
Visual Basic Language Reference

Left Function (Visual Basic)


Returns a string containing a specified number of characters from the left side of a string.

Public Shared Function Left( _


ByVal str As String, _
ByVal Length As Integer _
) As String

Parameters
str
Required. String expression from which the leftmost characters are returned.
Length
Required. Integer expression. Numeric expression indicating how many characters to return. If 0, a zero-length string ("") is
returned. If greater than or equal to the number of characters in str, the entire string is returned.
Exceptions
Exception type Error number Condition
ArgumentException 5 Length < 0.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
To determine the number of characters in str, use the Len function. If used in a Windows Forms application, or any other class
that has a Left property, you must fully qualify the function with Microsoft.VisualBasic.Left.
Note
The LeftB function in previous versions of Visual Basic returns a string in bytes rather than characters. It is used primarily for
converting strings in double-byte character set (DBCS) applications. All current Visual Basic strings are in Unicode, and LeftB
is no longer supported.

Example
This example demonstrates the use of the Left function to return a substring of a given String. In a class that has a Left
property, it may be necessary to fully qualify the Left function.
VB
Dim TestString As String = "Hello World!"
' Returns "Hello".
Dim subString As String = Microsoft.VisualBasic.Left(TestString, 5)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Right Function (Visual Basic)
Len Function (Visual Basic)
Mid Function (Visual Basic)
ArgumentException
Concepts
Programming Element Support Changes Summary
Visual Basic Language Reference

Len Function (Visual Basic)


Returns an integer containing either the number of characters in a string or the nominal number of bytes required to store a
variable.

Public Shared Function Len( _


ByVal Expression As { Boolean | Byte | SByte | Char | Double |
Integer | UInteger | Long | ULong | Object | Short | UShort |
Single | String | DateTime | Decimal } _
) As Integer

Parameters
Expression
Any valid String expression or variable name. If Expression is of type Object, the Len function returns the size as it will be
written to the file by the FilePut function.
Remarks
With user-defined types and Object variables, the Len function returns the size as it will be written to the file by the FilePut
function. If an Object contains a String, it will return the length of the string. If an Object contains any other type, it will return
the size of the object as it will be written to the file by the FilePut function.
The VBFixedString attribute can be applied to string fields in objects to indicate the size of the string, in bytes, when written to
disk. The Len function uses the VBFixedString attribute, if available, when determining the size of Object variables.
Note
The Len function may not be able to determine the actual number of storage bytes required when used with variable-length
strings in user-defined data types.

Note
The LenB function in earlier versions of Visual Basic returns the number of bytes in a string rather than characters. It is used
primarily for converting strings in double-byte character set (DBCS) applications. All current Visual Basic strings are in Unico
de, and LenB is no longer supported.

Example
This example uses Len to return the number of characters in a string.
VB
' Initializes variable.
Dim TestString As String = "Hello World"
' Returns 11.
Dim TestLen As Integer = Len(TestString)

Smart Device Developer Notes


The Len function accepts only String and Object variables as parameters. If an Object contains a String, it will return the
length of the String. If a parameter is a NULL Object reference, the function returns zero. If an Object contains any other type,
an exception is thrown.
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Data Type Summary (Visual Basic)
FilePut Function
VBFixedStringAttribute Class
String Manipulation Summary
Data Type Summary (Visual Basic)
InStr Function (Visual Basic)
Concepts
Programming Element Support Changes Summary
Visual Basic Language Reference

LineInput Function
Reads a single line from an open sequential file and assigns it to a String variable.

Public Function LineInput(ByVal FileNumber As Integer) As String

Parameters
FileNumber
Required. Any valid file number.
Exceptions
Exception type Error number Condition
EndOfStreamException 62 End of file reached.

IOException 52 FileNumber does not exist.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The LineInput function is provided for backward compatibility and may have an impact on performance. For non-legacy
applications, the My.Computer.FileSystem object provides better performance. For more information, see
File Access with Visual Basic.
Data read with LineInput is usually written to a file with Print.
Security Note
When reading from files, do not make decisions about the contents of a file based on the file name extension. For example, a
file named Form1.vb may not be a Visual Basic source file.

The LineInput function reads from a file one character at a time until it encounters a carriage return (Chr(13)) or carriage
return/line feed (Chr(13) + Chr(10)) sequence. Carriage return/line feed sequences are skipped rather than appended to the
character string.
Security Note
Reading from a file with the LineInput function requires Read access from the FileIOPermissionAccess enumeration.

Example
This example uses the LineInput function to read a line from a sequential file and assign it to a variable. This example assumes
that TestFile is a text file with a few lines of sample data.
VB
Dim TextLine As String
' Open file.
FileOpen(1, "TESTFILE", OpenMode.Input)
' Loop until end of file.
While Not EOF(1)
' Read line into variable.
TextLine = LineInput(1)
' Print to the console.
WriteLine(1, TextLine)
End While
FileClose(1)
Smart Device Developer Notes
This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Write Text to Files with a StreamWriter in Visual Basic
How to: Write Text to Files in Visual Basic
Reference
Chr, ChrW Functions
Input Function
Other Resources
File Access with Visual Basic
Visual Basic Language Reference

Loc Function
Returns a Long value specifying the current read/write position within an open file.

Public Function Loc(ByVal FileNumber As Integer) As Long

Parameters
FileNumber
Required. Any valid Integer file number.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.

IOException 54 File mode is invalid.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Loc function is zero-based; using it to get the first byte in a file will return 0.
The Loc function is provided for backward compatibility and may have an impact on performance. For non-legacy applications,
the My.Computer.FileSystem object provides better performance. For more information, see File Access with Visual Basic.
The following describes the return value for each file access mode:
Mode Return value
Random Number of the last record read from or written to the file.

Sequenti Current byte position in the file divided by 128. However, information returned by Loc for sequential files is neither
al used nor required.

Binary Position of the last byte read or written.


Example
This example uses the Loc function to return the current read/write position within an open file. This example assumes that
MyFile is a text file with a few lines of sample data.

VB
Dim location As Long
Dim oneChar As Char
FileOpen(1, "C:\TESTFILE.TXT", OpenMode.Binary)
While location < LOF(1)
Input(1, oneChar)
location = Loc(1)
WriteLine(1, location & ControlChars.CrLf)
End While
FileClose(1)

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
EOF Function
LOF Function
Seek Function
IOException
Visual Basic Language Reference

Lock, Unlock Functions


Controls access by other processes to all or part of a file opened using the Open function.
The My feature gives you greater productivity and performance in file I/O operations than Lock and Unlock. For more
information, see My.Computer.FileSystem Object.

Public Overloads Sub Lock(ByVal FileNumber As Integer)


' -or-
Public Overloads Sub Unlock(ByVal FileNumber As Integer)
' -or-
Public Overloads Sub Lock(_
ByVal FileNumber As Integer, _
ByVal Record As Long _
)
' -or-
Public Overloads Sub Unlock( _
ByVal FileNumber As Integer, _
ByVal Record As Long _
)
' -or-
Public Overloads Sub Lock( _
ByVal FileNumber As Integer, _
ByVal FromRecord As Long, _
ByVal ToRecord As Long _
)
' -or-
Public Overloads Sub Unlock( _
ByVal FileNumber As Integer, _
ByVal FromRecord As Long, _
ByVal ToRecord As Long _
)

Parameters
FileNumber
Required. Any valid file number.
Record
Optional. Number of the only record or byte to lock or unlock
FromRecord
Optional. Number of the first record or byte to lock or unlock.
ToRecord
Optional. Number of the last record or byte to lock or unlock.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.

IOException 54 File mode is invalid.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Lock and Unlock functions are used in environments where several processes might need access to the same file.
Lock and Unlock functions are always used in pairs. The arguments to Lock and Unlock must match exactly.
If Record, or FromRecord and ToRecord are not supplied, the lock will be for the entire file. If Record alone is specified the
single record will be locked/unlocked.
If the file has been opened for sequential input or output, Lock and Unlock affect the entire file, regardless of the range
specified by FromRecord and ToRecord.
Example
This example illustrates the use of the Lock and Unlock functions. This example assumes that People.txt is a file containing
records of the structure Person.
VB
Structure Person
Dim Name As String
Dim ID As Integer
End Structure
Sub PutInLockedFile(ByVal index As Integer, ByVal onePerson As Person)
Try
FileOpen(1, "c:\people.txt", OpenMode.Binary)
Lock(1)
FilePut(index, onePerson)
Unlock(1)
FileClose(1)
Catch
' Error recovery code here.
End Try
End Sub

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
FileOpen Function
IOException Class
Other Resources
File Access with Visual Basic
Visual Basic Language Reference

LOF Function
Returns a Long representing the size, in bytes, of a file opened using the FileOpen function.
The My feature gives you greater productivity and performance in file I/O operations than LOF. For more information, see
My.Computer.FileSystem Object.

Public Function LOF(ByVal FileNumber As Integer) As Long

Parameters
FileNumber
Required. An Integer containing a valid file number.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.

IOException 54 File mode is invalid.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Use the FileLen function to obtain the length of a file that is not open.
Example
This example uses the LOF function to determine the size of an open file. This example assumes that TestFile is a text file
containing sample data.
VB
Dim length As Long
FileOpen(1, "C:\TESTFILE.TXT", OpenMode.Input) ' Open file.
length = LOF(1) ' Get length of file.
MsgBox(length)
FileClose(1) ' Close file.

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
EOF Function
FileLen Function
Loc Function
FileOpen Function
IOException Class
Other Resources
Reading from Files in Visual Basic
Writing to Files in Visual Basic
Visual Basic Language Reference

LSet Function
Returns a left-aligned string containing the specified string adjusted to the specified length.

Public Shared Function LSet( _


ByVal Source As String, _
ByVal Length As Integer _
) As String

Parameters
Source
Required. String expression. String variable to be adjusted.
Length
Required. Integer expression. Length of returned string.
Remarks
If Source is longer than Length, LSet returns only the rightmost characters, up to the length of Length. If Source is shorter than
Length, LSet adds spaces to the right end of the returned string to produce the appropriate length.
Example
This example demonstrates the use of the LSet function.
VB
Dim TestString As String = "Left"
Dim lString As String
' Returns "Left "
lString = LSet(TestString, 10)
' Returns "Le"
lString = LSet(TestString, 2)
' Returns "Left"
lString = LSet(TestString, 4)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Data Type Summary (Visual Basic)
RSet Function
Concepts
Efficient Use of Data Types
Visual Basic Language Reference

M-R Functions
The following table contains a listing of the Visual Basic run-time member functions.

Mid Minute MIRR MkDir

Month MonthName MsgBox NPer

NPV Oct Partition Pmt

PPmt Print PrintLine PV

QBColor Randomize Rate Rename

Replace Reset RGB Right

RmDir Rnd RSet RTrim

The math function Round that was available as a Visual Basic run-time member function in version 6.0 and earlier has been
replaced by a method (Round) in the Math class of the .NET Framework class library. For more information, see
Math Functions (Visual Basic).
Smart Device Developer Notes
The following are not supported in smart device applications: MkDir, Print, PrintLine, Rename, Reset, and RmDir.
See Also
Reference
A-C Functions
D-G Functions
H-L Functions
S-Z Functions
Other Resources
Visual Basic Reference
Visual Basic Language Reference

Mid Function (Visual Basic)


Returns a string containing a specified number of characters from a string.

Public Shared Function Mid( _


ByVal str As String, _
ByVal Start As Integer, _
Optional ByVal Length As Integer _
) As String

Parameters
str
Required. String expression from which characters are returned.
Start
Required. Integer expression. Starting position of the characters to return. If Start is greater than the number of characters in
str, the Mid function returns a zero-length string (""). Start is one based.
Length
Optional. Integer expression. Number of characters to return. If omitted or if there are fewer than Length characters in the
text (including the character at position Start), all characters from the start position to the end of the string are returned.
Exceptions
Exception type Error number Condition
ArgumentException 5 Start <= 0 or Length < 0.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
To determine the number of characters in str, use the Len function.
Visual Basic has a Mid function and a Mid statement. These elements both operate on a specified number of characters in a
string, but the Mid function returns the characters while the Mid statement replaces the characters. For more information, see
Mid Statement.
Note
The MidB function in previous versions of Visual Basic returns a string in bytes rather than characters. It is used primarily for
converting strings in double-byte character set (DBCS) applications. All Visual Basic strings are in Unicode, and MidB is no lo
nger supported.

Example
This example uses the Mid function to return a specified number of characters from a string.
VB
' Creates text string.
Dim TestString As String = "Mid Function Demo"
' Returns "Mid".
Dim FirstWord As String = Mid(TestString, 1, 3)
' Returns "Demo".
Dim LastWord As String = Mid(TestString, 14, 4)
' Returns "Function Demo".
Dim MidWords As String = Mid(TestString, 5)
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Left Function (Visual Basic)
Len Function (Visual Basic)
Trim, LTrim, and RTrim Functions
Mid Statement
Right Function (Visual Basic)
ArgumentException
Concepts
Programming Element Support Changes Summary
Other Resources
Strings in Visual Basic
Introduction to Strings in Visual Basic
Visual Basic Language Reference

Minute Function
Returns an Integer value from 0 through 59 representing the minute of the hour.

Public Function Minute(ByVal TimeValue As DateTime) As Integer

Parameters
TimeValue
Required. Date value from which you want to extract the minute.
Remarks
You can also obtain the minute of the hour by calling DatePart and specifying DateInterval.Minute for the Interval
argument.
Example
This example uses the Minute function to obtain the minute of the hour from a specified time. In the development
environment, the time literal is displayed in short time format using the locale settings of your code.
VB
Dim thisTime As Date
Dim thisMinute As Integer
thisTime = #4:35:17 PM#
thisMinute = Minute(thisTime)
' thisMinute now contains 35.

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Day Function (Visual Basic)
Hour Function (Visual Basic)
Now Property
Second Function (Visual Basic)
TimeOfDay Property
DatePart Function (Visual Basic)
System
DateTime
ArgumentException
ArgumentOutOfRangeException
Visual Basic Language Reference

MIRR Function
Returns a Double specifying the modified internal rate of return for a series of periodic cash flows (payments and receipts).

Function MIRR( _
ByRef ValueArray() As Double, _
ByVal FinanceRate As Double, _
ByVal ReinvestRate As Double _
) As Double

Parameters
ValueArray
Required. Array of Double specifying cash-flow values. The array must contain at least one negative value (a payment) and
one positive value (a receipt).
FinanceRate
Required. Double specifying interest rate paid as the cost of financing.
ReinvestRate
Required. Double specifying interest rate received on gains from cash reinvestment.
Exceptions
Exception type Error number Condition
ArgumentException 5 Rank of ValueArray does not equal 1, FinanceRate = -1, or ReinvestRate = -1

DivideByZeroException 11 Division by zero has occurred.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The modified internal rate of return is the internal rate of return when payments and receipts are financed at different rates.
The MIRR function takes into account both the cost of the investment (FinanceRate) and the interest rate received on
reinvestment of cash (ReinvestRate).
The FinanceRate and ReinvestRatearguments are percentages expressed as decimal values. For example, 12 percent is
expressed as 0.12.
The MIRR function uses the order of values within the array to interpret the order of payments and receipts. Be sure to enter
your payment and receipt values in the correct sequence.
Example
This example uses the MIRR function to return the modified internal rate of return for a series of cash flows contained in the
array Values(). LoanAPR represents the financing interest, and InvAPR represents the interest rate received on reinvestment.
VB
' Define money format.
Dim MoneyFmt As String = "###,##0.00"
' Define percentage format.
Dim PercentFmt As String = "#0.00"
Dim values(4) As Double
' Business start-up costs.
values(0) = -70000
' Positive cash flows reflecting income for four successive years.
values(1) = 22000
values(2) = 25000
values(3) = 28000
values(4) = 31000

' Use the MIRR function to calculate the internal return rate.
' Set the loan rate.
Dim LoanAPR As Double = 0.1
' Set the reinvestment rate.
Dim InvAPR As Double = 0.12
' Calculate internal rate.
Dim RetRate As Double = MIRR(values, LoanAPR, InvAPR)
' Display internal return rate.
MsgBox("The modified internal rate of return for these cash flows is " & _
Format(Math.Abs(RetRate) * 100, CStr(PercentFmt)) & "%.")

Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IRR Function
NPV Function
Financial Summary
ArgumentException
DivideByZeroException
Visual Basic Language Reference

MkDir Function
Creates a new directory.
The My feature gives you greater productivity and performance in file I/O operations than MkDir. For more information, see
My.Computer.FileSystem.CreateDirectory Method.

Public Sub MkDir(ByVal Path As String)

Parameters
Path
Required. String expression that identifies the directory to be created. The Path may include the drive. If no drive is specified,
MkDir creates the new directory on the current drive.
Exceptions
Exception type Error number Condition
ArgumentException 52 Path is not specified or is empty.

SecurityException 70 Permission denied.

IOException 75 Directory already exists.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Security Note
Both read and write file I/O permissions are necessary to create a directory or folder. For more information, see
FileIOPermission and Code Access Permissions.

Remarks
This function creates any new directories specified in Path, unless they already exist or if some part of Path is invalid. The Path
parameter must specify a directory path, not a file path.
Example
This example uses the MkDir function to create a directory. If the drive is not specified, the new directory is created on the
current drive.
VB
' Make new directory.
MkDir("C:\TESTDIR")

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Create a Directory in Visual Basic
Reference
ChDir Function
CurDir Function
RmDir Function
ArgumentException Class
IOException Class
Visual Basic Language Reference

Month Function (Visual Basic)


Returns an Integer value from 1 through 12 representing the month of the year.

Public Function Month(ByVal DateValue As DateTime) As Integer

Parameters
DateValue
Required. Date value from which you want to extract the month.
Remarks
You can also obtain the month of the year by calling DatePart and specifying DateInterval.Month for the Interval argument.
Example
This example uses the Month function to obtain the month from a specified date. In the development environment, the date
literal is displayed in short date format using the locale settings of your code.
VB
Dim thisDate As Date
Dim thisMonth As Integer
thisDate = #2/12/1969#
thisMonth = Month(thisDate)
' thisMonth now contains 2.

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Day Function (Visual Basic)
Now Property
Weekday Function (Visual Basic)
Year Function (Visual Basic)
DatePart Function (Visual Basic)
System
DateTime
ArgumentException
ArgumentOutOfRangeException
Visual Basic Language Reference

MonthName Function (Visual Basic)


Returns a String value containing the name of the specified month.

Public Function MonthName( _


ByVal Month As Integer, _
Optional ByVal Abbreviate As Boolean = False _
) As String

Parameters
Month
Required. Integer. The numeric designation of the month, from 1 through 13; 1 indicates January and 12 indicates
December. You can use the value 13 with a 13-month calendar. If your system is using a 12-month calendar and Month is
13, MonthName returns an empty string.
Abbreviate
Optional. Boolean value that indicates if the month name is to be abbreviated. If omitted, the default is False, which means
the month name is not abbreviated.
Exceptions
Exception type Error number Condition
ArgumentException 5 Month is less than 1 or greater than 13.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The string returned by MonthName depends not only on the input arguments, but also on the Regional Options settings
specified in the Windows Control Panel.
Note
MonthName uses the current calendar setting from the CurrentCulture property of the CultureInfo class in the
System.Globalization namespace. The default CurrentCulture values are determined by Control Panel settings.

Example
This example uses the MonthName function to determine the name of the month, by the integer given. The Boolean value will
determine whether the full name (False) or the abbreviated name (True) will be displayed.
VB
Dim thisMonth As Integer
Dim name As String
thisMonth = 4
' Set Abbreviate to True to return an abbreviated name.
name = MonthName(thisMonth, True)
' name now contains "Apr".

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
WeekdayName Function (Visual Basic)
System
System.Globalization
DateTime
ArgumentException
CultureInfo
Visual Basic Language Reference

MsgBox Function (Visual Basic)


Displays a message in a dialog box, waits for the user to click a button, and then returns an integer indicating which button the
user clicked.

Public Function MsgBox( _


ByVal Prompt As Object, _
Optional ByVal Buttons As MsgBoxStyle = MsgBoxStyle.OKOnly, _
Optional ByVal Title As Object = Nothing _
) As MsgBoxResult

Parameters
Prompt
Required. String expression displayed as the message in the dialog box. The maximum length of Prompt is approximately
1024 characters, depending on the width of the characters used. If Prompt consists of more than one line, you can separate
the lines using a carriage return character (Chr(13)), a line feed character (Chr(10)), or a carriage return/linefeed character
combination (Chr(13) & Chr(10)) between each line.
Buttons
Optional. Numeric expression that is the sum of values specifying the number and type of buttons to display, the icon style to
use, the identity of the default button, and the modality of the message box. If you omit Buttons, the default value is zero.
Title
Optional. String expression displayed in the title bar of the dialog box. If you omit Title, the application name is placed in the
title bar.
Settings
The MsgBoxStyle enumeration values are listed in the following table.
Member Value Description
OKOnly 0 Displays OK button only.

OKCancel 1 Displays OK and Cancel buttons.

AbortRetryIgnore 2 Displays Abort, Retry, and Ignore buttons.

YesNoCancel 3 Displays Yes, No, and Cancel buttons.

YesNo 4 Displays Yes and No buttons.

RetryCancel 5 Displays Retry and Cancel buttons.

Critical 16 Displays Critical Message icon.

Question 32 Displays Warning Query icon.

Exclamation 48 Displays Warning Message icon.

Information 64 Displays Information Message icon.

DefaultButton1 0 First button is default.

DefaultButton2 256 Second button is default.


DefaultButton3 512 Third button is default.

ApplicationModal 0 Application is modal. The user must respond to the message box before continuing work in the c
urrent application.

SystemModal 4096 System is modal. All applications are suspended until the user responds to the message box.

MsgBoxSetForegro 65536 Specifies the message box window as the foreground window.
und

MsgBoxRight 52428 Text is right-aligned.


8

MsgBoxRtlReading 10485 Specifies text should appear as right-to-left reading on Hebrew and Arabic systems.
76

The first group of values (0–5) describes the number and type of buttons displayed in the dialog box. The second group (16, 32,
48, 64) describes the icon style. The third group (0, 256, 512) determines which button is the default. The fourth group (0,
4096) determines the modality of the message box, and the fifth group specifies whether or not the message box window is
the foreground window, along with the alignment and direction of the text. When adding numbers to create a final value for
the Buttons argument, use only one number from each group.
Return Value
Constant Value
OK 1

Cancel 2

Abort 3

Retry 4

Ignore 5

Yes 6

No 7
Exceptions
Exception type Error numb Condition
er
ArgumentException 5 Prompt is not a String expression, or Title is invalid.

InvalidOperationException 5 Process is not running in User Interactive mode.

InvalidEnumArgumentException 5 One or more parameters not a member of MsgBoxResult or MsgBoxStyle en


umeration.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If the dialog box displays a Cancel button, pressing the ESC key has the same effect as clicking Cancel. If the dialog box
contains a Help button, context-sensitive Help is provided for the dialog box. However, no value is returned until one of the
other buttons is clicked.
Note
To specify more than the first argument, you must use the MsgBox function in an expression. If you omit any positional argu
ments, you must retain the corresponding comma delimiter.

Note
The MsgBox function requires UIPermission at the SafeTopLevelWindows level, which may affect its execution in partial-tru
st situations. For more information, see Requesting Permissions and UIPermission.

Example
This example uses the MsgBox function to display a critical-error message in a dialog box with Yes and No buttons. The No
button is specified as the default response. This is done by combining the MsgBox constant values into one numeric
expression. In this case, adding 4 (the Yes/No button combination) and 16 (the Critical Message window) and 256 (the
second button as default button) gives a total of 276. The value returned by the MsgBox function depends on the button
chosen by the user: Yes returns a value of 6; No returns a value of 7.
VB
Dim msg As String
Dim title As String
Dim style As MsgBoxStyle
Dim response As MsgBoxResult
msg = "Do you want to continue?" ' Define message.
style = MsgBoxStyle.DefaultButton2 Or _
MsgBoxStyle.Critical Or MsgBoxStyle.YesNo
title = "MsgBox Demonstration" ' Define title.
' Display message.
response = MsgBox(msg, style, title)
If response = MsgBoxResult.Yes Then ' User chose Yes.
' Perform some action.
Else
' Perform some other action.
End If

Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
InputBox Function (Visual Basic)
Visual Basic Language Reference

NPer Function
Returns a Double specifying the number of periods for an annuity based on periodic fixed payments and a fixed interest rate.

Function NPer( _
ByVal Rate As Double, _
ByVal Pmt As Double, _
ByVal PV As Double, _
Optional ByVal FV As Double = 0, _
Optional ByVal Due As DueDate = DueDate.EndOfPeriod _
) As Double

Parameters
Rate
Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of
10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
Pmt
Required. Double specifying payment to be made each period. Payments usually contain principal and interest that does not
change over the life of the annuity.
PV
Required. Double specifying present value, or value today, of a series of future payments or receipts. For example, when you
borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.
FV
Optional. Double specifying future value or cash balance you want after you have made the final payment. For example, the
future value of a loan is $0 because that is its value after the final payment. However, if you want to save $50,000 over 18
years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
Due
Optional. Object of type DueDate Enumeration that specifies when payments are due. This argument must be either
DueDate.EndOfPeriod if payments are due at the end of the payment period, or DueDate.BegOfPeriod if payments are due at
the beginning of the period. If omitted, DueDate.EndOfPeriod is assumed.
Exceptions
Exception type Error number Condition
ArgumentException 5 Rate <= -1.

ArgumentException 5 Rate = 0 and Pmt = 0

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage)
or an investment (such as a monthly savings plan).
For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as
dividend checks) is represented by positive numbers.
Example
This example uses the NPer function to return the number of periods during which payments must be made to pay off a loan
whose value is contained in PVal. Also provided are the interest percentage rate per period (APR / 12), the payment (Payment),
the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of the
payment period (PayType).
VB
Sub TestNPer()
Dim TotPmts As Double
Dim PVal, APR, Payment As Double
Dim PayType As DueDate
Dim Response As MsgBoxResult

' Usually 0 for a loan.


Dim Fval As Double = 0
PVal = CDbl(InputBox("How much do you want to borrow?"))
APR = CDbl(InputBox("What is the annual percentage rate of your loan?"))
' Usually 0 for a loan.
If APR > 1 Then APR = APR / 100
Payment = CDbl(InputBox("How much do you want to pay each month?"))
Response = MsgBox("Do you make payments at the end of month?", MsgBoxStyle.YesNo)
If Response = MsgBoxResult.No Then
PayType = DueDate.BegOfPeriod
Else
PayType = DueDate.EndOfPeriod
End If
TotPmts = NPer(APR / 12, -Payment, PVal, FVal, PayType)
If Int(TotPmts) <> TotPmts Then TotPmts = Int(TotPmts) + 1

MsgBox("It will take you " & TotPmts & " months to pay off your loan.")
End Sub

Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Financial Summary
ArgumentException
Visual Basic Language Reference

NPV Function
Returns a Double specifying the net present value of an investment based on a series of periodic cash flows (payments and
receipts) and a discount rate.

Function NPV( _
ByVal Rate As Double, _
ByRef ValueArray() As Double _
) As Double

Parameters
Rate
Required. Double specifying discount rate over the length of the period, expressed as a decimal.
ValueArray
Required. Array of Double specifying cash flow values. The array must contain at least one negative value (a payment) and
one positive value (a receipt).
Exceptions
Exception type Error number Condition
ArgumentException 5 ValueArray is Nothing, rank of ValueArray <> 1, or Rate = -1

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The net present value of an investment is the current value of a future series of payments and receipts.
The NPV function uses the order of values within the array to interpret the order of payments and receipts. Be sure to enter
your payment and receipt values in the correct sequence.
The NPV investment begins one period before the date of the first cash flow value and ends with the last cash flow value in the
array.
The net present value calculation is based on future cash flows. If your first cash flow occurs at the beginning of the first period,
the first value must be added to the value returned by NPV and must not be included in the cash flow values of ValueArray.
The NPV function is similar to the PV function (present value) except that the PV function allows cash flows to begin either at
the end or the beginning of a period. Unlike the variable NPV cash flow values, PV cash flows must be fixed throughout the
investment.
Example
This example uses the NPV function to return the net present value for a series of cash flows contained in the array values().
The return value, stored in FixedRetRate, represents the fixed internal rate of return.
VB
' Define money format.
Dim MoneyFmt As String = "###,##0.00"
' Define percentage format.
Dim PercentFmt As String = "#0.00"

Dim values(4) As Double


' Business start-up costs.
values(0) = -70000
' Positive cash flows reflecting income for four successive years.
values(1) = 22000
values(2) = 25000
values(3) = 28000
values(4) = 31000
' Use the NPV function to calculate the net present value.
' Set fixed internal rate.
Dim FixedRetRate As Double = 0.0625
' Calculate net present value.
Dim NetPVal As Double = NPV(FixedRetRate, values)
' Display net present value.
MsgBox("The net present value of these cash flows is " & _
Format(NetPVal, MoneyFmt) & ".")

Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
IRR Function
MIRR Function
Financial Summary
ArgumentException
Visual Basic Language Reference

Oct Function
Returns a string representing the octal value of a number.

Public Shared Function Oct( _


ByVal Number As { Byte | SByte | Short | UShort | _
Integer | UInteger | Long | ULong | Object } _
) As String

Parameters
Number
Required. Any valid numeric expression or String expression.
Exceptions
Exception type Error number Condition
ArgumentNullException 5 Number is not specified.

ArgumentException 5 Number is not a numeric type.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If Number is not already a whole number, it is rounded to the nearest whole number before being evaluated.
If Number is Oct returns
Empty Zero (0)

Any other number Up to 22 octal characters

You can represent octal numbers directly by preceding numbers in the proper range with &O. For example, &O10 is the octal
notation for decimal 8.
Example
This example uses the Oct function to return the octal value of a number.
VB
Dim TestOct As String
' Returns "4".
TestOct = Oct(4)
' Returns "10".
TestOct = Oct(8)
' Returns "713".
TestOct = Oct(459)

Requirements
Namespace: Microsoft.VisualBasic
Module: Conversion
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Conversion Summary
Hex Function (Visual Basic)
Type Conversion Functions
ArgumentNullException
Visual Basic Language Reference

Partition Function
Returns a string representing the calculated range that contains a number.

Public Function Partition( _


ByVal Number As Long, _
ByVal Start As Long, _
ByVal Stop As Long, _
ByVal Interval As Long _
) As String

Parameters
Number
Required. Long. Whole number that you want to locate within one of the calculated ranges.
Start
Required. Long. Whole number that indicates the start of the set of calculated ranges. Start cannot be less than 0.
Stop
Required. Long. Whole number that indicates the end of the set of calculated ranges. Stop cannot be less than or equal to
Start.
Interval
Required. Long. Whole number that indicates the size of each range calculated between Start and Stop. Interval cannot be
less than 1.
Exceptions
Exception type Error number Condition
ArgumentException 5 Start < 0, Stop <= Start, or Interval < 1.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Partition function calculates a set of numeric ranges, each containing the number of values specified by Interval. The first
range begins at Start, and the last range ends at Stop. The Partition function then identifies which range contains Number and
returns a string describing that range. The range is represented in the string as "lowervalue:uppervalue", where the low end of
the range (lowervalue) is separated from the high end (uppervalue) by a colon (:).
If necessary, the Partition function inserts leading spaces before lowervalue and uppervalue so that they both have the same
number of characters as the string representation of the value (Stop + 1). This ensures that if you use the output of the
Partition function with several values of Number, the resulting text will be handled properly during any subsequent sort
operation.
The following table shows some sample strings for ranges calculated using three sets of Start, Stop, and Interval. The "First
range" and "Last range" columns show the lowest and highest ranges possible given the values of Start and Stop. The "Before
first range" and "After last range" columns show the strings returned for values of Number less than Start and greater than
Stop, respectively.
Start Stop Interval Before first range First range Last range After last range
0 99 5 " : -1" " 0: 4" " 95: 99" "100: "

20 199 10 " : 19" " 20: 29" "190:199" "200: "

100 1010 20 " : 99" " 100: 119" "1000:1010" "1011: "
In the preceding table, the third line shows the result when Start and Stop define a set of numbers that cannot be evenly
divided by Interval. The last range ends at Stop, making it only 11 numbers long, even though Interval is 20.
If Interval is 1, the range is "Number:Number", regardless of the Start and Stop arguments. For example, if Number is 267, Stop
is 1000, and Interval is 1, Partition returns " 267: 267".
Partition can be useful when constructing database queries. You can create a SELECT query that shows how many orders
occur within various value ranges, for example with invoice values from 1 to 1000, 1001 to 2000, and so on.
Example
The following example sets up a series of ranges for decades from 1950 through 2049. It locates the value of year within the
appropriate range and returns a String value showing the range. If year has a value of 1984, for example, Partition returns
"1980:1989".
VB
Dim year As Long = 1984
' Assume the value of year is provided by data or by user input.
Dim decade As String
decade = Partition(year, 1950, 2049, 10)
MsgBox("Year " & CStr(year) & " is in decade " & decade & ".")

Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Other Resources
How Do I (SQL Server)
Visual Basic Language Reference

Pmt Function
Returns a Double specifying the payment for an annuity based on periodic, fixed payments and a fixed interest rate.

Function Pmt( _
ByVal Rate As Double, _
ByVal NPer As Double, _
ByVal PV As Double, _
Optional ByVal FV As Double = 0, _
Optional ByVal Due As DueDate = DueDate.EndOfPeriod _
) As Double

Parameters
Rate
Required. Double specifies the interest rate per period. For example, if you get a car loan at an annual percentage rate (APR)
of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
NPer
Required. Double specifies the total number of payment periods in the annuity. For example, if you make monthly payments
on a four-year car loan, your loan has a total of 4 × 12 (or 48) payment periods.
PV
Required. Double specifies the present value (or lump sum) that a series of payments to be paid in the future is worth now.
For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car
payments you will make.
FV
Optional. Double specifying future value or cash balance you want after you have made the final payment. For example, the
future value of a loan is $0 because that is its value after the final payment. However, if you want to save $50,000 during 18
years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
Due
Optional. Object of type DueDate Enumeration that specifies when payments are due. This argument must be either
DueDate.EndOfPeriod if payments are due at the end of the payment period, or DueDate.BegOfPeriod if payments are due at
the beginning of the period. If omitted, DueDate.EndOfPeriod is assumed.
Exceptions
Exception type Error number Condition
ArgumentException 5 NPer = 0.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
An annuity is a series of fixed cash payments made during a period of time. An annuity can be a loan (such as a home
mortgage) or an investment (such as a monthly savings plan).
The Rate and NPer arguments must be calculated using payment periods expressed in the same units. For example, if Rate is
calculated using months, NPer must also be calculated using months.
For all arguments, cash paid (such as deposits to savings) is represented by negative numbers; cash received (such as dividend
checks) is represented by positive numbers.
Example
This example uses the Pmt function to return the monthly payment for a loan during a fixed period. Given are the interest
percentage rate per period (APR / 12), the total number of payments (TotPmts), the present value or principal of the loan
(PVal), the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of
the payment period (PayType).
VB
Sub TestPMT()
Dim PVal, APR, Payment, TotPmts As Double
Dim PayType As DueDate
Dim Response As MsgBoxResult
' Define money format.
Dim Fmt As String = "###,###,##0.00"
' Usually 0 for a loan.
Dim FVal As Double = 0
PVal = CDbl(InputBox("How much do you want to borrow?"))
APR = CDbl(InputBox("What is the annual percentage rate of your loan?"))
If APR > 1 Then APR = APR / 100 ' Ensure proper form.
TotPmts = CDbl(InputBox("How many monthly payments will you make?"))
Response = MsgBox("Do you make payments at the end of month?", MsgBoxStyle.YesNo)
If Response = MsgBoxResult.No Then
PayType = DueDate.BegOfPeriod
Else
PayType = DueDate.EndOfPeriod
End If
Payment = Pmt(APR / 12, TotPmts, -PVal, FVal, PayType)

MsgBox("Your payment will be " & Format(Payment, Fmt) & " per month.")
End Sub

Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Financial Summary
ArgumentException
Visual Basic Language Reference

PPmt Function
Returns a Double specifying the principal payment for a given period of an annuity based on periodic fixed payments and a
fixed interest rate.

Function PPmt( _
ByVal Rate As Double, _
ByVal Per As Double, _
ByVal NPer As Double, _
ByVal PV As Double, _
Optional ByVal FV As Double = 0, _
Optional ByVal Due As DueDate = DueDate.EndOfPeriod _
) As Double

Parameters
Rate
Required. Double specifies the interest rate per period. For example, if you get a car loan at an annual percentage rate (APR)
of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
Per
Required. Double specifies the payment period in the range 1 through NPer.
NPer
Required. Double specifies the total number of payment periods in the annuity. For example, if you make monthly payments
on a four-year car loan, your loan has a total of 4 x 12 (or 48) payment periods.
PV
Required. Double specifies the current value of a series of future payments or receipts. For example, when you borrow
money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.
FV
Optional. Double specifying future value or cash balance you want after you have made the final payment. For example, the
future value of a loan is $0 because that is its value after the final payment. However, if you want to save $50,000 over 18
years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
Due
Optional. Object of type DueDate Enumeration that specifies when payments are due. This argument must be either
DueDate.EndOfPeriod if payments are due at the end of the payment period, or DueDate.BegOfPeriod if payments are due at
the beginning of the period. If omitted, DueDate.EndOfPeriod is assumed.
Exceptions
Exception type Error number Condition
ArgumentException 5 Per <=0 or Per > NPer.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage)
or an investment (such as a monthly savings plan).
The Rate and NPer arguments must be calculated using payment periods expressed in the same units. For example, if Rate is
calculated using months, NPer must also be calculated using months.
For all arguments, cash paid (such as deposits to savings) is represented by negative numbers; cash received (such as dividend
checks) is represented by positive numbers.
Example
This example uses the PPmt function to calculate how much of a payment for a specific period is principal when all the
payments are of equal value. Given are the interest percentage rate per period (APR / 12), the payment period for which the
principal portion is desired (Period), the total number of payments (TotPmts), the present value or principal of the loan (PVal),
the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of the
payment period (PayType).
VB
Sub TestPPMT()
Dim PVal, APR, TotPmts, Payment, Period, P, I As Double
Dim PayType As DueDate
Dim Msg As String
Dim Response As MsgBoxResult
' Define money format.
Dim Fmt As String = "###,###,##0.00"
' Usually 0 for a loan.
Dim Fval As Double = 0
PVal = CDbl(InputBox("How much do you want to borrow?"))
APR = CDbl(InputBox("What is the annual percentage rate of your loan?"))
' Ensure proper form.
If APR > 1 Then APR = APR / 100
TotPmts = CDbl(InputBox("How many monthly payments do you have to make?"))
Response = MsgBox("Do you make payments at the end of month?", MsgBoxStyle.YesNo)
If Response = MsgBoxResult.No Then
PayType = DueDate.BegOfPeriod
Else
PayType = DueDate.EndOfPeriod
End If
Payment = Math.Abs(-Pmt(APR / 12, TotPmts, PVal, FVal, PayType))
Msg = "Your monthly payment is " & Format(Payment, Fmt) & ". "
Msg = Msg & "Would you like a breakdown of your principal and "
Msg = Msg & "interest per period?"
' See if chart is desired.
Response = MsgBox(Msg, MsgBoxStyle.YesNo)
If Response <> MsgBoxResult.No Then
If TotPmts > 12 Then MsgBox("Only first year will be shown.")
Msg = "Month Payment Principal Interest" & vbNewLine
For Period = 1 To TotPmts
' Show only first 12.
If Period > 12 Then Exit For
P = PPmt(APR / 12, Period, TotPmts, -PVal, FVal, PayType)
' Round principal.
P = (Int((P + 0.005) * 100) / 100)
I = Payment - P
' Round interest.
I = (Int((I + 0.005) * 100) / 100)
Msg = Msg & Period & vbTab & Format(Payment, Fmt)
Msg = Msg & vbTab & Format(P, Fmt) & vbTab & Format(I, Fmt) & vbNewLine
Next Period
' Display amortization table.
MsgBox(Msg)
End If
End Sub

Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Financial Summary
ArgumentException
Visual Basic Language Reference

Print, PrintLine Functions


Writes display-formatted data to a sequential file.

Public Sub Print( _


ByVal FileNumber As Integer, _
ByVal ParamArray Output() As Object _
)
' -or-
Public Sub PrintLine( _
ByVal FileNumber As Integer, _
ByVal ParamArray Output() As Object _
)

Parameters
FileNumber
Required. Any valid file number.
Output
Optional. Zero or more comma-delimited expressions to write to a file.
The Output argument settings are:
Setti Description
ng
SPC( Used to insert space characters in the output, where n is the number of space characters to insert.
n)

TAB( Used to position the insertion point to an absolute column number, where n is the column number. Use TAB with no ar
n ) gument to position the insertion point at the beginning of the next print zone.

expre Numeric expressions or string expressions to print.


ssion
Exceptions
Exception type Error number Condition
IOException 54 File mode is invalid.

IOException 52 FileNumber does not exist.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Print and PrintLine functions are provided for backward compatibility and may have an impact on performance. For non-
legacy applications, the My.Computer.FileSystem object provides better performance. For more information, see
File Access with Visual Basic.
Print does not include a line feed at the end of a line; PrintLine, however, does include a line feed.
Data written with Print is usually read from a file with LineInput or Input.
If you omit Output for PrintLine, a blank line is printed to the file; for Print, nothing is output. Multiple expressions separated
with a comma will be aligned on tab boundaries, but mixing commas and TAB may result in inconsistent results.
For Boolean data, either True or False is printed. The True and False keywords are not translated, regardless of the locale.
Date data is written to the file using the standard short date format recognized by your system. When either the date or the
time component is missing or zero, only the part provided is written to the file.
Nothing is written to the file if Output data is empty. However, if Output list data is DBNull, Null is written to the file.
For Error data, the output appears as Error errorcode. The Error keyword is not translated regardless of the locale.

All data written to the file using Print is internationally aware; that is, the data is properly formatted using the appropriate
decimal separator. If the user wishes to output data for use by multiple locales, then Write should be used.
Writing to a file with the Print or PrintLine functions requires Write access from the FileIOPermissionAccess enumeration.
For more information, see FileIOPermissionAccess Enumeration.
Example
This example uses the Print and PrintLine functions to write data to a file.
VB
FileOpen(1, "c:\trash.txt", OpenMode.Output) ' Open file for output.
Print(1, "This is a test.") ' Print text to file.
PrintLine(1) ' Print blank line to file.
PrintLine(1, "Zone 1", TAB(), "Zone 2") ' Print in two print zones.
PrintLine(1, "Hello", "World") ' Separate strings with a tab.
PrintLine(1, SPC(5), "5 leading spaces ") ' Print five leading spaces.
PrintLine(1, TAB(10), "Hello") ' Print word at column 10.

' Assign Boolean, Date, and Error values.


Dim aBool As Boolean
Dim aDate As DateTime
aBool = False
aDate = DateTime.Parse("February 12, 1969")

' Dates and booleans are translated using locale settings of your system.
PrintLine(1, aBool, " is a Boolean value")
PrintLine(1, aDate, " is a date")
FileClose(1) ' Close file.

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Write Text to Files in Visual Basic
How to: Write Text to Files with a StreamWriter in Visual Basic
Reference
FileOpen Function
SPC Function
TAB Function
Write, WriteLine Functions
Other Resources
File Access with Visual Basic
Visual Basic Language Reference

PV Function
Returns a Double specifying the present value of an annuity based on periodic, fixed payments to be paid in the future and a
fixed interest rate.

Function PV( _
ByVal Rate As Double, _
ByVal NPer As Double, _
ByVal Pmt As Double, _
Optional ByVal FV As Double = 0, _
Optional ByVal Due As DueDate = DueDate.EndOfPeriod _
) As Double

Parameters
Rate
Required. Double specifies the interest rate per period. For example, if you get a car loan at an annual percentage rate (APR)
of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
NPer
Required. Double specifies the total number of payment periods in the annuity. For example, if you make monthly payments
on a four-year car loan, your loan has 4 x 12 (or 48) payment periods.
Pmt
Required. Double specifies the payment to be made each period. Payments usually contain principal and interest that does
not change during the life of the annuity.
FV
Optional. Double specifies the future value or cash balance you want after you make the final payment. For example, the
future value of a loan is $0 because that is its value after the final payment. However, if you want to save $50,000 over 18
years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
Due
Optional. Object of type DueDate Enumeration that specifies when payments are due. This argument must be either
DueDate.EndOfPeriod if payments are due at the end of the payment period, or DueDate.BegOfPeriod if payments are due at
the beginning of the period. If omitted, DueDate.EndOfPeriod is assumed.
Remarks
An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage)
or an investment (such as a monthly savings plan).
The Rate and NPer arguments must be calculated using payment periods expressed in the same units. For example, if Rate is
calculated using months, NPer must also be calculated using months.
For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as
dividend checks) is represented by positive numbers.
Example
In this example, the PV function returns the present value of an $1,000,000 annuity that will provide $50,000 a year for the
next 20 years. Provided are the expected annual percentage rate (APR), the total number of payments (TotPmts), the amount of
each payment (YrIncome), the total future value of the investment (FVal), and a number that indicates whether each payment is
made at the beginning or end of the payment period (PayType). Note that YrIncome is a negative number because it represents
cash paid out from the annuity each year.
VB
Sub TestPV()
' Define money format.
Dim Fmt As String = "###,##0.00"
' Annual percentage rate.
Dim APR As Double = 0.0825
' Total number of payments.
Dim TotPmts As Double = 20
' Yearly income.
Dim YrIncome As Double = 50000
' Future value.
Dim FVal As Double = 1000000
' Payment at beginning of month.
Dim PayType As DueDate = DueDate.BegOfPeriod
Dim PVal As Double = PV(APR, TotPmts, -YrIncome, FVal, PayType)
MsgBox("The present value is " & Format(PVal, Fmt) & ".")
End Sub

Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Financial Summary
Visual Basic Language Reference

QBColor Function
Returns an Integer value representing the RGB color code corresponding to the specified color number.

QBColor(Color)

Parameters
Color
Required. A whole number in the range 0–15.
Settings
The Color argument has these settings.
Number Color Number Color
0 Black 8 Gray

1 Blue 9 Light blue

2 Green 10 Light green

3 Cyan 11 Light cyan

4 Red 12 Light red

5 Magenta 13 Light magenta

6 Yellow 14 Light yellow

7 White 15 Bright white


Exceptions
Exception type Error number Condition
ArgumentException 5 Color is outside of range 0 to 15, inclusive.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Starting with the least-significant byte, the returned value specifies the red, green, and blue values used to set the appropriate
color in the RGB system used by the Visual Basic language.
Example
This example uses the QBColor function to change to the color indicated by colorInteger. QBColor accepts integer values
between 0 and 15.
VB
Dim colorInteger As Integer
' Use 4 for red.
colorInteger = QBColor(4)

Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
RGB Function (Visual Basic)
ArgumentException Class
Visual Basic Language Reference

Randomize Function (Visual Basic)


Initializes the random-number generator.

Public Shared Sub Randomize ([ Number ])

Parameters
Number
Optional. An Object or any valid numeric expression.
Remarks
Randomize uses Number to initialize the Rnd function's random-number generator, giving it a new seed value. If you omit
Number, the value returned by the system timer is used as the new seed value.
If Randomize is not used, the Rnd function (with no arguments) uses the same number as a seed the first time it is called, and
thereafter uses the last-generated number as a seed value.
Note
To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a n
umeric argument. Using Randomize with the same value for Number does not repeat the previous sequence.

Security Note
Because the Random statement and the Rnd function start with a seed value and generate numbers that fall within a finite r
ange, the results may be predictable by someone who knows the algorithm used to generate them. Consequently, the Rand
om statement and the Rnd function should not be used to generate random numbers for use in cryptography. For more info
rmation, see RandomNumberGenerator.

Example
This example uses the Randomize statement to initialize the random-number generator. Because the number argument has
been omitted, Randomize uses the return value from the Timer function as the new seed value.
VB
' Initialize the random-number generator.
Randomize()
' Generate random value between 1 and 6.
Dim value As Integer = CInt(Int((6 * Rnd()) + 1))

Requirements
Namespace: Microsoft.VisualBasic
Module: VBMath
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Math Summary
Rnd Function (Visual Basic)
Visual Basic Language Reference

Rate Function
Returns a Double specifying the interest rate per period for an annuity.

Function Rate( _
ByVal NPer As Double, _
ByVal Pmt As Double, _
ByVal PV As Double, _
Optional ByVal FV As Double = 0, _
Optional ByVal Due As DueDate = DueDate.EndOfPeriod, _
Optional ByVal Guess As Double = 0.1 _
) As Double

Parameters
NPer
Required. Double specifies the total number of payment periods in the annuity. For example, if you make monthly payments
on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.
Pmt
Required. Double specifies the payment to be made each period. Payments usually contain principal and interest that
doesn't change over the life of the annuity.
PV
Required. Double specifies the present value, or value today, of a series of future payments or receipts. For example, when
you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will
make.
FV
Optional. Double specifies the future value or cash balance you want after you make the final payment. For example, the
future value of a loan is $0 because that is its value after the final payment. However, if you want to save $50,000 over 18
years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
Due
Optional. Object of type DueDate Enumeration that specifies when payments are due. This argument must be either
DueDate.EndOfPeriod if payments are due at the end of the payment period, or DueDate.BegOfPeriod if payments are due at
the beginning of the period. If omitted, DueDate.EndOfPeriod is assumed.
Guess
Optional. Double specifying value you estimate is returned by Rate. If omitted, Guess is 0.1 (10 percent).
Exceptions
Exception type Error number Condition
ArgumentException 5 NPer <= 0.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage)
or an investment (such as a monthly savings plan).
For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as
dividend checks) is represented by positive numbers.
Rate is calculated by iteration. Starting with the value of Guess, Rate cycles through the calculation until the result is accurate
to within 0.00001 percent. If Rate cannot find a result after 20 tries, it fails. If your guess is 10 percent and Rate fails, try a
different value for Guess.
Example
This example uses the Rate function to calculate the interest rate of a loan given the total number of payments (TotPmts), the
amount of the loan payment (Payment), the present value or principal of the loan (PVal), the future value of the loan (FVal), a
number that indicates whether the payment is due at the beginning or end of the payment period (PayType), and an
approximation of the expected interest rate (Guess).
VB
Sub TestRate()
Dim PVal, Payment, TotPmts, APR As Double
Dim PayType As DueDate
' Define percentage format.
Dim Fmt As String = "##0.00"
Dim Response As MsgBoxResult
' Usually 0 for a loan.
Dim FVal As Double = 0
' Guess of 10 percent.
Dim Guess As Double = 0.1
PVal = CDbl(InputBox("How much did you borrow?"))
Payment = CDbl(InputBox("What's your monthly payment?"))
TotPmts = CDbl(InputBox("How many monthly payments do you have to make?"))
Response = MsgBox("Do you make payments at the end of the month?", MsgBoxStyle.YesNo)
If Response = MsgBoxResult.No Then
PayType = DueDate.BegOfPeriod
Else
PayType = DueDate.EndOfPeriod
End If
APR = (Rate(TotPmts, -Payment, PVal, FVal, PayType, Guess) * 12) * 100
MsgBox("Your interest rate is " & Format(CInt(APR), Fmt) & " percent.")
End Sub

Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Financial Summary
ArgumentException
Visual Basic Language Reference

Rename Function
Renames a disk file or directory.
The My feature gives you greater productivity and performance in file I/O operations than Rename. For more information, see
My.Computer.FileSystem Object.

Public Sub Rename( _


ByVal OldPath As String, _
ByVal NewPath As String _
)

Parameters
OldPath
Required. String expression that specifies the existing file name and location. OldPath may include the directory, and drive,
of the file.
NewPath
Required. String expression that specifies the new file name and location. NewPath may include directory and drive of the
destination location. The file name specified by NewPath cannot already exist.
Exceptions
Exception type Error number Condition
ArgumentException 5 Path is invalid.

FileNotFoundException 53 OldPath file does not exist.

IOException 58 NewPath file already exists.

IOException 75 Access is invalid.

IOException 74 Cannot rename to different device.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Rename function renames a file and moves it to a different directory, if necessary. The Rename function can move a file
across drives, but it can only rename an existing directory when both NewPath and OldPath are located on the same drive.
Rename cannot create a new file or directory.
Using the Rename function on an open file produces an error. You must close an open file before renaming it. Rename
arguments cannot include multiple-character (*) and single-character (?) wildcards.
Security Note
When using Rename to copy a file from an unprotected location to a protected location, the file retains the less restricted rig
hts. Check to make sure you are not introducing a possible security risk.

Example
This example uses the Rename function to rename a file. For purposes of this example, assume that the directories that are
specified already exist.
VB
Dim OldName, NewName As String
OldName = "OLDFILE"
' Define file names.
NewName = "NEWFILE"
' Rename file.
Rename(OldName, NewName)
OldName = "C:\OLDDIR\OLDFILE"
NewName = "C:\NEWDIR\NEWFILE"
' Move and rename file.
Rename(OldName, NewName)

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Rename a File in Visual Basic
How to: Rename a Directory in Visual Basic
Reference
Kill Function
ArgumentException Class
FileNotFoundException Class
IOException Class
Visual Basic Language Reference

Replace Function (Visual Basic)


Returns a string in which a specified substring has been replaced with another substring a specified number of times.

Public Function Replace(


ByVal Expression As String,
ByVal Find As String,
ByVal Replacement As String,
Optional ByVal Start As Integer = 1,
Optional ByVal Count As Integer = -1,
Optional ByVal Compare As CompareMethod = CompareMethod.Binary
) As String

Parameters
Expression
Required. String expression containing substring to replace.
Find
Required. Substring being searched for.
Replacement
Required. Replacement substring.
Start
Optional. Position within Expression where substring search is to begin. If omitted, 1 is assumed.
Count
Optional. Number of substring substitutions to perform. If omitted, the default value is –1, which means "make all possible
substitutions."
Compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings for values.
Settings
The Compare argument can have the following values.
Constant Description
Binary Performs a binary comparison

Text Performs a textual comparison


Return Value
Replace returns the following values.
If Replace returns
Find is zero-length or Nothing Copy of Expression

Replace is zero-length Copy of Expression with no occurrences of Fin


d

Expression is zero-length or Nothing, or Start is greater than length of Expressi Nothing


on

Count is 0 Copy of Expression


Exceptions
Exception type Error number Condition
ArgumentException 5 Count < -1 or Start <= 0.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The return value of the Replace function is a string that begins at the position specified by Start and concludes at the end of
the Expression string, with the substitutions made as specified by the Find and Replace values.
Example
This example demonstrates the Replace function.

Dim TestString As String = "Shopping List"


' Returns "Shipping List".
Dim aString As String = Replace(TestString, "o", "i")

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Filter Function (Visual Basic)
ArgumentException
Visual Basic Language Reference

Reset Function
Closes all disk files opened using the FileOpen function.
The My feature gives you greater productivity and performance in file I/O operations than Reset. For more information, see
My.Computer.FileSystem Object.

Public Sub Reset()

Remarks
The Reset function closes all active files opened by the FileOpen function and has the same function as FileClose() without
any parameters.
Example
This example uses the Reset function to close all open files and write the contents of all file buffers to disk. Note the use of the
Object variable FileNumber as both a string and a number.
VB
' Open 5 files named TEST1, TEST2, etc.
Dim fileNumber As Integer
' Open 5 files.
For fileNumber = 1 To 5
FileOpen(fileNumber, "TEST" & fileNumber, OpenMode.Output)
PrintLine(fileNumber, "Hello World")
Next fileNumber
' Close files and write contents to disk.
Reset()

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
FileClose Function
End Statement
FileOpen Function
Visual Basic Language Reference

RGB Function (Visual Basic)


Returns an Integer value representing an RGB color value from a set of red, green and blue color components.

RGB( _
Red As Integer, _
Green As Integer, _
Blue As Integer _
)

Parameters
Red
Required. Integer in the range 0–255, inclusive, that represents the intensity of the red component of the color.
Green
Required. Integer in the range 0–255, inclusive, that represents the intensity of the green component of the color.
Blue
Required. Integer in the range 0–255, inclusive, that represents the intensity of the blue component of the color.
Exceptions
Exception type Error number Condition
ArgumentException 5 Green, Blue, or Red outside of range 0 and 255, inclusive.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Application methods and properties that accept a color specification expect that specification to be a number representing an
RGB color value. An RGB color value specifies the relative intensity of red, green, and blue to cause a specific color to be
displayed.
If the value for any argument to RGB is greater than 255, 255 is used.
The following table lists some standard colors and the red, green, and blue values they include.
Color Red value Green value Blue value
Black 0 0 0

Blue 0 0 255

Green 0 255 0

Cyan 0 255 255

Red 255 0 0

Magenta 255 0 255

Yellow 255 255 0

White 255 255 255


Example
This example shows how the RGB function is used to return a whole number representing an RGB color value.
VB
Dim red, rgbValue As Integer
Dim i As Integer = 75
' Return the value for red.
red = RGB(255, 0, 0)
' Same as RGB(75, 139, 203).
rgbValue = RGB(i, 64 + i, 128 + i)

Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
QBColor Function
ArgumentException Class
Visual Basic Language Reference

Right Function (Visual Basic)


Returns a string containing a specified number of characters from the right side of a string.

Public Shared Function Right( _


ByVal str As String, _
ByVal Length As Integer _
) As String

Parameters
str
Required. String expression from which the rightmost characters are returned.
Length
Required. Integer. Numeric expression indicating how many characters to return. If 0, a zero-length string ("") is returned. If
greater than or equal to the number of characters in str, the entire string is returned.
Exceptions
Exception type Error number Condition
ArgumentException 5 Length < 0.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
To determine the number of characters in str, use the Len function. If used in a Windows Form, or any other class that has a
Right property, you must fully qualify the function with Microsoft.VisualBasic.Right.
Note
The RightB function in earlier versions of Visual Basic returns a string in bytes, rather than characters. It is used primarily for
converting strings in double-byte character set (DBCS) applications. All current Visual Basic strings are in Unicode, and Right
B is no longer supported.

Example
This example demonstrates the use of the Right function to return a substring of a given String. In a class that has a Right
property, it may be necessary to fully qualify the Right function.
VB
Dim TestString As String = "Hello World!"
' Returns "World!".
Dim subString As String = Microsoft.VisualBasic.Right(TestString, 6)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Left Function (Visual Basic)
Len Function (Visual Basic)
Mid Function (Visual Basic)
ArgumentException
Concepts
Programming Element Support Changes Summary
Visual Basic Language Reference

RmDir Function
Removes an existing directory.
The My feature gives you greater productivity and performance in file I/O operations than RmDir. For more information, see
My.Computer.FileSystem.DeleteDirectory Method.

Public Sub RmDir(ByVal Path As String)

Parameters
Path
Required. String expression that identifies the directory or folder to be removed. Path can include the drive. If no drive is
specified, RmDir removes the directory on the current drive.
Exceptions
Exception type Error number Condition
ArgumentException 52 Path is not specified or is empty.

IOException 75 Target directory contains files.

FileNotFoundException 76 Directory does not exist.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
An error occurs if you try to use RmDir on a directory containing files. Use the Kill function to delete all files before attempting
to remove a directory.
Example
This example uses the RmDir function to remove an existing directory.
VB
' Assume that MYDIR is an empty directory.
' Remove MYDIR.
RmDir("MYDIR")

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Delete a Directory in Visual Basic
Reference
ChDir Function
CurDir Function
Kill Function
MkDir Function
ArgumentException Class
IOException Class
FileNotFoundException Class
Visual Basic Language Reference

Rnd Function (Visual Basic)


Returns a random number of type Single.

Public Shared Function Rnd[(Number)] As Single

Parameters
Number
Optional. A Single value or any valid Single expression.
Return Value
If number is Rnd generates
Less than zero The same number every time, using Number as the seed.

Greater than zero The next random number in the sequence.

Equal to zero The most recently generated number.

Not supplied The next random number in the sequence.


Remarks
The Rnd function returns a value less than 1, but greater than or equal to zero.
The value of Number determines how Rnd generates a random number.
For any given initial seed, the same number sequence is generated because each successive call to the Rnd function uses the
previously generated number as a seed for the next number in the sequence.
Before calling Rnd, use the Randomize statement without an argument to initialize the random-number generator with a
seed based on the system timer.
To produce random integers in a given range, use the following formula.
VB
randomvalue = CInt(Int((upperbound - lowerbound + 1) * Rnd() + lowerbound))

Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.
Note
To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a n
umeric argument. Using Randomize with the same value for Number does not repeat the previous sequence.

Security Note
Because the Random statement and the Rnd function start with a seed value and generate numbers that fall within a finite r
ange, the results may be predictable by someone who knows the algorithm used to generate them. Consequently, the Rand
om statement and the Rnd function should not be used to generate random numbers for use in cryptography.

Example
This example uses the Rnd function to generate a random integer value in the range from 1 to 6.
VB
' Initialize the random-number generator.
Randomize()
' Generate random value between 1 and 6.
Dim value As Integer = CInt(Int((6 * Rnd()) + 1))

Requirements
Namespace: Microsoft.VisualBasic
Module: VBMath
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Randomize Function (Visual Basic)
Math Summary
Randomize Function (Visual Basic)
Visual Basic Language Reference

RSet Function
Returns a right-aligned string containing the specified string adjusted to the specified length.

Public Shared Function RSet( _


ByVal Source As String, _
ByVal Length As Integer _
) As String

Parameters
Source
Required. String expression. String to be adjusted.
Length
Required. Integer expression. Length of returned string.
Remarks
If Source is longer than Length, RSet returns only the leftmost characters, up to the length of Length. If Source is shorter than
Length, RSet adds spaces to the left end of the string to produce the appropriate length.
Example
This example demonstrates the use of the RSet function.
VB
Dim TestString As String = "Right"
' Returns " Right"
Dim rString As String = RSet(TestString, 11)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Data Type Summary (Visual Basic)
LSet Function
Concepts
Efficient Use of Data Types
Visual Basic Language Reference

Trim, LTrim, and RTrim Functions


Returns a string containing a copy of a specified string with no leading spaces (LTrim), no trailing spaces (RTrim), or no
leading or trailing spaces (Trim).

Public Shared Function LTrim(ByVal str As String) As String


Public Shared Function RTrim(ByVal str As String) As String
Public Shared Function Trim(ByVal str As String) As String

Parameters
str
Required. Any valid String expression.
Remarks
The LTrim, RTrim, and Trim functions remove spaces from the ends of strings. To remove other forms of white space, such as
tab characters, use the System.String.Trim method.
Example
This example uses the LTrim function to strip leading spaces and the RTrim function to strip trailing spaces from a string
variable. It uses the Trim function to strip both types of spaces.
VB
' Initializes string.
Dim TestString As String = " <-Trim-> "
Dim TrimString As String
' Returns "<-Trim-> ".
TrimString = LTrim(TestString)
' Returns " <-Trim->".
TrimString = RTrim(TestString)
' Returns "<-Trim->".
TrimString = LTrim(RTrim(TestString))
' Using the Trim function alone achieves the same result.
' Returns "<-Trim->".
TrimString = Trim(TestString)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Left Function (Visual Basic)
Right Function (Visual Basic)
Trim
Visual Basic Language Reference

S-Z Functions
The following table contains a listing of the Visual Basic run-time member functions.

SaveSetting Second Seek SetAttr

Shell SLN Space SPC

Split Str StrComp StrConv

StrDup StrReverse Switch SYD

SystemTypeName TAB TimeSerial TimeValue

Trim TypeName UBound UCase

Unlock Val VarType VbTypeName

Weekday WeekdayName Write WriteLine

Year

The math functions Sgn, Sin, Sqr, and Tan that were available as Visual Basic run-time member functions in version 6.0 and
earlier have been replaced by methods (Sign, Sin, Sqrt, and Tan) in the Math class of the .NET Framework class library. For
more information, see Math Functions (Visual Basic).
Smart Device Developer Notes
The following are not supported in smart device applications: SaveSetting, Seek, SetAttr, Shell, SPC, StrConv, TAB, Unlock,
VarType, Write, and WriteLine.
See Also
Reference
A-C Functions
D-G Functions
H-L Functions
M-R Functions
Other Resources
Visual Basic Reference
Visual Basic Language Reference

SaveSetting Function
Saves or creates an application entry in the Windows registry.
The My feature gives you greater productivity and performance in registry operations than SaveSetting. For more
information, see My.Computer.Registry Object.

Public Sub SaveSetting( _


ByVal AppName As String, _
ByVal Section As String, _
ByVal Key As String, _
ByVal Setting As String _
)

Parameters
AppName
Required. String expression containing the name of the application or project to which the setting applies.
Section
Required. String expression containing the name of the section in which the key setting is being saved.
Key
Required. String expression containing the name of the key setting being saved.
Setting
Required. Expression containing the value to which Key is being set.
Exceptions
Exception type Error number Condition
ArgumentException 5 Key registry could not be created, or user is not logged in.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The SaveSetting function adds the key to HKEY_CURRENT_USER\Software\VB and VBA Program Settings.
If the key setting cannot be saved for any reason, an error occurs.
SaveSetting requires that a user be logged on since it operates under the HKEY_LOCAL_USER registry key, which is not
active until a user logs on interactively.
Registry settings that are to be accessed from a non-interactive process (such as Mtx.exe) should be stored under either the
HKEY_LOCAL_MACHINE\Software\ or the HKEY_USER\DEFAULT\Software registry keys.
SaveSetting requires Write and Create Registry Permission.
Example
The following example first uses the SaveSetting function to make entries in the Windows registry for the MyApp application,
and then uses the DeleteSetting function to remove them.
VB
' Place some settings in the registry.
SaveSetting("MyApp", "Startup", "Top", "75")
SaveSetting("MyApp","Startup", "Left", "50")
' Remove Startup section and all its settings from registry.
DeleteSetting ("MyApp", "Startup")
' Remove MyApp from the registry.
DeleteSetting ("MyApp")

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DeleteSetting Function
GetAllSettings Function
GetSetting Function
RegistryPermission Class
Concepts
Common Registry Tasks
Visual Basic Language Reference

Second Function (Visual Basic)


Returns an Integer value from 0 through 59 representing the second of the minute.

Public Function Second(ByVal TimeValue As DateTime) As Integer

Parameters
TimeValue
Required. Date value from which you want to extract the second.
Remarks
You can also obtain the second of the minute by calling DatePart and specifying DateInterval.Second for the Interval
argument.
Example
The following example uses the Second function to obtain the second of the minute from a specified time. In the development
environment, the time literal is displayed in short time format using the locale settings of your code.
VB
Dim thisTime As Date
Dim thisSecond As Integer
thisTime = #4:35:17 PM#
thisSecond = Second(thisTime)
' thisSecond now contains 17.

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Day Function (Visual Basic)
Hour Function (Visual Basic)
Minute Function
Now Property
TimeOfDay Property
DatePart Function (Visual Basic)
System
DateTime
ArgumentException
ArgumentOutOfRangeException
Visual Basic Language Reference

Seek Function
Returns a Long specifying the current read/write position within a file opened using the FileOpen function, or sets the
position for the next read/write operation within a file opened using the FileOpen function.
The My feature gives you greater productivity and performance in file I/O operations than Seek. For more information, see
My.Computer.FileSystem Object.

Public Overloads Function Seek( _


ByVal FileNumber As Integer _
) As Long
' -or-
Public Overloads Sub Seek( _
ByVal FileNumber As Integer, _
ByVal Position As Long _
)

Parameters
FileNumber
Required. An Integer containing a valid file number.
Position
Required. Number in the range 1–2,147,483,647, inclusive, that indicates where the next read/write operation should occur.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.

IOException 54 File mode is invalid.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Seek returns a value between 1 and 2,147,483,647 (equivalent to 2^31 – 1), inclusive.
The following describes the return values for each file access mode:
Mode Return Value
Random Number of the next record read or written

Binary, Input, Output, Byte position at which the next operation takes place. The first byte in a file is at position 1, the secon
Append d byte is at position 2, and so on.
Example
This example uses the Seek function to return the current file position. The example assumes TestFile is a file containing
records of the structure Record.
VB
Structure Record ' Define user-defined type.
Dim ID As Integer
Dim Name As String
End Structure

For files opened in Random mode, Seek returns the number of next record.
VB
FileOpen(1, "TESTFILE", OpenMode.Random)
Do While Not EOF(1)
WriteLine(1,Seek(1)) ' Write record number.
FileGet(1, MyRecord, -1) ' Read next record.
Loop
FileClose(1)

For files opened in modes other than Random mode, Seek returns the byte position at which the next operation takes place.
Assume TestFile is a file containing a few lines of text.
VB
' Report character position at beginning of each line.
Dim TextLine As String
FileOpen(1, "TESTFILE", OpenMode.Input) ' Open file for reading.
While Not EOF(1)
' Read next line.
TextLine = LineInput(1)
' Position of next line.
MsgBox(Seek(1))
End While
FileClose(1)

This example uses the Seek function to set the position for the next read or write within a file. This example assumes
People.txt is a file containing records of the structure Record.

VB
Structure TestRecord
Dim Name As String
Dim ID As Integer
End Structure

For files opened in modes other than Random mode, Seek sets the byte position at which the next operation takes place.
Assume TestFile is a file containing a few lines of text.
VB
Dim someText As String = "This is a test string."
' Open file for output.
FileOpen(1, "TESTFILE", OpenMode.Input)
' Move to the third character.
Seek(1, 3)
Input(1, someText)
Console.WriteLine(someText)
FileClose(1)

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
FileGet Function
Loc Function
FileOpen Function
FilePut Function
IOException Class
Other Resources
Reading from Files in Visual Basic
Writing to Files in Visual Basic
Visual Basic Language Reference

SetAttr Function
Sets attribute information for a file.
The My feature gives you greater productivity and performance in file I/O operations than SetAttr. For more information, see
My.Computer.FileSystem Object.

Public Sub SetAttr( _


ByVal PathName As String, _
ByVal Attributes As FileAttribute _
)

Parameters
PathName
Required. String expression that specifies a file name. PathName can include directory or folder, and drive.
Attributes
Required. Constant or numeric expression, whose sum specifies file attributes.
Settings
The Attributes argument enumeration values are:
Value Constant Description
Normal vbNormal Normal (default).

ReadOnly vbReadOnly Read-only.

Hidden vbHidden Hidden.

System vbSystem System file.

Volume vbVolume Volume label

Directory vbDirectory Directory or folder.

Archive vbArchive File has changed since last backup.

Alias vbAlias File has a different name.


Note
These enumerations are specified by the Visual Basic language. The names can be used anywhere in your code in place of the
actual values.

Exceptions
Exception type Error number Condition
ArgumentException 52 PathName invalid or does not exist.

ArgumentException 5 Attribute type is invalid.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
A run-time error occurs if you try to set the attributes of an open file.
Example
This example uses the SetAttr function to set attributes for a file.
VB
' Set hidden attribute.
SetAttr("TESTFILE", vbHidden)
' Set hidden and read-only attributes.
SetAttr("TESTFILE", vbHidden Or vbReadOnly)

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
FileAttr Function
GetAttr Function
ArgumentException Class
FileAttribute Enumeration
My.Computer.FileSystem Object
Visual Basic Language Reference

Shell Function
Runs an executable program and returns an integer containing the program's process ID if it is still running.

Public Function Shell( _


ByVal PathName As String, _
Optional ByVal Style As AppWinStyle = AppWinStyle.MinimizedFocus, _
Optional ByVal Wait As Boolean = False, _
Optional ByVal Timeout As Integer = -1 _
) As Integer

Parameters
PathName
Required. String. Name of the program to execute, together with any required arguments and command-line switches.
PathName can also include the drive and the directory path or folder.
If you do not know the path to the program, you can use the My.Computer.FileSystem.GetFiles Method to locate it. For
example, you can call My.Computer.FileSystem.GetFiles("C:\", True, "testFile.txt"), which returns the full path of
every file named testFile.txt anywhere on drive C:\.
Style
Optional. AppWinStyle. A value chosen from the AppWinStyle Enumeration specifying the style of the window in which the
program is to run. If Style is omitted, Shell uses AppWinStyle.MinimizedFocus, which starts the program minimized and
with focus.
Wait
Optional. Boolean. A value indicating whether the Shell function should wait for completion of the program. If Wait is
omitted, Shell uses False.
Timeout
Optional. Integer. The number of milliseconds to wait for completion if Wait is True. If Timeout is omitted, Shell uses -1,
which means there is no timeout and Shell does not return until the program finishes. Therefore, if you omit Timeout or set
it to -1, it is possible that Shell might never return control to your program.
Exceptions
Exception type Error number Condition
ArgumentException 5 Style is not within range 0 through 9, inclusive.

FileNotFoundException 53 Shell cannot find the PathName file.

NullReferenceException 91 PathName is Nothing.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The return value of the Shell function depends on whether the program named in PathName is still executing when Shell
returns. If you set Wait to True and the program finishes before the timeout expires, Shell returns zero. If the timeout expires,
or if you omit Wait or set it to False, Shell returns the process ID of the program. The process ID is a unique number that
identifies the running program.
Failure to Start
If the Shell function cannot start the named program, a FileNotFoundException error occurs. This can happen, for example,
when you attempt to run a 16-bit program, such as command.com, from an application using System.Windows.Forms. For a
workaround, you can run a 32-bit program that calls the desired 16-bit program. In the case of command.com, you can run
cmd.exe as an alternative.
Waiting for Completion
By default, the Shell function runs the program asynchronously. This means that a program started with the Shell function
might not finish executing before the statements following the Shell function are executed. If you want to wait for the program
to finish before you continue, set Wait to True.
Determining the Exit Code
A process can return an exit code when it terminates. However, you cannot use Shell to retrieve this exit code, because Shell
returns zero if it waits for termination, and also because the process runs in a different object from Shell.
To retrieve the exit code from a process, you must write your own code to initiate the process and wait for termination. The
following example shows how to initiate a process, wait for it to terminate, and retrieve its exit code.

Dim procID As Integer


Dim newProc As Diagnostics.Process
newProc = Diagnostics.Process.Start("C:\WINDOWS\NOTEPAD.EXE")
procID = newProc.Id
newProc.WaitForExit()
Dim procEC As Integer = -1
If newProc.HasExited Then
procEC = newProc.ExitCode
End If
MsgBox("Process with ID " & CStr(ProcID) & _
" terminated with exit code " & CStr(procEC))

Protecting the File Specification


You should always enclose the entire path and file specification in quotation marks, as the following example shows.

ID = Shell("""C:\Program Files\display.exe"" -a -q", , True, 100000)

Each pair of adjacent double quotation marks (" ") within the string literal is interpreted as one double quotation character in
the string. Therefore, the preceding example presents the following string to the Shell function:

"C:\Program Files\display.exe" -a -q

If you did not have the path enclosed in quotation marks, Windows would look for a file called Program.exe in the C:\ directory,
instead of display.exe in the C:\Program Files directory.
Security Note
If you do not enclose the path and file specification in quotation marks, there is a security risk if the file name or a path node
contains spaces. In the preceding example, the path node \Program Files includes a space. If the specification were not insid
e quotation marks and a program named Program.exe had been installed in C:\, for example by illicit tampering, Windows w
ould execute it instead of display.exe.

Security Note
The Shell function requires unmanaged code permission, which might affect its execution in partial-trust situations. For mor
e information, see SecurityPermission and Code Access Permissions.

Example
The following example uses the Shell function to run an application specified by the user. Specifying
Microsoft.VisualBasic.AppWinStyle.NormalFocus as the second argument opens the application in normal size and gives it the
focus.
VB
Dim procID As Integer
' Run calculator.
procID = Shell("C:\Windows\system32\calc.exe", AppWinStyle.NormalFocus)
' The preceding path is for Windows XP.
' The Windows 2000 path is C:\WINNT\system32\calc.exe.
Smart Device Developer Notes
This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
AppWinStyle Enumeration
My.Computer.FileSystem.GetFiles Method
AppActivate Function
ArgumentException
FileNotFoundException
NullReferenceException
Visual Basic Language Reference

SLN Function
Returns a Double specifying the straight-line depreciation of an asset for a single period.

Function SLN( _
ByVal Cost As Double, _
ByVal Salvage As Double, _
ByVal Life As Double _
) As Double

Parameters
Cost
Required. Double specifying initial cost of the asset.
Salvage
Required. Double specifying value of the asset at the end of its useful life.
Life
Required. Double specifying length of the useful life of the asset.
Exceptions
Exception type Error number Condition
ArgumentException 5 Life = 0.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The depreciation period must be expressed in the same unit as the Life argument. All arguments must be positive numbers.
Example
This example uses the SLN function to return the straight-line depreciation of an asset for a single period given the asset's
initial cost (InitCost), the salvage value at the end of the asset's useful life (SalvageVal), and the total life of the asset in years
(LifeTime).
VB
Dim InitCost, SalvageVal, LifeTime, DepYear As Double
Dim Fmt As String = "###,##0.00"

InitCost = CDbl(InputBox("What's the initial cost of the asset?"))


SalvageVal = CDbl(InputBox("Enter the asset's value at end of its life."))
LifeTime = CDbl(InputBox("What's the asset's useful life in years?"))

' Use the SLN function to calculate the deprecation per year.
Dim SlnDepr As Double = SLN(InitCost, SalvageVal, LifeTime)
Dim msg As String = "The depreciation per year: " & Format(SlnDepr, Fmt)
msg &= vbCrLf & "Year" & vbTab & "Linear" & vbTab & "Doubling" & vbCrLf

' Use the SYD and DDB functions to calculate the deprecation for each year.
For DepYear = 1 To LifeTime
msg &= DepYear & vbTab & _
Format(SYD(InitCost, SalvageVal, LifeTime, DepYear), Fmt) & vbTab & _
Format(DDB(InitCost, SalvageVal, LifeTime, DepYear), Fmt) & vbCrLf
Next
MsgBox(msg)
Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
SYD Function
DDB Function
Financial Summary
ArgumentException
Visual Basic Language Reference

Space Function (Visual Basic)


Returns a string consisting of the specified number of spaces.

Public Shared Function Space(ByVal Number As Integer) As String

Parameters
Number
Required. Integer expression. The number of spaces you want in the string.
Exceptions
Exception type Error number Condition
ArgumentException 5 Number < 0.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Space function is useful for formatting output and clearing data in fixed-length strings.
Example
This example uses the Space function to return a string consisting of a specified number of spaces.
VB
Dim TestString As String
' Returns a string with 10 spaces.
TestString = Space(10)
' Inserts 10 spaces between two strings.
TestString = "Hello" & Space(10) & "World"

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
SPC Function
ArgumentException
Visual Basic Language Reference

SPC Function
Used with the Print or PrintLine function to position output.

Public Function SPC(ByVal Count As Short) As SPCInfo

Parameters
Count
Required. The number of spaces to insert before displaying or printing the next expression in a list.
Remarks
If Count is less than the output line width, the next print position immediately follows the number of spaces printed. If Count is
greater than the output line width, SPC calculates the next print position using the formula:
currentprintposition(+(Count Mod width))
For example, if the current print position is 24, the output line width is 80, and you specify SPC(90), the next print will start at
position 34 (current print position + the remainder of 90/80). If the difference between the current print position and the
output line width is less than Count (or Count Mod width), the SPC function skips to the beginning of the next line and
generates spaces equal to Count – (width – currentprintposition).
Note
Make sure your tabular columns are wide enough to accommodate wide letters.

Example
This example uses the SPC function to position output in a file and in the Output window.
VB
' The SPC function can be used with the Print function.
FileOpen(1, "TESTFILE", OpenMode.Output) ' Open file for output.
Print(1, "10 spaces between here", SPC(10), "and here.")
FileClose(1) ' Close file.

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Mod Operator (Visual Basic)
Print, PrintLine Functions
Space Function (Visual Basic)
TAB Function
FileWidth Function
Visual Basic Language Reference

Split Function (Visual Basic)


Returns a zero-based, one-dimensional array containing a specified number of substrings.

Function Split(
ByVal Expression As String,
Optional ByVal Delimiter As String = " ",
Optional ByVal Limit As Integer = -1,
Optional ByVal Compare As CompareMethod = CompareMethod.Binary
) As String()

Parameters
Expression
Required. String expression containing substrings and delimiters.
Delimiter
Optional. Any single character used to identify substring limits. If Delimiter is omitted, the space character (" ") is assumed to
be the delimiter.
Limit
Optional. Maximum number of substrings into which the input string should be split. The default, –1, indicates that the input
string should be split at every occurrence of the Delimiter string.
Compare
Optional. Numeric value indicating the comparison to use when evaluating substrings. See "Settings" for values.
Returns
String array. If Expression is a zero-length string (""), Split returns a single-element array containing a zero-length string. If
Delimiter is a zero-length string, or if it does not appear anywhere in Expression, Split returns a single-element array
containing the entire Expression string.
Settings
The Compare argument can have the following values.
Constant Description Value
CompareMethod.Binary Performs a binary comparison 0

CompareMethod.Text Performs a textual comparison 1


Remarks
By default, or when Limit equals -1, the Split function splits the input string at every occurrence of the delimiter string, and
returns the substrings in an array. When the Limit parameter is greater than zero, the Split function splits the string at the first
Limit-1 occurrences of the delimiter, and returns an array with the resulting substrings. For example, Split("a:b:c", ":")
returns the array {"a", "b", "c"}, while Split("a:b:c", ":", 2) returns the array {"a", "b:c"}.
When the Split function encounters two delimiters in a row, or a delimiter at the beginning or end of the string, it interprets
them as surrounding an empty string (""). For example, Split("xx", "x") returns the array containing three empty strings:
one from between the beginning of the string and the first "x", one from between the two "x" strings, and one from between
the last "x" and the end of the string.
This table demonstrates how the optional Delimiter, Limit, and Compare parameters can change the behavior of the Split
function.
Split Call Return Value
Split("42, 12, 19") {"42," , "12," , "19"}
Split("42, 12, 19", ", ") {"42", "12", "19"}

Split("42, 12, 19", ", ", 2) {"42", "12, 19"}


Split("192.168.0.1", ".") {"192", "168", "0", "1"}

Split("Alice and Bob", " AND ") {"Alice and Bob"}

Split("Alice and Bob", " AND ", ,CompareMethod.Text) {"Alice", "Bob"}

Split("someone@example.com", "@",1) {"someone@example.com"}

Split("someone@example.com", "@",2) {"someone", "example.com"}


Example
The following example demonstrates how to split a string at its spaces.
VB
Dim TestString As String = "Look at these!"
' Returns an array containing "Look", "at", and "these!".
Dim TestArray() As String = Split(TestString)

The following example demonstrates how to split strings with multiple delimiters in a row and filter out the empty strings.
VB
Dim TestString As String = "apple pear banana "
Dim TestArray() As String = Split(TestString)
' TestArray holds {"apple", "", "", "", "pear", "banana", "", ""}
Dim LastNonEmpty As Integer = -1
For i As Integer = 0 To TestArray.Length - 1
If TestArray(i) <> "" Then
LastNonEmpty += 1
TestArray(LastNonEmpty) = TestArray(i)
End If
Next
ReDim Preserve TestArray(LastNonEmpty)
' TestArray now holds {"apple", "pear", "banana"}

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Join Function (Visual Basic)
CompareMethod Enumeration
Visual Basic Language Reference

Str Function
Returns a String representation of a number.

Public Shared Function Str(ByVal Number As Object) As String

Parameters
Number
Required. An Object containing any valid numeric expression.
Exceptions
Exception type Error number Condition
ArgumentNullException 5 Number is not specified.

InvalidCastException 5 Number is not a numeric type.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
When numbers are converted to strings, a leading space is always reserved for the sign of Number. If Number is positive, the
returned string contains a leading space, and the plus sign is implied. A negative number will include the minus sign (-) and no
leading space.
Use the Format function to convert numeric values you want formatted as dates, times, or currency or in other user-defined
formats. Unlike the Str function, the Format function does not include a leading space for the sign of Number.
Note
The Str function recognizes only the period (.) as a valid decimal separator. If different decimal separators are used (for exam
ple, in international applications), use the CStr or Format functions to convert a number to a string. To get the string represe
ntation of a number in a particular culture, use the number's ToString(IFormatProvider) method. For example, use
ToString when converting a value of type Double to a string.

Example
This example uses the Str function to return a String representation of a number. When a positive number is converted to a
string, a leading space is always reserved for its sign.
VB
Dim TestString As String
' Returns " 459".
TestString = Str(459)
' Returns "-459.65".
TestString = Str(-459.65)
' Returns " 459.001".
TestString = Str(459.001)

Requirements
Namespace: Microsoft.VisualBasic
Module: Conversion
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Conversion Summary
Format Function
Type Conversion Functions
Format Function
Val Function
ArgumentNullException
InvalidCastException
Visual Basic Language Reference

StrComp Function (Visual Basic)


Returns -1, 0, or 1, based on the result of a string comparison.

Public Shared Function StrComp( _


ByVal String1 As String, _
ByVal String2 As String, _
<Microsoft.VisualBasic.OptionCompareAttribute> _
Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod _
) As Integer

Parameters
String1
Required. Any valid String expression.
String2
Required. Any valid String expression.
Compare
Optional. Specifies the type of string comparison. If Compare is omitted, the Option Compare setting determines the type
of comparison.
Settings
The Compare argument settings are:
Consta Description
nt
Binary Performs a binary comparison, based on a sort order derived from the internal binary representations of the characte
rs.

Text Performs a text comparison, based on a case-insensitive text sort order determined by your application's current cult
ure information.
Return Value
The StrComp function has the following return values.
If StrComp returns
String1 sorts ahead of String2 -1

String1 is equal to String2 0

String1 sorts after String2 1


Exceptions
Exception type Error number Condition
ArgumentException 5 Compare value is not valid.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The strings are compared by alphanumeric sort values beginning with the first character. For further information on binary
comparisons, textual comparisons, and sort order, see Option Compare Statement.
Security Note
If your application makes security decisions based on the result of a comparison or case-change operation, then the operatio
n should use the System.String.Compare(System.String,System.String,System.StringComparison) method, and pass Ordinal
or OrdinalIgnoreCase for the comparisonType argument. For more information, see
How Culture Affects Strings in Visual Basic.

Example
This example uses the StrComp function to return the results of a string comparison. If the third argument is omitted, the
comparison type defined in the Option Compare statement or project defaults is performed.
VB
' Defines variables.
Dim TestStr1 As String = "ABCD"
Dim TestStr2 As String = "abcd"
Dim TestComp As Integer
' The two strings sort equally. Returns 0.
TestComp = StrComp(TestStr1, TestStr2, CompareMethod.Text)
' TestStr1 sorts after TestStr2. Returns -1.
TestComp = StrComp(TestStr1, TestStr2, CompareMethod.Binary)
' TestStr2 sorts before TestStr1. Returns 1.
TestComp = StrComp(TestStr2, TestStr1)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
InStr Function (Visual Basic)
ArgumentException
Other Resources
Strings in Visual Basic
Introduction to Strings in Visual Basic
Visual Basic Language Reference

StrConv Function
Returns a string converted as specified.

Public Shared Function StrConv( _


ByVal str As String, _
ByVal Conversion As Microsoft.VisualBasic.VbStrConv, _
Optional ByVal LocaleID As Integer,
) As String

Parameters
str
Required. String expression to be converted.
Conversion
Required. VbStrConv Enumeration member. The enumeration value specifying the type of conversion to perform.
LocaleID
Optional. The LocaleID value, if different from the application's current culture value. For more information about locale IDs
and culture information, see CultureInfo. (The application's current culture value is the default.)
Settings
The Conversion argument settings are:
Enumeration member Description
VbStrConv.None Performs no conversion

VbStrConv.LinguisticC Uses linguistic rules for casing, rather than File System (default). Valid with VbStrConv.UpperCase
asing and VbStrConv.LowerCase only.

VbStrConv.UpperCase Converts the string to uppercase characters.

VbStrConv.LowerCase Converts the string to lowercase characters.

VbStrConv.ProperCase Converts the first letter of every word in string to uppercase.

VbStrConv.Wide * Converts narrow (half-width) characters in the string to wide (full-width) characters.

VbStrConv.Narrow * Converts wide (full-width) characters in the string to narrow (half-width) characters.

VbStrConv.Katakana ** Converts Hiragana characters in the string to Katakana characters.

VbStrConv.Hiragana ** Converts Katakana characters in the string to Hiragana characters.

VbStrConv.SimplifiedC Converts Traditional Chinese characters to Simplified Chinese.


hinese *

VbStrConv.Traditional Converts Simplified Chinese characters to Traditional Chinese.


Chinese *

* Applies to Asian locales.


** Applies to Japan only.
Note
These constants are specified in the .NET Framework common language runtime. As a result, they can be used anywhere in y
our code in place of the actual values. Most can be combined (for example, UpperCase + Wide), except when they are mutuall
y exclusive (for example, VbStrConv.Wide + VbStrConv.Narrow).

The following are valid word separators for proper casing: Null (Chr$(0)), horizontal tab (Chr$(9)), line feed (Chr$(10)),
vertical tab (Chr$(11)), form feed (Chr$(12)), carriage return (Chr$(13)), space (single-byte character set) (Chr$(32)). The
actual value for a space, which can be full or half width, varies by country/region for East Asian cultures.
Exceptions
Exception type Error numbe Condition
r
ArgumentException 5 Unsupported LocaleID, Conversion < 0 or > 2048, or unsupported conversion for specified l
ocale.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The constants VbStrConv.Wide, VbStrConv.Narrow, VbStrConv.SimplifiedChinese, VbStrConv.TraditionalChinese,
VbStrConv.Katakana, and VbStrConv.Hiragana can cause run-time errors when used in locales where they do not apply,
but not always: the constants VbStrConv.Katakana and VbStrConv.Hiragana can be used in a non-Japanese system with
the Japanese Language Pack installed. In addition, use of the constants VbStrConv.Wide and VbStrConv.Narrow is
supported on any system with an East Asian language installed.
This function uses the application's culture information when manipulating the string so that the case changes are appropriate
for the locale in which the application is being used.
Security Note
If your application makes security decisions based on the result of a comparison or case-change operation, then the operatio
n should use the System.String.Compare(System.String,System.String,System.StringComparison) method, and pass Ordinal
or OrdinalIgnoreCase for the comparisonType argument. For more information, see
How Culture Affects Strings in Visual Basic.

Example
This example converts text into all lowercase letters.
VB
Dim sText As String = "Hello World"
' Returns "hello world".
Dim sNewText As String = StrConv(sText, VbStrConv.LowerCase)

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Chr, ChrW Functions
String Data Type (Visual Basic)
Type Conversion Functions
ArgumentException
Visual Basic Language Reference

StrDup Function
Returns a string or object consisting of the specified character repeated the specified number of times.

Public Shared Function StrDup( _


ByVal Number As Integer, _
ByVal Character As { Char | String } _
) As String
' -or-
Public Shared Function StrDup( _
ByVal Number As Integer, _
ByVal Character As Object _
) As Object

Parameters
Number
Required. Integer expression. The length to the string to be returned.
Character
Required. Any valid Char, String, or Object expression. Only the first character of the expression will be used. If Character is
of type Object, it must contain either a Char or a String value.
Exceptions
Exception type Error number Condition
ArgumentException 5 Number is less than 0 or Character type is not valid.

ArgumentNullException 5 Character is Nothing.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
This function returns a String made up of repeated characters. The character that makes up the string is the first character in
the Character argument, and it is duplicated Number number of times.
Example
This example uses the StrDup function to return a string of duplicated characters.
VB
Dim aString As String = "Wow! What a string!"
Dim aObject As New Object
Dim TestString As String
aObject = "This is a String contained within an Object"
' Returns "PPPPP"
TestString = StrDup(5, "P")
' Returns "WWWWWWWWWW"
TestString = StrDup(10, aString)
' Returns "TTTTTT"
TestString = CStr(StrDup(6, aObject))

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
SPC Function
ArgumentException
ArgumentNullException
Visual Basic Language Reference

StrReverse Function (Visual Basic)


Returns a string in which the character order of a specified string is reversed.

Public Function StrReverse(ByVal Expression As String) As String

Parameters
Expression
Required. String expression whose characters are to be reversed. If Expression is a zero-length string (""), a zero-length string
is returned.
Remarks
The StrReverse function returns a string that contains the same characters as Expression, but in the opposite order.
Example
VB
Dim TestString As String = "ABCDEFG"
' Returns "GFEDCBA".
Dim revString As String = StrReverse(TestString)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
InStrRev Function (Visual Basic)
Visual Basic Language Reference

Switch Function
Evaluates a list of expressions and returns an Object value corresponding to the first expression in the list that is True.

Public Function Switch( _


ByVal ParamArray VarExpr() As Object _
) As Object

Parameters
VarExpr
Required. Object parameter array. Must have an even number of elements. You can supply a list of Object variables or
expressions separated by commas, or a single-dimensional array of Object elements.
Exceptions
Exception type Error number Condition
ArgumentException 5 Number of arguments is odd.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The argument supplied to VarExpr consists of paired expressions and values. The Switch function evaluates the odd-
numbered expressions from lowest to highest index in VarExpr, and returns the even-numbered value associated with the first
expression that evaluates to True. For example, if VarExpr(0) is True, Switch returns VarExpr(1), and if VarExpr(0) is False but
VarExpr(2) is True, Switch returns VarExpr(3), and so on.
If you do not supply the VarExpr argument, Switch returns Nothing.
Note
The expressions in the argument list can include function calls. As part of preparing the argument list for the call to Switch, t
he Visual Basic compiler calls every function in every expression. This means that you cannot rely on a particular function not
being called if an expression earlier in the argument list is True.

Example
The following example uses the Switch function to return the name of a language that matches the name of a city. It requires
that Option Strict be Off.
VB
Function matchLanguage(ByVal cityName As String) As String
Return CStr(Microsoft.VisualBasic.Switch( _
cityName = "London", "English", _
cityName = "Rome", "Italian", _
cityName = "Paris", "French"))
End Function

Because the System.Diagnostics namespace also contains a class called Switch, a call to the Switch function must be qualified
with the Microsoft.VisualBasic namespace.
Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Choose Function
IIf Function
Select...Case Statement (Visual Basic)
Concepts
Parameter Arrays
Visual Basic Language Reference

SYD Function
Returns a Double specifying the sum-of-years digits depreciation of an asset for a specified period.

Function SYD( _
ByVal Cost As Double, _
ByVal Salvage As Double, _
ByVal Life As Double, _
ByVal Period As Double _
) As Double

Parameters
Cost
Required. Double specifying the initial cost of the asset.
Salvage
Required. Double specifying the value of the asset at the end of its useful life.
Life
Required. Double specifying the length of the useful life of the asset.
Period
Required. Double specifying the period for which asset depreciation is calculated.
Exceptions
Exception type Error number Condition
ArgumentException 5 Salvage < 0, Period > Life, or Period <=0.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Life and Period arguments must be expressed in the same units. For example, if Life is given in months, Period must also
be given in months. All arguments must be positive numbers.
Example
This example uses the SYD function to return the depreciation of an asset for a specified period given the asset's initial cost
(InitCost), the salvage value at the end of the asset's useful life (SalvageVal), and the total life of the asset in years (LifeTime).
VB
Dim InitCost, SalvageVal, LifeTime, DepYear As Double
Dim Fmt As String = "###,##0.00"

InitCost = CDbl(InputBox("What's the initial cost of the asset?"))


SalvageVal = CDbl(InputBox("Enter the asset's value at end of its life."))
LifeTime = CDbl(InputBox("What's the asset's useful life in years?"))

' Use the SLN function to calculate the deprecation per year.
Dim SlnDepr As Double = SLN(InitCost, SalvageVal, LifeTime)
Dim msg As String = "The depreciation per year: " & Format(SlnDepr, Fmt)
msg &= vbCrLf & "Year" & vbTab & "Linear" & vbTab & "Doubling" & vbCrLf

' Use the SYD and DDB functions to calculate the deprecation for each year.
For DepYear = 1 To LifeTime
msg &= DepYear & vbTab & _
Format(SYD(InitCost, SalvageVal, LifeTime, DepYear), Fmt) & vbTab & _
Format(DDB(InitCost, SalvageVal, LifeTime, DepYear), Fmt) & vbCrLf
Next
MsgBox(msg)

Requirements
Namespace: Microsoft.VisualBasic
Module: Financial
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DDB Function
SLN Function
Financial Summary
ArgumentException
Visual Basic Language Reference

SystemTypeName Function
Returns a String value containing the system data type name of a variable.

Public Function SystemTypeName(ByVal VbName As String) As String

Parameters
VbName
Required. A String variable containing a Visual Basic type name.
Remarks
SystemTypeName returns the fully qualified common language runtime (CLR) type name corresponding to the Visual Basic
type name. For example, if VbName contains "Date", SystemTypeName returns "System.DateTime". If SystemTypeName
does not recognize the value of VbName, it returns Nothing (not the string "Nothing").
Example
The following example uses the SystemTypeName function to return data type names for several variables.
VB
Dim vbLongName As String = "Long"
Dim vbDateName As String = "Date"
Dim vbBadName As String = "Number"
Dim testSysName As String
testSysName = SystemTypeName(vbLongName)
' The preceding call returns "System.Int64".
testSysName = SystemTypeName(vbDateName)
' The preceding call returns "System.DateTime".
testSysName = SystemTypeName(vbBadName)
' The preceding call returns Nothing.

Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Data Type Summary (Visual Basic)
String Data Type (Visual Basic)
VbTypeName Function
Visual Basic Language Reference

TAB Function
Used with the Print or PrintLine functions to position output.

Public Overloads Function TAB() As TABInfo


' -or-
Public Overloads Function TAB(ByVal Column As Short) As TABInfo

Parameters
Column
Optional. The column number moved to before displaying or printing the next expression in a list. If omitted, TAB moves the
insertion point to the beginning of the next print zone.
Remarks
If the current print position on the current line is greater than Column, TAB skips to the column value equal to Column on the
next output line. If Column is less than 1, TAB moves the print position to column 1. If Column is greater than the output line
width, TAB calculates the next print position using the formula:
Column Mod width
For example, if width is 80 and you specify TAB(90), the next print will start at column 10 (the remainder of 90/80). If Column
is less than the current print position, printing begins on the next line at the calculated print position. If the calculated print
position is greater than the current print position, printing begins at the calculated print position on the same line.
The leftmost print position on an output line is always 1. When you use the Print or PrintLine functions to print to files, the
rightmost print position is the current width of the output file, which you can set using the FileWidth function.
The TAB function can also be used with the WriteLine function. It cannot be used with System.Diagnostics.Debug.WriteLine or
System.Console.WriteLine.
Note
Make sure your tabular columns are wide enough to accommodate wide letters.

Example
This example uses the TAB function to position output in a file and in the Output window.
VB
FileOpen(1, "TESTFILE", OpenMode.Output) ' Open file for output.
' The second word prints at column 20.
Print(1, "Hello", TAB(20), "World.")
' If the argument is omitted, cursor is moved to the next print zone.
Print(1, "Hello", TAB(), "World")
FileClose(1)

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Mod Operator (Visual Basic)
Print, PrintLine Functions
Space Function (Visual Basic)
SPC Function
FileWidth Function
Visual Basic Language Reference

TimeSerial Function (Visual Basic)


Returns a Date value representing a specified hour, minute, and second, with the date information set relative to January 1 of
the year 1.

Public Function TimeSerial( _


ByVal Hour As Integer, _
ByVal Minute As Integer, _
ByVal Second As Integer _
) As DateTime

Parameters
Hour
Required. Integer expression from 0 through 23. However, values outside this range are also accepted.
Minute
Required. Integer expression from 0 through 59. However, values outside this range are also accepted. The value of Minute
is added to the calculated hour, so a negative value specifies minutes before that hour.
Second
Required. Integer expression from 0 through 59. However, values outside this range are also accepted. The value of Second
is added to the calculated minute, so a negative value specifies seconds before that minute.
Exceptions
Exception type Error number Condition
ArgumentException 5 Argument is outside the range -2,147,483,648 through 2,147,483,647

ArgumentOutOfRangeException 9 Calculated time is less than negative 24 hours.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The following example demonstrates negative, zero, and positive argument values. The TimeSerial function returns a time
representing 15 minutes before three hours before noon, or 8:45:00 AM.

Dim alarmTime As Date = TimeSerial(12 - 3, -15, 0)

If either Minute or Second exceeds its normal range, it is applied to the next larger unit as appropriate. For example, if you
specify 75 minutes, it is evaluated as one hour and 15 minutes.
TimeSerial reduces the total seconds modulo 86,400, which is the number of seconds in a day. Therefore, the returned time is
always between 00:00:00 and 23:59:59.
The Date data type includes date components. TimeSerial sets all of these to 1, so the returned value represents the first day
of the year 1. However, if the values of the arguments cause the calculated time to exceed 24 hours, the day is incremented as
necessary. In the following example, the values of Hour and Minute result in a combined time of more than 24 hours.

MsgBox(TimeSerial(23, 75, 0))


' The preceding statement displays "1/2/0001 12:15:00 AM".

If the values of the arguments result in a negative calculated time, the date information is set to 1/1/0001 and the time
information is adjusted to be between 00:00:00 and 23:59:59. However, if the calculated time is less than negative 24 hours, an
ArgumentOutOfRangeException error occurs.
Since every Date value is supported by a System.DateTime structure, its methods give you additional options in assembling a
Date value. For example, you can employ one of the overloaded DateTime constructors to populate a Date variable using the
desired combination of components. The following example sets newDateTime to May 6, 1978 at one tenth of a second before
8:30 in the morning:

Dim newDateTime As Date = New Date(1978, 5, 6, 8, 29, 59, 900)

Example
The following example uses the TimeSerial function to return a time for the specified hour, minute, and second.
VB
Dim thisTime As Date
thisTime = TimeSerial(16, 35, 17)

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DateSerial Function (Visual Basic)
DateValue Function (Visual Basic)
Hour Function (Visual Basic)
Minute Function
Now Property
Second Function (Visual Basic)
TimeValue Function (Visual Basic)
Visual Basic Language Reference

TimeValue Function (Visual Basic)


Returns a Date value containing the time information represented by a string, with the date information set to January 1 of the
year 1.

Public Function TimeValue(ByVal StringTime As String) As DateTime

Parameters
StringTime
Required. String expression representing a date/time value from 00:00:00 on January 1 of the year 1 through 23:59:59 on
December 31, 9999.
Exceptions
Exception type Error number Condition
InvalidCastException 13 StringTime includes invalid date information.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
You can enter valid times using a 12-hour or 24-hour clock. For example, "2:24 P.M." and "14:24" are both valid StringTime
arguments.
If the StringTime argument includes date information, TimeValue does not include it in the returned value. However, if
StringTime includes invalid date information, for example "January 32," an InvalidCastException error occurs.
Example
The following example uses the TimeValue function to convert a string to a time. You can also use date literals to directly
assign a time to a Date variable.
VB
Dim thisTime As Date
thisTime = TimeValue("4:35:17 PM")

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
DateSerial Function (Visual Basic)
DateValue Function (Visual Basic)
Hour Function (Visual Basic)
Minute Function
Now Property
Second Function (Visual Basic)
TimeSerial Function (Visual Basic)
DateTime
Visual Basic Language Reference

Trim, LTrim, and RTrim Functions


Returns a string containing a copy of a specified string with no leading spaces (LTrim), no trailing spaces (RTrim), or no
leading or trailing spaces (Trim).

Public Shared Function LTrim(ByVal str As String) As String


Public Shared Function RTrim(ByVal str As String) As String
Public Shared Function Trim(ByVal str As String) As String

Parameters
str
Required. Any valid String expression.
Remarks
The LTrim, RTrim, and Trim functions remove spaces from the ends of strings. To remove other forms of white space, such as
tab characters, use the System.String.Trim method.
Example
This example uses the LTrim function to strip leading spaces and the RTrim function to strip trailing spaces from a string
variable. It uses the Trim function to strip both types of spaces.
VB
' Initializes string.
Dim TestString As String = " <-Trim-> "
Dim TrimString As String
' Returns "<-Trim-> ".
TrimString = LTrim(TestString)
' Returns " <-Trim->".
TrimString = RTrim(TestString)
' Returns "<-Trim->".
TrimString = LTrim(RTrim(TestString))
' Using the Trim function alone achieves the same result.
' Returns "<-Trim->".
TrimString = Trim(TestString)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
Left Function (Visual Basic)
Right Function (Visual Basic)
Trim
Visual Basic Language Reference

TypeName Function (Visual Basic)


Returns a String value containing data-type information about a variable.

Public Function TypeName(ByVal VarName As Object) As String

Parameters
VarName
Required. Object variable. If Option Strict is Off, you can pass a variable of any data type except a structure.
Remarks
The following table shows the String values returned by TypeName for different contents of VarName.
VarName contents String returned
16-bit True or False value type "Boolean"

8-bit binary value type "Byte"

16-bit character value type "Char"

64-bit date and time value type "Date"

Reference type indicating missing or nonexistent data "DBNull"

128-bit fixed-point numeric value type "Decimal"

64-bit floating-point numeric value type "Double"

32-bit integer value type "Integer"

Reference type pointing to an unspecialized object "Object"

Reference type pointing to a specialized object created from class objectclass "objectclass"

64-bit integer value type "Long"

Reference type with no object currently assigned to it "Nothing"

8-bit signed integer value type "SByte"

16-bit integer value type "Short"

32-bit floating-point numeric value type "Single"

Reference type pointing to a string of 16-bit characters "String"

32-bit unsigned integer value type "UInteger"

64-bit unsigned integer value type "ULong"

16-bit unsigned integer value type "UShort"


If VarName is an array, the returned string can be any one of the strings in the preceding table with empty parentheses
appended. For example, if VarName points to an array of integers, TypeName returns "Integer()".
When TypeName returns the name of a reference type such as a class, it returns only the name itself, not the qualified name.
For example, if VarName points to an object of class System.Drawing.Printing.PaperSource, TypeName returns
"PaperSource". Note that if the variable is declared to be of a certain class type but does not have an object assigned to it,
TypeName returns "Nothing".
Example
The following example uses the TypeName function to return data type information about several variables.
VB
Dim testType As String
Dim strVar As String = "String for testing"
Dim decVar As Decimal
Dim intVar, arrayVar(5) As Integer
testType = TypeName(strVar)
' The preceding call returns "String".
testType = TypeName(decVar)
' The preceding call returns "Decimal".
testType = TypeName(intVar)
' The preceding call returns "Integer".
testType = TypeName(arrayVar)
' The preceding call returns "Integer()".

Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Data Type Summary (Visual Basic)
IsArray Function (Visual Basic)
IsDate Function (Visual Basic)
IsDBNull Function
IsError Function
IsNothing Function
IsNumeric Function (Visual Basic)
IsReference Function
Visual Basic Language Reference

UBound Function (Visual Basic)


Returns the highest available subscript for the indicated dimension of an array.

Public Function UBound( _


ByVal Array As System.Array, _
Optional ByVal Rank As Integer = 1 _
) As Integer

Parameters
Array
Required. Array of any data type. The array in which you want to find the highest possible subscript of a dimension.
Rank
Optional. Integer. The dimension for which the highest possible subscript is to be returned. Use 1 for the first dimension, 2
for the second, and so on. If Rank is omitted, 1 is assumed.
Return Value
Integer. The highest value the subscript for the specified dimension can contain. If Array has only one element, UBound
returns 0. If Array has no elements, for example if it is a zero-length string, UBound returns -1.
Exceptions
Exception type Error number Condition
ArgumentNullException 9 Array is Nothing

RankException 9 Rank is less than 1 or Rank is greater than the rank of Array.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Since array subscripts start at 0, the length of a dimension is greater by one than the highest available subscript for that
dimension.
For an array with the following dimensions, UBound returns the values in the following table:

Dim a(100, 5, 4) As Byte

Call to UBound Return value


UBound(a, 1) 100

UBound(a, 2) 5

UBound(a, 3) 4

You can use UBound to determine the total number of elements in an array, but you must adjust the value it returns to
account for the fact that the subscripts start at 0. The following example calculates the total size of the array a in the preceding
example:

Dim total As Integer


total = (UBound(A, 1) + 1) * (UBound(A, 2) + 1) * (UBound(A, 3) + 1)

The value calculated for total is 3030, which is 101 * 6 * 5.


Example
The following example uses the UBound function to determine the highest available subscript for the indicated dimension of
an array.
VB
Dim highest, bigArray(10, 15, 20), littleArray(6) As Integer
highest = UBound(bigArray, 1)
highest = UBound(bigArray, 3)
highest = UBound(littleArray)
' The three calls to UBound return 10, 20, and 6 respectively.

Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
LBound Function (Visual Basic)
Dim Statement (Visual Basic)
ReDim Statement (Visual Basic)
ArgumentException
RankException
Visual Basic Language Reference

UCase Function (Visual Basic)


Returns a string or character containing the specified string converted to uppercase.

Public Shared Function UCase(ByVal Value As Char) As Char


' -or-
Public Shared Function UCase(ByVal Value As String) As String

Parameters
Value
Required. Any valid String or Char expression.
Remarks
Only lowercase letters are converted to uppercase; all uppercase letters and nonletter characters remain unchanged.
This function uses the application's culture information when manipulating the string so that the case changes are appropriate
for the locale in which the application is being used.
Security Note
If your application makes security decisions based on the result of a comparison or case-change operation, then the operatio
n should use the System.String.Compare(System.String,System.String,System.StringComparison) method, and pass Ordinal
or OrdinalIgnoreCase for the comparisonType argument. For more information, see
How Culture Affects Strings in Visual Basic.

Example
This example uses the UCase function to return an uppercase version of a string.
VB
' String to convert.
Dim LowerCase As String = "Hello World 1234"
' Returns "HELLO WORLD 1234".
Dim UpperCase As String = UCase(LowerCase)

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
String Manipulation Summary
LCase Function (Visual Basic)
Other Resources
Strings in Visual Basic
Introduction to Strings in Visual Basic
Visual Basic Language Reference

Val Function
Returns the numbers contained in a string as a numeric value of appropriate type.

Public Overloads Function Val(ByVal InputStr As String) As Double


' -or-
Public Overloads Function Val(ByVal Expression As Object) As Double
' -or-
Public Overloads Function Val(ByVal Expression As Char) As Integer

Parameters
Expression, InputStr
Required. Any valid String expression, Object variable, or Char value. If Expression is of type Object, its value must be
convertible to String or an ArgumentException error occurs.
Exceptions
Exception type Error number Condition
OverflowException 6 InputStr is too large.

InvalidCastException 13 Number is badly formed.

ArgumentException 438 Object type expression not convertible to String.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Val function stops reading the string at the first character it cannot recognize as part of a number. Symbols and characters
that are often considered parts of numeric values, such as dollar signs and commas, are not recognized. However, the function
recognizes the radix prefixes &O (for octal) and &H (for hexadecimal). Blanks, tabs, and linefeed characters are stripped from the
argument.
The following call returns the value 1615198.

Val(" 1615 198th Street N.E.")

The following call returns the decimal value -1.

Val("&HFFFF")

Note
The Val function recognizes only the period (.) as a valid decimal separator. When different decimal separators are used, as i
n international applications, use CDbl or CInt instead to convert a string to a number. To convert the string representation of
a number in a particular culture to a numeric value, use the numeric type's Parse(String, IFormatProvider) method. For e
xample, use System.Double.Parse(System.String,System.IFormatProvider) when converting a string to a Double.

Example
The following example uses the Val function to return the numbers contained in each string. Val stops converting at the first
character that cannot be interpreted as a numeric digit, numeric modifier, numeric punctuation, or white space.
VB
Dim valResult As Double
' The following line of code sets valResult to 2457.
valResult = Val("2457")
' The following line of code sets valResult to 2457.
valResult = Val(" 2 45 7")
' The following line of code sets valResult to 24.
valResult = Val("24 and 57")

Requirements
Namespace: Microsoft.VisualBasic
Module: Conversion
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Str Function
Type Conversion Functions
OverflowException
InvalidCastException
ArgumentException
Visual Basic Language Reference

VarType Function (Visual Basic)


Returns an Integer value containing the data type classification of a variable.

Public Function VarType(ByVal VarName As Object) As VariantType

Parameters
VarName
Required. Object variable. If Option Strict is Off, you can pass a variable of any data type except a structure.
Remarks
The integer value returned by VarType is a member of the VariantType Enumeration.
The following table shows the values returned by VarType for special cases of VarName.
Data type represented by VarNam Value returned by VarType
e
Nothing (Visual Basic) VariantType.Object

DBNull VariantType.Null

Enumeration Underlying data type (SByte, Byte, Short, UShort, Integer, UInteger, Long, or ULong
)

Array Bitwise OR of array element type and VariantType.Array

Array of arrays Bitwise OR of VariantType.Object and VariantType.Array

Structure (System.ValueType) VariantType.UserDefinedType

Exception VariantType.Error

Unknown VariantType.Object
Example
The following example uses the VarType function to return data type classification information about several variables.
VB
Dim testString As String = "String for testing"
Dim testObject As New Object
Dim testNumber, testArray(5) As Integer
Dim testVarType As VariantType
testVarType = VarType(testVarType)
' Returns VariantType.Integer.
testVarType = VarType(testString)
' Returns VariantType.String.
testVarType = VarType(testObject)
' Returns VariantType.Object.
testVarType = VarType(testNumber)
' Returns VariantType.Integer.
testVarType = VarType(testArray)
' Returns the bitwise OR of VariantType.Array and VariantType.Integer.

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Data Type Summary (Visual Basic)
Object Data Type
VariantType Enumeration
Visual Basic Language Reference

VbTypeName Function
Returns a String value containing the Visual Basic data type name of a variable.

Public Function VbTypeName(ByVal UrtName As String) As String

Parameters
UrtName
Required. String variable containing a type name used by the common language runtime.
Remarks
VbTypeName returns the Visual Basic type name corresponding to the common language runtime type name. For example, if
UrtName contains "Int32" or "System.Int32", VbTypeName returns "Integer". If VbTypeName does not recognize the value
of UrtName, it returns Nothing (not the string "Nothing").
The type name in UrtName can be obtained from various sources, for example from the Name property in the MemberInfo
array of the Type class.
Example
The following example uses the VbTypeName function to return data type names for several variables.
VB
Dim sysDateName As String = "System.DateTime"
Dim sysShortName As String = "Int16"
Dim sysBadName As String = "Nonsense"
Dim testVbName As String
testVbName = VbTypeName(sysDateName)
' Returns "Date".
testVbName = VbTypeName(sysShortName)
' Returns "Short".
testVbName = VbTypeName(sysBadName)
' Returns Nothing.

Requirements
Namespace: Microsoft.VisualBasic
Module: Information
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Data Type Summary (Visual Basic)
String Data Type (Visual Basic)
SystemTypeName Function
Visual Basic Language Reference

Weekday Function (Visual Basic)


Returns an Integer value containing a number representing the day of the week.

Public Function Weekday( _


ByVal DateValue As DateTime, _
Optional ByVal DayOfWeek As FirstDayOfWeek = FirstDayOfWeek.Sunday _
) As Integer

Parameters
DateValue
Required. Date value for which you want to determine the day of the week.
DayOfWeek
Optional. A value chosen from the FirstDayOfWeek enumeration that specifies the first day of the week. If not specified,
FirstDayOfWeek.Sunday is used.
Settings
The DayOfWeek argument can have one of the following settings.
Enumeration value Value Description
FirstDayOfWeek.System 0 First day of week specified in system settings

FirstDayOfWeek.Sunday 1 Sunday (default)

FirstDayOfWeek.Monday 2 Monday (complies with ISO standard 8601, section 3.17)

FirstDayOfWeek.Tuesday 3 Tuesday

FirstDayOfWeek.Wednesday 4 Wednesday

FirstDayOfWeek.Thursday 5 Thursday

FirstDayOfWeek.Friday 6 Friday

FirstDayOfWeek.Saturday 7 Saturday
Exceptions
Exception type Error number Condition
ArgumentException 5 DayOfWeek is less than 0 or more than 7.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The value returned by the Weekday function is the day of the week that the DateValue corresponds to, relative to the first day
of the week defined by the DayOfWeek value. For example, if the date refers to a Wednesday and the first day of the week is
specified as Monday, the function returns 3.
Note
Weekday uses the current calendar setting from the CurrentCulture property of the CultureInfo class in the
System.Globalization namespace. The default CurrentCulture values are determined by Control Panel settings.
Example
The following example uses the Weekday function to obtain the day of the week from a specified date.
VB
Dim oldDate As Date
Dim oldWeekDay As Integer
oldDate = #2/12/1969#
oldWeekDay = Weekday(oldDate)
' oldWeekDay now contains 4 because thisDate represents a Wednesday.

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Day Function (Visual Basic)
Month Function (Visual Basic)
Now Property
WeekdayName Function (Visual Basic)
Year Function (Visual Basic)
DatePart Function (Visual Basic)
DateTime
Visual Basic Language Reference

WeekdayName Function (Visual Basic)


Returns a String value containing the name of the specified weekday.

Public Function WeekdayName( _


ByVal Weekday As Integer, _
Optional ByVal Abbreviate As Boolean = False, _
Optional ByVal FirstDayOfWeekValue As FirstDayOfWeek = FirstDayOfWeek.System _
) As String

Parameters
Weekday
Required. Integer. The numeric designation for the weekday, from 1 through 7; 1 indicates the first day of the week and 7
indicates the last day of the week. The identities of the first and last days depend on the setting of FirstDayOfWeekValue.
Abbreviate
Optional. Boolean value that indicates if the weekday name is to be abbreviated. If omitted, the default is False, which
means the weekday name is not abbreviated.
FirstDayOfWeekValue
Optional. A value chosen from the FirstDayOfWeek enumeration that specifies the first day of the week. If not specified,
FirstDayOfWeek.System is used.
Settings
The FirstDayOfWeekValue argument can have one of the following settings.
Enumeration value Value Description
FirstDayOfWeek.System 0 First day of week specified in system settings (default)

FirstDayOfWeek.Sunday 1 Sunday

FirstDayOfWeek.Monday 2 Monday (complies with ISO standard 8601, section 3.17)

FirstDayOfWeek.Tuesday 3 Tuesday

FirstDayOfWeek.Wednesday 4 Wednesday

FirstDayOfWeek.Thursday 5 Thursday

FirstDayOfWeek.Friday 6 Friday

FirstDayOfWeek.Saturday 7 Saturday
Exceptions
Exception type Error numb Condition
er
ArgumentException 5 Weekday is less than 1 or greater than 7, or FirstDayOfWeekValue is less than 0 or greater t
han 7.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The string returned by WeekdayName depends not only on the input arguments, but also on the Regional Options settings
specified in the Windows Control Panel.
Note
WeekdayName uses the current calendar setting from the CurrentCulture property of the CultureInfo class in the
System.Globalization namespace. The default CurrentCulture values are determined by Control Panel settings.

Example
The following example uses the Weekday function to obtain the day of the week from a specified date, and then the
WeekDayName function to obtain the name of the weekday from its number.
VB
Dim oldDate As Date
Dim oldWeekDayName As String
oldDate = #2/12/1969#
oldWeekDayName = WeekdayName(Weekday(oldDate))
' oldWeekDayName now contains "Wednesday".

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Day Function (Visual Basic)
Month Function (Visual Basic)
Now Property
Weekday Function (Visual Basic)
MonthName Function (Visual Basic)
Year Function (Visual Basic)
DatePart Function (Visual Basic)
DateTime
Visual Basic Language Reference

Write, WriteLine Functions


Writes data to a sequential file. Data written with Write is usually read from a file with Input.

Public Sub Write( _


ByVal FileNumber As Integer, _
ByVal ParamArray Output As Object _
)
' -or-
Public Sub WriteLine( _
ByVal FileNumber As Integer, _
ByVal ParamArray Output() As Object _
)

Parameters
FileNumber
Required. An Integer expression containing any valid file number.
Output
Optional. One or more comma-delimited expressions to write to a file.
Exceptions
Exception type Error number Condition
IOException 52 FileNumber does not exist.

IOException 54 File mode is invalid.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Write and WriteLine functions are provided for backward compatibility and may have an impact on performance. For
non-legacy applications, the My.Computer.FileSystem object provides better performance. For more information, see
File Access with Visual Basic.
If you omit Output, a blank line is printed to the file. Multiple expressions can be separated with a comma.
Unlike the Print function, the Write function inserts commas between items and quotation marks around strings as they are
written to the file. You do not have to put explicit delimiters in the list. When Write is used to write data to a file, only numeric,
Boolean, date, null, and Error data formats are supported. The following universal assumptions are followed so the data can
always be read and correctly interpreted using Input, regardless of locale:
Numeric data is always written using the period as the decimal separator.
For Boolean data, either #TRUE# or #FALSE# is printed. The True and False keywords are not translated, regardless of
locale.
Date data is written to the file using the universal date format. When either the date or the time component is missing or
zero, only the part provided gets written to the file.
Nothing is written to the file if Output data is empty. However, for null data, #NULL# is written.
For Error data, the output appears as #ERROR errorcode#. The Error keyword is not translated, regardless of locale.

WriteLine inserts a newline character (that is, a carriage return/line feed, or Chr(13) + Chr(10)), after it has written the final
character in Output to the file.
You can embed quotation marks in a string by using double quotation marks, or "". For example,
VB
Dim x As String = "Double quotation marks aren't ""difficult"" to handle."

returns a string with the value of Double quotation marks aren't "difficult" to handle.

Writing to a file with the Write or WriteLine functions requires Append access from the FileIOPermissionAccess
enumeration. For more information, see FileIOPermissionAccess Enumeration.
Example
This example uses the Write function to write raw data to a sequential file.
VB
FileOpen(1, "TESTFILE", OpenMode.Output) ' Open file for output.
Write(1, "This is a test.") ' Print text to file.
WriteLine(1) ' Print blank line to file.
WriteLine(1, "Zone 1", TAB(), "Zone 2") ' Print in two print zones.
WriteLine(1, "Hello", " ", "World") ' Separate strings with space.
WriteLine(1, SPC(5), "5 leading spaces ") ' Print five leading spaces.
WriteLine(1, TAB(10), "Hello") ' Print word at column 10.
' Assign Boolean, Date, and Error values.
Dim aBool As Boolean
Dim aDate As DateTime
aBool = False
aDate = DateTime.Parse("February 12, 1969")
' Dates and Booleans are translated using locale settings of
' your system.
WriteLine(1, aBool, " is a Boolean value")
WriteLine(1, aDate, " is a date")
FileClose(1) ' Close file.

Smart Device Developer Notes


This function is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: FileSystem
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Write Text to Files in Visual Basic
How to: Write Text to Files with a StreamWriter in Visual Basic
Reference
Input Function
FileOpen Function
Print, PrintLine Functions
Other Resources
File Access with Visual Basic
Visual Basic Language Reference

Year Function (Visual Basic)


Returns an Integer value from 1 through 9999 representing the year.

Public Function Year(ByVal DateValue As DateTime) As Integer

Parameters
DateValue
Required. Date value from which you want to extract the year.
Remarks
You can also obtain the year by calling DatePart and specifying DateInterval.Year for the Interval argument.
Example
The following example uses the Year function to obtain the year from a specified date. In the development environment, the
date literal is displayed in short date format using the locale settings of your code.
VB
Dim thisDate As Date
Dim thisYear As Integer
thisDate = #2/12/1969#
thisYear = Year(thisDate)
' thisYear now contains 1969.

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Day Function (Visual Basic)
Month Function (Visual Basic)
Now Property
Weekday Function (Visual Basic)
DatePart Function (Visual Basic)
DateTime
ArgumentOutOfRangeException
Visual Basic Language Reference

Keywords (Visual Basic)


The topics in this section contain tables of the Visual Basic language keywords, both reserved and unreserved.
In This Section
A-E Keywords
F-O Keywords
P-Z Keywords
Related Sections
Visual Basic Reference
Visual Basic
Visual Basic Language Reference

A-E Keywords
The following table contains a listing of Visual Basic language keywords.

Alias AddHandler Ansi As

Assembly Auto Binary ByRef

ByVal Case Catch Class

Custom Default DirectCast Each

Else ElseIf End Error


Smart Device Developer Notes
The following are not supported in smart device applications: Ansi, Auto, and End.
See Also
Reference
F-O Keywords
P-Z Keywords
Other Resources
Visual Basic Reference
Visual Basic Language Reference

Alias
Indicates that an external procedure has another name in its DLL.
Remarks
The Alias keyword can be used in this context:
Declare Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

AddHandler
AddHandler associates an event with an event handler at run time, or declares what code to execute when adding an event
handler.
Remarks
The AddHandler keyword is used in these contexts:
Event Statement
The AddHandler keyword declares a custom AddHandler accessor.
AddHandler Statement
The AddHandler keyword associates an event with an event handler.
See Also
Tasks
How to: Declare Events That Avoid Blocking
How to: Declare Events That Conserve Memory Use
Visual Basic Language Reference

Ansi
Specifies that Visual Basic should marshal all strings to American National Standards Institute (ANSI) values regardless of the
name of the external procedure being declared.
When you call a procedure defined outside your project, the Visual Basic compiler does not have access to the information it
needs to call the procedure correctly. This information includes where the procedure is located, how it is identified, its calling
sequence and return type, and the string character set it uses. The Declare Statement creates a reference to an external
procedure and supplies this necessary information.
The charsetmodifier part in the Declare statement supplies the character set information for marshaling strings during a call
to the external procedure. It also affects how Visual Basic searches the external file for the external procedure name. The Ansi
modifier specifies that Visual Basic should marshal all strings to ANSI values and should look up the procedure without
modifying its name during the search.
If no character set modifier is specified, Ansi is the default.
Remarks
The Ansi modifier can be used in this context:
Declare Statement
Smart Device Developer Notes
This keyword is not supported.
See Also
Reference
Auto
Unicode (Visual Basic)
Visual Basic Language Keywords
Visual Basic Language Reference

As (Visual Basic)
Introduces an As clause, which identifies a data type in a declaration statement or a constraint list on a generic type parameter.
Remarks
The As keyword can be used in these contexts:
Class Statement
Const Statement
Declare Statement
Delegate Statement
Dim Statement
Enum Statement
Event Statement
For...Next Statements
For Each...Next Statements
Function Statement
Interface Statement
Operator Statement
Property Statement
Structure Statement
Sub Statement
Try...Catch...Finally Statements
See Also
Tasks
How to: Create a New Variable
Reference
Type List
Visual Basic Language Keywords
Concepts
Data Types in Visual Basic
Variable Declaration in Visual Basic
Generic Types in Visual Basic
Visual Basic Language Reference

Assembly
Specifies that an attribute at the beginning of a source file applies to the entire assembly.
Remarks
Many attributes pertain to an individual programming element, such as a class or property. You apply such an attribute by
attaching the attribute block, within angle brackets (< >), directly to the declaration statement.
If an attribute pertains not only to the following element but to the entire assembly, you place the attribute block at the
beginning of the source file and identify the attribute with the Assembly keyword. If it applies to the current assembly module,
you use the Module keyword.
You can also apply an attribute to an assembly in the AssemblyInfo.vb file, in which case you do not have to use an attribute
block in your main source-code file.
See Also
Reference
Module (Visual Basic)
Concepts
Application of Attributes
Visual Basic Language Reference

Auto
Specifies that Visual Basic should marshal strings according to .NET Framework rules based on the external name of the
external procedure being declared.
When you call a procedure defined outside your project, the Visual Basic compiler does not have access to the information it
needs to call the procedure correctly. This information includes where the procedure is located, how it is identified, its calling
sequence and return type, and the string character set it uses. The Declare Statement creates a reference to an external
procedure and supplies this necessary information.
The charsetmodifier part in the Declare statement supplies the character set information for marshaling strings during a call
to the external procedure. It also affects how Visual Basic searches the external file for the external procedure name. The Auto
modifier specifies that Visual Basic should marshal strings according to .NET Framework rules, and that it should determine the
base character set of the run-time platform and possibly modify the external procedure name if the initial search fails. For
more information, see "Character Sets" in Declare Statement.
If no character set modifier is specified, Ansi is the default.
Remarks
The Auto modifier can be used in this context:
Declare Statement
Smart Device Developer Notes
This keyword is not supported.
See Also
Reference
Ansi
Unicode (Visual Basic)
Visual Basic Language Keywords
Visual Basic Language Reference

Binary
Sets the string comparison method to a strict binary sort order.
Remarks
The Option Compare statement must appear in a source file before any other statements. It affects string comparison for all
code generated by that source file.
When to Use Binary
You might need to compare string elements based on their true binary value, particularly if the strings can contain characters
that are not to be interpreted as text. In such a case you do not want to bias comparisons with alphabetic equivalences such as
case insensitivity. To specify a pure binary comparison, set Option Compare to Binary.
The Binary keyword can be used in this context:
Option Compare Statement
See Also
Reference
Text
Visual Basic Language Keywords
Visual Basic Language Reference

ByRef
Specifies that an argument is passed in such a way that the called procedure can change the value of a variable underlying the
argument in the calling code.
Remarks
The ByRef modifier can be used in these contexts:
Declare Statement
Function Statement
Sub Statement
See Also
Reference
Visual Basic Language Keywords
Concepts
Argument Passing By Value and By Reference
Visual Basic Language Reference

ByVal
Specifies that an argument is passed in such a way that the called procedure or property cannot change the value of a variable
underlying the argument in the calling code.
Remarks
The ByVal modifier can be used in these contexts:
Declare Statement
Function Statement (Visual Basic)
Operator Statement
Property Statement
Sub Statement (Visual Basic)
See Also
Reference
Visual Basic Language Keywords
Concepts
Argument Passing By Value and By Reference
Visual Basic Language Reference

Case (Visual Basic)


Introduces a value or set of values against which the value of an expression is to be tested.
Remarks
The Case keyword can be used in this context:
Select...Case Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

Catch (Visual Basic)


Introduces a statement block to be run if a particular exception occurs inside a Try block.
Remarks
Each Try structure must include either a Finally block or at least one Catch block.
When to Use Catch
If you anticipate that a particular exception might occur during a particular section of code, put the code in a Try block and use
a Catch block to retain control and handle the exception if it occurs. You can use as many different Catch blocks as necessary
within a Try structure.
The Catch keyword can be used in this context:
Try...Catch...Finally Statement (Visual Basic)
See Also
Reference
Finally (Visual Basic)
Visual Basic Language Keywords
Visual Basic Language Reference

Class (Visual Basic)


Constrains a generic type parameter to require that any type argument passed to it be a reference type, or introduces a
Class Statement (Visual Basic).
Remarks
When you declare a type parameter for a generic type, you can impose a constraint, a set of one or more requirements that
limit the type argument that can be passed to that type parameter. For more information, see "Constraints" in
Generic Types in Visual Basic.
Among the possible requirements in a constraint is that the type argument must be a reference type, for example a String,
array, or delegate, or an object created from a class. You specify this by including the Class keyword in the constraint.
Another possible requirement is that the type argument must be a value type, for example a structure, enumeration, or
elementary data type. You specify a value type requirement by including the Structure (Visual Basic) keyword in the constraint.
You do not have to specify either Class or Structure in a constraint. You cannot specify them both in the same constraint.
The Class constraint is not the same as the Class Statement (Visual Basic).
See Also
Reference
Structure (Visual Basic)
Class Statement (Visual Basic)
Concepts
Generic Types in Visual Basic
Value Types and Reference Types
Visual Basic Language Reference

Custom
Specifies that an event has additional, specialized code for adding handlers, removing handlers, and raising events.
Remarks
The Custom keyword can be used in this context:
Event Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

Default (Visual Basic)


Identifies a property as the default property of its class, structure, or interface.
Remarks
A class, structure, or interface can designate at most one of its properties as the default property, provided that property takes
at least one parameter. If code makes a reference to a class or structure without specifying a member, Visual Basic resolves that
reference to the default property.
Default properties can result in a small reduction in source code-characters, but they can make your code more difficult to
read. If the calling code is not familiar with your class or structure, when it makes a reference to the class or structure name it
cannot be certain whether that reference accesses the class or structure itself, or a default property. This can lead to compiler
errors or subtle run-time logic errors.
You can somewhat reduce the chance of default property errors by always using the Option Strict Statement to set compiler
type checking to On.
If you are planning to use a predefined class or structure in your code, you must determine whether it has a default property,
and if so, what its name is.
Because of these disadvantages, you should consider not defining default properties. For code readability, you should also
consider always referring to all properties explicitly, even default properties.
The Default modifier can be used in this context:
Property Statement
See Also
Tasks
How to: Declare and Call a Default Property in Visual Basic
Reference
Visual Basic Language Keywords
Concepts
Default Properties
Visual Basic Language Reference

DirectCast
Introduces a type conversion operation based on inheritance or implementation.
Remarks
DirectCast does not use the Visual Basic run-time helper routines for conversion, so it can provide somewhat better
performance than CType when converting to and from data type Object.
You use the DirectCast keyword the same way you use the CType Function and the TryCast keyword. You supply an
expression as the first argument and a type to convert it to as the second argument. DirectCast requires an inheritance or
implementation relationship between the data types of the two arguments. This means that one type must inherit from or
implement the other.
Errors and Failures
DirectCast generates a compiler error if it detects that no inheritance or implementation relationship exists. But the lack of a
compiler error does not guarantee a successful conversion. If the desired conversion is narrowing, it could fail at run time. If
this happens, the runtime throws an InvalidCastException error.
Conversion Keywords
A comparison of the type conversion keywords is as follows.
Keyword Data types Argument relationship Run-time failure
CType Function Any data types Widening or narrowing conversion must be defined between the t Throws InvalidCastExce
wo data types ption

DirectCast Any data types One type must inherit from or implement the other type Throws InvalidCastExce
ption

TryCast Reference types One type must inherit from or implement the other type Returns
only Nothing (Visual Basic)
Example
The following example demonstrates two uses of DirectCast, one that fails at run time and one that succeeds.
VB
Dim q As Object = 2.37
Dim i As Integer = CType(q, Integer)
' The following conversion fails at run time
Dim j As Integer = DirectCast(q, Integer)
Dim f As New System.Windows.Forms.Form
Dim c As System.Windows.Forms.Control
' The following conversion succeeds.
c = DirectCast(f, System.Windows.Forms.Control)

In the preceding example, the run-time type of q is Double. CType succeeds because Double can be converted to Integer.
However, the first DirectCast fails at run time because the run-time type of Double has no inheritance relationship with
Integer, even though a conversion exists. The second DirectCast succeeds because it converts from type Form to type Control,
from which Form inherits.
See Also
Concepts
Widening and Narrowing Conversions
Implicit and Explicit Conversions
Visual Basic Language Reference

Each
Specifies the loop variable to be used in a For Each loop.
Remarks
The Each keyword is used in this context:
For Each...Next Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

Else (Visual Basic)


Introduces a group of statements to be run or compiled if no other conditional group of statements has been run or compiled.
Remarks
The Else keyword can be used in these contexts:
If...Then...Else Statement
Select...Case Statement
#If...Then...#Else Directive
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

ElseIf (Visual Basic)


Introduces a condition to be tested if the previous conditional test has failed.
Remarks
The ElseIf keyword can be used in these contexts:
If...Then...Else Statement
#If...Then...#Else Directive
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

End (Visual Basic)


When followed by an additional keyword, terminates the definition of the statement block introduced by that keyword.

End AddHandler
End Class
End Enum
End Event
End Function
End Get
End If
End Interface
End Module
End Namespace
End Operator
End Property
End RaiseEvent
End RemoveHandler
End Select
End Set
End Structure
End Sub
End SyncLock
End Try
End While
End With

Parts
End
Required. Terminates the definition of the programming element.
AddHandler
Required to terminate an AddHandler accessor begun by a matching AddHandler statement in a custom Event Statement.
Class
Required to terminate a class definition begun by a matching Class Statement (Visual Basic).
Enum
Required to terminate an enumeration definition begun by a matching Enum Statement (Visual Basic).
Event
Required to terminate a Custom event definition begun by a matching Event Statement.
Function
Required to terminate a Function procedure definition begun by a matching Function Statement (Visual Basic). If execution
encounters an End Function statement, control returns to the calling code.
Get
Required to terminate a Property procedure definition begun by a matching Get Statement. If execution encounters an End
Get statement, control returns to the statement requesting the property's value.
If
Required to terminate an If...Then...Else block definition begun by a matching If statement. See
If...Then...Else Statement (Visual Basic).
Interface
Required to terminate an interface definition begun by a matching Interface Statement (Visual Basic).
Module
Required to terminate a module definition begun by a matching Module Statement.
Namespace
Required to terminate a namespace definition begun by a matching Namespace Statement.
Operator
Required to terminate an operator definition begun by a matching Operator Statement.
Property
Required to terminate a property definition begun by a matching Property Statement.
RaiseEvent
Required to terminate a RaiseEvent accessor begun by a matching RaiseEvent statement in a custom Event Statement.
RemoveHandler
Required to terminate a RemoveHandler accessor begun by a matching RemoveHandler statement in a custom
Event Statement.
Select
Required to terminate a Select...Case block definition begun by a matching Select statement. See
Select...Case Statement (Visual Basic).
Set
Required to terminate a Property procedure definition begun by a matching Set Statement (Visual Basic). If execution
encounters an End Set statement, control returns to the statement setting the property's value.
Structure
Required to terminate a structure definition begun by a matching Structure Statement.
Sub
Required to terminate a Sub procedure definition begun by a matching Sub Statement (Visual Basic). If execution encounters
an End Sub statement, control returns to the calling code.
SyncLock
Required to terminate a SyncLock block definition begun by a matching SyncLock statement. See SyncLock Statement.
Try
Required to terminate a Try...Catch...Finally block definition begun by a matching Try statement. See
Try...Catch...Finally Statement (Visual Basic).
While
Required to terminate a While loop definition begun by a matching While statement. See
While...End While Statement (Visual Basic).
With
Required to terminate a With block definition begun by a matching With statement. See
With...End With Statement (Visual Basic).
Remarks
The End Statement, without an additional keyword, terminates execution immediately.
When preceded by a number sign (#), the End keyword terminates a preprocessing block introduced by the corresponding
directive.
#End
Required. Terminates the definition of the preprocessing block.
#ExternalSource
Required to terminate an external source block begun by a matching #ExternalSource Directive.
#If
Required to terminate a conditional compilation block begun by a matching #If directive. See #If...Then...#Else Directives.
#Region
Required to terminate a source region block begun by a matching #Region Directive.
Smart Device Developer Notes
The End statement, without an additional keyword, is not supported.
See Also
Reference
End Statement
Visual Basic Language Reference

Error (Visual Basic)


Simulates or responds to a run-time error.
Remarks
The Error keyword can be used in these contexts:
Error Statement
On Error Statement
See Also
Reference
Visual Basic Language Keywords
Other Resources
Exception and Error Handling in Visual Basic
Visual Basic Language Reference

F-O Keywords
The following table contains a listing of Visual Basic language keywords.

False Finally For Friend

Global Handles Implements In

Is Lib Loop Me

Module MustInherit MustOverride MyBase

MyClass Narrowing New Next

Nothing NotInheritable NotOverridable Of

Off On Option Optional

Overloads Overridable Overrides


See Also
Reference
A-E Keywords
P-Z Keywords
Other Resources
Visual Basic Reference
Visual Basic Language Reference

False (Visual Basic)


Represents a Boolean value that fails a conditional test.
Remarks
Boolean Data Type (Visual Basic) values are not stored as numbers, and the stored values are not intended to be equivalent to
numbers. You should never write code that relies on equivalent numeric values for True and False. Whenever possible, you
should restrict usage of Boolean variables to the logical values for which they are designed. If it is necessary to mix Boolean
and numeric values, be sure you understand the conversion method you choose. For more information, see "Boolean Type
Does Not Convert to Numeric Type Accurately" in Troubleshooting Data Types.
See Also
Tasks
Troubleshooting Data Types
Reference
Boolean Data Type (Visual Basic)
True (Visual Basic)
Visual Basic Language Reference

Finally (Visual Basic)


Introduces a statement block to be run before exiting a Try structure.
Remarks
Each Try structure must include either a Finally block or at least one Catch block.
Note
Control does not pass from a Try or Catch block to the corresponding Finally block in the following cases:

An End Statement is encountered within the Try or Catch block.


A StackOverflowException is thrown within the Try or Catch block.
When to Use Finally
If you have one or more statements that must run before you exit the Try structure, use a Finally block. Control passes to the
Finally block just before it passes out of the Try structure. This is true even if an exception occurs anywhere inside the Try
structure.
The Finally keyword can be used in this context:
Try...Catch...Finally Statement (Visual Basic)
See Also
Reference
Catch (Visual Basic)
Visual Basic Language Keywords
Visual Basic Language Reference

For (Visual Basic)


Introduces a loop that is iterated with different values of a loop variable.
Remarks
The For keyword is used in these contexts:
For...Next Statement
For Each...Next Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

Friend (Visual Basic)


Specifies that one or more declared programming elements are accessible only from within the assembly that contains their
declaration.
Remarks
Rules
Declaration Context. You can use Friend only at module, interface, or namespace level. This means the declaration
context for a Friend element must be a source file, namespace, interface, module, class, or structure, and cannot be a
procedure.
Combined Modifiers. You can use the Friend modifier in conjunction with the Protected (Visual Basic) modifier in the
same declaration. This combination confers both friend and protected access on the declared elements, so they are
accessible from anywhere in the same assembly, from their own class, and from derived classes. You can specify
Protected Friend only on members of classes.
Behavior
Access Level. All code within a declaration context can access its elements. Code in other classes, structures, and
modules that are compiled to the same assembly can access all the Friend elements in that assembly.
Friend access is not a superset or subset of protected access.
Access Modifiers. The keywords that specify access level are called access modifiers. For a comparison of the access
modifiers, see Access Levels in Visual Basic.
When to Use Friend
In many cases, you want programming elements such as classes and structures to be used by the entire assembly, not only by
the component that declares them. However, you might not want them to be accessible by code outside the assembly, for
example if the application is proprietary. If you want to limit access to an element in this way, you can declare it with Friend.
Friend access is often the preferred level for an application's programming elements. Note that the access level of an interface,
module, class, or structure defaults to Friend if you do not declare it otherwise.
The Friend modifier can be used in these contexts:
Class Statement
Const Statement
Declare Statement
Delegate Statement
Dim Statement
Enum Statement
Event Statement
Function Statement
Interface Statement
Module Statement
Property Statement
Structure Statement
Sub Statement
See Also
Reference
Public (Visual Basic)
Protected (Visual Basic)
Private (Visual Basic)
Concepts
Access Levels in Visual Basic
Procedures in Visual Basic
Other Resources
Structures: Your Own Data Types
Understanding Classes
Visual Basic Language Reference

Global
Allows you to access a .NET Framework programming element when you have blocked it with your namespace structure.
Remarks
If you have defined a nested hierarchy of namespaces, code inside that hierarchy might be blocked from accessing the System
namespace of the .NET Framework. The following example illustrates a hierarchy in which the SpecialSpace.System
namespace blocks access to System.

Namespace SpecialSpace
Namespace System
Class abc
Function getValue() As System.Int32
Dim n As System.Int32
Return n
End Function
End Class
End Namespace
End Namespace

As a result, the Visual Basic compiler cannot successfully resolve the reference to System.Int32, because SpecialSpace.System
does not define Int32. You can use the Global keyword to start the qualification chain at the outermost level of the .NET
Framework class library. This allows you to specify the System namespace or any other namespace in the class library. The
following example illustrates this.

Namespace SpecialSpace
Namespace System
Class abc
Function getValue() As Global.System.Int32
Dim n As Global.System.Int32
Return n
End Function
End Class
End Namespace
End Namespace

You can use Global to access other root-level namespaces, such as Microsoft.VisualBasic, and any namespace associated with
your project.
The Global keyword can be used in these contexts:
Class Statement (Visual Basic)
Const Statement (Visual Basic)
Declare Statement
Delegate Statement
Dim Statement (Visual Basic)
Enum Statement (Visual Basic)
Event Statement
For...Next Statement (Visual Basic)
For Each...Next Statement (Visual Basic)
Function Statement (Visual Basic)
Interface Statement (Visual Basic)
Operator Statement
Property Statement
Structure Statement
Sub Statement (Visual Basic)
Try...Catch...Finally Statement (Visual Basic)
Using Statement (Visual Basic)
See Also
Reference
Namespace Statement
.NET Framework Class Library Reference
System
Microsoft.VisualBasic
Visual Basic Language Reference

Handles
Declares that a procedure handles a specified event.

proceduredeclaration Handles eventlist

Parts
proceduredeclaration
The Sub procedure declaration for the procedure that will handle the event.
eventlist
List of the events for proceduredeclaration to handle. The events must be raised by either the base class for the current class,
or by an object declared using the WithEvents keyword.
Remarks
Use the Handles keyword at the end of a procedure declaration to cause it to handle events raised by an object variable
declared using the WithEvents keyword. The Handles keyword can also be used in a derived class to handle events from a
base class.
The signature of the procedure must match the signatures of each event in eventlist.
The Handles keyword and the AddHandler statement both allow you to specify that particular procedures handle particular
events, but there are differences. Use the Handles keyword when defining a procedure to specify that it handles a particular
event. The AddHandler statement connects procedures to events at run time. For more information, see
AddHandler Statement.
For custom events, the application invokes the event's AddHandler accessor when it adds the procedure as an event handler.
For more information on custom events, see Event Statement.
Example
VB
Public Class ContainerClass
' Module or class level declaration.
WithEvents Obj As New Class1

Public Class Class1


' Declare an event.
Public Event Ev_Event()
Sub CauseSomeEvent()
' Raise an event.
RaiseEvent Ev_Event()
End Sub
End Class

Sub EventHandler() Handles Obj.Ev_Event


' Handle the event.
MsgBox("EventHandler caught event.")
End Sub
' Call the TestEvents procedure from an instance of the ContainerClass
' class to test the Ev_Event event and the event handler.
Public Sub TestEvents()
Obj.CauseSomeEvent()
End Sub
End Class

The following example demonstrates how a derived class can use the Handles statement to handle an event from a base class.
VB
Public Class BaseClass
' Declare an event.
Event Ev1()
End Class
Class DerivedClass
Inherits BaseClass
Sub TestEvents() Handles MyBase.Ev1
' Add code to handle this event.
End Sub
End Class

See Also
Reference
WithEvents
AddHandler Statement
RemoveHandler Statement
Event Statement
RaiseEvent Statement
Concepts
Events and Event Handlers
Visual Basic Language Reference

Implements (Visual Basic)


Indicates that a class or structure member is providing the implementation for a member defined in an interface.
Remarks
The Implements keyword is not the same as the Implements Statement. You use the Implements statement to specify that a
class or structure implements one or more interfaces, and then for each member you use the Implements keyword to specify
which interface and which member it implements.
If a class or structure implements an interface, it must include the Implements statement immediately after the
Class Statement (Visual Basic) or Structure Statement, and it must implement all the members defined by the interface.
Reimplementation
In a derived class, you can reimplement an interface member that the base class has already implemented. This is different
from overriding the base class member in the following respects:
The base class member does not need to be Overridable to be reimplemented.
You can reimplement the member with a different name.
The Implements keyword can be used in these contexts:
Event Statement
Function Statement (Visual Basic)
Property Statement
Sub Statement (Visual Basic)
See Also
Reference
Implements Statement
Interface Statement (Visual Basic)
Class Statement (Visual Basic)
Structure Statement
Concepts
Implements Keyword and Implements Statement
Visual Basic Language Reference

In (Visual Basic)
Specifies the group that the loop variable is to traverse in a For Each loop.
Remarks
The In keyword can be used in this context:
For Each...Next Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

Is (Visual Basic)
Introduces an Is clause that makes a comparison.
Remarks
The Is keyword is used with the TypeOf keyword in a TypeOf...Is expression to test whether the run-time type of an
expression is compatible with a given type.
The Is keyword can be used in these contexts:
Is Operator
Select...Case Statement
See Also
Reference
TypeOf Operator (Visual Basic)
Visual Basic Language Keywords
Visual Basic Language Reference

Lib
Introduces a Lib clause, which identifies the external file (DLL or code resource) containing an external procedure.
Remarks
The Lib keyword can be used in this context:
Declare Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

Loop
Terminates a loop introduced with a Do statement.
Remarks
The Loop keyword can be used in this context:
Do...Loop Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

Me
Provides a way to refer to the specific instance of a class or structure in which the code is currently executing.
Remarks
The Me keyword behaves like either an object variable or a structure variable referring to the current instance. Using Me is
particularly useful for passing information about the currently executing instance of a class or structure to a procedure in
another class, structure, or module. For example, suppose you have the following procedure in a module.

Sub ChangeFormColor(FormName As Form)


Randomize()
FormName.BackColor = Color.FromArgb(Rnd() * 256, Rnd() * 256, Rnd() * 256)
End Sub

You can call this procedure and pass the current instance of the Form class as an argument using the following statement.

ChangeFormColor(Me)

The Me keyword can be used in these contexts:


Class Statement
Structure Statement
See Also
Reference
MyBase
MyClass
Concepts
Object Variable Assignment
Visual Basic Language Reference

Module (Visual Basic)


Specifies that an attribute at the beginning of a source file applies to the current assembly module.
Remarks
Many attributes pertain to an individual programming element, such as a class or property. You apply such an attribute by
attaching the attribute block, within angle brackets (< >), directly to the declaration statement.
If an attribute pertains not only to the following element but to the current assembly module, you place the attribute block at
the beginning of the source file and identify the attribute with the Module keyword. If it applies to the entire assembly, you
use the Assembly keyword.
The Module modifier is not the same as the Module Statement.
See Also
Reference
Assembly
Module Statement
Concepts
Application of Attributes
Visual Basic Language Reference

MustInherit
Specifies that a class can be used only as a base class and that you cannot create an object directly from it.
Remarks
The purpose of a base class (also known as an abstract class) is to define functionality that is common to all the classes derived
from it. This saves the derived classes from having to redefine the common elements. In some cases, this common functionality
is not complete enough to make a usable object, and each derived class defines the missing functionality. In such a case, you
want the consuming code to create objects only from the derived classes. You use MustInherit on the base class to enforce
this.
Another use of a MustInherit class is to restrict a variable to a set of related classes. You can define a base class and derive all
these related classes from it. The base class does not need to provide any functionality common to all the derived classes, but it
can serve as a filter for assigning values to variables. If your consuming code declares a variable as the base class, Visual Basic
allows you to assign only an object from one of the derived classes to that variable.
The .NET Framework defines several MustInherit classes, among them Array, Enum, and ValueType. ValueType is an example
of a base class that restricts a variable. All value types derive from ValueType. If you declare a variable as ValueType, you can
assign only value types to that variable.
Rules
Declaration Context. You can use MustInherit only in a Class statement.
Combined Modifiers. You cannot specify MustInherit together with NotInheritable in the same declaration.
Example
The following example illustrates both forced inheritance and forced overriding. The base class shape defines a variable
acrossLine. The classes circle and square derive from shape. They inherit the definition of acrossLine, but they must define
the function area because that calculation is different for each kind of shape.
VB
Public MustInherit Class shape
Public acrossLine As Double
Public MustOverride Function area() As Double
End Class
Public Class circle : Inherits shape
Public Overrides Function area() As Double
Return Math.PI * acrossLine
End Function
End Class
Public Class square : Inherits shape
Public Overrides Function area() As Double
Return acrossLine * acrossLine
End Function
End Class
Public Class consumeShapes
Public Sub makeShapes()
Dim shape1, shape2 As shape
shape1 = New circle
shape2 = New square
End Sub
End Class

You can declare shape1 and shape2 to be of type shape. However, you cannot create an object from shape because it lacks the
functionality of the function area and is marked MustInherit.
Because they are declared as shape, the variables shape1 and shape2 are restricted to objects from the derived classes circle
and square. Visual Basic does not allow you to assign any other object to these variables, which gives you a high level of type
safety.
Usage
The MustInherit modifier can be used in this context:
Class Statement
See Also
Reference
Inherits Statement
NotInheritable
Visual Basic Language Keywords
Other Resources
Inheritance in Visual Basic
Visual Basic Language Reference

MustOverride
Specifies that a property or procedure is not implemented in this class and must be overridden in a derived class before it can
be used.
Remarks
You can use MustOverride only in a property or procedure declaration statement. The property or procedure specifying
MustOverride must be a member of a class, and the class must be marked MustInherit.
Rules
Incomplete Declaration. When you specify MustOverride, you do not supply any additional lines of code for the
property or procedure, not even the End Function, End Property, or End Sub statement.
Combined Modifiers. You cannot specify MustOverride together with NotOverridable, Overridable, or Shared in
the same declaration.
Shadowing and Overriding. Both shadowing and overriding redefine an inherited element, but there are significant
differences between the two approaches. For more information, see Shadowing in Visual Basic.
Alternate Terms. An element that cannot be used except in an override is sometimes called a pure virtual element.
The MustOverride modifier can be used in these contexts:
Function Statement (Visual Basic)
Property Statement
Sub Statement (Visual Basic)
See Also
Reference
NotOverridable
Overridable
Overrides
MustInherit
Visual Basic Language Keywords
Concepts
Shadowing in Visual Basic
Visual Basic Language Reference

MyBase
Provides a way to refer to the base class of the current class instance.
Remarks
The MyBase keyword behaves like an object variable referring to the base class of the current instance of a class. MyBase is
commonly used to access base class members that are overridden or shadowed in a derived class. In particular, MyBase.New
is used to explicitly call a base class constructor from a derived class constructor.
It is invalid to use MyBase to call MustOverride base methods.
For more information and an example, see How to: Access a Variable Hidden by a Derived Class.
See Also
Reference
Me
MyClass
New (Visual Basic)
Concepts
Inheritance Basics
Visual Basic Language Reference

MyClass
Provides a way to refer to the current class instance members without them being replaced by any derived class overrides.
Remarks
The MyClass keyword behaves like an object variable referring to the current instance of a class as originally implemented.
MyClass is similar to Me, but every method and property call on MyClass is treated as if the method or property were
NotOverridable. Therefore, the method or property is not affected by overriding in a derived class. The following example
compares Me and MyClass.

Class baseClass
Public Overridable Sub testMethod()
MsgBox("Base class string")
End Sub
Public Sub useMe()
' The following call uses the calling class's version, even if
' that version is an override.
Me.testMethod()
End Sub
Public Sub useMyClass()
' The following call uses this version and not any override.
MyClass.testMethod()
End Sub
End Class
Class derivedClass : Inherits baseClass
Public Overrides Sub testMethod()
MsgBox("Derived class string")
End Sub
End Class
Class testClasses
Sub startHere()
Dim testObj As derivedClass = New derivedClass()
' The following call displays "Derived class string".
testObj.useMe()
' The following call displays "Base class string".
testObj.useMyClass()
End Sub
End Class

Even though derivedClass overrides testMethod, the MyClass keyword in useMyClass nullifies the effects of overriding, and
the compiler resolves the call to the base class version of testMethod.
You cannot use MyClass inside a Shared (Visual Basic) method, but you can use it inside an instance method to access a
shared member of a class.
See Also
Reference
Me
MyBase
Concepts
Inheritance Basics
Visual Basic Language Reference

Narrowing
Indicates that a conversion operator (CType) converts a class or structure to a type that might not be able to hold some of the
possible values of the original class or structure.
Converting with the Narrowing Keyword
The conversion procedure must specify Public Shared in addition to Narrowing.
Narrowing conversions do not always succeed at run time, and can fail or incur data loss. Examples are Long to Integer,
String to Date, and a base type to a derived type. This last conversion is narrowing because the base type might not contain all
the members of the derived type and thus is not an instance of the derived type.
If Option Strict is On, the consuming code must use CType for all narrowing conversions.
The Narrowing keyword can be used in this context:
Operator Statement
See Also
Tasks
How to: Define an Operator
Reference
Operator Statement
Widening
CType Function
Option Strict Statement
Concepts
Widening and Narrowing Conversions
Visual Basic Language Reference

New (Visual Basic)


Introduces a New clause to create a new object instance, or specifies a constructor constraint on a type parameter.
Remarks
In a type parameter list, a New constraint specifies that the supplied type must expose an accessible parameterless constructor.
For more information on type parameters and constraints, see Type List.
In a declaration or assignment statement, a New clause must specify a defined class from which the instance can be created.
This means the class must expose a constructor that the calling code can access.
You can use a New clause in a declaration statement or an assignment statement. When the statement runs, it calls the
constructor of the specified class, passing any arguments you have supplied. The following example demonstrates this.

Dim someObj As Object


someObj = New someClass("String required by constructor")
Dim nextLabel As New Label()

Since arrays are classes, New can create a new array instance, as shown in the following example.

Dim intArray As Integer()


intArray = New Integer() {0, 1, 2, 3}

The common language runtime (CLR) throws an OutOfMemoryException error if there is insufficient memory to create the
new instance.
The New keyword can be used in these contexts:
Dim Statement (Visual Basic)
Of
See Also
Reference
Visual Basic Language Keywords
Type List
Using Constructors and Destructors
OutOfMemoryException
Concepts
Generic Types in Visual Basic
Object Lifetime: How Objects Are Created and Destroyed
Visual Basic Language Reference

Next
Terminates a loop that is iterated with different values of a loop variable, or specifies that execution should continue with the
statement following the statement that generated an error.
Remarks
The Next keyword can be used in these contexts:
For...Next Statement
For Each...Next Statement
On Error Statement
Resume Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

Nothing (Visual Basic)


Represents the default value of any data type.
Remarks
Assigning Nothing to a variable sets it to the default value for its declared type. If that type contains variable members, they
are all set to their default values. The following example illustrates this.

Public Structure testStruct


Public name As String
Public number As Short
End Structure
Dim ts As testStruct, i As Integer, b As Boolean
ts = Nothing
' The preceding statement sets ts.name to "" and ts.number to 0.
i = Nothing
b = Nothing
' The preceding statements set i to 0 and b to False.

If the variable is of a reference type — that is, an object variable — Nothing means the variable is not associated with any
object. The following example demonstrates this.

Dim testObject As Object


testObject = Nothing
' The preceding statement sets testObject to not refer to any instance.

When you assign Nothing to an object variable, it no longer refers to any object instance. If the variable had previously
referred to an instance, setting it to Nothing does not terminate the instance itself. The instance is terminated, and the
memory and system resources associated with it are released, only after the garbage collector (GC) detects that there are no
active references remaining.
See Also
Reference
Dim Statement (Visual Basic)
Concepts
Object Lifetime: How Objects Are Created and Destroyed
Lifetime in Visual Basic
Visual Basic Language Reference

NotInheritable
Specifies that a class cannot be used as a base class.
Remarks
Alternate Terms. A class that cannot be inherited is sometimes called a sealed class.
The NotInheritable modifier can be used in this context:
Class Statement (Visual Basic)
See Also
Reference
Inherits Statement
MustInherit
Visual Basic Language Keywords
Visual Basic Language Reference

NotOverridable
Specifies that a property or procedure cannot be overridden in a derived class.
Remarks
NotOverridable is the default setting for a property or procedure that does not itself override a base class property or
procedure.
An element that cannot be overridden is sometimes called a sealed element.
Rules
Declaration Context. You can use NotOverridable only in a property or procedure declaration statement. You can
specify NotOverridable only on a property or procedure that overrides another property or procedure, that is, only in
combination with Overrides.
Combined Modifiers. You cannot specify NotOverridable together with MustOverride, Overridable, or Shared in
the same declaration.
The NotOverridable modifier can be used in these contexts:
Function Statement (Visual Basic)
Property Statement
Sub Statement (Visual Basic)
See Also
Reference
MustOverride
Overridable
Overrides
Visual Basic Language Keywords
Concepts
Shadowing in Visual Basic
Visual Basic Language Reference

Of
Introduces an Of clause, which identifies a type parameter on a generic class, structure, interface, delegate, or procedure. For
information on generic types, see Generic Types in Visual Basic.
Using the Of Keyword
The following code example uses the Of keyword to define the outline of a class that takes two type parameters. It constrains
the keyType parameter by the IComparable interface, which means the consuming code must supply a type argument that
implements IComparable. This is necessary so that the add procedure can call the
System.IComparable.CompareTo(System.Object) method. For more information on constraints, see Type List.

Public Class Dictionary(Of entryType, keyType As IComparable)


Public Sub add(ByVal e As entryType, ByVal k As keyType)
Dim dk As keyType
If k.CompareTo(dk) = 0 Then
End If
End Sub
Public Function find(ByVal k As keyType) As entryType
End Function
End Class

If you complete the preceding class definition, you can construct a variety of dictionary classes from it. The types you supply
to entryType and keyType determine what type of entry the class holds and what type of key it associates with each entry.
Because of the constraint, you must supply to keyType a type that implements IComparable.
The following code example creates an object that holds String entries and associates an Integer key with each one. Integer
implements IComparable and therefore satisfies the constraint on keyType.

Dim d As New dictionary(Of String, Integer)

The Of keyword can be used in these contexts:


Class Statement
Delegate Statement
Function Statement
Interface Statement
Structure Statement
Sub Statement
See Also
Reference
Type List
IComparable
Concepts
Generic Types in Visual Basic
Visual Basic Language Reference

Off
Turns a compiler option off.
Remarks
The Off keyword can be used in these contexts:
Option Explicit Statement
Option Strict Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

On
Introduces a response to a run-time error or turns a compiler option on.
Remarks
The On keyword is used in these contexts:
On Error Statement
Option Explicit Statement
Option Strict Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

Option (Visual Basic)


Introduces a statement that specifies a compiler option that applies to the entire source file.
Remarks
The compiler options can control whether all variables must be explicitly declared, whether narrowing type conversions must
be explicit, or whether strings should be compared as text or as binary quantities.
The Option keyword can be used in these contexts:
Option Compare Statement
Option Explicit Statement (Visual Basic)
Option Strict Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

Optional (Visual Basic)


Specifies that a procedure argument can be omitted when the procedure is called.
Remarks
The Optional modifier can be used in these contexts:
Declare Statement
Function Statement
Property Statement
Sub Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

Overloads
Specifies that a property or procedure redeclares one or more existing properties or procedures with the same name.
Remarks
Overloading is the practice of supplying more than one definition for a given property or procedure name in the same scope.
Redeclaring a property or procedure with a different signature is sometimes called hiding by signature.
Rules
Declaration Context. You can use Overloads only in a property or procedure declaration statement.
Combined Modifiers. You cannot specify Overloads together with Shadows in the same procedure declaration.
Required Differences. The signature in this declaration must be different from the signature of every property or
procedure that it overloads. The signature comprises the property or procedure name together with the following:
the number of parameters
the order of the parameters
the data types of the parameters
the number of type parameters (for a generic procedure)
the return type (only for a conversion operator procedure)
All overloads must have the same name, but each must differ from all the others in one or more of the preceding
respects. This allows the compiler to distinguish which version to use when code calls the property or procedure.
Disallowed Differences. Changing one or more of the following is not valid for overloading a property or procedure,
because they are not part of the signature:
whether or not it returns a value (for a procedure)
the data type of the return value (except for a conversion operator)
the names of the parameters or type parameters
the constraints on the type parameters (for a generic procedure)
parameter modifier keywords (such as ByRef or Optional)
property or procedure modifier keywords (such as Public or Shared)
Optional Modifier. You do not have to use the Overloads modifier when you are defining multiple overloaded
properties or procedures in the same class. However, if you use Overloads in one of the declarations, you must use it in
all of them.
Shadowing and Overloading. Overloads can also be used to shadow an existing member, or set of overloaded
members, in a base class. When you use Overloads in this way, you declare the property or method with the same name
and the same parameter list as the base class member, and you do not supply the Shadows keyword.
The Overloads modifier can be used in these contexts:
Function Statement
Operator Statement
Property Statement
Sub Statement
See Also
Tasks
How to: Define a Conversion Operator
Reference
Shadows
Concepts
Procedure Overloading
Generic Types in Visual Basic
Operator Procedures
Visual Basic Language Reference

Overridable
Specifies that a property or procedure can be overridden by an identically named property or procedure in a derived class.
Remarks
Overridable is the default setting for a property or procedure that itself overrides a base class property or procedure.
Both shadowing and overriding redefine an inherited element, but there are significant differences between the two
approaches. For more information, see Shadowing in Visual Basic.
An element that can be overridden is sometimes called a virtual element. If it can be overridden, but does not have to be, it is
sometimes also called a concrete element.
Rules
Declaration Context. You can use Overridable only in a property or procedure declaration statement.
Combined Modifiers. You cannot specify Overridable together with MustOverride, NotOverridable, or Shared in
the same declaration. Because an overriding element is implicitly overridable, you cannot combine Overridable with
Overrides.
The Overridable modifier can be used in these contexts:
Function Statement (Visual Basic)
Property Statement
Sub Statement (Visual Basic)
See Also
Reference
MustOverride
NotOverridable
Overrides
Visual Basic Language Keywords
Concepts
Shadowing in Visual Basic
Visual Basic Language Reference

Overrides
Specifies that a property or procedure overrides an identically named property or procedure inherited from a base class.
Remarks
Rules
Declaration Context. You can use Overrides only in a property or procedure declaration statement.
Combined Modifiers. You cannot specify Overrides together with Shadows or Shared in the same declaration.
Because an overriding element is implicitly overridable, you cannot combine Overridable with Overrides.
Matching Signatures. The signature of this declaration must exactly match the signature of the property or procedure
that it overrides. This means the parameter lists must have the same number of parameters, in the same order, with the
same data types.
In addition to the signature, the overriding declaration must also exactly match the following:
The access level
The return type, if any
Generic Signatures. For a generic procedure, the signature includes the number of type parameters. Therefore, the
overriding declaration must match the base class version in that respect as well.
Additional Matching. In addition to matching the signature of the base class version, this declaration must also match
it in the following respects:
Access-level modifier (such as Public (Visual Basic))
Passing mechanism of each parameter (ByVal or ByRef)
Constraint lists on each type parameter of a generic procedure
Shadowing and Overriding. Both shadowing and overriding redefine an inherited element, but there are significant
differences between the two approaches. For more information, see Shadowing in Visual Basic.
The Overrides modifier can be used in these contexts:
Function Statement
Property Statement
Sub Statement
See Also
Reference
MustOverride
NotOverridable
Overridable
Visual Basic Language Keywords
Type List
Concepts
Shadowing in Visual Basic
Generic Types in Visual Basic
Visual Basic Language Reference

P-Z Keywords
The following table contains a listing of Visual Basic language keywords.

ParamArray Partial Preserve Private

Protected Public RaiseEvent ReadOnly

Resume Shadows Shared Static

Step Structure Text Then

To True TryCast Unicode

Until When While Widening

WithEvents WriteOnly
Smart Device Developer Notes
The following is not supported in smart device applications: Unicode.
See Also
Reference
A-E Keywords
F-O Keywords
Other Resources
Visual Basic Reference
Visual Basic Language Reference

ParamArray
Specifies that a procedure parameter takes an optional array of elements of the specified type. ParamArray can be used only
on the last parameter of a parameter list.
Remarks
ParamArray allows you to pass an arbitrary number of arguments to the procedure. A ParamArray parameter is always
declared using ByVal.
You can supply one or more arguments to a ParamArray parameter by passing an array of the appropriate data type, a
comma-separated list of values, or nothing at all. For details, see "Calling a ParamArray" in Parameter Arrays.
Security Note
Whenever you deal with an array which can be indefinitely large, there is a risk of overrunning some internal capacity of you
r application. If you accept a parameter array from the calling code, you should test its length and take appropriate steps if it i
s too large for your application.

The ParamArray modifier can be used in these contexts:


Declare Statement
Function Statement (Visual Basic)
Property Statement
Sub Statement (Visual Basic)
See Also
Tasks
How to: Define a Procedure with an Indefinite Number of Parameters
How to: Call a Procedure that Takes an Indefinite Number of Parameters
Reference
Visual Basic Language Keywords
Concepts
Parameter Arrays
Visual Basic Language Reference

Partial (Visual Basic)


Indicates that a class or structure declaration is a partial definition of the class or structure.

[ <attrlist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] _


Partial { Class | Structure } name [ (Of typelist) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ variabledeclarations ]
[ proceduredeclarations ]
{ End Class | End Structure }

Parts
attrlist
Optional. List of attributes that apply to this class or structure. You must enclose the Attribute List in angle brackets (< >).
accessmodifier
Optional. Specifies what code can access this class or structure. See Access Levels in Visual Basic.
Shadows
Optional. See Shadows.
MustInherit
Optional. See MustInherit.
NotInheritable
Optional. See NotInheritable.
name
Required. Name of this class or structure. Must match the name defined in all other partial declarations of the same class or
structure.
Of
Optional. Specifies that this is a generic class or structure. See Generic Types in Visual Basic.
typelist
Required if you use Of. See Type List.
Inherits
Optional. See Inherits Statement.
classname
Required if you use Inherits. The name of the class or interface from which this class derives.
Implements
Optional. See Implements Statement.
interfacenames
Required if you use Implements. The names of the interfaces this class or structure implements.
variabledeclarations
Optional. Statements which declare additional variables and events for the class or structure.
proceduredeclarations
Optional. Statements which declare and define additional procedures for the class or structure.
End Class or End Structure
Ends this partial Class or Structure definition.
Remarks
You can divide the definition of a class or structure among several declarations with the Partial keyword. You can use as many
partial declarations as desired, in as many different source files as desired. However, all the declarations must be in the same
assembly and the same namespace.
Note
Visual Basic uses partial-class definitions to separate generated code from user-authored code in separate source files. For ex
ample, the Windows Form Designer defines partial classes for controls such as Form. You should not modify the generated
code in these controls.

Under normal circumstances, you should not split the development of a single class or structure across two or more
declarations. Therefore, in most cases you do not need the Partial keyword.
All the rules for class and structure creation, such as those for modifier usage and inheritance, apply when creating a partial
class or structure.
Best Practices
Keyword Usage. For readability, every partial declaration of a class or structure should include the Partial keyword. The
compiler allows at most one partial declaration to omit the keyword; if two or more omit it the compiler signals an error.
Behavior
Union of Declarations. The compiler treats the class or structure as the union of all its partial declarations. Every
modifier from every partial definition applies to the entire class or structure, and every member from every partial
definition is available to the entire class or structure.
Type Promotion Not Allowed For Partial Types in Modules. If a partial definition is inside a module, type promotion
of that class or structure is automatically defeated. In such a case, a set of partial definitions can cause unexpected results
and even compiler errors. For more information, see Type Promotion.
The compiler merges partial definitions only when their fully qualified paths are identical.
The Partial keyword can be used in these contexts:
Class Statement
Structure Statement
Example
The following example splits the definition of class sampleClass into two declarations, each of which defines a different Sub
procedure.
VB
Partial Public Class sampleClass
Public Sub sub1()
End Sub
End Class
Partial Public Class sampleClass
Public Sub sub2()
End Sub
End Class

The two partial definitions in the preceding example could be in the same source file or in two different source files.
See Also
Reference
Class Statement (Visual Basic)
Structure Statement
Shadows
Concepts
Type Promotion
Generic Types in Visual Basic
Visual Basic Language Reference

Preserve
Prevents the contents of an array from being cleared when the array is redimensioned.
Remarks
The Preserve keyword can be used in this context:
ReDim Statement (Visual Basic)
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

Private (Visual Basic)


Specifies that one or more declared programming elements are accessible only from within their declaration context, including
from within any contained types.
Remarks
If a programming element represents proprietary functionality, or contains confidential data, you usually want to limit access
to it as strictly as possible. You achieve the maximum limitation by allowing only the module, class, or structure that defines it
to access it. To limit access to an element in this way, you can declare it with Private.
Rules
Declaration Context. You can use Private only at module level. This means the declaration context for a Private
element must be a module, class, or structure, and cannot be a source file, namespace, interface, or procedure.
Behavior
Access Level. All code within a declaration context can access its Private elements. This includes code within a contained
type, such as a nested class or an assignment expression in an enumeration. No code outside of the declaration context
can access its Private elements.
Access Modifiers. The keywords that specify access level are called access modifiers. For a comparison of the access
modifiers, see Access Levels in Visual Basic.
The Private modifier can be used in these contexts:
Class Statement
Const Statement
Declare Statement
Delegate Statement
Dim Statement
Enum Statement
Event Statement
Function Statement
Interface Statement
Property Statement
Structure Statement
Sub Statement
See Also
Reference
Public (Visual Basic)
Protected (Visual Basic)
Friend (Visual Basic)
Concepts
Access Levels in Visual Basic
Procedures in Visual Basic
Other Resources
Structures: Your Own Data Types
Understanding Classes
Visual Basic Language Reference

Protected (Visual Basic)


Specifies that one or more declared programming elements are accessible only from within their own class or from a derived
class.
Remarks
Sometimes a programming element declared within a class contains sensitive data or restricted code, and you want to limit
access to the element. However, if the class is inheritable and you anticipate a hierarchy of derived classes, it might be
necessary for these derived classes to access the data or code. In such a case, you want the element to be accessible both from
the base class and from all derived classes. To limit access to an element in this way, you can declare it with Protected.
Rules
Declaration Context. You can use Protected only at class level. This means the declaration context for a Protected
element must be a class, and cannot be a source file, namespace, interface, module, structure, or procedure.
Combined Modifiers. You can use the Protected modifier in conjunction with the Friend (Visual Basic) modifier in the
same declaration. This combination makes the declared elements accessible from anywhere in the same assembly, from
their own class, and from derived classes. You can specify Protected Friend only on members of classes.
Behavior
Access Level. All code within a class can access its elements. Code in any class that derives from a base class can access
all the Protected elements of the base class. This is true for all generations of derivation, meaning that a class can access
Protected elements of the base class of the base class, and so on.
Protected access is not a superset or subset of friend access.
Access Modifiers. The keywords that specify access level are called access modifiers. For a comparison of the access
modifiers, see Access Levels in Visual Basic.
The Protected modifier can be used in these contexts:
Class Statement
Const Statement
Declare Statement
Delegate Statement
Dim Statement
Enum Statement
Event Statement
Function Statement
Interface Statement
Property Statement
Structure Statement
Sub Statement
See Also
Reference
Public (Visual Basic)
Friend (Visual Basic)
Private (Visual Basic)
Concepts
Access Levels in Visual Basic
Procedures in Visual Basic
Other Resources
Structures: Your Own Data Types
Understanding Classes
Visual Basic Language Reference

Public (Visual Basic)


Specifies that one or more declared programming elements have no access restrictions.
Remarks
If you are publishing a component or set of components, such as a class library, you usually want the programming elements
to be accessible by any code that interoperates with your assembly. To confer such unlimited access on an element, you can
declare it with Public.
Public access is the normal level for a programming element when you do not need to limit access to it. Note that the access
level of an element declared within an interface, module, class, or structure defaults to Public if you do not declare it
otherwise.
Rules
Declaration Context. You can use Public only at module, interface, or namespace level. This means the declaration
context for a Public element must be a source file, namespace, interface, module, class, or structure, and cannot be a
procedure.
Behavior
Access Level. All code that can access a module, class, or structure can access its Public elements.
Default Access. Local variables inside a procedure default to public access, and you cannot use any access modifiers on
them.
Access Modifiers. The keywords that specify access level are called access modifiers. For a comparison of the access
modifiers, see Access Levels in Visual Basic.
The Public modifier can be used in these contexts:
Class Statement
Const Statement
Declare Statement
Delegate Statement
Dim Statement
Enum Statement
Event Statement
Function Statement
Interface Statement
Module Statement
Operator Statement
Property Statement
Structure Statement
Sub Statement
See Also
Reference
Protected (Visual Basic)
Friend (Visual Basic)
Private (Visual Basic)
Concepts
Access Levels in Visual Basic
Procedures in Visual Basic
Other Resources
Structures: Your Own Data Types
Understanding Classes
Visual Basic Language Reference

RaiseEvent
Raises an event at run time, or declares what code to execute when raising an event.
Remarks
The RaiseEvent keyword can be used in these contexts:
Event Statement
The RaiseEvent keyword declares a custom RaiseEvent accessor.
RaiseEvent Statement
The RaiseEvent keyword raises an event.
See Also
Tasks
How to: Raise an Event (Visual Basic)
How to: Declare Events That Avoid Blocking
How to: Declare Events That Conserve Memory Use
Visual Basic Language Reference

ReadOnly (Visual Basic)


Specifies that a variable or property can be read but not written.
Remarks
Rules
Declaration Context. You can use ReadOnly only at module level. This means the declaration context for a ReadOnly
element must be a class, structure, or module, and cannot be a source file, namespace, or procedure.
Combined Modifiers. You cannot specify ReadOnly together with Static in the same declaration.
Assigning a Value. Code consuming a ReadOnly property cannot set its value. But code that has access to the
underlying storage can assign or change the value at any time.
You can assign a value to a ReadOnly variable only in its declaration or in the constructor of a class or structure in which
it is defined.
When to Use a ReadOnly Variable
There are situations in which you cannot use a Const Statement (Visual Basic) to declare and assign a constant value. For
example, the Const statement might not accept the data type you want to assign, or you might not be able to compute the
value at compile time with a constant expression. You might not even know the value at compile time. In these cases, you can
use a ReadOnly variable to hold a constant value.
Security Note
If the data type of the variable is a reference type, such as an array or a class instance, its members can be changed even if th
e variable itself is ReadOnly. The following example illustrates this.

ReadOnly characterArray() As Char = {"x"c, "y"c, "z"c}


Sub changeArrayElement()
characterArray(1) = "M"c
End Sub

When initialized, the array pointed to by characterArray() holds "x", "y", and "z". Because the variable characterArray is
ReadOnly, you cannot change its value once it is initialized; that is, you cannot assign a new array to it. However, you can
change the values of one or more of the array members. Following a call to the procedure changeArrayElement, the array
pointed to by characterArray() holds "x", "M", and "z".
Note that this is similar to declaring a procedure parameter to be ByVal, which prevents the procedure from changing the
calling argument itself but allows it to change its members.
Example
The following example defines a ReadOnly property for the date on which an employee was hired. The class stores the
property value internally as a Private variable, and only code inside the class can change that value. However, the property is
Public, and any code that can access the class can read the property.
VB
Class employee
' Only code inside class employee can change the value of hireDateValue.
Private hireDateValue As Date
' Any code that can access class employee can read property dateHired.
Public ReadOnly Property dateHired() As Date
Get
Return hireDateValue
End Get
End Property
End Class

The ReadOnly modifier can be used in these contexts:


Dim Statement
Property Statement
See Also
Reference
WriteOnly
Visual Basic Language Keywords
Visual Basic Language Reference

RemoveHandler
Removes the association between an event and an event handler, or declares which code to execute when adding an event
handler.
Remarks
The RemoveHandler keyword can be used in these contexts:
Event Statement
The RemoveHandler keyword declares a custom RemoveHandler accessor.
RemoveHandler Statement
The RemoveHandler keyword removes the association between an event and an event handler.
See Also
Tasks
How to: Declare Events That Avoid Blocking
How to: Declare Events That Conserve Memory Use
Visual Basic Language Reference

Resume
Specifies where execution should continue after an error has been handled.
Remarks
The Resume keyword can be used in these contexts:
On Error Statement (Visual Basic)
Resume Statement
See Also
Reference
Visual Basic Language Keywords
Other Resources
Exception and Error Handling in Visual Basic
Visual Basic Language Reference

Shadows
Specifies that a declared programming element redeclares and hides an identically named element, or set of overloaded
elements, in a base class.
Remarks
The main purpose of shadowing (which is also known as hiding by name) is to preserve the definition of your class members.
The base class might undergo a change that creates an element with the same name as one you have already defined. If this
happens, the Shadows modifier forces references through your class to be resolved to the member you defined, instead of to
the new base class element.
Both shadowing and overriding redefine an inherited element, but there are significant differences between the two
approaches. For more information, see Shadowing in Visual Basic.
Rules
Declaration Context. You can use Shadows only at class level. This means the declaration context for a Shadows
element must be a class, and cannot be a source file, namespace, interface, module, structure, or procedure.
You can declare only one shadowing element in a single declaration statement.
Combined Modifiers. You cannot specify Shadows together with Overloads, Overrides, or Static in the same
declaration.
Element Types. You can shadow any kind of declared element with any other kind. If you shadow a property or
procedure with another property or procedure, the parameters and the return type do not have to match those in the
base class property or procedure.
Accessing. The shadowed element in the base class is normally unavailable from within the derived class that shadows
it. However, the following considerations apply.
If the shadowing element is not accessible from the code referring to it, the reference is resolved to the shadowed
element. For example, if a Private element shadows a base class element, code that does not have permission to
access the Private element accesses the base class element instead.
If you shadow an element, you can still access the shadowed element through an object declared with the type of
the base class. You can also access it through MyBase.
The Shadows modifier can be used in these contexts:
Class Statement
Const Statement
Declare Statement
Delegate Statement
Dim Statement
Enum Statement
Event Statement
Function Statement
Interface Statement
Property Statement
Structure Statement
Sub Statement
See Also
Reference
Shared (Visual Basic)
Static (Visual Basic)
Private (Visual Basic)
MyBase
MustOverride
NotOverridable
Overloads
Overridable
Overrides
Concepts
Shadowing in Visual Basic
Visual Basic Language Reference

Shared (Visual Basic)


Specifies that one or more declared programming elements are associated with a class or structure at large, and not with a
specific instance of the class or structure.
Remarks
When to Use Shared
Sharing a member of a class or structure makes it available to every instance, rather than nonshared, where each instance
keeps its own copy. This is useful, for example, if the value of a variable applies to the entire application. If you declare that
variable to be Shared, then all instances access the same storage location, and if one instance changes the variable's value, all
instances access the updated value.
Sharing does not alter the access level of a member. For example, a class member can be shared and private (accessible only
from within the class), or nonshared and public. For more information, see Access Levels in Visual Basic.
Rules
Declaration Context. You can use Shared only at module level. This means the declaration context for a Shared
element must be a class or structure, and cannot be a source file, namespace, or procedure.
Combined Modifiers. You cannot specify Shared together with Overrides, Overridable, NotOverridable, MustOverride,
or Static (Visual Basic) in the same declaration.
Accessing. You access a shared element by qualifying it with its class or structure name, not with the variable name of a
specific instance of its class or structure. You do not even have to create an instance of a class or structure to access its
shared members.
The following example calls the shared procedure IsNaN exposed by the Double structure.
If Double.IsNaN(result) Then MsgBox("Result is mathematically undefined.")

Implicit Sharing. You cannot use the Shared modifier in a Const Statement (Visual Basic), but constants are implicitly
shared. Similarly, you cannot declare a member of a module or an interface to be Shared, but they are implicitly shared.
Behavior
Storage. A shared variable or event is stored in memory only once, no matter how many or few instances you create of
its class or structure. Similarly, a shared procedure or property holds only one set of local variables.
Accessing through an Instance Variable. It is possible to access a shared element by qualifying it with the name of a
variable that contains a specific instance of its class or structure. Although this usually works as expected, the compiler
generates a warning message and makes the access through the class or structure name instead of the variable.
Accessing through an Instance Expression. If you access a shared element through an expression that returns an
instance of its class or structure, the compiler makes the access through the class or structure name instead of evaluating
the expression. This produces unexpected results if you intended the expression to perform other actions as well as
returning the instance. The following example illustrates this.

Sub main()
shareTotal.total = 10
' The preceding line is the preferred way to access total.
Dim instanceVar As New shareTotal
instanceVar.total += 100
' The preceding line generates a compiler warning message and
' accesses total through class shareTotal instead of through
' the variable instanceVar. This works as expected and adds
' 100 to total.
returnClass().total += 1000
' The preceding line generates a compiler warning message and
' accesses total through class shareTotal instead of calling
' returnClass(). This adds 1000 to total but does not work as
' expected, because the MsgBox in returnClass() does not run.
MsgBox("Value of total is " & CStr(shareTotal.total))
End Sub
Public Function returnClass() As shareTotal
MsgBox("Function returnClass() called")
Return New shareTotal
End Function
Public Class shareTotal
Public Shared total As Integer
End Class

In the preceding example, the compiler generates a warning message both times the code accesses the shared variable
total through an instance. In each case it makes the access directly through the class shareTotal and does not make use
of any instance. In the case of the intended call to the procedure returnClass, this means it does not even generate a call
to returnClass, so the additional action of displaying "Function returnClass() called" is not performed.
The Shared modifier can be used in these contexts:
Dim Statement
Event Statement
Function Statement
Operator Statement
Property Statement
Sub Statement
See Also
Reference
Shadows
Static (Visual Basic)
Concepts
Lifetime in Visual Basic
Procedures in Visual Basic
Shared Members in Visual Basic
Other Resources
Structures: Your Own Data Types
Understanding Classes
Visual Basic Language Reference

Static (Visual Basic)


Specifies that one or more declared local variables are to remain in existence and retain their latest values after termination of
the procedure in which they are declared.
Remarks
Normally, a local variable in a procedure ceases to exist as soon as the procedure terminates. A static variable remains in
existence and retains its most recent value. The next time your code calls the procedure, the variable is not reinitialized, and it
still holds the latest value you assigned to it. A static variable continues to exist for the lifetime of the class or module in which
it is defined.
Rules
Declaration Context. You can use Static only on local variables. This means the declaration context for a Static
variable must be a procedure or a block within a procedure, and it cannot be a source file, namespace, class, structure, or
module.
You cannot use Static inside a structure procedure.
Combined Modifiers. You cannot specify Static together with ReadOnly, Shadows, or Shared in the same
declaration.
Behavior
The behavior of any local variable depends on whether it is declared in a Shared procedure. If the procedure is Shared, all its
local variables are automatically shared, including the Static variables. There is only one copy of such a variable for the entire
application. You call a Shared procedure using the class name, not a variable pointing to an instance of the class.
If the procedure is not Shared, its local variables are instance variables, including the Static variables. There is an independent
copy of each variable in each instance of the class. You call a nonshared procedure using a variable pointing to a specific
instance of the class. Any variable in that instance is independent of a variable with the same name in another instance.
Therefore, they can hold different values.
Example
The following example demonstrates the use of Static.
VB
Function updateSales(ByVal thisSale As Decimal) As Decimal
Static totalSales As Decimal = 0
totalSales += thisSale
Return totalSales
End Function

The Static variable totalSales is initialized to 0 only once. Each time you enter updateSales, totalSales still has the most
recent value you calculated for it.
The Static modifier can be used in this context:
Dim Statement (Visual Basic)
See Also
Reference
Shadows
Shared (Visual Basic)
Concepts
Lifetime in Visual Basic
Variable Declaration in Visual Basic
Other Resources
Structures: Your Own Data Types
Understanding Classes
Visual Basic Language Reference

Step
Specifies an increment value for a loop counter.
Remarks
The Step keyword can be used in this context:
For...Next Statement (Visual Basic)
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

Structure (Visual Basic)


Constrains a generic type parameter to require that any type argument passed to it be a value type, or introduces a
Structure Statement.
Remarks
When you declare a type parameter for a generic type, you can impose a constraint, a set of one or more requirements that
limit the type argument that can be passed to that type parameter. For more information, see "Constraints" in
Generic Types in Visual Basic.
Among the possible requirements in a constraint is that the type argument must be a value type, for example a structure,
enumeration, or elementary data type. You specify this by including the Structure keyword in the constraint.
Another possible requirement is that the type argument must be a reference type, for example a String, array, or delegate, or
an object created from a class. You specify a reference type requirement by including the Class (Visual Basic) keyword in the
constraint.
You do not have to specify either Class or Structure in a constraint. You cannot specify them both in the same constraint.
The Structure constraint is not the same as the Structure Statement.
See Also
Reference
Class (Visual Basic)
Structure Statement
Concepts
Generic Types in Visual Basic
Value Types and Reference Types
Visual Basic Language Reference

Text
Sets the string comparison method to sort equivalent text characters as equal.
Remarks
The Option Compare statement must appear in a source file before any other statements. It affects string comparison for all
code generated by that source file.
When to Use Text
If your strings contain all text characters, you often want to compare them, taking into account alphabetic equivalences such as
case insensitivity and closely related letters. For example, you might want to consider A and a to be equal, and Ä and ä to come
before B and b. To specify a text comparison, set Option Compare to Text.
The Text keyword can be used in this context:
Option Compare Statement
See Also
Reference
Binary
Visual Basic Language Keywords
Visual Basic Language Reference

Then
Introduces a statement block to be compiled or executed if a tested condition is true.
Remarks
The Then keyword can be used in these contexts:
#If...Then...#Else Directive
If...Then...Else Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

To
Separates the beginning and ending values of a loop counter or of a value match range.
Remarks
The To keyword can be used in these contexts:
For...Next Statement
Select...Case Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

True (Visual Basic)


Represents a Boolean value that passes a conditional test.
Remarks
Boolean Data Type (Visual Basic) values are not stored as numbers, and the stored values are not intended to be equivalent to
numbers. You should never write code that relies on equivalent numeric values for True and False. Whenever possible, you
should restrict usage of Boolean variables to the logical values for which they are designed. If it is necessary to mix Boolean
and numeric values, be sure you understand the conversion method you choose. For more information, see "Boolean Type
Does Not Convert to Numeric Type Accurately" in Troubleshooting Data Types.
See Also
Tasks
Troubleshooting Data Types
Reference
Boolean Data Type (Visual Basic)
False (Visual Basic)
Visual Basic Language Reference

TryCast
Introduces a type conversion operation that does not throw an exception.
Remarks
If an attempted conversion fails, CType and DirectCast both throw an InvalidCastException error. This can adversely affect the
performance of your application. TryCast returns Nothing (Visual Basic), so that instead of having to handle a possible
exception, you need only test the returned result against Nothing.
You use the TryCast keyword the same way you use the CType Function and the DirectCast keyword. You supply an
expression as the first argument and a type to convert it to as the second argument. TryCast operates only on reference types,
such as classes and interfaces. It requires an inheritance or implementation relationship between the two types. This means
that one type must inherit from or implement the other.
Errors and Failures
TryCast generates a compiler error if it detects that no inheritance or implementation relationship exists. But the lack of a
compiler error does not guarantee a successful conversion. If the desired conversion is narrowing, it could fail at run time. If
this happens, TryCast returns Nothing (Visual Basic).
Conversion Keywords
A comparison of the type conversion keywords is as follows.
Keyword Data types Argument relationship Run-time failure
CType Function Any data types Widening or narrowing conversion must be defined between the t Throws InvalidCastExce
wo data types ption

DirectCast Any data types One type must inherit from or implement the other type Throws InvalidCastExce
ption

TryCast Reference types One type must inherit from or implement the other type Returns
only Nothing (Visual Basic)
Example
The following example shows how to use TryCast.
VB
Function PrintTypeCode(ByVal obj As Object) As String
Dim objAsConvertible As IConvertible = TryCast(obj, IConvertible)
If objAsConvertible Is Nothing Then
Return obj.ToString() & " does not implement IConvertible"
Else
Return "Type code is " & objAsConvertible.GetTypeCode()
End If
End Function

See Also
Concepts
Widening and Narrowing Conversions
Implicit and Explicit Conversions
Visual Basic Language Reference

Unicode (Visual Basic)


Specifies that Visual Basic should marshal all strings to Unicode values regardless of the name of the external procedure being
declared.
When you call a procedure defined outside your project, the Visual Basic compiler does not have access to the information it
needs to call the procedure correctly. This information includes where the procedure is located, how it is identified, its calling
sequence and return type, and the string character set it uses. The Declare Statement creates a reference to an external
procedure and supplies this necessary information.
The charsetmodifier part in the Declare statement supplies the character set information for marshaling strings during a call
to the external procedure. It also affects how Visual Basic searches the external file for the external procedure name. The
Unicode modifier specifies that Visual Basic should marshal all strings to Unicode values and should look up the procedure
without modifying its name during the search.
If no character set modifier is specified, Ansi is the default.
Remarks
The Unicode modifier can be used in this context:
Declare Statement
Smart Device Developer Notes
This keyword is not supported.
See Also
Reference
Ansi
Auto
Visual Basic Language Keywords
Visual Basic Language Reference

Until
Specifies a condition that terminates the execution of a Do loop.
Remarks
The Until keyword can be used in this context:
Do...Loop Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

When
Adds a conditional test to a Catch statement.
Remarks
The When keyword can be used in this context:
Try...Catch...Finally Statement
See Also
Reference
Visual Basic Language Keywords
Visual Basic Language Reference

While (Visual Basic)


Specifies a condition that allows the execution of a Do loop to continue.
Remarks
The While keyword is not the same as the opening statement of the While...End While block.
The While keyword can be used in this context:
Do...Loop Statement
See Also
Reference
While...End While Statement (Visual Basic)
Visual Basic Language Reference

Widening
Indicates that a conversion operator (CType) converts a class or structure to a type that can hold all possible values of the
original class or structure.
Converting with the Widening Keyword
The conversion procedure must specify Public Shared in addition to Widening.
Widening conversions always succeed at run time and never incur data loss. Examples are Single to Double, Char to String,
and a derived type to its base type. This last conversion is widening because the derived type contains all the members of the
base type and thus is an instance of the base type.
The consuming code does not have to use CType for widening conversions, even if Option Strict is On.
The Widening keyword can be used in this context:
Operator Statement
See Also
Tasks
How to: Define an Operator
Reference
Operator Statement
Narrowing
CType Function
Option Strict Statement
Concepts
Widening and Narrowing Conversions
Visual Basic Language Reference

WithEvents
Specifies that one or more declared member variables refer to an instance of a class that can raise events.
Remarks
When a variable is defined using WithEvents, you can declaratively specify that a method handles the variable's events using
the Handles keyword.
You can use WithEvents only at class or module level. This means the declaration context for a WithEvents variable must be
a class or module and cannot be a source file, namespace, structure, or procedure.
You cannot use WithEvents on a structure member.
You can declare only individual variables—not arrays—with WithEvents.
Rules
Element Types. You must declare WithEvents variables to be object variables so that they can accept class instances.
However, you cannot declare them as Object. You must declare them as the specific class that can raise the events.
The WithEvents modifier can be used in this context: Dim Statement (Visual Basic)
See Also
Reference
Handles
Visual Basic Language Keywords
Concepts
WithEvents and the Handles Clause
Other Resources
Events in Visual Basic
Visual Basic Language Reference

WriteOnly
Specifies that a property can be written but not read.
Remarks
Rules
Declaration Context. You can use WriteOnly only at module level. This means the declaration context for a WriteOnly
property must be a class, structure, or module, and cannot be a source file, namespace, or procedure.
You can declare a property as WriteOnly, but not a variable.
When to Use WriteOnly
Sometimes you want the consuming code to be able to set a value but not discover what it is. For example, sensitive data, such
as a social registration number or a password, needs to be protected from access by any component that did not set it. In these
cases, you can use a WriteOnly property to set the value.
Security Note
When you define and use a WriteOnly property, consider the following additional protective measures:

Overriding. If the property is a member of a class, allow it to default to NotOverridable, and do not declare it
Overridable or MustOverride. This prevents a derived class from making undesired access through an override.
Access Level. If you hold the property's sensitive data in one or more variables, declare them Private (Visual Basic) so
that no other code can access them.
Encryption. Store all sensitive data in encrypted form rather than in plain text. If malicious code somehow gains access
to that area of memory, it is more difficult to make use of the data. Encryption is also useful if it is necessary to serialize
the sensitive data.
Resetting. When the class, structure, or module defining the property is being terminated, reset the sensitive data to
default values or to other meaningless values. This gives extra protection when that area of memory is freed for general
access.
Persistence. Do not persist any sensitive data, for example on disk, if you can avoid it. Also, do not write any sensitive
data to the Clipboard.
The WriteOnly modifier can be used in this context:
Property Statement
See Also
Reference
ReadOnly (Visual Basic)
Private (Visual Basic)
Visual Basic Language Keywords
Visual Basic Language Reference

Modules (Visual Basic)


The topics in this section document the Visual Basic run-time modules and contain tables of their member procedures,
properties, constants, and enumerations.
In This Section
Constants Module (Visual Basic)
ControlChars Module (Visual Basic)
Conversion Module (Visual Basic)
DateAndTime Module (Visual Basic)
ErrObject Module (Visual Basic)
FileSystem Module (Visual Basic)
Financial Module (Visual Basic)
Globals Module (Visual Basic)
Information Module (Visual Basic)
Interaction Module (Visual Basic)
Strings Module (Visual Basic)
VbMath Module (Visual Basic)
Related Sections
Visual Basic Reference
Visual Basic
Visual Basic Language Reference

Constants Module (Visual Basic)


The Constants module contains miscellaneous constants. These constants can be used anywhere in your code.
Remarks
This module supports the Visual Basic language constants that correspond to the members of many Visual Basic enumerations:
Members
vbAbort vbAbortRetryIgnore vbApplicationModal vbArchive

vbArray vbBack vbBinaryCompare vbBoolean

vbByte vbCancel vbCr vbCritical

vbCrLf vbCurrency vbDate vbDecimal

vbDefaultButton1 vbDefaultButton2 vbDefaultButton3 vbDirectory

vbDouble vbEmpty vbExclamation vbFalse

vbFirstFourDays vbFirstFullWeek vbFirstJan1 vbFormFeed

vbFriday vbGeneralDate vbGet vbHidden

vbHide vbHiragana vbIgnore vbInformation

vbInteger vbKatakana vbLet vbLf

vbLinguisticCasing vbLong vbLongDate vbLongTime

vbLowerCase vbMaximizedFocus vbMethod vbMinimizedFocus

vbMinimizedNoFocus vbMonday vbMsgBoxHelp vbMsgBoxRight

vbMsgBoxRtlReading vbMsgBoxSetForeground vbNarrow vbNewLine

vbNo vbNormal vbNormalFocus vbNormalNoFocus

vbNull vbNullChar vbNullString vbObject

vbObjectError vbOK vbOKCancel vbOKOnly

vbProperCase vbQuestion vbReadOnly vbRetry

vbRetryCancel vbSaturday vbSet vbShortDate

vbShortTime vbSimplifiedChinese vbSingle vbString

vbSunday vbSystem vbSystemModal vbTab

vbTextCompare vbThursday vbTraditionalChinese vbTrue


vbTuesday vbUpperCase vbUseDefault vbUserDefinedType

vbUseSystem vbUseSystemDayOfWeek vbVariant vbVerticalTab

vbVolume vbWednesday vbWide vbYes

vbYesNo vbYesNoCancel
See Also
Reference
AppWinStyle Enumeration
BuiltInRole Enumeration
CallType Enumeration
CompareMethod Enumeration
DateFormat Enumeration
DateInterval Enumeration
DueDate Enumeration
FileAttribute Enumeration
FirstDayOfWeek Enumeration
FirstWeekOfYear Enumeration
MsgBoxResult Enumeration
MsgBoxStyle Enumeration
OpenAccess Enumeration
OpenMode Enumeration
OpenShare Enumeration
Print and Display Constants
TriState Enumeration
VariantType Enumeration
VbStrConv Enumeration
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

ControlChars Module (Visual Basic)


The ControlChars module contains constants used as control characters. These constants can be used anywhere in your code.
Remarks
This module supports the Visual Basic language keywords and run-time library members that provide constant control
characters for printing and displaying text. For more information, see Print and Display Constants.
Members
Back Cr CrLf FormFeed

Lf NewLine NullChar Quote

Tab VerticalTab
See Also
Reference
Print and Display Constants
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Conversion Module (Visual Basic)


The Conversion module contains the procedures used to perform various conversion operations.
Remarks
This module supports the Visual Basic language keywords and run-time library members that convert decimal numbers to
other bases, numbers to strings, strings to numbers, and one data type to another.
Members
ErrorToString Fix Hex Int

Oct Str Val


Example
This example uses the Hex function to return the hexadecimal value of a number.
VB
Dim TestHex As String
' Returns 5.
TestHex = Hex(5)
' Returns A.
TestHex = Hex(10)
' Returns 1CB.
TestHex = Hex(459)

See Also
Reference
Conversion Summary
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

DateAndTime Module (Visual Basic)


The DateAndTime module contains the procedures and properties used in date and time operations.
Remarks
This module supports the Visual Basic language keywords and run-time library members that get the current date or time,
perform date calculations, return a date or time, set the date or time, or time the duration of a process.
Members
DateAdd DateDiff DatePart DateSerial

DateString DateValue Day Hour

Minute Month MonthName Now

Second TimeOfDay Timer TimeSerial

TimeString TimeValue Today WeekDay

WeekDayName Year
Example
This example uses the Today property to return the current system date.

Dim thisDate As Date


thisDate = Today

See Also
Reference
Dates and Times Summary
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

ErrObject Module (Visual Basic)


The ErrObject module contains properties and procedures used to identify and handle run-time errors using the Err object.
Remarks
The ErrObject module supports the Err object. For more information, see Err Object (Visual Basic).
Members
Clear Description Erl GetException

HelpContext HelpFile LastDLLError Number

Raise Source
Example
This example uses the properties of the Err object in constructing an error-message dialog box. Notice what happens when you
use the Clear method first: When you then generate a Visual Basic error with the Raise method, Visual Basic's default values
become the properties of the Err object.

Dim Msg As String


' If an error occurs, construct an error message.
On Error Resume Next ' Defer error handling.
Err.Clear
Err.Raise(6) ' Generate an "Overflow" error.
' Check for error, then show message.
If Err.Number <> 0 Then
Msg = "Error # " & Str(Err.Number) & " was generated by " _
& Err.Source & ControlChars.CrLf & Err.Description
MsgBox(Msg, MsgBoxStyle.Information, "Error")
End If

See Also
Reference
Err Object (Visual Basic)
Conversion Summary
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

FileSystem Module (Visual Basic)


The FileSystem module contains the procedures used to perform file, directory or folder, and system operations.
The My feature gives you greater productivity and performance in file I/O operations than using the FileSystem module. For
more information, see My.Computer.FileSystem Object.
Remarks
This module supports the Visual Basic language keywords and run-time library members that access files and folders.
Members
ChDir ChDrive CurDir Dir

EOF FileAttr FileClose FileCopy

FileDateTime FileGet FileGetObject FileLen

FileOpen FilePut FilePutObject FileWidth

FreeFile GetAttr Input InputString

Kill LineInput Loc Lock

LOF MkDir Print PrintLine

Rename Reset RmDir Seek

SetAttr SPC TAB Unlock

Write WriteLine
Example
This example uses the GetAttr function to determine the attributes of a file and directory or folder.
VB
Dim MyAttr As FileAttribute
' Assume file TESTFILE is normal and readonly.
MyAttr = GetAttr("C:\TESTFILE.txt") ' Returns vbNormal.

' Test for normal.


If (MyAttr And FileAttribute.Normal) = FileAttribute.Normal Then
MsgBox("This file is normal.")
End If
' Test for normal and readonly.
Dim normalReadonly As FileAttribute
normalReadonly = FileAttribute.Normal Or FileAttribute.ReadOnly
If (MyAttr And normalReadonly) = normalReadonly Then
MsgBox("This file is normal and readonly.")
End If

' Assume MYDIR is a directory or folder.


MyAttr = GetAttr("C:\MYDIR")
If (MyAttr And FileAttribute.Directory) = FileAttribute.Directory Then
MsgBox("MYDIR is a directory")
End If
See Also
Reference
Directories and Files Summary
Input and Output Summary
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Financial Module (Visual Basic)


The Financial module contains procedures used to perform financial operations.
Remarks
This module supports the Visual Basic run-time library members that perform financial calculations such as depreciation,
present and future values, interest rates, rates of return, and payments.
Members
DDB FV IPmt IRR

MIRR NPer NPV Pmt

PPmt PV Rate SLN

SYD
Example
This example uses the Rate function to calculate the interest rate of a loan, given the total number of payments (TotPmts), the
amount of the loan payment (Payment), the present value or principal of the loan (PVal), the future value of the loan (FVal), a
number that indicates whether the payment is due at the beginning or end of the payment period (PayType), and an
approximation of the expected interest rate (Guess).
VB
Sub TestRate()
Dim PVal, Payment, TotPmts, APR As Double
Dim PayType As DueDate

' Define percentage format.


Dim Fmt As String = "##0.00"
Dim Response As MsgBoxResult
' Usually 0 for a loan.
Dim FVal As Double = 0
' Guess of 10 percent.
Dim Guess As Double = 0.1
PVal = CDbl(InputBox("How much did you borrow?"))
Payment = CDbl(InputBox("What's your monthly payment?"))
TotPmts = CDbl(InputBox("How many monthly payments do you have to make?"))
Response = MsgBox("Do you make payments at the end of the month?", MsgBoxStyle.YesNo)
If Response = MsgBoxResult.No Then
PayType = DueDate.BegOfPeriod
Else
PayType = DueDate.EndOfPeriod
End If
APR = (Rate(TotPmts, -Payment, PVal, FVal, PayType, Guess) * 12) * 100

MsgBox("Your interest rate is " & Format(CInt(APR), Fmt) & " percent.")
End Sub

See Also
Reference
Financial Summary
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Globals Module (Visual Basic)


The Globals module contains script engine functions.
Remarks
This module supports the Visual Basic language keywords and runtime library members that provide information about the
runtime currently in use.
Members
ScriptEngine ScriptEngineBuildVersion ScriptEngineMajorVersion ScriptEngineMinorVersion
Example
The following example uses the ScriptEngineMajorVersion property and related properties to return a string describing the
current runtime information:

Function getRuntimeInfo() As String


Dim runtime As String = ScriptEngine & " Version "
runtime &= CStr(ScriptEngineMajorVersion) & "."
runtime &= CStr(ScriptEngineMinorVersion) & "."
runtime &= CStr(ScriptEngineBuildVersion)
' Return the current runtime information.
Return runtime
End Function

See Also
Reference
ScriptEngine Property
ScriptEngineBuildVersion Property
ScriptEngineMajorVersion Property
ScriptEngineMinorVersion Property
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Information Module (Visual Basic)


The Information module contains the procedures used to return, test for, or verify information.
Remarks
This module supports the Visual Basic language keywords and run-time library members that provide error information,
validate data, determine array bounds, and retrieve data type and color information.
Members
Err IsArray IsDate IsDBNull

IsError IsNothing IsNumeric IsReference

LBound QBColor RGB SystemTypeName

TypeName UBound VarType VbTypeName


Example
The following example uses the VbTypeName function to return data type names for several variables.

Dim sysDateName As String = "System.DateTime"


Dim sysShortName As String = "Int16"
Dim sysBadName As String = "Nonsense"
Dim testVbName As String
testVbName = VbTypeName(sysDateName)
' Returns "Date".
testVbName = VbTypeName(sysShortName)
' Returns "Short".
testVbName = VbTypeName(sysBadName)
' Returns Nothing.

See Also
Reference
Information and Interaction Summary
Data Types Summary
Declarations and Constants Summary
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Interaction Module (Visual Basic)


The Interaction module contains procedures used to interact with objects, applications, and systems.
Remarks
This module supports the Visual Basic language keywords and run-time library members that run other programs, call a
method or property, sound a beep from the computer, provide a command-line string, manipulate COM objects, and control
dialog boxes.
Members
AppActivate Beep CallByName Choose

Command CreateObject DeleteSetting Environ

GetAllSettings GetObject GetSetting IIf

InputBox MsgBox Partition SaveSetting

Shell Switch
Example
The following example uses the Shell function to run an application specified by the user. Specifying
Microsoft.VisualBasic.AppWinStyle.NormalFocus as the second argument opens the application in normal size and gives it the
focus.

Dim procID As Integer


' Run calculator.
procID = Shell("C:\Windows\system32\calc.exe", AppWinStyle.NormalFocus)
' The preceding path is for Windows XP.
' The Windows 2000 path is C:\WINNT\system32\calc.exe.

See Also
Reference
Information and Interaction Summary
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Strings Module (Visual Basic)


The Strings module contains procedures used to perform string operations.
Remarks
This module supports the Visual Basic language keywords and run-time library members that manipulate strings.
Members
Asc AscW Chr ChrW

Filter Format FormatCurrency FormatDateTime

FormatNumber FormatPercent GetChar InStr

InStrRev Join LCase Left

Len LSet LTrim Mid

Replace Right RSet RTrim

Space Split StrComp StrConv

StrDup StrReverse Trim UCase


Example
The following example demonstrates how to split a string at its spaces.
VB
Dim TestString As String = "Look at these!"
' Returns an array containing "Look", "at", and "these!".
Dim TestArray() As String = Split(TestString)

See Also
Reference
String Manipulation Summary
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

VbMath Module (Visual Basic)


The VbMath module contains procedures used to perform mathematical operations.
Remarks
This module supports the Visual Basic language keywords and run-time library members for generating random numbers.
Members
Randomize Rnd
Example
This example uses the Rnd function to generate a random integer value in the range from 1 to 6.
VB
' Initialize the random-number generator.
Randomize()
' Generate random value between 1 and 6.
Dim value As Integer = CInt(Int((6 * Rnd()) + 1))

See Also
Reference
Math Summary
Derived Math Functions (Visual Basic)
Keywords and Members by Task
Visual Basic Language Keywords
Visual Basic Run-Time Library Members
Keywords Compared in Different Languages
Visual Basic Language Reference

Objects (Visual Basic)


The topics in this section document the Visual Basic run-time objects and contain tables of their member procedures,
properties, and events.
In This Section
Collection Object (Visual Basic)
Collection Object Members
Err Object (Visual Basic)
Err Object Members
Related Sections
Visual Basic Reference
Visual Basic
Visual Basic Language Reference

Collection Object (Visual Basic)


A Visual Basic Collection is an ordered set of items that can be referred to as a unit.
Remarks
The Visual Basic Collection object provides a convenient way to refer to a related group of items as a single object. The items,
or elements, in a collection need only be related by the fact that they exist in the collection. Elements of a collection do not have
to share the same data type.
You can create a collection the same way you create other objects, as the following example illustrates.

Dim coll As New Microsoft.VisualBasic.Collection()

Once you have created a collection, you can do any of the following:
Add an element with the Add Method.
Remove an element with the Remove Method.
Remove all elements with the Clear Method.
Find out how many elements the collection contains with the Count Property.
Check whether a specific element is present with the Contains Method.
Return a specific element from the collection with the Item Property.
Iterate through the entire collection with the For Each...Next Statement (Visual Basic).
Note
Although the Visual Basic Collection object has functionality identical to the Collection object in Visual Basic 6.0, the t
wo cannot interoperate in a COM environment.

Caution
Iterating through a Visual Basic Collection is not a thread-safe procedure. Even if the collection is synchronized, other t
hreads can still modify the collection, causing the enumerator to throw an exception. To guarantee thread safety during
enumeration, either lock the collection or catch the exceptions resulting from changes made by other threads. For more
information on locking a programming element, see SyncLock Statement.

Example
The following example creates the Collection object names and a dialog box with which a user can add objects (names) to the
collection. It then displays the names in the collection, and finally empties the collection without disposing of the Collection
object itself.
To see how this works, choose the Add Class command from the Project menu and declare a public variable called
instanceName at the module level of nameClass (type Public instanceName) to hold the names of each instance. Leave the
default name as nameClass. Copy and paste the following code into the General section of another module, and then start it
with the statement classNamer in another procedure. (This example works only with host applications that support classes.)
VB
Public Class nameClass
Public instanceName As String
End Class
Sub classNamer()
' Create a Visual Basic Collection object.
Dim names As New Microsoft.VisualBasic.Collection()
Dim key As Integer
Dim msg As String
Dim name As String
Dim nameList As String = ""
' 1. Get names from the user to add to the collection.
Do
Dim inst As New nameClass()
key += 1
msg = "Please enter a name for this object." & vbCrLf _
& "Press Cancel to see names in collection."
name = InputBox(msg, "Name the Collection items")
inst.instanceName = name
' If user entered a name, add it to the collection.
If inst.instanceName <> "" Then
names.Add(inst, CStr(key))
End If
Loop Until name = ""
' 2. Create and display a list of names from the collection.
For Each oneInst As nameClass In names
nameList &= oneInst.instanceName & vbCrLf
Next oneInst
MsgBox(nameList, , "Instance Names in names Collection")
' 3. Remove elements from the collection without disposing of the collection.
For count As Integer = 1 To names.Count
names.Remove(1)
' Since Visual Basic collections are reindexed automatically,
' remove the first member on each iteration.
Next count
End Sub

Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Collection Object Members
GetEnumerator Method (Collection Object)
Visual Basic Language Reference

Collection Object Members


A Visual Basic Collection object exposes the following members:
Properties
Property Description
Count Property Read-only. Returns an Integer containing the number of elements in a Visual Basic collection.

Item Property Read-only. Returns a specific element of a Visual Basic Collection object either by position or by key.
Methods
Method Description
Add Method Adds an element to a Visual Basic Collection object.

Clear Method Removes all elements from a Visual Basic Collection object.

Contains Method (Collection Object) Returns a Boolean indicating whether a Visual Basic Collection object contains an elem
ent with a specific key.

GetEnumerator Method Returns an enumerator object for iterating over the collection.

Remove Method Removes an element from a Visual Basic Collection object.


See Also
Reference
Collection Object (Visual Basic)
Visual Basic Language Reference

Add Method (Collection Object)


Adds an element to a Collection object.

Public Sub Add( _


ByVal Item As Object, _
Optional ByVal Key As String, _
Optional ByVal { Before | After } As Object = Nothing _
)

Parameters
Item
Required. An object of any type that specifies the element to add to the collection.
Key
Optional. A unique String expression that specifies a key string that can be used instead of a positional index to access this
new element in the collection.
Before
Optional. An expression that specifies a relative position in the collection. The element to be added is placed in the collection
before the element identified by the Before argument. If Before is a numeric expression, it must be a number from 1 through
the value of the collection's Count Property (Collection Object). If Before is a String expression, it must correspond to the key
string specified when the element being referred to was added to the collection. You cannot specify both Before and After.
After
Optional. An expression that specifies a relative position in the collection. The element to be added is placed in the collection
after the element identified by the After argument. If After is a numeric expression, it must be a number from 1 through the
value of the collection's Count property. If After is a String expression, it must correspond to the key string specified when
the element referred to was added to the collection. You cannot specify both Before and After.
Exceptions/Error Codes
Exception type Error number Condition
ArgumentException 5 Both Before and After are specified.
The Before or After argument does not refer to an existing element of the collection.
The specified Key already exists.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The Before or After argument must refer to an existing element of the collection; otherwise, an error occurs.
An error also occurs if a specified Key value matches the key for an existing element of the collection.
Example
The following example uses the Add method to add child objects — instances of a class called child containing a Public
property name — to a collection called family. To see how this works, create a Form with two Button controls and set their Text
properties to Add and List. Add the child class definition and the family declaration to the form code. Modify the _Click
event handlers for the Add and List buttons as shown. The Add button allows you to add children. The List button displays the
names of all the children.
VB
Public Class child
Public name As String
Sub New(ByVal newName As String)
name = newName
End Sub
End Class
' Create a Collection object.
Private family As New Collection()
Private Sub addChild_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim newName As String
newName = InputBox("Name of new family member: ")
If newName <> "" Then
family.Add(New child(newName), newName)
End If
End Sub
Private Sub listChild_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
For Each aChild As child In family
MsgBox(aChild.name)
Next
End Sub

Requirements
Namespace: Microsoft.VisualBasic
Module: Collection
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Collection Object (Visual Basic)
Item Property (Collection Object)
Remove Method (Collection Object)
Visual Basic Language Reference

Clear Method (Collection Object)


Deletes all elements of a Visual Basic Collection object.

Public Sub Clear()

Remarks
The Clear method empties the collection and resets its Count property to 0.
Example
VB
Dim customers As New Microsoft.VisualBasic.Collection()
' Insert code that adds customers to collection.
customers.Clear()

Requirements
Namespace: Microsoft.VisualBasic
Module: Collection
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Collection Object (Visual Basic)
Item Property (Collection Object)
Count Property (Collection Object)
Contains Method (Collection Object)
Add Method (Collection Object)
Remove Method (Collection Object)
Visual Basic Language Reference

Contains Method (Collection Object)


Returns a Boolean value indicating whether a Visual Basic Collection object contains an element with a specific key.

Public Function Contains( _


ByVal Key As String _
) As Boolean

Parameters
Key
Required. A String expression that specifies the key for which to search the elements of the collection.
Exceptions/Error Codes
Exception type Error number Condition
ArgumentException 5 The specified Key is Nothing.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
Contains returns True if the collection contains an element with a key exactly matching Key. Otherwise, Contains returns
False.
A Visual Basic Collection can hold some elements that have keys and other elements without keys. This depends on whether
the call to the Add Method (Collection Object) supplies an argument to the optional Key parameter.
Example
VB
Dim customers As New Microsoft.VisualBasic.Collection()
Dim accountNumber As String = "1234"
' Insert code that obtains new customer objects.
' Use the new customer's account number as the key.
customers.Add(newCustomer, accountNumber)
' The preceding statements can be repeated for several customers.
Dim searchNumber As String = "1234"
' Insert code to obtain an account number to search for.
If customers.Contains(searchNumber) Then
MsgBox("The desired customer is in the collection.")
Else
MsgBox("The desired customer is not in the collection.")
End If

If you intend to search the collection for elements using their keys, remember to supply the Key argument every time you call
the Add method.
Requirements
Namespace: Microsoft.VisualBasic
Module: Collection
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Collection Object (Visual Basic)
Item Property (Collection Object)
Count Property (Collection Object)
Add Method (Collection Object)
Remove Method (Collection Object)
Clear Method (Collection Object)
Visual Basic Language Reference

Count Property (Collection Object)


Returns an Integer containing the number of elements in a collection. Read-only.

Public ReadOnly Property Count() As Integer

Remarks
Use the Count property to determine the number of elements in a Collection object.
Example
This example illustrates the use of the Count property to display the number of elements in a Collection Object (Visual Basic)
in the variable birthdays.
VB
Dim birthdays As New Collection()
birthdays.Add(New DateTime(2001, 1, 12), "Bill")
birthdays.Add(New DateTime(2001, 1, 13), "Joe")
birthdays.Add(New DateTime(2001, 1, 14), "Mike")
birthdays.Add(New DateTime(2001, 1, 15), "Pete")
... MsgBox("Number of birthdays in collection: " & CStr(birthdays.Count))

The Collection object is one-based, which means that the index values of the elements range from 1 through the value of the
Count property.
Requirements
Namespace: Microsoft.VisualBasic
Class: Collection
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Collection Object (Visual Basic)
Add Method (Collection Object)
Item Property (Collection Object)
Remove Method (Collection Object)
Visual Basic Language Reference

GetEnumerator Method (Collection Object)


Returns a reference to an enumerator object, which is used to iterate over a Collection Object (Visual Basic).

Public Function GetEnumerator() As IEnumerator

Remarks
The For Each...Next Statement (Visual Basic) calls GetEnumerator to obtain an enumerator object to support iteration over a
collection's elements. Normally, you use a For Each...Next loop to traverse a collection or array, and you do not need to call
GetEnumerator explicitly.
If you need closer control over the iteration than the For Each...Next statements provide, you can use the GetEnumerator
method to perform a customized traversal. The following are some cases in which you might need to do this.
You might want to return to the beginning of the collection and start the iteration again before it is finished.
You might want to skip over one or more elements for a variety of reasons.
You might need to change the elements of the collection in the middle of a traversal. In this case you must obtain a new
enumerator object because the previous one is invalidated.
Example
The following example shows how to use GetEnumerator to retrieve all the elements of a Collection object.
VB
Dim customers As New Collection
' Insert code to add elements to the customers collection.
Dim custEnum As IEnumerator = customers.GetEnumerator()
custEnum.Reset()
Dim thisCustomer As Object
While custEnum.MoveNext()
thisCustomer = custEnum.Current()
' Insert code to process this element of the collection.
End While

GetEnumerator constructs and returns an enumerator object, which implements the IEnumerator interface of the
System.Collections namespace. The enumerator object exposes the Current property and the MoveNext and Reset methods.
For more information, see For Each...Next Statement (Visual Basic).
Requirements
Namespace: Microsoft.VisualBasic
Module: Collection
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Collection Object (Visual Basic)
Visual Basic Language Reference

Item Property (Collection Object)


Returns a specific element of a Collection object either by position or by key. Read-only.

Default Public ReadOnly Property Item( _


ByVal { Key As String | Index As Integer | Index As Object } _
) As Object

Parameters
Key
A unique String expression that specifies a key string that can be used, instead of a positional index, to access an element of
the collection. Key must correspond to the Key argument specified when the element was added to the collection.
Index
(A) A numeric expression that specifies the position of an element of the collection. Index must be a number from 1 through
the value of the collection's Count Property (Collection Object). Or (B) An Object expression that specifies the position or key
string of an element of the collection.
Exceptions
Exception type Error number Condition
ArgumentException 5 Key is invalid or does not match an existing element of the collection.
Index cannot be interpreted as character or numeric data.

IndexOutOfRangeException 9 Key is Nothing.


Index does not match an existing element of the collection.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
If Index is of type Object, the Item property attempts to treat it as a String, Char, Char array, or integer value. If Item cannot
convert Index to String or Integer, it throws an ArgumentException exception.
The Item property is the default property for a collection. Therefore, the following lines of code are equivalent.

MsgBox(CStr(customers.Item(1)))
MsgBox(CStr(customers(1)))

Example
The following example uses the Item property to retrieve a reference to an object in a collection. It creates birthdays as a
Collection object and then retrieves the object representing Bill's birthday, using the key "Bill" as the Index argument.
VB
Dim birthdays As New Collection()
birthdays.Add(New DateTime(2001, 1, 12), "Bill")
birthdays.Add(New DateTime(2001, 1, 13), "Joe")
birthdays.Add(New DateTime(2001, 1, 14), "Mike")
birthdays.Add(New DateTime(2001, 1, 15), "Pete")
... Dim aBirthday As DateTime
aBirthday = birthdays.Item("Bill")
MsgBox(CStr(aBirthday))
aBirthday = birthdays("Bill")
MsgBox(CStr(aBirthday))
Note that the first call explicitly specifies the Item property, but the second does not. Both calls work because the Item
property is the default property for a Collection object.
Requirements
Namespace: Microsoft.VisualBasic
Module: Collection
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Collection Object (Visual Basic)
Add Method (Collection Object)
Count Property (Collection Object)
Remove Method (Collection Object)
Visual Basic Language Reference

Remove Method (Collection Object)


Removes an element from a Collection object.

Public Overloads Sub Remove(_


ByVal { Key As String | Index As Integer } _
)

Parameters
Key
A unique String expression that specifies a key string that can be used, instead of a positional index, to access an element of
the collection. Key must correspond to the Key argument specified when the element was added to the collection.
Index
A numeric expression that specifies the position of an element of the collection. Index must be a number from 1 through the
value of the collection's Count Property (Collection Object).
Exceptions
Exception type Error number Condition
ArgumentException 5 Key is invalid or not specified.

IndexOutOfRangeException 9 Index does not match an existing element of the collection.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
When Remove deletes an element from a collection, it decrements the collection's Count Property (Collection Object) by one.
It also decrements the Index value of every element that formerly followed the deleted element in the collection.
If an element was added to the collection without a Key, you must use its Index to remove it.
Example
This example illustrates the use of the Remove method to remove objects from a Collection Object (Visual Basic) in the
variable birthdays.
VB
Dim birthdays As New Collection()
birthdays.Add(New DateTime(2001, 1, 12), "Bill")
birthdays.Add(New DateTime(2001, 1, 13), "Joe")
birthdays.Add(New DateTime(2001, 1, 14), "Mike")
birthdays.Add(New DateTime(2001, 1, 15), "Pete")
... birthdays.Remove(1)
birthdays.Remove("Mike")

Following the four calls to the Add method, the Count property contains 4, element "Bill" has index value 1, and element
"Pete" has index value 4.

Following the first call to Remove, Count is 3, element "Bill" is deleted, and element "Pete" has index value 3.
Following the second call to Remove, Count is 2, element "Mike" is deleted, and element "Pete" has index value 2.
Requirements
Namespace: Microsoft.VisualBasic
Module: Collection
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Collection Object (Visual Basic)
Add Method (Collection Object)
Visual Basic Language Reference

Err Object (Visual Basic)


Contains information about run-time errors.
Remarks
The properties of the Err object are set by the generator of an error—Visual Basic, an object, or the programmer.
When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and
that you can use to handle the error. To generate a run-time error in your code, use the Raise method.
The Err object's properties are reset to zero or zero-length strings ("") after an Exit Sub, Exit Function, Exit Property, or
Resume Next statement within an error-handling routine. Using any form of the Resume statement outside of an error-
handling routine will not reset the Err object's properties. You can use the Clear method to explicitly reset Err.
Use the Raise method rather than the Error statement to generate run-time errors for system errors and class modules. Your
decision about whether to use the Raise method in other code depends on the richness of the information you want to return.
The Err object is an intrinsic object with global scope. Therefore, you do not need to create an instance of it in your code.
Example
This example uses the properties of the Err object in constructing an error-message dialog box. Notice that if you use the Clear
method first, when you generate a Visual Basic error with the Raise method, Visual Basic's default values become the
properties of the Err object.
VB
Dim Msg As String
' If an error occurs, construct an error message.
On Error Resume Next ' Defer error handling.
Err.Clear()
Err.Raise(6) ' Generate an "Overflow" error.
' Check for error, then show message.
If Err.Number <> 0 Then
Msg = "Error # " & Str(Err.Number) & " was generated by " _
& Err.Source & ControlChars.CrLf & Err.Description
MsgBox(Msg, MsgBoxStyle.Information, "Error")
End If

Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Get Information about Visual Basic Run-Time Errors
How to: Retrieve Information from an Error Object
Reference
Err Object Members
Error Statement
On Error Statement (Visual Basic)
Exit Statement (Visual Basic)
Resume Statement
Visual Basic Language Reference

Err Object Members


The Err object contains properties whose values are determined by the error that just occurred. The Number property contains
the cause of the error, and the Description property contains a text message that describes the error in detail. Helpfile and
HelpContext allow you to display a related help file when a user presses the Help button or the F1 key. LastDLLError
displays the last DLL called and whether or not the call was successful. Source specifies a string expression representing the
object or application that generated the error.
Properties
Description Property Read/write. Returns or sets a descriptive string associated with an error.

Erl Property Read-only. Returns an integer indicating the line number of the last executed statement.

HelpContext Property Read/write. Returns or sets an Integer containing the context ID for a topic in a Help file.

HelpFile Property Read/write. Returns or sets a String expression containing the fully qualified path to a Help file.

LastDLLError Property Read-only. Returns a system error code produced by a call to a dynamic-link library (DLL).

Number Property Read/write. Returns or sets a numeric value specifying an error.

Source Property Read/write. Returns or sets a String expression specifying the name of the object or application that ori
ginally generated the error.
Methods
Clear Method Clears all property settings of the Err object.

Raise Method Generates a run-time error; can be used instead of the Error statement.
See Also
Tasks
How to: Retrieve Information from an Error Object
Reference
Err Object (Visual Basic)
Visual Basic Language Reference

Clear Method (Err Object)


Clears all property settings of the Err object.

object.Clear

Parameters
object
Always the Err object.
Remarks
Use Clear to explicitly clear the Err object after an error has been handled, such as when you use deferred error handling with
On Error Resume Next. The Clear method is called automatically whenever any of the following statements executes:
Any type of Resume statement
Exit Sub, Exit Function, or Exit Property
Any On Error statement
Any Try...Catch...Finally statement
Note
The On Error Resume Next construct may be preferable to On Error GoTo when handling errors generated during ac
cess to other objects. Checking Err after each interaction with an object removes ambiguity about which object was acc
essed by the code: You can be sure which object placed the error code in Err.Number, as well as which object originall
y generated the error (the object specified in Err.Source).

Example
This example uses the Err object's Clear method to reset the numeric properties of the Err object to zero and its string
properties to zero-length strings. Without the call to Clear, the second call to MsgBox would display the same error message.
VB
Sub ClearErr()
' Produce overflow error
On Error Resume Next
Dim zero As Integer = 0
Dim result As Integer = 8 / zero
MsgBox(Err.Description)
Err.Clear()
MsgBox(Err.Description)
End Sub

Requirements
Namespace: Microsoft.VisualBasic
Module: ErrObject
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Retrieve Information from an Error Object
Reference
Err Object (Visual Basic)
Description Property (Err Object)
HelpContext Property (Err Object)
HelpFile Property (Err Object)
LastDllError Property (Err Object)
Number Property (Err Object)
On Error Statement (Visual Basic)
Raise Method (Err Object)
Source Property (Err Object)
Visual Basic Language Reference

Description Property (Err Object)


Returns or sets a String expression containing a descriptive string associated with an error. Read/write.

Public Property Description() As String

Remarks
The Description property setting consists of a short description of the error. Use this property to alert the user to an error that
you cannot or do not want to handle. When generating a user-defined error, assign a short description of your error to the
Description property. If the Description property is not filled in, and the value of the Number property corresponds to a
Visual Basic run-time error, then the string returned by the ErrorToString function is set in the Description property when the
error is generated.
Example
This example assigns a user-defined message to the Description property of the Err object.
VB
On Error Resume Next
Err.Raise(60000)
Err.Description = "Your Widget needs a new Frob!"
MsgBox(Err.Description)

Requirements
Namespace: Microsoft.VisualBasic
Module: ErrObject
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Err Object (Visual Basic)
ErrorToString Function
HelpContext Property (Err Object)
HelpFile Property (Err Object)
LastDllError Property (Err Object)
Number Property (Err Object)
Source Property (Err Object)
Visual Basic Language Reference

Erl Property (Err Object)


Returns an integer indicating the line number of the last executed statement. Read-only.

Public ReadOnly Property Erl() As Integer

Remarks
If Visual Basic encounters no line numbers, it returns 0.
Example
This example uses the Erl property to indicate the line number.
VB
10: On Error Resume Next
20: Err.Raise(60000)
' Returns 20.
30: MsgBox(Erl())

Smart Device Developer Notes


This property is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: ErrObject
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Err Object (Visual Basic)
ErrorToString Function
Visual Basic Language Reference

HelpContext Property (Err Object)


Returns or sets an Integer containing the context ID for a topic in a Help file. Read/write.

Public Property HelpContext() As Integer

Remarks
The HelpContext property is used to display context-sensitive Help for an application. If a Help file is specified in HelpFile, the
HelpContext property is used to automatically display the Help file identified. If both the HelpFile and HelpContext
properties are empty, the value of the Number property is checked. If the value of the Number property corresponds to a
Visual Basic run-time error value, then the Visual Basic Help context ID for the error is used. If the value of the Number
property does not correspond to a Visual Basic error, the contents screen for the Visual Basic Help file is displayed.
Note
You should write routines in your application to handle typical errors. When programming with an object, you can use the ob
ject's Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error is n
ot recoverable.

Example
This example uses the HelpContext property of the Err object to show the Visual Basic Help topic for the Overflow error.
VB
Dim Msg As String
Err.Clear()
On Error Resume Next ' Suppress errors for demonstration purposes.
Err.Raise(6) ' Generate "Overflow" error.
If Err.Number <> 0 Then
Msg = "Press F1 or HELP to see " & Err.HelpFile & " topic for" & _
" the following HelpContext: " & Err.HelpContext
MsgBox(Msg, , "Error:")
End If

Requirements
Namespace: Microsoft.VisualBasic
Module: ErrObject
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Err Object (Visual Basic)
Description Property (Err Object)
ErrorToString Function
HelpFile Property (Err Object)
LastDllError Property (Err Object)
Number Property (Err Object)
Source Property (Err Object)
Visual Basic Language Reference

HelpFile Property (Err Object)


Returns or sets a String expression containing the fully qualified path to a Help file. Read/write.

Public Property HelpFile() As String

Remarks
If a Help file is specified by the HelpFile property, it is automatically called when the user presses the Help key (or the F1 key)
in the error message dialog box. If the HelpContext property contains a valid context ID for the specified file, that topic is
automatically displayed. If no HelpFile is specified, the Visual Basic Help file is displayed.
Note
You should write routines in your application to handle typical errors. When programming with an object, you can use the ob
ject's Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error is n
ot recoverable.

Example
This example uses the HelpFile property of the Err object to start the Help system. By default, the HelpFile property contains
the name of the Visual Basic Help file.
VB
Dim Msg As String
Err.Clear()
On Error Resume Next ' Suppress errors for demonstration purposes.
Err.Raise(6) ' Generate "Overflow" error.
If Err.Number <> 0 Then
Msg = "Press F1 or HELP to see " & Err.HelpFile & " topic for" & _
" the following HelpContext: " & Err.HelpContext
MsgBox(Msg, , "Error:")
End If

Requirements
Namespace: Microsoft.VisualBasic
Module: ErrObject
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Err Object (Visual Basic)
Description Property (Err Object)
HelpContext Property (Err Object)
LastDllError Property (Err Object)
Number Property (Err Object)
Source Property (Err Object)
Visual Basic Language Reference

LastDllError Property (Err Object)


Returns a system error code produced by a call to a dynamic-link library (DLL). Read-only.

ReadOnly Property LastDllError() As Integer

Remarks
The LastDllError property applies only to DLL calls made from Visual Basic code. When such a call is made, the called function
usually returns a code indicating success or failure, and the LastDllError property is filled. Check the documentation for the
DLL's functions to determine the return values that indicate success or failure. Whenever the failure code is returned, the Visual
Basic application should immediately check the LastDllError property. No exception is raised when the LastDllError property
is set.
Note
The LastDllError property requires unmanaged code permission, which may affect its execution in partial-trust situations. Fo
r more information, see SecurityPermission and Code Access Permissions.

Example
The following example shows how you can use the LastDllError property after calling a function in the Windows API. The
PrintWindowCoordinates procedure takes a handle to a window and calls the GetWindowRect function. GetWindowRect
fills the RECT data structure with the lengths of the sides of the rectangle that make up the window. If you pass an invalid
handle, an error occurs, and the error number is available through the LastDllError property.
VB
Declare Function GetWindowRect Lib "user32" _
(ByVal hwnd As Integer, ByRef lpRect As RECT) As Integer
...
Public Structure RECT
Public Left As Integer
Public Top As Integer
Public Right As Integer
Public Bottom As Integer
End Structure
...
Const ERROR_INVALID_WINDOW_HANDLE As Long = 1400
Const ERROR_INVALID_WINDOW_HANDLE_DESCR As String = _
"Invalid window handle."

VB
Private Sub PrintWindowCoordinates(ByVal hwnd As Integer)
' Prints left, right, top, and bottom positions
' of a window in pixels.

Dim rectWindow As RECT


' Pass in window handle and empty the data structure.
' If function returns 0, an error occurred.
If GetWindowRect(hwnd, rectWindow) = 0 Then
' Check LastDllError and display a dialog box if the error
' occurred because an invalid handle was passed.
If Err.LastDllError = ERROR_INVALID_WINDOW_HANDLE Then
MsgBox(ERROR_INVALID_WINDOW_HANDLE_DESCR, Title:="Error!")
End If
Else
Debug.Print(rectWindow.Bottom)
Debug.Print(rectWindow.Left)
Debug.Print(rectWindow.Right)
Debug.Print(rectWindow.Top)
End If
End Sub

Smart Device Developer Notes


This property always returns zero.
Requirements
Namespace: Microsoft.VisualBasic
Module: ErrObject
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Err Object (Visual Basic)
Declare Statement
Description Property (Err Object)
ErrorToString Function
HelpContext Property (Err Object)
HelpFile Property (Err Object)
Number Property (Err Object)
Source Property (Err Object)
Visual Basic Language Reference

Number Property (Err Object)


Returns or sets a numeric value specifying an error. Read/write.

Public Property Number() As Integer

Remarks
When returning a user-defined error from an object, set Err.Number by adding the number you selected as an error code to
the VbObjectError constant. For example, you use the following code to return the number 1051 as an error code:
VB
Err.Raise(Number:=vbObjectError + 1051, Source:="SomeClass")

Example
This example illustrates a typical use of the Number property in an error-handling routine.
VB
' Typical use of Number property.
Sub test()
On Error GoTo out

Dim x, y As Integer
x = 1 / y ' Create division by zero error.
Exit Sub
out:
MsgBox(Err.Number)
MsgBox(Err.Description)
' Check for division by zero error.
If Err.Number = 11 Then
y = y + 1
End If
Resume Next
End Sub

Requirements
Namespace: Microsoft.VisualBasic
Module: ErrObject
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Err Object (Visual Basic)
Description Property (Err Object)
ErrorToString Function
HelpContext Property (Err Object)
HelpFile Property (Err Object)
LastDllError Property (Err Object)
Source Property (Err Object)
Visual Basic Language Reference

Raise Method (Err Object)


Generates a run-time error; can be used instead of the Error statement.

Public Sub Raise( _


ByVal Number As Integer, _
Optional ByVal Source As Object = Nothing, _
Optional ByVal Description As Object = Nothing, _
Optional ByVal HelpFile As Object = Nothing, _
Optional ByVal HelpContext As Object = Nothing _
)

Parameters
Number
Required. Long integer that identifies the nature of the error. Visual Basic errors are in the range 0–65535; the range 0–512
is reserved for system errors; the range 513–65535 is available for user-defined errors. When setting the Number property
to your own error code in a class module, you add your error code number to the vbObjectError constant. For example, to
generate the error number 513, assign vbObjectError + 513 to the Number property.
Source
Optional. String expression naming the object or application that generated the error. When setting this property for an
object, use the form project.class. If Source is not specified, the process ID of the current Visual Basic project is used.
Description
Optional. String expression describing the error. If unspecified, the value in the Number property is examined. If it can be
mapped to a Visual Basic run-time error code, the string that would be returned by the Error function is used as the
Description property. If there is no Visual Basic error corresponding to the Number property, the "Application-defined or
object-defined error" message is used.
HelpFile
Optional. The fully qualified path to the Help file in which help on this error can be found. If unspecified, Visual Basic uses the
fully qualified drive, path, and file name of the Visual Basic Help file.
HelpContext
Optional. The context ID identifying a topic within HelpFile that provides help for the error. If omitted, the Visual Basic Help-
file context ID for the error corresponding to the Number property is used, if it exists.
Exceptions
Exception type Error number Condition
ArgumentException 5 Number is greater than 65535.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
All of the Raise arguments except Number are optional. If you omit optional arguments, and the property settings of the Err
object contain values that have not been cleared, those values serve as the values for your error.
Because the Err object gives richer information than when you generate errors with the Error statement, Raise is useful for
generating errors when writing class modules. For example, with the Raise method, the source that generated the error can be
specified in the Source property, online Help for the error can be referenced, and so on.
Example
This example uses the Err object's Raise method to generate an error within a function written in Visual Basic. The calling
function can catch the error and report it to the user with a message box.
VB
Const WidthError As Integer = 1
Const WidthHelp As Object = 101

Sub TestWidth(ByVal width As Integer)


If width > 1000 Then
Err.Raise(vbObjectError + 512 + WidthError, "TestWidth", _
"Width must be less than 1000.", "HelpFile.hlp", WidthHelp)
End If
End Sub

Sub CallingProcedure()
Try
TestWidth(2000)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Requirements
Namespace: Microsoft.VisualBasic
Module: ErrObject
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Err Object (Visual Basic)
Clear Method (Err Object)
Description Property (Err Object)
Error Statement
HelpContext Property (Err Object)
HelpFile Property (Err Object)
LastDllError Property (Err Object)
Number Property (Err Object)
On Error Statement (Visual Basic)
Source Property (Err Object)
ArgumentException Class
Visual Basic Language Reference

Source Property (Err Object)


Returns or sets a String expression specifying the name of the object or application that originally generated the error.
Read/write.

Public Property Source() As String

Remarks
The Source property specifies a String expression representing the object that generated the error; the expression is usually
the object's class name or process ID. Use the Source property to provide information when your code is unable to handle an
error generated in an accessed object. For example, if you access Microsoft Excel and it generates a Division by zero error,
Microsoft Excel sets Err.Number to its error code for that error and sets Source to "Excel.Application".
When the application is generating an error from code, Source is your application's programmatic ID. Within a class, Source
should contain a name having the form project.class. When an unexpected error occurs in your code, the Source property is
automatically filled in. For errors in a module, Source contains the project name.
Example
This example demonstrates the use of the Source property in a typical error-handling routine. When an error is raised from
Class1, the string "Class1" is assigned to the Source property of the Err object. This string is then displayed in an informative
message indicating the source and number of the error.
VB
Public Class Class1
Public Sub MySub()
On Error Resume Next
Err.Raise(60000, "Class1")
MsgBox(Err.Source & " caused an error of type " & Err.Number)
End Sub
End Class

Requirements
Namespace: Microsoft.VisualBasic
Module: ErrObject
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Err Object (Visual Basic)
Description Property (Err Object)
ErrorToString Function
GetObject Function (Visual Basic)
HelpContext Property (Err Object)
HelpContext Property (Err Object)
HelpFile Property (Err Object)
LastDllError Property (Err Object)
Number Property (Err Object)
On Error Statement (Visual Basic)
Visual Basic Language Reference

My.Application Object
Provides properties, methods, and events related to the current application.
Remarks
The properties exposed by the My.Application object return data that is associated only with the current application or DLL.
No system-level information can be altered with My.Application.
Some members are available only for Windows Forms or console applications.
Example
This example uses the My.Application.CommandLineArgs property to examine the application's command-line arguments.
If an argument is found that starts with /input=, the rest of that argument is displayed.
VB
Private Sub ParseCommandLineArgs()
Dim inputArgument As String = "/input="
Dim inputName As String = ""

For Each s As String In My.Application.CommandLineArgs


If s.ToLower.StartsWith(inputArgument) Then
inputName = s.Remove(0, inputArgument.Length)
End If
Next

If inputName = "" Then


MsgBox("No input name")
Else
MsgBox("Input name: " & inputName)
End If
End Sub

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase (the base class ConsoleApplicationBase provides members available in console
applications, and its base class ApplicationBase provides the members that are available in all projects)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Application Object Members
My.Application.ApplicationContext Property
My.Application.Info Object
My.Application.Log Object
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
Microsoft.VisualBasic.ApplicationServices.ApplicationBase
Visual Basic Language Reference

My.Application Object Members


The My.Application Object provides properties, methods, and events related to the current application.
Properties
Property Description
ApplicationContext Gets the ApplicationContext object for the current thread of a Windows Forms application.
This property is available only for Windows Forms applications.

CommandLineArgs Gets a collection containing the command-line arguments as strings for the current applic
ation.

Culture Gets the culture that the current thread uses for string manipulation and string formatting.

Deployment Gets the current application's ClickOnce deployment object, which provides support for u
pdating the current deployment programmatically and the on-demand download of files.

Info Returns the My.Application.Info Object, which provides properties for getting the informat
ion about the application's assembly, such as the version number, description, and so on.

IsNetworkDeployed Gets a Boolean that represents whether the application was network deployed.

Log Returns the My.Application.Log Object, which provides a property and methods for writin
g event and exception information to the application's event log listeners.

MinimumSplashScreenDisplayTime Gets or sets the minimum length of time, in milliseconds, for which the splash screen is di
splayed.

OpenForms Gets a collection of all the application's open forms.


This property is available only for Windows Forms applications.

SaveMySettingsOnExit Determines whether the application saves the user settings on exit.
This property is available only for Windows Forms and console applications.

SplashScreen Gets or sets the splash screen for this application.


This property is available only for Windows Forms applications.

UICulture Gets the culture that the current thread uses for retrieving culture-specific resources.
Methods
Method Description
ChangeCulture Changes the culture that the current thread uses for string manipulation and string formatting.

ChangeUICulture Changes the culture that the current thread uses for retrieving culture-specific resources.

DoEvents Processes all Windows messages currently in the message queue.


This method is available only for Windows Forms applications.

GetEnvironmentVariable Returns the value of the specified environment variable.


Run Sets up and starts the Visual Basic Application model.
This method is available only for Windows Forms applications.
Events
Event Description
NetworkAvailabilityChanged Occurs when the network availability changes.
This event is available only for Windows Forms applications.

Shutdown Occurs when the application shuts down.


This event is available only for Windows Forms applications.

Startup Occurs when the application starts.


This event is available only for Windows Forms applications.

StartupNextInstance Occurs when attempting to start a single-instance application and the application is already activ
e.
This event is available only for Windows Forms applications.

UnhandledException Occurs when the application encounters an unhandled exception.


This event is available only for Windows Forms applications.
See Also
Reference
My.Application Object
Visual Basic Language Reference

My.Application.ApplicationContext Property
Gets the ApplicationContext object for the current thread of a Windows Forms application.

' Usage
Dim value As System.Windows.Forms.ApplicationContext = My.Application.ApplicationContext
' Declaration
Public ReadOnly Property ApplicationContext As System.Windows.Forms.ApplicationContext

Return Value
This property returns the ApplicationContext object for the current thread. That object contains contextual information about
the thread.
Remarks
This is an advanced member; it does not appear in IntelliSense unless you click the All tab.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library No

Console Application No

Windows Control Library No

Web Control Library No

Windows Service No

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Application Object
System.Windows.Forms.ApplicationContext
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.ApplicationContext
Visual Basic Language Reference

My.Application.ChangeCulture Method
Changes the culture used by the current thread for string manipulation and for string formatting.

' Usage
My.Application.ChangeCulture(cultureName)
' Declaration
Public Sub ChangeCulture( _
ByVal cultureName As String _
)

Parameters
cultureName
String. Name of the culture as a string. For a list of possible names, see CultureInfo.
Exceptions
The following conditions can cause an exception:
The cultureName argument is Nothing (ArgumentNullException).
The cultureName argument is not a valid culture name (ArgumentException).
Remarks
The My.Application.ChangeCulture method changes the current thread's CurrentCulture property. CurrentCulture
determines the default formats for dates, times, currency, numbers, sorting order of text, string comparisons, and casing for all
computations on that thread.
To retrieve the current culture, you can use the My.Application.Culture Property or the CurrentCulture property.
The CurrentCulture setting is different from a language setting. It contains only data related to the standard settings for a
geographical region. Therefore, the CurrentCulture property can only be set to a specific culture or to the InvariantCulture.
Use the My.Application.ChangeUICulture method to change the culture that the current thread uses for retrieving culture-
specific resources.
Security Note
The My.Application.ChangeCulture method requires a SecurityPermission with the ControlThread set. Manipulating threa
ds is dangerous because of the security state associated with threads. Therefore, this permission should be given only as nec
essary to trustworthy code. You cannot change a thread's culture in semi-trusted code.

Example
This example demonstrates how changing the culture changes the string representation of dates.
VB
Private Sub TestChangeCulture()
' Store the current culture.
Dim currentculture As String = My.Application.Culture.Name
MsgBox("Current culture is " & currentculture)

Dim jan1 As New Date(2005, 1, 1, 15, 15, 15)


My.Application.ChangeCulture("en-US")
MsgBox("Date represented in en-US culture: " & jan1)
' 1/1/2005 3:15:15 PM
My.Application.ChangeCulture("")
MsgBox("Date represented in invariant culture" & jan1)
' 01/01/2005 15:15:15
' Restore the culture.
My.Application.ChangeCulture(currentculture)
End Sub

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase, ApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
The following permission may be necessary:
Permission Description
SecurityPermission Describes a set of security permissions applied to code. Associated enumeration: ControlThread.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application Object
My.Application.Culture Property
My.Application.ChangeUICulture Method
Microsoft.VisualBasic.ApplicationServices.ApplicationBase.ChangeCulture(System.String)
CurrentCulture
Visual Basic Language Reference

My.Application.ChangeUICulture Method
Changes the culture that the current thread uses for retrieving culture-specific resources.

' Usage
My.Application.ChangeUICulture(cultureName)
' Declaration
Public Sub ChangeUICulture( _
ByVal cultureName As String _
)

Parameters
cultureName
String. Name of the culture as a string. For a list of possible names, see CultureInfo.
Exceptions
The following conditions can cause an exception:
The cultureName argument is Nothing (ArgumentNullException).
The cultureName argument is not a valid culture name (ArgumentException).
Remarks
The My.Application.ChangeUICulture method changes the current thread's CurrentUICulture property. The
CurrentUICulture property determines the culture used by the Resource Manager and the My.Resources object; it uses this
information to look up culture-specific resources at run time.
To retrieve the current UI culture, you can use the My.Application.UICulture Property or the CurrentUICulture property.
Use the My.Application.ChangeCulture method to change the culture that the current thread uses for string manipulation
and string formatting.
Example
This example uses the My.Application.ChangeUICulture method to set the culture that the My.Resources Object uses for
retrieving resources.
VB
Sub ShowLocalizedMessage()
Dim culture As String = My.Application.UICulture.Name
My.Application.ChangeUICulture("fr-FR")
MsgBox(My.Resources.Message)
My.Application.ChangeUICulture(culture)
End Sub

For this example to work, your application must have a string named Message in the application's resource file, and the
application should have the French-culture version of that resource file, Resources.fr-FR.resx. For more information, see
How to: Add or Remove Resources.
If the application does not have the French-culture version of that resource file, the My.Resource object retrieves the resource
from the default-culture resource file.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase, ApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Retrieve Localized Resources in Visual Basic
Reference
My.Application Object
My.Application.ChangeCulture Method
My.Resources Object
Microsoft.VisualBasic.ApplicationServices.ApplicationBase.ChangeUICulture(System.String)
Visual Basic Language Reference

My.Application.Culture Property
Gets the culture that the current thread uses for string manipulation and string formatting.

' Usage
Dim value As System.Globalization.CultureInfo = My.Application.Culture
' Declaration
Public ReadOnly Property Culture As System.Globalization.CultureInfo

Return Value
Returns a CultureInfo object that represents the culture the current thread uses for string manipulation and string formatting.
Remarks
The My.Application.CurrentCulture property gets the CultureInfo object that the current thread uses for string
manipulation and string formatting. This object is identical to the one returned by the CurrentCulture property, which controls
many of the string-related computations on that thread. The CurrentCulture property determines the default formats for
dates, times, currency, and numbers. It also determines how to sort, compare, and capitalize strings.
To change the culture, you can use the My.Application.ChangeCulture Method or assign a different CultureInfo object to the
CurrentCulture property.
The CurrentCulture setting is different from a language setting. It contains only data related to the standard settings for a
geographical region.
Use the My.Application.CurrentUICulture property to get the culture that the current thread uses for retrieving culture-
specific resources.
Example
This example demonstrates how the culture affects the string representation of dates.
VB
Private Sub TestChangeCulture()
' Store the current culture.
Dim currentculture As String = My.Application.Culture.Name
MsgBox("Current culture is " & currentculture)
Dim jan1 As New Date(2005, 1, 1, 15, 15, 15)

My.Application.ChangeCulture("en-US")
MsgBox("Date represented in en-US culture: " & jan1)
' 1/1/2005 3:15:15 PM

My.Application.ChangeCulture("")
MsgBox("Date represented in invariant culture" & jan1)
' 01/01/2005 15:15:15

' Restore the culture.


My.Application.ChangeCulture(currentculture)
End Sub

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase, ApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Application Object
My.Application.ChangeCulture Method
My.Application.UICulture Property
System.Globalization.CultureInfo
CurrentCulture
Microsoft.VisualBasic.ApplicationServices.ApplicationBase.Culture
Visual Basic Language Reference

My.Application.CommandLineArgs Property
Gets a collection containing the command-line arguments as strings for the current application.

' Usage
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Application.
CommandLineArgs
' Declaration
Public ReadOnly Property CommandLineArgs As System.Collections.ObjectModel.ReadOnlyCollecti
on(Of String)

Return Value
A ReadOnlyCollection of String, containing the command-line arguments as strings for the current application.
Remarks
The My.Application.CommandLineArgs property provides read-only access to the current application's command-line
arguments for applications that are not ClickOnce deployed.
For a single-instance application, the My.Application.CommandLineArgs property returns the command-line arguments for
the first instance of an application. To access the arguments for subsequent attempts to start a single-instance application, you
must handle the My.Application.StartupNextInstance Event and examine the CommandLine property of the StartupEventArgs
argument.
Note
The My.Application.CommandLineArgs property returns only the command-line arguments. This is different from the be
havior of the CommandLine property, which returns the application name in addition to the arguments.

Note
In an application that is ClickOnce deployed, use the ActivationUri property of the My.Application.Deployment object to g
et the command-line arguments. For more information, see My.Application.Deployment Property.

Tasks
The following table lists examples of tasks involving the My.Application.CommandLineArgs property.
To See
Check if the application started with the string /batch as an argu How to: Enable a Batch Mode for Window Forms Applications
ment

Check the command-line arguments of subsequent attempts to My.Application.StartupNextInstance Event


start a single-instance application
Example
This example uses the My.Application.CommandLineArgs property to examine the application's command-line arguments.
If an argument is found that starts with /input=, the rest of that argument is displayed.
VB
Private Sub ParseCommandLineArgs()
Dim inputArgument As String = "/input="
Dim inputName As String = ""

For Each s As String In My.Application.CommandLineArgs


If s.ToLower.StartsWith(inputArgument) Then
inputName = s.Remove(0, inputArgument.Length)
End If
Next
If inputName = "" Then
MsgBox("No input name")
Else
MsgBox("Input name: " & inputName)
End If
End Sub

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: ConsoleApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library No

Console Application Yes

Windows Control Library No

Web Control Library No

Windows Service Yes

Web Site No
Permissions
The following permission may be necessary:
Permission Description
EnvironmentPermission Controls the ability to access the PATH environment variable. Associated enumeration: Read.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application Object
My.Application.StartupNextInstance Event
ReadOnlyCollection
Microsoft.VisualBasic.ApplicationServices.ConsoleApplicationBase.CommandLineArgs
StartupEventArgs
CommandLine
Visual Basic Language Reference

My.Application.Deployment Property
Gets the current application's ClickOnce deployment object, which provides support for updating the current deployment
programmatically and support for the on-demand download of files.

' Usage
Dim value As System.Deployment.Application.ApplicationDeployment = My.Application.Deploymen
t
' Declaration
Public ReadOnly Property Deployment As System.Deployment.Application.ApplicationDeployment

Return Value
Returns the ApplicationDeployment object for the application's ClickOnce deployment.
Exceptions
The following condition can cause an exception:
The application is not deployed as a ClickOnce application (InvalidDeploymentException).
Remarks
The My.Application.Deployment property returns the application's ClickOnce ApplicationDeployment object. The
ApplicationDeployment object provides support for updating the current deployment programmatically as well as support
for the on-demand download of files. For more information on ClickOnce applications and how to deploy them, see
ClickOnce Deployment and Publishing ClickOnce Applications.
Check the My.Application.IsNetworkDeployed Property before accessing the My.Application.Deployment property.
Otherwise, if the application is not deployed using ClickOnce, reading the My.Application.Deployment property results in an
InvalidDeploymentException exception. For more information on deploying a ClickOnce application, see
How to: Publish a ClickOnce Application.
For more information on using the My.Application.Deployment property, see
Overview of the Visual Basic Application Model.
Tasks
The following table lists examples of tasks involving the My.Application.Deployment property.
To See
Check for an application update How to: Check for ClickOnce Application Updates

Download an application update How to: Download ClickOnce Application Updates


Example
This example downloads and installs the update after checking that the application is network-deployed. The Update method
does not update the application unless it is out of date. The application has to restart to use the update. For more information,
see How to: Download ClickOnce Application Updates.
VB
Sub UpdateApplication()
If My.Application.IsNetworkDeployed Then
My.Application.Deployment.Update()
End If
End Sub

Only applications that are ClickOnce deployed can be updated using the My.Application.Deployment object. For more
information on deploying a ClickOnce application, see How to: Publish a ClickOnce Application.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: ConsoleApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library No

Console Application Yes

Windows Control Library No

Web Control Library No

Windows Service Yes

Web Site No
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Check for ClickOnce Application Updates
How to: Download ClickOnce Application Updates
How to: Publish a ClickOnce Application
Reference
My.Application Object
My.Application.IsNetworkDeployed Property
System.Deployment.Application.ApplicationDeployment
Microsoft.VisualBasic.ApplicationServices.ConsoleApplicationBase.Deployment
Concepts
Overview of the Visual Basic Application Model
Other Resources
Publishing ClickOnce Applications
Visual Basic Language Reference

My.Application.DoEvents Method
Processes all Windows messages currently in the message queue.

' Usage
My.Application.DoEvents()
' Declaration
Public Sub DoEvents()

Remarks
The My.Application.DoEvents method allows your application to handle other events that might be raised while you code
runs. The My.Application.DoEvents method has the same behavior as the DoEvents method.
When you run a Windows Forms application, it creates a new form, which then waits for events to be handled. Each time the
form handles an event, such as a button click, it processes all the code associated with that event. All other events wait in the
queue. While your code handles the event, your application does not respond. For example, the window does not repaint if
another window is dragged on top.
If you call My.Application.DoEvents in your code, your application can handle the other events. For example, if your code
adds data to a ListBox in a loop, and after each step of the loop it calls My.Application.DoEvents, your form repaints when
another window is dragged over it. If you remove My.Application.DoEvents from your code, your form will not repaint until
the click event handler of the button is finished executing.
Typically, you use this method in a loop to process messages.
Note
The My.Application.DoEvents method does not process events in exactly the same way as the form does. Use multithreadi
ng to make the form directly handle the events. For more information, see Multithreading in Visual Basic.

Caution
If a method that handles a user interface (UI) event calls the My.Application.DoEvents method, the method might be re-en
tered before it finishes. This can happen because the My.Application.DoEvents method processes Windows messages, and
Windows messages can raise events.

Tasks
The following table lists an example of a task involving the My.Application.DoEvents method.
To See
Allow a form to respond to UI input while busy Walkthrough: Handling Events
Example
This example uses the My.Application.DoEvents method to allow the UI for TextBox1 to update.
VB
Private Sub TestDoEvents()
For i As Integer = 0 To 10000
TextBox1.Text = i.ToString
My.Application.DoEvents()
Next
End Sub

This code should be in a form that has a TextBox1 component with a Text property.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library No

Console Application No

Windows Control Library No

Web Control Library No

Windows Service No

Web Site No
Permissions
The following permissions may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration: AllWindows.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application Object
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoEvents
DoEvents
Visual Basic Language Reference

My.Application.GetEnvironmentVariable Method
Returns the value of the specified environment variable.

' Usage
Dim value As String = My.Application.GetEnvironmentVariable(name)
' Declaration
Public Function GetEnvironmentVariable( _
ByVal name As String _
) As String

Parameters
name
A String containing the name of the environment variable.
Return Value
A String containing the value of the environment variable with the name name.
Exceptions
The following conditions can cause an exception:
The name argument is Nothing (ArgumentNullException).
The environment variable specified by name does not exist (ArgumentException).
The calling code does not have EnvironmentPermission with Read access (SecurityException).
Remarks
The My.Application.GetEnvironmentVariable method returns the environment variable with the name name. This method
is similar to System.Environment.GetEnvironmentVariable(System.String), except that this method raises an exception if the
environment variable specified by name does not exist.
Example
This example uses the My.Application.GetEnvironmentVariable method to get and display the value of the PATH
environment variable, if available. Otherwise, it displays a message indicating that the PATH environment variable does not
exist.
VB
Private Sub TestGetEnvironmentVariable()
Try
MsgBox("PATH = " & My.Application.GetEnvironmentVariable("PATH"))
Catch ex As System.ArgumentException
MsgBox("Environment variable 'PATH' does not exist.")
End Try
End Sub

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase, ApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Application Object
GetEnvironmentVariable
GetEnvironmentVariable
Visual Basic Language Reference

My.Application.Info Property
Gets an object that provides properties for getting information about the application's assembly, such as the version number,
description, and so on.

' Usage
Dim value As Microsoft.VisualBasic.ApplicationServices.AssemblyInfo = My.Application.Info
' Declaration
Public ReadOnly Property Info As AssemblyInfo

Return Value
This property returns the My.Application.Info object for the current application.
Remarks
This property provides easy access to the My.Application.Info. For more information, see My.Application.Info Object.
Example
This example uses the My.Application.Info.Version property to display the version of the application.
VB
MsgBox("Application version: " & My.Application.Info.Version.ToString)

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: ApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Application Object
My.Application.Info Object
Visual Basic Language Reference

My.Application.IsNetworkDeployed Property
Gets a Boolean that represents whether the application was deployed from a network using ClickOnce.

' Usage
Dim value As Boolean = My.Application.IsNetworkDeployed
' Declaration
Public ReadOnly Property IsNetworkDeployed As Boolean

Return Value
A Boolean that represents whether the application was deployed from a network. The value is True if the current application
was deployed from a network; otherwise the value is False.
Remarks
The My.Application.IsNetworkDeployed property indicates whether the application was deployed from a network using
ClickOnce. For more information on ClickOnce applications, see ClickOnce Deployment.
You should check that this property is True before accessing the My.Application.Deployment Property. Otherwise, if the
application is not deployed from a network using ClickOnce, reading the My.Application.Deployment property results in an
InvalidDeploymentException exception.
For more information on configuring ClickOnce, see Publishing ClickOnce Applications. For more information on deploying a
ClickOnce application, see How to: Publish a ClickOnce Application.
For more information on using the My.Application.IsNetworkDeployed property, see
Overview of the Visual Basic Application Model.
Tasks
The following table lists examples of tasks involving the My.Application.IsNetworkDeployed property.
To See
Check for an application update. How to: Check for ClickOnce Application Updates

Download an application update. How to: Download ClickOnce Application Updates


Example
This example downloads and installs the update after checking that the application is deployed from a network. The Update
method does not update the application unless it is out of date. The application has to restart to use the update. For more
information, see How to: Download ClickOnce Application Updates.
VB
Sub UpdateApplication()
If My.Application.IsNetworkDeployed Then
My.Application.Deployment.Update()
End If
End Sub

Only applications that are ClickOnce-deployed can be updated using the My.Application.Deployment object. For more
information on deploying a ClickOnce application, see How to: Publish a ClickOnce Application.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: ConsoleApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library No

Console Application Yes

Windows Control Library No

Web Control Library No

Windows Service Yes

Web Site No
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Check for ClickOnce Application Updates
How to: Download ClickOnce Application Updates
How to: Publish a ClickOnce Application
Reference
My.Application Object
My.Application.Deployment Property
IsNetworkDeployed
Concepts
Overview of the Visual Basic Application Model
Visual Basic Language Reference

My.Application.Log Property
Gets an object that provides properties and methods for writing event and exception information to the application's log
listeners.

' Usage
Dim value As Microsoft.VisualBasic.Logging.Log = My.Application.Log
' Declaration
Public ReadOnly Property Log As MyLog

Return Value
This property returns the My.Application.Log object for the current application.
Remarks
This property provides easy access to the My.Application.Log object. For more information, see My.Application.Log Object.
Example
This example shows how to use the My.Application.Log.WriteEntry method to log tracing information. For more
information, see How to: Write Log Messages.
VB
Public Sub TracingTest(ByVal fileName As String)
My.Application.Log.WriteEntry( _
"Entering TracingTest with argument " & _
fileName & ".")
' Code to trace goes here.
My.Application.Log.WriteEntry( _
"Exiting TracingTest with argument " & _
fileName & ".")
End Sub

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: ApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application Object
My.Application.Log Object
Visual Basic Language Reference

My.Application.MinimumSplashScreenDisplayTime Property
Determines the minimum length of time, in milliseconds, for which the splash screen is displayed.

' Usage
Dim value As Integer = My.Application.MinimumSplashScreenDisplayTime
' Declaration
Public Property MinimumSplashScreenDisplayTime As Integer

Return Value
Integer. The minimum length of time, in milliseconds, for which the splash screen is displayed.
Remarks
The My.Application.MinimumSplashScreenDisplayTime property allows you to specify the minimum length of time you
want the application's splash screen to be displayed. If the main form finishes initializing in less time than what is specified by
this property, the splash screen remains until the requested amount of time passes, at which time the main form is displayed. If
your application takes longer to start, the splash screen is closed once the main form becomes active.
When you add a splash screen to your application using the Project Designer, it sets the
My.Application.MinimumSplashScreenDisplayTime property to 2000, giving a minimum display time of two seconds.
This property supports the Visual Basic Application model. For more information, see
Overview of the Visual Basic Application Model.
You should set the My.Application.MinimumSplashScreenDisplayTime property in a method that overrides the
OnInitialize or OnCreateSplashScreen method. Code that overrides methods of the WindowsFormsApplicationBase class
should be entered in the ApplicationEvents.vb file, which is hidden by default.
To access the Code Editor window for overriding members
1. With a project selected in Solution Explorer, click Properties on the Project menu.
2. Click the Application tab.
3. Click the View Application Events button to open the Code Editor.
For more information, see How to: Handle Application Events (Visual Basic).
Example
This example demonstrates how to set the My.Application.MinimumSplashScreenDisplayTime property by overriding the
OnInitialize property.
VB
Protected Overrides Function OnInitialize( _
ByVal commandLineArgs As _
System.Collections.ObjectModel.ReadOnlyCollection(Of String) _
) As Boolean
' Set the display time to 5000 milliseconds (5 seconds).
Me.MinimumSplashScreenDisplayTime = 5000
Return MyBase.OnInitialize(commandLineArgs)
End Function

This example requires that the project have a splash screen.


You must enter this code in the Code Editor window for application events. For more information, see
How to: Handle Application Events (Visual Basic).
Permissions
No permissions are required.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library No

Console Application No

Windows Control Library No

Web Control Library No

Windows Service No

Web Site No
See Also
Reference
My.Application Object
My.Application.SplashScreen Property
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.MinimumSplashScreenDisplayTime
OnInitialize
OnCreateSplashScreen
WindowsFormsApplicationBase
Concepts
Extending the Visual Basic Application Model
Visual Basic Language Reference

My.Application.NetworkAvailabilityChanged Event
Occurs when the network availability changes.

' Usage
Public Sub Me_NetworkAvailabilityChanged( _
ByVal sender As Object, _
ByVal e As NetworkAvailableEventArgs _
) Handles Me.NetworkAvailabilityChanged
End Sub
' Declaration
Public Event NetworkAvailabilityChanged( _
ByVal sender As Object, _
ByVal e As NetworkAvailableEventArgs _
)

Parameters
sender
Required. The Object that raised the event.
e
Required. A NetworkAvailableEventArgs object that contains information about the availability of the network.
Remarks
An application raises the NetworkAvailabilityChanged event every time the availability of the network changes. You can use
the IsNetworkAvailable property of the e parameter to get the new state of the network connection. To get the current state of
the network connection, use the My.Computer.Network.IsAvailable Property.
This event is raised on the application's main thread with the other user-interface events. This allows the event handler to
access directly the application's UI. However, if the application is busy handling another user-interface event when this event is
raised, this event cannot be processed until the other event handler finishes or calls the My.Application.DoEvents Method.
The My.Computer.Network.NetworkAvailabilityChanged Event provides the same functionality as this event but is available for
all application types.
The code for the NetworkAvailabilityChanged event handler is stored in the ApplicationEvents.vb file, which is hidden by
default.
To access the Code Editor window for application events
1. Have a project selected in Solution Explorer. Click Properties on the Project menu.
2. Click the Application tab.
3. Click the View Application Events button to open the Code Editor.
For more information, see How to: Handle Application Events (Visual Basic).
Note
Many network hubs will provide a network connection even if the hub is disconnected from a larger network. Consequently,
for wired connections, this event indicates change in the connection between the computer and a hub.

Note
The NetworkAvailabilityChanged event is not raised by applications when run on Windows 95 and Windows 98, or when
run by a non-administrator on Windows 2000. If your application might run on those platforms, use the
My.Computer.Network.IsAvailable Property to check for network availability.

Example
This example calls the SetConnectionStatus method of the default Form1 class when the network availability changes.
You must enter the code in the Code Editor window for application events. To access this window, follow the instructions from
this topic's Remarks section.
VB
Private Sub MyApplication_NetworkAvailabilityChanged( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.Devices.NetworkAvailableEventArgs _
) Handles Me.NetworkAvailabilityChanged
My.Forms.Form1.SetConnectionStatus(e.IsNetworkAvailable)
End Sub

Compiling the Code


The project should have a form named Form1. It should have a method named SetConnectionStatus that takes a Boolean
parameter.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library No

Console Application No

Windows Control Library No

Web Control Library No

Windows Service No

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Application Object
My.Forms Object
My.Computer.Network.NetworkAvailabilityChanged Event
Microsoft.VisualBasic.Devices.NetworkAvailableEventArgs
Visual Basic Language Reference

My.Application.OpenForms Property
Gets a collection of all the application's open forms.

' Usage
Dim value As System.Windows.Forms.FormCollection = My.Application.OpenForms
' Declaration
Public ReadOnly Property OpenForms As System.Windows.Forms.FormCollection

Return Value
A FormCollection object that contains all of the application's open forms.
Remarks
The My.Application.OpenForms property gets a collection of all the application's open forms. The behavior is identical to the
System.Windows.Forms.Application.OpenForms property.
Note
The My.Application.OpenForms property returns all open forms, regardless of which thread opened them. You should che
ck the InvokeRequired property of each form before accessing it; otherwise, it might throw an InvalidOperationException exc
eption. For more information, see How to: Access All Open Forms of an Application.

Tasks
The following table lists examples of tasks involving the My.Application.OpenForms property.
To See
Display the titles of all the application's open forms How to: Access All Open Forms of an Application
Example
This example loops over the application's open forms, selects the ones directly accessible by the current thread, and displays
their titles in a ListBox control. To access the open forms, see How to: Access All Open Forms of an Application.
VB
Private Sub GetOpenFormTitles()
Dim formTitles As New Collection
Try
For Each f As Form In My.Application.OpenForms
If Not f.InvokeRequired Then
' Can access the form directly.
formTitles.Add(f.Text)
End If
Next
Catch ex As Exception
formTitles.Add("Error: " & ex.Message)
End Try
Form1.ListBox1.DataSource = formTitles
End Sub

This example requires that your Windows Forms application have a form named Form1 that contains a list box named
ListBox1.

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library No

Console Application No

Windows Control Library No

Web Control Library No

Windows Service No

Web Site No
Permissions
The following permission may be necessary:
Permission Description
UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration: AllWindows.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application Object
System.Windows.Forms.FormCollection
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OpenForms
System.Windows.Forms.Application.OpenForms
Visual Basic Language Reference

My.Application.Run Method
Sets up and starts the Visual Basic Application model.

' Usage
My.Application.Run(commandLine)
' Declaration
Public Sub Run( _
ByVal commandLine As String() _
)

Parameters
commandLine
Array of type String. The command line from Sub Main.
Remarks
The My.Application.Run method provides support for the Visual Basic Application model. This method should be called only
from the application's Sub Main. By default, the Sub Main of a Windows Forms application calls this method. For more
information, see Overview of the Visual Basic Application Model.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library No

Console Application No

Windows Control Library No

Web Control Library No

Windows Service No

Web Site No
Permissions
The following permissions may be necessary:
Permission Description
EnvironmentPermission Controls the ability to access all environment variables. Associated enumeration: Unrestricted.

FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

RegistryPermission Controls the ability to access registry variables. Associated enumeration: Unrestricted.

UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration
: AllWindows.
WebPermission Controls rights to access HTTP Internet resources. Associated enumeration: Unrestricted.

SocketPermission Controls rights to make or accept connections on a transport address. Associated enumeratio
n: Unrestricted.

PerformanceCounterPermission Controls access to a Windows NT performance counter component. Associated enumeration:


Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application Object
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(System.String[])
Concepts
Overview of the Visual Basic Application Model
Visual Basic Language Reference

My.Application.SaveMySettingsOnExit Property
Determines whether the application saves the user settings on exit.

' Usage
Dim value As Boolean = My.Application.SaveMySettingsOnExit
' Declaration
Public Property SaveMySettingsOnExit As Boolean

Return Value
Boolean. True indicates that the application saves the user settings on exit. Otherwise, the settings are not implicitly saved.
Remarks
The SaveMySettingsOnExit property allows the user to change how the application saves settings, at run time. You can
explicitly save setting changes by using the Save method of the My.Settings object. For more information about changing and
saving settings, see My.Settings Object.
The changes to this property are not persisted when the application closes. To change the SaveMySettingsOnExit property
permanently, you must change the setting in the Project Designer:
To change the setting in the Project Designer
1. Have a project selected in Solution Explorer. Click Properties on the Project menu.
2. Click the Application tab.
3. Select Save My.Settings on Shutdown.
For more information, see Managing Application Properties.
Example
This example has two parts.
The InitializeSaveMySettingsOnExit subroutine, which initializes the checked state of a CheckBox control to the
current value of the SaveMySettingsOnExit property.
The SaveMySettingsOnExit_CheckedChanged subroutine, which handles changes to a CheckBox control to update the
My.Application.SaveMySettingsOnExit property.
VB
Private Sub InitializeSaveMySettingsOnExit()
SaveMySettingsOnExit.Checked = _
My.Application.SaveMySettingsOnExit
End Sub
Private Sub SaveMySettingsOnExit_CheckedChanged( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) Handles SaveMySettingsOnExit.CheckedChanged
My.Application.SaveMySettingsOnExit = _
SaveMySettingsOnExit.Checked
End Sub

For this example to work, your application must have a CheckBox control named SaveMySettingsOnExit.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library No

Console Application No

Windows Control Library No

Web Control Library No

Windows Service No

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Application Object
My.Settings Object
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.SaveMySettingsOnExit
Save
Visual Basic Language Reference

My.Application.Shutdown Event
Occurs when the application shuts down.

' Usage
Public Sub Me_Shutdown( _
ByVal sender As Object, _
ByVal e As System.EventArgs _
) Handles Me.Shutdown
End Sub
' Declaration
Public Event Shutdown( _
ByVal sender As Object, _
ByVal e As System.EventArgs _
)

Parameters
sender
The Object that raised the event.
e
An EventArgs object that contains Empty.
Remarks
An application raises the Shutdown event before it exits. This allows you to control how the application closes its resources.
This event is part of the Visual Basic Application model. For more information, see
Overview of the Visual Basic Application Model.
The code for the Shutdown event handler is stored in the ApplicationEvents.vb file, which is hidden by default.
To access the Code Editor window for application events
1. With a project selected in Solution Explorer, click Properties on the Project menu.
2. Click the Application tab.
3. Click the View Application Events button to open the Code Editor.
For more information, see How to: Handle Application Events (Visual Basic).
Tasks
The following table lists examples of tasks involving the My.Application.Shutdown event.
To See
Use the events provided by the Visual Basic Application mo How to: Run Code When the Application Starts or Ends
del to run code

Log a message when the application shuts down How to: Log Messages When the Application Starts or Shuts Down
Example
This example logs messages when the application shuts down.
VB
Private Sub MyApplication_Shutdown( _
ByVal sender As Object, _
ByVal e As System.EventArgs _
) Handles Me.Shutdown
My.Application.Log.WriteEntry("Application Shut Down.")
End Sub
You must enter the code in the Code Editor window for application events. To access this window, follow the instructions from
this topic's Remarks section. For more information, see How to: Log Messages When the Application Starts or Shuts Down.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library No

Console Application No

Windows Control Library No

Web Control Library No

Windows Service No

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Log Messages When the Application Starts or Shuts Down
How to: Handle Application Events (Visual Basic)
Reference
My.Application Object
System.EventArgs
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Shutdown
Concepts
Overview of the Visual Basic Application Model
Visual Basic Language Reference

My.Application.SplashScreen Property
Gets or sets the splash screen for this application.

' Usage
Dim value As System.Windows.Forms.Form = My.Application.SplashScreen
' Declaration
Public Property SplashScreen As System.Windows.Forms.Form

Return Value
A Form object that the application uses as the splash screen.
Exceptions
The following condition can cause an exception:
The same value assigned to this property and the My.Application.MainForm property (ArgumentNullException).
Remarks
The My.Application.SplashScreen property allows you to get or set the Form object that the application uses as the splash
screen, the first graphic form that is displayed while an application is being started.
This property supports the Visual Basic Application model. For more information, see
Overview of the Visual Basic Application Model.
The changes to this property are not persisted when the application closes. To change the splash screen permanently, you must
change the setting in the Project Designer. For more information, see
How to: Specify a Splash Screen for an Application (Visual Basic).
Example
This example uses the My.Application.SplashScreen property and the My.Application.Startup event to update the splash
screen with status information as the application starts.
VB
Private Sub MyApplication_Startup( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs _
) Handles Me.Startup
' Get the splash screen.
Dim splash As SplashScreen1 = CType(My.Application.SplashScreen, SplashScreen1)
' Display current status information.
splash.Status = "Current user: " & My.User.Name
End Sub

This example requires that the project have a splash screen named SplashScreen1. The splash screen needs to have a property
named Status that updates its user interface.
You must enter this code in the Code Editor window for application events. For more information, see
How to: Handle Application Events (Visual Basic).
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library No

Console Application No

Windows Control Library No

Web Control Library No

Windows Service No

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Application Object
My.Application.MinimumSplashScreenDisplayTime Property
System.Windows.Forms.Form
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.SplashScreen
Visual Basic Language Reference

My.Application.Startup Event
Occurs when the application starts.

' Usage
Public Sub Me_Startup( _
ByVal sender As Object, _
ByVal e As StartupEventArgs _
) Handles Me.Startup
End Sub
' Declaration
Public Event Startup( _
ByVal sender As Object, _
ByVal e As StartupEventArgs _
)

Parameters
sender
The Object that raised the event.
e
A StartupEventArgs object that contains the application's command-line arguments.
Remarks
A normal (non-single-instance) application raises the Startup event every time it starts. A single-instance application raises the
Startup event when it starts only if the application is not already active; otherwise, it raises the StartupNextInstance event.
For more information, see My.Application.StartupNextInstance Event and
How to: Specify Instancing Behavior for an Application.
This event is part of the Visual Basic Application model. For more information, see
Overview of the Visual Basic Application Model.
You can use the Cancel property of the e parameter to control the loading of an application's startup form. When the Cancel
property is set to True, the startup form does not start. In that case, your code should call an alternate startup code path. For
example, see How to: Enable a Batch Mode for Window Forms Applications.
You can use the CommandLine property of the e parameter or the My.Application.CommandLineArgs Property to access the
application's command-line arguments.
The code for the Startup event handler is stored in the ApplicationEvents.vb file, which is hidden by default.
To access the Code Editor window for application events
1. With a project selected in Solution Explorer, click Properties on the Project menu.
2. Click the Application tab.
3. Click the View Application Events button to open the Code Editor.
For more information, see How to: Handle Application Events (Visual Basic).
Tasks
The following table lists examples of tasks involving the My.Application.Startup event.
To See
Use the events provided by the Visual Basic Application model t How to: Run Code When the Application Starts or Ends
o run code

Check if the application started with the string /batch as an argu How to: Enable a Batch Mode for Window Forms Applications
ment
Example
This example uses the My.Application.SplashScreen property and the My.Application.Startup event to update the splash
screen with status information as the application starts.
VB
Private Sub MyApplication_Startup( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs _
) Handles Me.Startup
' Get the splash screen.
Dim splash As SplashScreen1 = CType(My.Application.SplashScreen, SplashScreen1)
' Display current status information.
splash.Status = "Current user: " & My.User.Name
End Sub

This example requires that the project have a splash screen named SplashScreen1. The splash screen needs to have property
named Status that updates its user interface.
You must enter the code in the Code Editor window for application events. To access this window, follow the instructions from
this topic's Remarks section. For more information, see How to: Handle Application Events (Visual Basic).
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library No

Console Application No

Windows Control Library No

Web Control Library No

Windows Service No

Web Site No
Permissions
The following permissions may be necessary:
Permission Description
SecurityPermission Controls the ability to add an event handler for this event. Associated enumeration:
System.Security.Permissions.SecurityPermissionFlag.ControlAppDomain.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Enable a Batch Mode for Window Forms Applications
How to: Handle Application Events (Visual Basic)
How to: Specify Instancing Behavior for an Application
Reference
My.Application Object
My.Application.StartupNextInstance Event
My.Application.CommandLineArgs Property
Microsoft.VisualBasic.ApplicationServices.StartupEventArgs
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Startup
Concepts
Overview of the Visual Basic Application Model
Visual Basic Language Reference

My.Application.StartupNextInstance Event
Occurs when attempting to start a single-instance application and the application is already active.

' Usage
Public Sub Me_StartupNextInstance( _
ByVal sender As Object, _
ByVal e As StartupNextInstanceEventArgs _
) Handles Me.StartupNextInstance
End Sub
' Declaration
Public Event StartupNextInstance( _
ByVal sender As Object, _
ByVal e As StartupNextInstanceEventArgs _
)

Parameters
sender
The Object that raised the event.
e
A StartupEventArgs object that contains the application's command-line arguments.
Remarks
A single-instance application raises the StartupNextInstance event when you attempt to restart the application when it is
already active. When a single-instance application starts for the first time, it raises the Startup event. For more information, see
My.Application.Startup Event and How to: Specify Instancing Behavior for an Application.
This event is part of the Visual Basic Application model. For more information, see
Overview of the Visual Basic Application Model.
This event is raised on the application's main thread with the other user-interface events. This allows the event handler to
access directly the application's user interface. However, if the application is busy handling another user-interface event when
this event is raised, this event cannot be processed until the other event handler finishes or calls the
My.Application.DoEvents Method.
Note
The StartupNextInstance event is raised only in single-instance applications. To enable single-instance behavior for your a
pplication, you must check the Make single instance application check box in the Project Designer. For more information,
see How to: Specify Instancing Behavior for an Application.

You must use the CommandLine property of the e parameter to access the arguments for subsequent attempts to start a
single-instance application. The My.Application.CommandLineArgs Property provides the arguments used to start the first
instance of a single-instance application.
The code for the StartupNextInstance event handler is stored in the ApplicationEvents.vb file, which is hidden by default.
To access the Code Editor window for application events
1. With a project selected in Solution Explorer, click Properties on the Project menu.
2. Click the Application tab.
3. Click the View Application Events button to open the Code Editor.
For more information, see How to: Handle Application Events (Visual Basic).
Tasks
The following table lists examples of tasks involving the My.Application.StartupNextInstance event.
To See
Use the events provided by the Visual Basic Application model to run c How to: Run Code When the Application Starts or Ends
ode

Check the command-line arguments of the first application instance My.Application.CommandLineArgs Property
Example
This example uses the e parameter of the StartupNextInstance event handler to examine the application's command-line
arguments. If an argument is found that starts with /input=, the rest of that argument is displayed.
VB
Private Sub MyApplication_StartupNextInstance( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs _
) Handles Me.StartupNextInstance
Dim inputArgument As String = "/input="
Dim inputName As String = ""
For Each s As String In e.CommandLine
If s.ToLower.StartsWith(inputArgument) Then
inputName = s.Remove(0, inputArgument.Length)
End If
Next

If inputName = "" Then


MsgBox("No input name")
Else
MsgBox("Input name: " & inputName)
End If
End Sub

You must enter the code in the Code Editor window for application events. To access this window, follow the instructions from
this topic's Remarks section. For more information, see How to: Handle Application Events (Visual Basic).
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library No

Console Application No

Windows Control Library No

Web Control Library No

Windows Service No

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Handle Application Events (Visual Basic)
How to: Specify Instancing Behavior for an Application
How to: Specify Instancing Behavior for an Application
Reference
My.Application Object
My.Application.Startup Event
My.Application.CommandLineArgs Property
StartupEventArgs
CommandLine
Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.StartupNextInstance
Concepts
Overview of the Visual Basic Application Model
Visual Basic Language Reference

My.Application.UICulture Property
Gets the culture that the current thread uses for retrieving culture-specific resources.

' Usage
Dim value As System.Globalization.CultureInfo = My.Application.UICulture
' Declaration
Public ReadOnly Property UICulture As System.Globalization.CultureInfo

Return Value
Returns a CultureInfo object that represents the culture that the current thread uses for retrieving culture-specific resources.
Remarks
The My.Application.CurrentUICulture property gets the CultureInfo object that the current thread uses for retrieving
culture-specific resources. This object is identical to the one returned by the CurrentUICulture property. The CurrentUICulture
property determines the culture used by the Resource Manager and the My.Resources object, information it needs to look up
culture-specific resources at run time.
To change the culture, you can use the My.Application.ChangeUICulture Method or assign a different CultureInfo object to the
CurrentUICulture property.
The CurrentCulture setting is different from a language setting. It contains only data related to the standard settings for a
geographical region.
Use the My.Application.CurrentCulture property to get the culture that the current thread uses for string manipulation and
string formatting.
Example
This example uses the My.Application.CurrentCulture property to cache the current culture, before changing it with the
My.Application.ChangeUICulture Method. The My.Application.ChangeUICulture method sets the culture that the
My.Resources Object uses for retrieving resources.
VB
Sub ShowLocalizedMessage()
Dim culture As String = My.Application.UICulture.Name
My.Application.ChangeUICulture("fr-FR")
MsgBox(My.Resources.Message)
My.Application.ChangeUICulture(culture)
End Sub

For this example to work, your application must have a string named Message in the application's resource file, and the
application should have the French-culture version of that resource file, Resources.fr-FR.resx. For more information, see
How to: Add or Remove Resources.
If the application does not have the French-culture version of that resource file, the My.Resource object retrieves the resource
from the default-culture resource file.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase, ApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Retrieve Localized Resources in Visual Basic
Reference
My.Application Object
My.Application.ChangeUICulture Method
My.Application.Culture Property
System.Globalization.CultureInfo
CurrentUICulture
Microsoft.VisualBasic.ApplicationServices.ApplicationBase.UICulture
Visual Basic Language Reference

My.Application.UnhandledException Event
Occurs when the application encounters an unhandled exception.

' Usage
Public Sub Me_UnhandledException( _
ByVal sender As Object, _
ByVal e As UnhandledExceptionEventArgs _
) Handles Me.UnhandledException
End Sub
' Declaration
Public Event UnhandledException( _
ByVal sender As Object, _
ByVal e As UnhandledExceptionEventArgs _
)

Parameters
sender
The Object that raised the event.
e
An UnhandledExceptionEventArgs object that contains the unhandled exception and additional information.
Remarks
An application raises the UnhandledException event when it encounters an unhandled exception. This event is part of the
Visual Basic Application model. For more information, see Overview of the Visual Basic Application Model.
You can use the Exception property of the e parameter to access the unhandled exception that caused this event.
You can use the ExitApplication property of the e parameter to control whether the application exits. By default,
ExitApplication is True, so the application exits after completing the UnhandledException event handler. You can set the
value to True in the UnhandledException event handler to keep the application running, and have it return to a waiting state.
The code for the UnhandledException event handler is stored in the ApplicationEvents.vb file, which is hidden by default.
To access the Code Editor window for application events:
1. With a project selected in Solution Explorer, click Properties on the Project menu.
2. Click the Application tab.
3. Click the View Application Events button to open the Code Editor.
For more information, see How to: Handle Application Events (Visual Basic).
Note
The Visual Basic compiler prevents applications that are built for debugging from raising this event, to allow a debugger to h
andle the unhandled exceptions. This means that if you are testing your application by running it under the Visual Studio Inte
grated Development Environment debugger, your UnhandledException event handler will not be called. For more informa
tion on building applications for debugging, see /debug (Visual Basic).

Tasks
The following table lists examples of tasks involving the My.Application.UnhandledException event.
To See
Use the events provided by the Visual Basic Application Model to run c How to: Run Code When the Application Starts or Ends
ode
Log unhandled exceptions How to: Log Exceptions in Visual Basic
Example
This example uses the My.Application.UnhandledException event to log any unhandled exceptions.
VB
Private Sub MyApplication_UnhandledException( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs _
) Handles Me.UnhandledException
My.Application.Log.WriteException(e.Exception, _
TraceEventType.Critical, _
"Unhandled Exception.")
End Sub

You must enter the code in the Code Editor window for application events. To access this window, follow the procedure found
in this topic's Remarks section. For more information, see How to: Handle Application Events (Visual Basic).
Because the UnhandledException event is not raised when a debugger is attached to the application, you need to run this
example outside of the Visual Studio Integrated Development Environment,
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: WindowsFormsApplicationBase
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library No

Console Application No

Windows Control Library No

Web Control Library No

Windows Service No

Web Site No
Permissions
The following permissions may be necessary:
Permission Description
SecurityPermission Controls the ability to add an event handler for this event. Associated enumeration:
System.Security.Permissions.SecurityPermissionFlag.ControlAppDomain.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application Object
Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs
Concepts
Overview of the Visual Basic Application Model
Visual Basic Language Reference

My.Application.Info Object
Provides properties for getting the information about the application, such as the version number, description, loaded
assemblies, and so on.
Remarks
Some of the properties exposed by the My.Application.Info object return the application's assembly information. To set the
information in the application's assembly, you must use the Assembly Information dialog box, accessible from the
Application pane of the Project Designer. For more information, see How to: Specify Assembly Information.
The My.Application.Info object provides functionality similar to the FileVersionInfo class but is scoped to give quick access to
the most common properties.
Other properties, such as LoadedAssemblies, provide access to the current state of the application.
Example
This example uses the My.Application.Info.Version property to display the version of the application.
VB
MsgBox("Application version: " & My.Application.Info.Version.ToString)

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Application.Info Object Members
My.Application Object
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo
FileVersionInfo
Visual Basic Language Reference

My.Application.Info Object Members


The My.Application.Info Object provides properties for getting information about the application such as the version number,
description, loaded assemblies, and so on.
Properties
Property Description
AssemblyName Gets the name, without the extension, of the assembly file for the application.

CompanyName Gets the company name associated with the application.

Copyright Gets the copyright notice associated with the application.

Description Gets the description associated with the application.

DirectoryPath Gets the directory where the application is stored.

LoadedAssemblies Gets a collection of all assemblies loaded by the application.

ProductName Gets the product name associated with the application.

StackTrace Gets the current stack trace information.

Title Gets the title associated with the application.

Trademark Gets the trademark notice associated with the application.

Version Gets the version number of the application.

WorkingSet Gets the amount of physical memory mapped to the process context.
See Also
Reference
My.Application.Info Object
Visual Basic Language Reference

My.Application.Info.AssemblyName Property
Gets the name, without the extension, of the assembly file for the application.

' Usage
Dim value As String = My.Application.Info.AssemblyName
' Declaration
Public ReadOnly Property AssemblyName As String

Return Value
A String containing the file name.
Remarks
The My.Application.Info.AssemblyName property gets the name of the file containing the manifest.
Example
This example uses the My.Application.Info.AssemblyName property to display the name of the application.
VB
MsgBox("Application assembly name: " & My.Application.Info.AssemblyName)

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application.Info Object
AssemblyName
Visual Basic Language Reference

My.Application.Info.CompanyName Property
Gets the company name associated with the application.

' Usage
Dim value As String = My.Application.Info.CompanyName
' Declaration
Public ReadOnly Property CompanyName As String

Return Value
A String that contains the company name associated with the application.
Exceptions
The following condition can cause an exception:
The assembly does not have an AssemblyCompanyAttribute (InvalidOperationException).
Remarks
The My.Application.Info.CompanyName property gets the company name associated with the application.
You can change the company name by changing the value for Company in the Assembly Information dialog box, accessible
from the Application pane of the Project Designer. For more information, see How to: Specify Assembly Information.
Example
This example uses the My.Application.Info.CompanyName property to display the company name associated with the
application.
VB
MsgBox("Application created by: " & My.Application.Info.CompanyName)

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Specify Assembly Information
Reference
My.Application.Info Object
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.CompanyName
Visual Basic Language Reference

My.Application.Info.Copyright Property
Gets the copyright notice associated with the application.

' Usage
Dim value As String = My.Application.Info.Copyright
' Declaration
Public ReadOnly Property Copyright As String

Return Value
A String containing the copyright notice associated with the application.
Exceptions
The following condition can cause an exception:
The assembly does not have an AssemblyCopyrightAttribute (InvalidOperationException).
Remarks
The My.Application.Info.CompanyName property gets the copyright notice associated with the application.
You can change the copyright notice by changing the value for Copyright in the Assembly Information dialog box,
accessible from the Application pane of the Project Designer. For more information, see
How to: Specify Assembly Information.
Example
This example uses the My.Application.Info.CompanyName property to display the company name associated with the
application.
VB
MsgBox("Application copyright: " & My.Application.Info.Copyright)

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Specify Assembly Information
Reference
My.Application.Info Object
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.Copyright
Visual Basic Language Reference

My.Application.Info.Description Property
Gets the description associated with the application.

' Usage
Dim value As String = My.Application.Info.Description
' Declaration
Public ReadOnly Property Description As String

Return Value
A String containing the description associated with the application.
Exceptions
The following condition can cause an exception:
The assembly does not have an AssemblyDescriptionAttribute (InvalidOperationException).
Remarks
The My.Application.Info.Description property gets the description associated with the application.
You can change the description by changing the value for Description in the Assembly Information dialog box, accessible
from the Application pane of the Project Designer. For more information, see How to: Specify Assembly Information.
Example
This example uses the My.Application.Info.Description property to display the description associated with the application.
VB
MsgBox("Application description: " & My.Application.Info.Description)

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Specify Assembly Information
Reference
My.Application.Info Object
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.Description
Visual Basic Language Reference

My.Application.Info.DirectoryPath Property
Gets the directory where the application is stored.

' Usage
Dim value As String = My.Application.Info.DirectoryPath
' Declaration
Public ReadOnly Property DirectoryPath As String

Return Value
A String that contains the directory where the application is stored.
Remarks
The My.Application.Info.DirectoryPath property gets the directory where the application is stored.
Example
This example uses the My.Application.Info.DirectoryPath property to display the directory path where the application is
stored.
VB
MsgBox("Application directory path: " & My.Application.Info.DirectoryPath)

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application.Info Object
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.DirectoryPath
Visual Basic Language Reference

My.Application.Info.LoadedAssemblies Property
Gets a collection of all assemblies loaded by the application.

' Usage
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of System.Reflection.Assembl
y) = My.Application.Info.LoadedAssemblies
' Declaration
Public ReadOnly Property LoadedAssemblies As System.Collections.ObjectModel.ReadOnlyCollect
ion(Of System.Reflection.Assembly)

Return Value
A ReadOnlyCollection of Assembly containing all the assemblies loaded by the application.
Exceptions
The following condition can cause an exception:
The application domain is not loaded (AppDomainUnloadedException).
Remarks
The My.Application.Info.LoadedAssemblies property is similar to the GetAssemblies method.
Example
This example uses the My.Application.Info.LoadedAssemblies property to display the assemblies loaded by the application.
VB
ListBox1.DataSource = My.Application.Info.LoadedAssemblies

This example requires that your Windows Forms application has a ListBox control named ListBox1.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Application.Info Object
ReadOnlyCollection
System.Reflection.Assembly
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.LoadedAssemblies
Visual Basic Language Reference

My.Application.Info.ProductName Property
Gets the product name associated with the application.

' Usage
Dim value As String = My.Application.Info.ProductName
' Declaration
Public ReadOnly Property ProductName As String

Return Value
A String containing the product name associated with the application.
Exceptions
The following condition can cause an exception:
The assembly does not have an AssemblyProductAttribute (InvalidOperationException).
Remarks
The My.Application.Info.ProductName property gets the product name associated with the application.
You can change the product name by changing the value for Product in the Assembly Information dialog box, accessible
from the Application pane of the Project Designer. For more information, see How to: Specify Assembly Information.
Example
This example uses the My.Application.Info.ProductName property to display the product name associated with the
application.
VB
MsgBox("Application product name: " & My.Application.Info.ProductName)

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Specify Assembly Information
Reference
My.Application.Info Object
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.ProductName
Visual Basic Language Reference

My.Application.Info.StackTrace Property
Gets the current stack-trace information.

' Usage
Dim value As String = My.Application.Info.StackTrace
' Declaration
Public ReadOnly Property StackTrace As String

Return Value
A String containing the current stack-trace information. The return value can be Empty.
Exceptions
The following condition can cause an exception:
The requested stack-trace information is out of range (ArgumentOutOfRangeException).
Remarks
The My.Application.Info.StackTrace property lists method calls in reverse chronological order—that is, it describes the most
recent method call first, and it lists each method call on the stack on a separate line. However, the
My.Application.Info.StackTrace property might not report as many method calls as expected, due to code transformations
that occur during optimization.
Typically, the stack-trace information is used for debugging applications.
The stack-trace information for each method call is formatted as follows:
"at FullClassName.MethodName(MethodParams) in FileName:line LineNumber "
The literal "at" is preceded by three spaces, and the literals "in" and ":line" are omitted if debug symbols are not available. The
placeholders FullClassName, MethodName, MethodParams, FileName, and LineNumber are replaced by actual values, defined
as follows:
Part Description
FullClass The full name of the class, including the namespace.
Name

Method The name of the method.


Name

MethodP The list of parameter type/name pairs. Each pair is separated by a comma (,). This information is omitted if MethodN
arams ame takes zero parameters.

FileNam The name of the source file where the MethodName method is declared. This information is omitted if debug symbol
e s are not available.

LineNum The number of the line in FileName that contains the source code from MethodName for the instruction that is on th
ber e call stack. This information is omitted if debug symbols are not available.

The My.Applicaiton.Info.StackTrace property provides functionality similar to the StackTrace property.


Example
This example uses the My.Application.Info.StackTrace property to display the stack trace of the application from the point at
which the code executes.
VB
MsgBox("Stack trace: " & My.Application.Info.StackTrace)
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access information in the file paths. Associated enumeration: PathDiscovery.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application.Info Object
StackTrace
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.StackTrace
Visual Basic Language Reference

My.Application.Info.Title Property
Gets the title associated with the application.

' Usage
Dim value As String = My.Application.Info.Title
' Declaration
Public ReadOnly Property Title As String

Return Value
A String containing the AssemblyTitleAttribute associated with the application.
Exceptions
The following condition can cause an exception:
The assembly does not have an AssemblyTitleAttribute (InvalidOperationException).
Remarks
The My.Application.Info.Title property gets the title associated with the application.
You can change the title by changing the value for Title in the Assembly Information dialog box, accessible from the
Application pane of the Project Designer. For more information, see How to: Specify Assembly Information.
Example
This example uses the My.Application.Info.Title property to display the title associated with the application.
VB
MsgBox("Application title: " & My.Application.Info.Title)

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Specify Assembly Information
Reference
My.Application.Info Object
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.Title
Visual Basic Language Reference

My.Application.Info.Trademark Property
Gets the trademark notice associated with the application.

' Usage
Dim value As String = My.Application.Info.Trademark
' Declaration
Public ReadOnly Property Trademark As String

Return Value
A String containing the trademark notice associated with the application.
Exceptions
The following condition can cause an exception:
The assembly does not have an AssemblyTrademarkAttribute (InvalidOperationException).
Remarks
The My.Application.Info.Trademark property gets the trademark notice associated with the application.
You can change the trademark notice by changing the value for Trademark in the Assembly Information dialog box,
accessible from the Application pane of the Project Designer. For more information, see
How to: Specify Assembly Information.
Example
This example uses the My.Application.Info.Trademark property to display the trademark information associated with the
application.
VB
MsgBox("Application trademark: " & My.Application.Info.Trademark)

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Specify Assembly Information
Reference
My.Application.Info Object
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.Trademark
Visual Basic Language Reference

My.Application.Info.Version Property
Gets the version number of the application.

' Usage
Dim value As System.Version = My.Application.Info.Version
' Declaration
Public ReadOnly Property Version As System.Version

Return Value
A Version object containing the version number of the application.
Exceptions
The following condition can cause an exception:
The application does not have sufficient permissions to access the assembly version (SecurityException).
Remarks
The My.Application.Info.Version property gets a Version object containing the version number of the application. You can
use the Major, Minor, Build, and Revision properties of the Version object to access specific version information about the
application.
ClickOnce-deployed applications should use the CurrentVersion property of the My.Application.Deployment Property.
Example
This example uses the My.Application.Info.Version property to display the version of the application.
VB
MsgBox("Application version: " & My.Application.Info.Version.ToString)

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application.Info Object
My.Application.Deployment Property
CurrentVersion
System.Version
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.Version
Visual Basic Language Reference

My.Application.Info.WorkingSet Property
Gets the amount of physical memory mapped to the process context.

' Usage
Dim value As Long = My.Application.Info.WorkingSet
' Declaration
Public ReadOnly Property WorkingSet As Long

Return Value
A Long containing the number of bytes of physical memory mapped to the process context.
Exceptions
The following condition can cause an exception:
A situation in which partial trust exists and the user lacks necessary permissions (SecurityException).
Remarks
The My.Application.Info.WorkingSet property has the same behavior as the WorkingSet property.
Note
This property always returns zero for Windows 98 and Windows Millennium Edition.

Example
This example uses the My.Application.Info.WorkingSet property to display the number of bytes of physical memory
mapped to the application.
VB
MsgBox("Application working set: " & My.Application.Info.WorkingSet)

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: AssemblyInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
The following permission may be necessary:
Permission Description
EnvironmentPermission Controls the ability to access all environment variables. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Application.Info Object
WorkingSet
Microsoft.VisualBasic.ApplicationServices.AssemblyInfo.WorkingSet
Visual Basic Language Reference

My.Application.Log Object
Provides a property and methods for writing event and exception information to the application's log listeners.
Remarks
The My.Application.Log object provides a straightforward entry point from which to access the .NET Framework's logging
services. The WriteEntry and WriteException methods write messages to the application's log listeners. The listeners can be
configured by the application's configuration file. For more information, see
Walkthrough: Changing Where My.Application.Log Writes Information and Working with Application Logs in Visual Basic.
The My.Application.Log object is available only for client applications. For Web applications, use My.Log. For more
information, see My.Log Object.
Tasks
The following table lists examples of tasks involving the My.Application.Log object.
To See
Write event information to the application's log liste How to: Write Log Messages
ners

Write exception information to the application's log l How to: Log Exceptions in Visual Basic
isteners

Determine where My.Application.Log writes infor Walkthrough: Determining Where My.Application.Log Writes Information
mation
Example
This example shows how to use the My.Application.Log.WriteEntry method to log tracing information. For more
information, see How to: Write Log Messages.
VB
Public Sub TracingTest(ByVal fileName As String)
My.Application.Log.WriteEntry( _
"Entering TracingTest with argument " & _
fileName & ".")
' Code to trace goes here.
My.Application.Log.WriteEntry( _
"Exiting TracingTest with argument " & _
fileName & ".")
End Sub

Requirements
Namespace: Microsoft.VisualBasic.Logging
Class: Log
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes


Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
See Also
Reference
My.Application.Log Object Members
My.Application Object
Visual Basic Language Reference

My.Application.Log Object Members


The My.Application.Log Object provides a property and methods for writing event and exception information to the
application's log listeners.
Properties
Property Description
TraceSource Gets to the TraceSource object that underlies the My.Application.Log object.
This is an advanced member; it does not appear in IntelliSense unless you click the All tab.
Methods
Method Description
WriteEntry Writes a message to the application's log listeners.

WriteException Writes exception information to the application's log listeners.


See Also
Reference
My.Application.Log Object
Visual Basic Language Reference

DefaultFileLogWriter Property (My.Application.Log and


My.Log)
Gets the FileLogTraceListener object that the Log object uses.

' Usage
Dim value As Logging.FileLogTraceListener = My.Application.Log.DefaultFileLogWriter
' Web usage
Dim value As Logging.FileLogTraceListener = My.Log.DefaultFileLogWriter
' Declaration
Public ReadOnly Property DefaultFileLogWriter As Logging.FileLogTraceListener

Return Value
Returns the FileLogTraceListener object that the Log object uses.
Remarks
You can use this property to determine the current configuration of the Log object's FileLogTraceListener object.
In client applications, the Log object is available through the My.Application.Log object. In Web applications, the Log object
is available through the My.Log object.
Requirements
Namespace: Microsoft.VisualBasic.Logging
Class: Log
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
Troubleshooting: Log Listeners
Reference
My.Application.Log Object
My.Log Object
FileLogTraceListener
Visual Basic Language Reference

TraceSource Property (My.Application.Log and My.Log)


Gets to the TraceSource object that underlies the Log object.

' Usage
Dim value As System.Diagnostics.TraceSource = My.Application.Log.TraceSource
' Web usage
Dim value As System.Diagnostics.TraceSource = My.Log.TraceSource
' Declaration
Public ReadOnly Property TraceSource As System.Diagnostics.TraceSource

Return Value
Returns the TraceSource object that underlies the Log object.
Remarks
You can use this property to determine the current configuration of the Log object.
In client applications, the Log object is available through the My.Application.Log object. In Web applications, the Log object
is available through the My.Log object.
This is an advanced member; it does not show in IntelliSense unless you select the All tab.
Tasks
The following table lists an example of a task involving the TraceSource property.
To See
Get information for each of the Log object's log listeners. Troubleshooting: Log Listeners
Requirements
Namespace: Microsoft.VisualBasic.Logging
Class: Log
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Tasks
Troubleshooting: Log Listeners
Reference
My.Application.Log Object
My.Log Object
System.Diagnostics.TraceSource
Microsoft.VisualBasic.Logging.Log.TraceSource
Visual Basic Language Reference

WriteEntry Method (My.Application.Log and My.Log)


Writes a message to the application's log listeners.

' Usage
My.Application.Log.WriteEntry(message)
My.Application.Log.WriteEntry(message ,severity)
My.Application.Log.WriteEntry(message ,severity ,id)
' Web usage
My.Log.WriteEntry(message)
My.Log.WriteEntry(message ,severity)
My.Log.WriteEntry(message ,severity ,id)
' Declaration
Public Sub WriteEntry( _
ByVal message As String _
)
' -or-
Public Sub WriteEntry( _
ByVal message As String, _
ByVal severity As System.Diagnostics.TraceEventType _
)
' -or-
Public Sub WriteEntry( _
ByVal message As String, _
ByVal severity As System.Diagnostics.TraceEventType, _
ByVal id As Integer _
)

Parameters
message
Required. The message to log. If message is Nothing, an empty string is used.
severity
The type of message. By default, TraceEventType.Information.
id
Message identifier, typically used for correlation. By default, related to entryType as described in the table.
Exceptions
The following conditions cause an exception:
The exception or message type is Nothing (ArgumentNullException).
The message type is not one of the TraceEventType enumeration values (InvalidEnumArgumentException).
Code with partial trust calls the method, but writes to an event log listener that requires full trust (SecurityException).
Remarks
The WriteEntry method writes a message to the application's event log listeners.
In client applications, the Log object is available through the My.Application.Log object. In Web applications, the Log object
is available through the My.Log object.
To learn which log listeners receive the WriteEntry method's messages, see
Walkthrough: Determining Where My.Application.Log Writes Information. You can change default log listeners. For more
information, see Working with Application Logs in Visual Basic.
For overloads that do not take the id argument, the id written to the log is defined by the following table.
severity Default id
Information 0

Warning 1

Error 2

Critical 3

Start 4

Stop 5

Suspend 6

Resume 7

Verbose 8

Transfer 9
Tasks
The following table lists examples of tasks involving the WriteEntry method.
To See
Write event information to the application's log liste How to: Write Log Messages
ners

Determine where Log writes information Walkthrough: Determining Where My.Application.Log Writes Information
Example
This example shows how to use the My.Application.Log.WriteEntry method to log tracing information. For more
information, see How to: Write Log Messages.
VB
Public Sub TracingTest(ByVal fileName As String)
My.Application.Log.WriteEntry( _
"Entering TracingTest with argument " & _
fileName & ".")
' Code to trace goes here.
My.Application.Log.WriteEntry( _
"Exiting TracingTest with argument " & _
fileName & ".")
End Sub

This code example can run only within a client application. Change My.Application.Log.WriteEntry to My.Log.WriteEntry
for Web applications.
Requirements
Namespace: Microsoft.VisualBasic.Logging
Class: Log
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library Yes

Console Application Yes


Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Write Log Messages
Walkthrough: Determining Where My.Application.Log Writes Information
Reference
My.Application.Log Object
My.Log Object
System.Diagnostics.TraceEventType
Microsoft.VisualBasic.Logging.Log.WriteEntry(System.String)
Concepts
Working with Application Logs in Visual Basic
Visual Basic Language Reference

WriteException Method (My.Application.Log and My.Log)


Writes exception information to the application's log listeners.

' Usage
My.Application.Log.WriteException(ex)
My.Application.Log.WriteException(ex ,severity ,additionalInfo)
My.Application.Log.WriteException(ex ,severity ,additionalInfo ,id)
' Web usage
My.Log.WriteException(ex)
My.Log.WriteException(ex ,severity ,additionalInfo)
My.Log.WriteException(ex ,severity ,additionalInfo ,id)
' Declaration
Public Sub WriteException( _
ByVal ex As System.Exception _
)
' -or-
Public Sub WriteException( _
ByVal ex As System.Exception, _
ByVal severity As System.Diagnostics.TraceEventType, _
ByVal additionalInfo As String _
)
' -or-
Public Sub WriteException( _
ByVal ex As System.Exception, _
ByVal severity As System.Diagnostics.TraceEventType, _
ByVal additionalInfo As String, _
ByVal id As Integer _
)

Parameters
ex
Required. Exception to log.
severity
The type of message. By default, Error.
additionalInfo
String to append to the message. By default, this is an empty string.
id
Message identifier, typically used for correlation. By default, related to entryType as described in the table in the Remarks
section.
Exceptions
The following conditions will cause an exception:
The exception or message type is Nothing (ArgumentNullException).
The message type is not one of the TraceEventType enumeration values (InvalidEnumArgumentException).
Code with partial trust calls the method, but writes to an event log listener that requires full trust (SecurityException).
Remarks
The WriteException method writes the information contained in an exception to the application's event log listeners.
In client applications, the Log object is available through the My.Application.Log object. In Web applications, the Log object
is available through the My.Log object.
To learn which log listeners receive the WriteException method's messages, see
Walkthrough: Determining Where My.Application.Log Writes Information. You can change default log listeners. For more
information, see Working with Application Logs in Visual Basic.
For overloads that do not take the id argument, the identifier written to the log is defined by the following table.
severity Default id
Information 0

Warning 1

Error 2

Critical 3

Start 4

Stop 5

Suspend 6

Resume 7

Verbose 8

Transfer 9
Tasks
The following table lists examples of tasks involving the WriteException method.
To See
Write exception information to the application's eve How to: Log Exceptions in Visual Basic
nt log listeners.

Determine where Log writes information. Walkthrough: Determining Where My.Application.Log Writes Information
Example
This example shows how to use the My.Application.Log.WriteException method to log exceptions. Uncomment the Dim and
MsgBox lines to cause a NullReferenceException exception. For more information, see How to: Log Exceptions in Visual Basic.

VB
Public Sub ExceptionLogTest(ByVal fileName As String)
Try
' Code that might generate an exception goes here.
' For example:
' Dim x As Object
' MsgBox(x.ToString)
Catch ex As Exception
My.Application.Log.WriteException(ex, _
TraceEventType.Error, _
"Exception in ExceptionLogTest " & _
"with argument " & fileName & ".")
End Try
End Sub

This code example can run only within a client application. Change My.Application.Log.WriteException to
My.Log.WriteException for Web applications.
Requirements
Namespace: Microsoft.VisualBasic.Logging
Class: Log
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Log Exceptions in Visual Basic
Walkthrough: Determining Where My.Application.Log Writes Information
Reference
My.Application.Log Object
My.Log Object
System.Exception
System.Diagnostics.TraceEventType
Microsoft.VisualBasic.Logging.Log.WriteException(System.Exception)
Concepts
Working with Application Logs in Visual Basic
Visual Basic Language Reference

My.Computer Object
Provides properties for manipulating computer components such as audio, the clock, the keyboard, the file system, and so on.
Remarks
The properties exposed by the My.Computer object return information about the computer on which the application is
deployed, as determined at run time. Typically, this data differs from what was available on the development computer.
Some members, such as the My.Computer.Audio object, are available only for non-server applications.
Tasks
The following table lists examples of tasks involving the My.Computer object.
To See
Check connection status How to: Check Connection Status in Visual Basic

Determine if a remote computer is available How to: Determine if a Remote Computer is Available in Visual Basic

Download a file How to: Download a File in Visual Basic

Upload a file How to: Upload a File in Visual Basic

Create a registry key How to: Create a Registry Key and Set Its Values in Visual Basic

Clear the Clipboard How to: Clear the Clipboard in Visual Basic

Read from the Clipboard How to: Read from the Clipboard in Visual Basic

Determine what is stored on the Clipboard How to: Determine What Type of File is Stored on the Clipboard in Visual Basic

Save audio to the Clipboard How to: Save an Audio Stream to the Clipboard in Visual Basic

Get an image from the Clipboard How to: Retrieve an Image from the Clipboard in Visual Basic
Example
This example uses the My.Computer.Name property to display the name of the computer on which the code runs.
VB
MsgBox("Computer name: " & My.Computer.Name)

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer (the base class ServerComputer provides the members that are available in all projects)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer Object Members
My.Computer.Audio Object
My.Computer.Clipboard Object
My.Computer.Clock Object
My.Computer.FileSystem Object
My.Computer.Info Object
My.Computer.Keyboard Object
My.Computer.Mouse Object
My.Computer.Network Object
My.Computer.Ports Object
My.Computer.Registry Object
Microsoft.VisualBasic.Devices.Computer
Microsoft.VisualBasic.Devices.ServerComputer
Visual Basic Language Reference

My.Computer Object Members


The My.Computer Object provides properties for manipulating computer components such as audio, the clock, the keyboard,
the file system, and so on.
Properties
Property Description
Audio Returns the My.Computer.Audio Object, which provides access to the audio system of the computer and provides
methods for playing .wav files.
This object is available only for non-server applications.

Clipboard Returns the My.Computer.Clipboard Object, which provides methods for manipulating the Clipboard.
This object is available only for non-server applications.

Clock Returns the My.Computer.Clock Object, which provides properties for accessing the current local time and Univers
al Coordinated Time (equivalent to Greenwich Mean Time) from the system clock.

FileSystem Returns the My.Computer.FileSystem Object, which provides properties and methods for working with drives, files,
and directories.

Info Returns the My.Computer.Info Object, which provides properties for getting information about the computer's me
mory, loaded assemblies, name, and operating system.

Keyboard Returns the My.Computer.Keyboard Object, which provides properties for accessing the current state of the keyboa
rd, such as what keys are pressed, and provides a method to send keystrokes to the active window.
This object is available only for non-server applications.

Mouse Returns the My.Computer.Mouse Object, which provides properties for getting information about the format and c
onfiguration of the mouse installed on the local computer.
This object is available only for non-server applications.

Name Gets the computer name.

Network Returns the My.Computer.Network Object, which can be used to access network types and events.

Ports Returns the My.Computer.Ports Object, which provides a property and a method for accessing the computer's seria
l ports.
This object is available only for non-server applications.

Registry Returns the My.Computer.Registry Object, which can be used to read from and write to the registry.

Screen Gets the Screen object that represents the computer's primary display screen.
This property is available only for non-server applications.
See Also
Reference
My.Computer Object
Visual Basic Language Reference

My.Computer.Audio Property
Gets an object that provides properties for methods for playing sounds.

' Usage
Dim value As Microsoft.VisualBasic.Devices.Audio = My.Computer.Audio
' Declaration
Public ReadOnly Property Audio As MyAudio

Return Value
This property returns the My.Computer.Audio object for the computer.
Remarks
This property provides easy access to the My.Computer.Audio object. For more information, see My.Computer.Audio Object.
Example
The My.Computer.Audio.Play method plays the specified sound in the background when AudioPlayMode.Background is
specified.
VB
Sub PlayBackgroundSoundFile()
My.Computer.Audio.Play("C:\Waterfall.wav", _
AudioPlayMode.Background)
End Sub

This code can run only within a Windows Forms application.


The file name should reference a .wav sound file on your system.
To simplify the management of your sound files, consider storing the files as application resources. The files can then be
accessed through the My.Resources Object.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer Object
My.Computer.Audio Object
Visual Basic Language Reference

My.Computer.Clipboard Property
Gets an object that provides methods for manipulating the Clipboard.

' Usage
Dim value As Microsoft.VisualBasic.MyServices.ClipboardProxy = My.Computer.Clipboard
' Declaration
Public ReadOnly Property Clipboard As ClipboardProxy

Return Value
This property returns the My.Computer.Clipboard Object for the computer.
Remarks
This property provides easy access to the My.Computer.Clipboard Object.
This property is available only for non-server applications.
Example
This example reads text from the Clipboard into the string textOnClipboard.
VB
Dim textOnClipboard As String = My.Computer.Clipboard.GetText()

This example fails if there is no text on the Clipboard.


Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer Object
My.Computer.Clipboard Object
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference

My.Computer.Clock Property
Gets an object that provides properties for accessing the current local time and Universal Coordinated Time (the equivalent to
Greenwich Mean Time) from the system clock.

' Usage
Dim value As Microsoft.VisualBasic.Devices.Clock = My.Computer.Clock
' Declaration
Public ReadOnly Property Clock As MyClock

Return Value
This property returns the My.Computer.Clock object for the computer.
Remarks
This property provides easy access to the My.Computer.Clock object. For more information, see My.Computer.Clock Object.
Example
The My.Computer.Audio.Play method plays the specified sound in the background when AudioPlayMode.Background is
specified.
VB
Sub PlayBackgroundSoundFile()
My.Computer.Audio.Play("C:\Waterfall.wav", _
AudioPlayMode.Background)
End Sub

This code can run only within a Windows Forms application.


The file name should reference a .wav sound file on your system.
To simplify the management of your sound files, consider storing the files as application resources. The files can then be
accessed through the My.Resources Object.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer, ServerComputer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer Object
My.Computer.Clock Object
Visual Basic Language Reference

My.Computer.FileSystem Property
Gets an object that provides properties and methods for working with drives, files, and directories.

' Usage
Dim value As Microsoft.VisualBasic.MyServices.FileSystemProxy = My.Computer.FileSystem
' Declaration
Public ReadOnly Property FileSystem As FileSystemProxy

Return Value
This property returns the My.Computer.FileSystem Object for the computer.
Remarks
This property provides easy access to the My.Computer.FileSystem Object.
Example
This example checks to determine whether the folder C:\backup\logs exists and checks its properties.
VB
Dim logInfo As System.IO.DirectoryInfo
If My.Computer.FileSystem.DirectoryExists("C:\backup\logs") Then
logInfo = My.Computer.FileSystem.GetDirectoryInfo _
("C:\backup\logs")
End If

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer, ServerComputer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer Object
My.Computer.FileSystem Object
Other Resources
Reading from Files in Visual Basic
Writing to Files in Visual Basic
Creating, Deleting, and Moving Files and Directories in Visual Basic
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference

My.Computer.Info Property
Gets an object that provides properties for getting information about the computer's memory, loaded assemblies, name, and
operating system.

' Usage
Dim value As Microsoft.VisualBasic.Devices.ComputerInfo = My.Computer.Info
' Declaration
Public ReadOnly Property Info As MyComputerInfo

Return Value
This property returns the My.Computer.Info object for the computer.
Remarks
This property provides easy access to the My.Computer.Info object. For more information, see My.Computer.Info Object.
Example
This example uses the My.Computer.Info.AvailablePhysicalMemory property to display the amount of available physical
memory for the computer on which the code runs.
VB
MsgBox("Computer's available physical memory: " & _
My.Computer.Info.AvailablePhysicalMemory)

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer, ServerComputer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer Object
My.Computer.Info Object
Visual Basic Language Reference

My.Computer.Keyboard Property
Gets an object that provides properties for accessing the current state of the keyboard, such as what keys are currently pressed,
and provides a method to send keystrokes to the active window.

' Usage
Dim value As Microsoft.VisualBasic.Devices.Keyboard = My.Computer.Keyboard
' Declaration
Public ReadOnly Property Keyboard As Microsoft.VisualBasic.Devices.Keyboard

Return Value
This property returns the My.Computer.Keyboard object for the computer.
Remarks
This property provides easy access to the My.Computer.Keyboard object. For more information, see
My.Computer.Keyboard Object.
Example
This example uses the My.Computer.Keyboard.CtrlKeyDown property to determine if the computer's CTRL key is currently
pressed.
VB
If My.Computer.Keyboard.CtrlKeyDown Then
MsgBox("CTRL key down")
Else
MsgBox("CTRL key up")
End If

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer Object
My.Computer.Keyboard Object
Visual Basic Language Reference

My.Computer.Mouse Property
Gets an object that provides properties for getting information about the format and configuration of the mouse installed on
the local computer.

' Usage
Dim value As Microsoft.VisualBasic.Devices.Mouse = My.Computer.Mouse
' Declaration
Public ReadOnly Property Mouse As Microsoft.VisualBasic.Devices.Mouse

Return Value
This property returns the My.Computer.Mouse object for the computer.
Remarks
This property provides easy access to the My.Computer.Mouse object. For more information, see
My.Computer.Mouse Object.
This property is available only for non-server applications.
Example
This example uses the My.Computer.Mouse.WheelExists and My.Computer.Mouse.WheelScrollLines properties to
determine if the mouse has a scroll wheel and how much to scroll when it rotates.
VB
If My.Computer.Mouse.WheelExists Then
Dim lines As Integer = My.Computer.Mouse.WheelScrollLines
If lines > 0 Then
MsgBox("Application scrolls " & _
lines & " line(s) for each wheel turn.")
Else
MsgBox("Application scrolls " & _
(-lines) & " page(s) for each wheel turn.")
End If
Else
MsgBox("Mouse has no scroll wheel.")
End If

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No


Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer Object
My.Computer.Mouse Object
Visual Basic Language Reference

My.Computer.Name Property
Gets the computer name.

' Usage
Dim value As String = My.Computer.Name
' Declaration
Public ReadOnly Property Name As String

Return Value
A String containing the name of the computer.
Remarks
The My.Computer.Name property provides functionality similar to the MachineName property.
Example
This example uses the My.Computer.Name property to display the name of the computer on which the code runs.
VB
MsgBox("Computer name: " & My.Computer.Name)

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer, ServerComputer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer Object
MachineName
Microsoft.VisualBasic.Devices.ServerComputer.Name
Visual Basic Language Reference

My.Computer.Network Property
Gets an object that provides a property and methods for interacting with the network to which the computer is connected.

' Usage
Dim value As Microsoft.VisualBasic.Devices.Network = My.Computer.Network
' Declaration
Public ReadOnly Property Network As MyNetwork

Return Value
This property returns the My.Computer.Network Object for the computer.
Remarks
This property provides easy access to the My.Computer.Network Object.
Example
This example uploads the file Order.txt to http://www.cohowinery.com/uploads.
VB
My.Computer.Network.UploadFile ( _
"C:\My Documents\Order.txt", _
"http://www.cohowinery.com/uploads.aspx")

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer, ServerComputer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer Object
My.Computer.Network Object
Other Resources
Performing Network Operations
Visual Basic Language Reference

My.Computer.Ports Property
Gets an object that provides a property and a method for accessing the computer's serial ports.

' Usage
Dim value As Microsoft.VisualBasic.Devices.Ports = My.Computer.Ports
' Declaration
Public ReadOnly Property Ports As MyPorts

Return Value
This property returns the My.Computer.Ports object.
Remarks
This property provides easy access to the My.Computer.Ports object. For more information, see My.Computer.Ports Object.
Example
This example describes how to send strings to the computer's COM1 serial port.
The Using block allows the application to close the serial port even if it generates an exception. All code that manipulates the
serial port should appear within this block, or within a Try...Catch...Finally block with a call to use the Close method.
The WriteLine method sends the data to the serial port.
VB
Sub SendSerialData(ByVal data As String)
' Send strings to a serial port.
Using com1 As IO.Ports.SerialPort = _
My.Computer.Ports.OpenSerialPort("COM1")
com1.WriteLine(data)
End Using
End Sub

For more information, see How to: Send Strings to Serial Ports in Visual Basic.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer Object
My.Computer.Ports Object
Visual Basic Language Reference

My.Computer.Registry Property
Gets an object that provides properties and methods for manipulating the registry.

' Usage
Dim value As Microsoft.VisualBasic.MyServices.RegistryProxy = My.Computer.Registry
' Declaration
Public ReadOnly Property Registry As RegistryProxy

Return Value
This property returns the My.Computer.Registry Object for the computer.
Remarks
This property provides easy access to the My.Computer.Registry Object.
Example
This example reads the value Name from HKEY_CURRENT_USER\Software\MyApp and displays it in a message box.
VB
Dim readValue As Object
readValue = My.Computer.Registry.GetValue _
("HKEY_CURRENT_USER\Software\MyApp", "Name", Nothing)
MsgBox("The value is " & CStr(readValue))

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer, ServerComputer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Reference
My.Computer Object
My.Computer.Registry Object
Concepts
Common Registry Tasks
Visual Basic Language Reference

My.Computer.Screen Property
Gets the Screen object that represents the computer's primary display screen.

' Usage
Dim value As System.Windows.Forms.Screen = My.Computer.Screen
' Declaration
Public ReadOnly Property Screen As System.Windows.Forms.Screen

Return Value
A Screen object that represents the computer's primary screen.
Remarks
The My.Computer.Screen property provides functionality similar to the PrimaryScreen property.
Example
This example uses the WorkingArea property of the My.Computer.Screen property to determine the working area of the
computer's primary display, and then resizes the form to fill the working area.
VB
Private Sub EnlargeForm()
Me.Size = My.Computer.Screen.WorkingArea.Size
Me.Location = New System.Drawing.Point(0, 0)
End Sub

This example needs to run in a Windows Forms application.


Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Computer
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer Object
System.Windows.Forms.Screen
PrimaryScreen
Microsoft.VisualBasic.Devices.Computer.Screen
Visual Basic Language Reference

My.Computer.Audio Object
Provides methods for playing sounds.
Remarks
You can use the My.Computer.Audio.Play and My.Computer.Audio.PlaySystemSound methods to play .wav sound files
and system sounds.
Tasks
The following table lists examples of tasks involving the My.Computer.Audio object.
To See
Play a sound in the background. How to: Play Sounds in Visual Basic

Play a sound once and wait for completion. How to: Play Sounds and Wait For Completion in Visual Basic

Play a sound many times. How to: Play Looping Sounds in Visual Basic

Stop a sound playing in the background. How to: Stop Playing Sounds in the Background in Visual Basic
Example
The My.Computer.Audio.Play method plays the specified sound in the background when AudioPlayMode.Background is
specified.
VB
Sub PlayBackgroundSoundFile()
My.Computer.Audio.Play("C:\Waterfall.wav", _
AudioPlayMode.Background)
End Sub

This code can run only within a Windows Forms application.


The file name should reference a .wav sound file on your system.
To simplify the management of your sound files, consider storing the files as application resources. The files can then be
accessed through the My.Resources Object.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Audio
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No


Windows Service Yes

Web Site No
See Also
Reference
My.Computer.Audio Object Members
My.Computer Object
Visual Basic Language Reference

My.Computer.Audio Object Members


The My.Computer.Audio Object provides methods for playing sounds.
Methods
Play Plays a .wav sound file.
This method is available only for non-server applications.

PlaySystemSound Plays a system sound.


This method is available only for non-server applications.

Stop Stops a sound playing in the background.


This method is available only for non-server applications.
See Also
Reference
My.Computer.Audio Object
Visual Basic Language Reference

My.Computer.Audio.Play Method
Plays a .wav sound file.

' Usage
My.Computer.Audio.Play(location)
My.Computer.Audio.Play(location ,playMode)
My.Computer.Audio.Play(data ,playMode)
My.Computer.Audio.Play(stream ,playMode)
' Declaration
Public Sub Play( _
ByVal location As String _
)
' -or-
Public Sub Play( _
ByVal location As String, _
ByVal playMode As AudioPlayMode _
)
' -or-
Public Sub Play( _
ByVal data As Byte(), _
ByVal playMode As AudioPlayMode _
)
' -or-
Public Sub Play( _
ByVal stream As System.IO.Stream, _
ByVal playMode As AudioPlayMode _
)

Parameters
location
A String containing the name of the sound file
data
Byte array that represents the sound file.
stream
Stream that represents the sound file.
playMode
AudioPlayMode Enumeration mode for playing the sound. By default, AudioPlayMode.Background.
Exceptions
The following conditions can cause an exception:
The data or stream is Nothing, or location is an empty string (ArgumentNullException).
The playMode argument is not one of the AudioPlayMode Enumeration values (InvalidEnumArgumentException).
The user does not have sufficient permissions to access the file named by location (IOException).
The file path is malformed in location (DirectoryNotFoundException)
The path name in location is too long (PathTooLongException)
A partial-trust situation exists in which the user lacks necessary permissions (SecurityException).
Remarks
The Play method plays the .wav sound file stored as a file at location, as a byte array in data, or as a stream in stream.
If the overload that takes only the location parameter is used, the Play method plays the sound in the background. Otherwise,
the playMode parameter determines how the sound will play.
playMode Description
AudioPlayMode.Backgrou Plays the sound in the background. The calling code continues to execute.
nd

AudioPlayMode.Backgrou Plays the sound in the background until the My.Computer.Audio.Stop Method is called. The callin
ndLoop g code continues to execute.

AudioPlayMode.WaitToC Plays the sound and waits until it completes before the calling code continues.
omplete

Background playing lets the application execute other code while the sound plays. For more information, see
How to: Play Looping Sounds in Visual Basic and How to: Play Sounds in Visual Basic.
Tasks
The following table lists examples of tasks involving the My.Computer.Audio.Play method.
To See
Play a sound once How to: Play Sounds and Wait For Completion in Visual Basic

Play a sound many times How to: Play Looping Sounds in Visual Basic

Play a sound in the background How to: Play Sounds in Visual Basic
Example
The My.Computer.Audio.Play method plays the specified sound in the background when PlayMode.Background is
specified.
VB
Sub PlayBackgroundSoundFile()
My.Computer.Audio.Play("C:\Waterfall.wav", _
AudioPlayMode.Background)
End Sub

This code example can only run within a Windows Forms application.
The file name should reference a .wav sound file on your system.
To simplify the management of your sound files, consider storing the files as application resources. They can then be accessed
through the My.Resources Object.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Audio
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes


Web Control Library No

Windows Service Yes

Web Site No
Permissions
The following permissions may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

SecurityPermission Describes a set of security permissions applied to code. Associated enumeration: ControlThread.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Play Sounds and Wait For Completion in Visual Basic
How to: Play Looping Sounds in Visual Basic
How to: Play Sounds in Visual Basic
Reference
My.Computer.Audio Object
My.Computer.Audio.Stop Method
AudioPlayMode Enumeration
System.IO.Stream
Microsoft.VisualBasic.Devices.Audio.Play(System.String)
Visual Basic Language Reference

My.Computer.Audio.PlaySystemSound Method
Plays a system sound.

' Usage
My.Computer.Audio.PlaySystemSound(systemSound)
' Declaration
Public Sub PlaySystemSound( _
ByVal systemSound As System.Media.SystemSound _
)

Parameters
systemSound
SystemSound object representing the system sound to play.
Exceptions
The following condition can cause an exception:
The systemSound is Nothing (ArgumentNullException).
Remarks
The PlaySystemSound method plays the system sound described by systemSound; the sound is played once, in the
background.
The value of systemSound must be one of the shared members from the SystemSounds class:
Asterisk
Beep
Exclamation
Hand
Question
Tasks
The following table lists an example of a task involving the My.Computer.Audio.PlaySystemSound method.
To See
Play a system sound How to: Play System Sounds in Visual Basic
Example
This example uses the My.Computer.Audio.PlaySystemSound method to play a system sound.
VB
Sub PlaySystemSound()
My.Computer.Audio.PlaySystemSound( _
System.Media.SystemSounds.Asterisk)
End Sub

This code example can run only within a Windows Forms application.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Audio
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Play System Sounds in Visual Basic
Reference
My.Computer.Audio Object
System.Media.SystemSound
SystemSounds
Microsoft.VisualBasic.Devices.Audio.PlaySystemSound(System.Media.SystemSound)
Visual Basic Language Reference

My.Computer.Audio.Stop Method
Stops a sound playing in the background.

' Usage
My.Computer.Audio.Stop()
' Declaration
Public Sub Stop()

Remarks
The My.Computer.Audio.Stop method stops a sound playing in the background that was started by the
My.Computer.Audio.Play method.
Background playing lets the application execute other code while the sound plays. For more information, see
How to: Play Looping Sounds in Visual Basic and How to: Play Sounds in Visual Basic.
In general, when an application plays a looping sound, it should stop the sound at some point.
Tasks
The following table lists an example of a task involving the My.Computer.Audio.Stop method.
To See
Stop a sound playing in the background How to: Stop Playing Sounds in the Background in Visual Basic
Example
This example uses the My.Computer.Audio.Stop method to stop the application currently playing background or looping
sound and uses the My.Computer.Audio.Play method to play a looping sound in the background.
VB
Sub PlayLoopingBackgroundSoundFile()
My.Computer.Audio.Play("C:\Waterfall.wav", _
AudioPlayMode.BackgroundLoop)
End Sub
Sub StopBackgroundSound()
My.Computer.Audio.Stop()
End Sub

This code example can run only within a Windows Forms application.
The file name should reference a .wav sound file on your system.
To simplify the management of your sound files, consider storing the files as application resources. These files can then be
accessed through the My.Resources Object.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Audio
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes


Console Application Yes

Windows Control Library Yes


Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Stop Playing Sounds in the Background in Visual Basic
Reference
My.Computer.Audio Object
Microsoft.VisualBasic.Devices.Audio.Stop
Visual Basic Language Reference

My.Computer.Clipboard Object
Provides methods for manipulating the Clipboard.
Remarks
Items moved or copied to the Clipboard persist even after the application is shut down.
Data on the Clipboard can be in any data format, also called a Clipboard format. For a list of predefined formats to use with the
Clipboard, see DataFormats. When an item is moved or copied to the Clipboard, items in other formats are cleared. To make
other formats persist, use DataObject, which copies everything existing on the current Clipboard, including items pasted from
other applications. Place data on the Clipboard in multiple formats to maximize the possibility that a target application, whose
format requirements you might not know, can successfully retrieve the data.
Because all Windows applications share the system Clipboard, the contents may change when you switch to another
application.
A class must be serializable for it to be put on the Clipboard. See Serialization for more information.
When accessing the Clipboard remotely, a ThreadStateException is thrown unless the accessing thread operates in STA (single-
threaded apartment) mode. To resolve this issue, set the ThreadApartmentState to STA. For more information, see
STAThreadAttribute.
Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard object.
To See
Clear the Clipboard How to: Clear the Clipboard in Visual Basic

Read from the Clipboard How to: Read from the Clipboard in Visual Basic

Find out what is stored on the Clipboard How to: Determine What Type of File is Stored on the Clipboard in Visual Basic

Save audio to the Clipboard How to: Save an Audio Stream to the Clipboard in Visual Basic

Get an image from the Clipboard How to: Retrieve an Image from the Clipboard in Visual Basic

Store data to the Clipboard How to: Write to the Clipboard in Visual Basic
Example
This example reads text from the Clipboard into the string textOnClipboard.
VB
Dim textOnClipboard As String = My.Computer.Clipboard.GetText()

This example will fail if there is no text on the Clipboard.


Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library Yes

Console Application Yes


Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
See Also
Reference
My.Computer.Clipboard Object Members
My.Computer Object
System.Windows.Forms.Clipboard
Visual Basic Language Reference

My.Computer.Clipboard Object Members


The My.Computer.Clipboard Object provides methods for working with the clipboard.
Methods
Method Description
Clear Clears the clipboard.
This method is available only for non-server applications.

ContainsAudio Determines whether the clipboard contains audio data.


This method is available only for non-server applications.

ContainsData Determines whether the clipboard contains data in the specified custom format.
This method is available only for non-server applications.

ContainsFileDropList Determines whether the clipboard contains a FileDropList.


This method is available only for non-server applications.

ContainsImage Determine whether the clipboard contains an image.


This method is available only for non-server applications.

ContainsText Determines whether the clipboard contains text.


This method is available only for non-server applications.

GetAudioStream Retrieves an audio stream from the clipboard.


This method is available only for non-server applications.

GetData Retrieves data from the clipboard.


This method is available only for non-server applications.

GetDataObject Retrieves a data object from the clipboard. This method is available only for non-server applications.

GetFileDropList Retrieves a FileDropList from the clipboard.


This method is available only for non-server applications.

GetImage Retrieves an image from the clipboard.


This method is available only for non-server applications.

GetText Retrieves text from the clipboard.


This method is available only for non-server applications.

SetAudio Writes audio data to the clipboard.


This method is available only for non-server applications.

SetData Writes data in the specified custom format to the clipboard.


This method is available only for non-server applications.
SetDataObject Writes a data object to the clipboard.
This method is available only for non-server applications.

SetFileDropList Writes a FileFropList to the clipboard.


This method is available only for non-server applications.

SetImage Writes an image to the clipboard.


This method is available only for non-server applications.

SetText Writes text to the clipboard.


This method is available only for non-server applications.
See Also
Tasks
How to: Clear the Clipboard in Visual Basic
How to: Read from the Clipboard in Visual Basic
How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
How to: Write to the Clipboard in Visual Basic
How to: Retrieve an Image from the Clipboard in Visual Basic
How to: Save an Audio Stream to the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
Visual Basic Language Reference

My.Computer.Clipboard.Clear Method
Clears the Clipboard.

' Usage
My.Computer.Clipboard.Clear()
' Declaration
Public Sub Clear()

Remarks
The UIPermission class controls access to the Clipboard, and the associated UIPermissionClipboard enumeration value
indicates the level of access. For more information, see Additional Security Considerations in Windows Forms.
Tasks
The following table lists an example of a task involving the My.Computer.Clipboard.Clear method.
To See
Clear the Clipboard How to: Clear the Clipboard in Visual Basic
Example
This example clears the Clipboard.

My.Computer.Clipboard.Clear()

This removes all data from the Clipboard.


Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Clear the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard Object Members
System.Windows.Forms.Clipboard.Clear
Visual Basic Language Reference

My.Computer.Clipboard.ContainsAudio Method
Indicates whether the Clipboard contains audio data.

' Usage
Dim value As Boolean = My.Computer.Clipboard.ContainsAudio()
' Declaration
Public Function ContainsAudio() As Boolean

Return Value
True if audio data is stored on the Clipboard; otherwise False.
Remarks
Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard.ContainsAudio method.
To See
Determine what type of data is stored on the Cl How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
ipboard
Example
This example determines whether the Clipboard contains audio data and displays the result.
VB
If My.Computer.Clipboard.ContainsAudio() Then
MsgBox("The clipboard contains audio data.")
Else
MsgBox("The clipboard does not contain audio data.")
End If

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.GetAudioStream Method
My.Computer.Clipboard.SetAudio Method
System.Windows.Forms.Clipboard.ContainsAudio
Other Resources
Playing Sounds
Visual Basic Language Reference

My.Computer.Clipboard.ContainsData Method
Indicates whether the Clipboard contains data in the specified custom format.

' Usage
Dim value As Boolean = My.Computer.Clipboard.ContainsData(format)
' Declaration
Public Function ContainsData( _
ByVal format As String _
) As Boolean

Parameters
format
String. Name of the custom format to be checked. Required.
Return Value
True if data in the specified custom format is stored on the Clipboard; otherwise False.
Exceptions
This method throws no exceptions.
Remarks
If you have placed custom formatted data on the Clipboard, this method allows you to check the Clipboard for data in that
format.
Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard.ContainsData method.
To See
Determine what type of data is stored on the Cl How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
ipboard
Example
This example checks for data in the custom format specialFormat.
VB
If My.Computer.Clipboard.ContainsData("specialFormat") Then
MsgBox("Data found.")
End If

Replace specialFormat with the name of the custom format you wish to check.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes


Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.GetData Method
My.Computer.Clipboard.GetDataObject Method
My.Computer.Clipboard.SetData Method
My.Computer.Clipboard.SetDataObject Method
ContainsData
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference

My.Computer.Clipboard.ContainsFileDropList Method
Returns a Boolean indicating whether the Clipboard contains a file drop list.

' Usage
Dim value As Boolean = My.Computer.Clipboard.ContainsFileDropList()
' Declaration
Public Function ContainsFileDropList() As Boolean

Return Value
True if a file drop list is stored on the Clipboard; otherwise False.
Remarks
A file drop list is a collection of strings containing path information for files.
Example
This example determines if there is a file drop list on the Clipboard and adds the list to the ListBox lstFiles if they exist.
VB
If My.Computer.Clipboard.ContainsFileDropList Then
Dim filelist As System.Collections.Specialized.StringCollection
filelist = My.Computer.Clipboard.GetFileDropList()
For Each filePath As String In filelist
lstFiles.Items.Add(filePath)
Next
End If

This code will create an exception if there is no ListBox named lstFiles.


Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.GetFileDropList Method
My.Computer.Clipboard.SetFileDropList Method
System.Windows.Forms.Clipboard.ContainsFileDropList
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference

My.Computer.Clipboard.ContainsImage Method
Returns a Boolean indicating whether an image is stored on the Clipboard.

' Usage
Dim value As Boolean = My.Computer.Clipboard.ContainsImage()
' Declaration
Public Function ContainsImage() As Boolean

Return Value
True if an image is stored on the Clipboard; otherwise False.
Exceptions
This method throws no exceptions.
Remarks
The method requires AllClipboard.
Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard.ContainsImage method.
To See
Determine whether the Clipboard contains an image How to: Retrieve an Image from the Clipboard in Visual Basic
Example
This example checks to see if there is an image on the Clipboard and, if so, gets the image and adds it to PictureBox1.
VB
If My.Computer.Clipboard.ContainsImage() Then
Dim grabpicture As System.Drawing.Image
grabpicture = My.Computer.Clipboard.GetImage()
PictureBox1.Image = grabpicture
End If

This example depends on the existence of a PictureBox named PictureBox1.


Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No


Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.GetImage Method
My.Computer.Clipboard.SetImage Method
System.Windows.Forms.Clipboard.ContainsImage
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference

My.Computer.Clipboard.ContainsText Method
Determines if there is text on the Clipboard.

' Usage
Dim value As Boolean = My.Computer.Clipboard.ContainsText()
Dim value As Boolean = My.Computer.Clipboard.ContainsText(format)
' Declaration
Public Function ContainsText() As Boolean
' -or-
Public Function ContainsText( _
ByVal format As System.Windows.Forms.TextDataFormat _
) As Boolean

Parameters
format
TextDataFormat. If specified, identifies what text format to be checked for. Required.
Return Value
True if the Clipboard contains text; otherwise False.
Remarks
Possible formats are CommaSeparatedValue, Html, Rtf and UnicodeText.
The method requires AllClipboard.
Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard.ContainsText method.
To See
Determine whether the Clipboard contains text How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
Example
This example determines if HTML text is stored on the Clipboard and reads from the Clipboard if it does.
VB
If My.Computer.Clipboard.ContainsText _
(System.Windows.Forms.TextDataFormat.Html) Then
Dim clipText As String = My.Computer.Clipboard.GetText()
End If

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes


Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.GetText Method
My.Computer.Clipboard.SetText Method
System.Windows.Forms.TextDataFormat
System.Windows.Forms.Clipboard.ContainsText
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference

My.Computer.Clipboard.GetAudioStream Method
Retrieves an audio stream from the Clipboard.

' Usage
Dim value As System.IO.Stream = My.Computer.Clipboard.GetAudioStream()
' Declaration
Public Function GetAudioStream() As System.IO.Stream

Return Value
Stream
Remarks
Example
This example retrieves an audio stream from the Clipboard and plays it.
VB
If My.Computer.Clipboard.ContainsAudio Then
Dim song As System.IO.Stream
song = My.Computer.Clipboard.GetAudioStream
My.Computer.Audio.Play(song, AudioPlayMode.WaitToComplete)
End If

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsAudio Method
My.Computer.Clipboard.SetAudio Method
System.IO.Stream
System.Windows.Forms.Clipboard.GetAudioStream
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference

My.Computer.Clipboard.GetData Method
Retrieves data in a custom format from the Clipboard.

' Usage
Dim value As Object = My.Computer.Clipboard.GetData(format)
' Declaration
Public Function GetData( _
ByVal format As String _
) As Object

Parameters
format
String. Name of the data format. Required.
Return Value
Object.
Remarks
Example
This example reads data in the format specialformat from the Clipboard and writes it to file.
VB
Dim someData As Object
someData = My.Computer.Clipboard.GetData("specialformat")
My.Computer.FileSystem.WriteAllBytes("C:\\mylogfile", someData, True)

Replace specialformat with the custom data format you wish to retrieve.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsData Method
My.Computer.Clipboard.GetDataObject Method
My.Computer.Clipboard.SetData Method
My.Computer.Clipboard.SetDataObject Method
GetData
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference

My.Computer.Clipboard.GetDataObject Method
Retrieves data from the Clipboard as an IDataObject.

' Usage
Dim value As System.Windows.Forms.IDataObject = My.Computer.Clipboard.GetDataObject()
' Declaration
Public Function GetDataObject() As System.Windows.Forms.IDataObject

Return Value
IDataObject
Remarks
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
Example
This example reads data from the Clipboard in the form of an IDataObject and then writes it to a file.
VB
Dim someData As Object
someData = My.Computer.Clipboard.GetDataObject()
My.Computer.FileSystem.WriteAllBytes("C:\mylogfile", someData, True)

Replace C:\mylogfile with the name of the file to which you want to write.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsData Method
My.Computer.Clipboard.GetData Method
My.Computer.Clipboard.SetData Method
My.Computer.Clipboard.SetDataObject Method
System.Windows.Forms.IDataObject
System.Windows.Forms.Clipboard.GetDataObject
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference

My.Computer.Clipboard.GetFileDropList Method
Retrieves a collection of strings representing file names from the Clipboard.

' Usage
Dim value As System.Collections.Specialized.StringCollection = My.Computer.Clipboard.GetFil
eDropList()
' Declaration
Public Function GetFileDropList() As System.Collections.Specialized.StringCollection

Return Value
StringCollection
Remarks
This method is available only for non-server applications.
A file drop list is a collection of strings containing path information for files.
Example
This example determines if there is a file drop list on the Clipboard and adds the list to the ListBox lstFiles if they exist.
VB
If My.Computer.Clipboard.ContainsFileDropList Then
Dim filelist As System.Collections.Specialized.StringCollection
filelist = My.Computer.Clipboard.GetFileDropList()
For Each filePath As String In filelist
lstFiles.Items.Add(filePath)
Next
End If

This code creates an exception if there is no ListBox named lstFiles.


Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsFileDropList Method
My.Computer.Clipboard.SetFileDropList Method
System.Collections.Specialized.StringCollection
System.Windows.Forms.Clipboard.GetFileDropList
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference

My.Computer.Clipboard.GetImage Method
Retrieves an image from the Clipboard.

' Usage
Dim value As System.Drawing.Image = My.Computer.Clipboard.GetImage()
' Declaration
Public Function GetImage() As System.Drawing.Image

Return Value
Image
Remarks
The GetImage method will return Nothing if there is no data on the Clipboard that is an image.
The method requires AllClipboard.
Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard.GetImage method.
To See
Retrieve an image from the Clipboard How to: Retrieve an Image from the Clipboard in Visual Basic
Example
This example checks to see if there is an image on the Clipboard before retrieving it and assigning it to PictureBox1.

VB
If My.Computer.Clipboard.ContainsImage() Then
Dim grabpicture As System.Drawing.Image
grabpicture = My.Computer.Clipboard.GetImage()
PictureBox1.Image = grabpicture
End If

For this example to function correctly, there must be a PictureBox named PictureBox1 on your form.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes


Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Determine What Type of File is Stored on the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsImage Method
My.Computer.Clipboard.SetImage Method
System.Drawing.Image
System.Windows.Forms.Clipboard.GetImage
Visual Basic Language Reference

My.Computer.Clipboard.GetText Method
Retrieves text from the Clipboard.

' Usage
Dim value As String = My.Computer.Clipboard.GetText()
Dim value As String = My.Computer.Clipboard.GetText(format)
' Declaration
Public Function GetText() As String
' -or-
Public Function GetText( _
ByVal format As System.Windows.Forms.TextDataFormat _
) As String

Parameters
format
TextDataFormat. If specified, identifies what text format should be retrieved. Default is CommaSeparatedValue. Required.
Return Value
String.
Exceptions
This method throws no exceptions.
Remarks
Possible formats are CommaSeparatedValue, Html, Rtf and UnicodeText.
The method requires AllClipboard.
This method returns an empty string if there is no data on the Clipboard that matches the specified format.
Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard.GetText method.
To See
Read text from the Clipboard How to: Read from the Clipboard in Visual Basic
Example
This example reads text from the Clipboard into the string textOnClipboard.
VB
Dim textOnClipboard As String = My.Computer.Clipboard.GetText()

This example fails if there is no text on the Clipboard.


Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library Yes

Console Application Yes


Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Read from the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsText Method
My.Computer.Clipboard.SetText Method
System.Windows.Forms.TextDataFormat
System.Windows.Forms.Clipboard.GetText
Visual Basic Language Reference

My.Computer.Clipboard.SetAudio Method
Writes audio data to the Clipboard.

' Usage
My.Computer.Clipboard.SetAudio(audioBytes)
My.Computer.Clipboard.SetAudio(audioStream)
' Declaration
Public Sub SetAudio( _
ByVal audioBytes As Byte() _
)
' -or-
Public Sub SetAudio( _
ByVal audioStream As System.IO.Stream _
)

Parameters
audioBytes
Byte array. Audio data to be written to the Clipboard. Required.
audioStream
Stream Audio data to be written to the clipboard. Required.
Exceptions
No exceptions are thrown by this method.
Remarks
This method can be used to write the audio data as either a byte array or an audio stream.
Security Note
Because the Clipboard can be accessed by other users, do not use it to store sensitive information, such as passwords or conf
idential data.

Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard.SetAudio method.
To See
Write audio data to the Clipboard How to: Save an Audio Stream to the Clipboard in Visual Basic
Example
This example creates the byte array musicReader, reads the file cool.wav into it, and then writes it to the Clipboard.
VB
Dim musicReader As Byte()
musicReader = My.Computer.FileSystem.ReadAllBytes("cool.wav")
My.Computer.Clipboard.SetAudio(musicReader)

Replace cool.wav with the name and path of the file you wish to read.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsAudio Method
My.Computer.Clipboard.GetAudioStream Method
System.IO.Stream
System.Windows.Forms.Clipboard.SetAudio
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference

My.Computer.Clipboard.SetData Method
Writes data in a custom format to the Clipboard.

' Usage
My.Computer.Clipboard.SetData(format ,data)
' Declaration
Public Sub SetData( _
ByVal format As String, _
ByVal data As Object _
)

Parameters
format
String. Format of data. Required.
data
Object. Data object to be written to the Clipboard. Required.
Exceptions
This method throws no exceptions.
Remarks
Security Note
Because the Clipboard can be accessed by other users, do not use it to store sensitive information, such as passwords or conf
idential data.

Example
This example writes the DataObject dataChunk to the Clipboard in the custom format specialFormat.
VB
My.Computer.Clipboard.SetData("specialFormat", dataChunk)

This example depends on the existence of the custom data format specialFormat.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No


Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsData Method
My.Computer.Clipboard.GetData Method
My.Computer.Clipboard.GetDataObject Method
My.Computer.Clipboard.SetDataObject Method
SetData
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference

My.Computer.Clipboard.SetDataObject Method
Writes a DataObject to the Clipboard.

' Usage
My.Computer.Clipboard.SetDataObject(data)
' Declaration
Public Sub SetDataObject( _
ByVal data As System.Windows.Forms.DataObject _
)

Parameters
data
DataObject. Data object to be written to the Clipboard. Required.
Remarks
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
Security Note
Because the Clipboard can be accessed by other users, do not use it to store sensitive information, such as passwords or conf
idential data.

Example
This example writes the data object dataChunk to the Clipboard.
VB
My.Computer.Clipboard.SetDataObject(dataChunk)

This example depends on the existence of the data object dataChunk.


Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsData Method
My.Computer.Clipboard.GetData Method
My.Computer.Clipboard.GetDataObject Method
My.Computer.Clipboard.SetData Method
SetDataObject
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference

My.Computer.Clipboard.SetFileDropList Method
Writes a collection of strings representing file paths to the Clipboard.

' Usage
My.Computer.Clipboard.SetFileDropList(filePaths)
' Declaration
Public Sub SetFileDropList( _
ByVal filePaths As System.Collections.Specialized.StringCollection _
)

Parameters
filePaths
StringCollection. List of file names. Required.
Remarks
A file drop list is a collection of strings representing file names.
Security Note
Because the Clipboard can be accessed by other users, do not use it to store sensitive information, such as passwords or conf
idential data.

Example
This example gets the collection of file names from MyDocuments, converts it to a file drop list, and writes it to the Clipboard.
VB
Dim list As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
list = My.Computer.FileSystem.GetFiles _
(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
Dim listReader As New System.Collections.Specialized.StringCollection
For Each item As String In list
listReader.Add(item)
Next
My.Computer.Clipboard.SetFileDropList(listReader)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No


Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsFileDropList Method
My.Computer.Clipboard.GetFileDropList Method
System.Collections.Specialized.StringCollection
SetFileDropList
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference

My.Computer.Clipboard.SetImage Method
Writes an image to the Clipboard.

' Usage
My.Computer.Clipboard.SetImage(image)
' Declaration
Public Sub SetImage( _
ByVal image As System.Drawing.Image _
)

Parameters
image
Image. Image to be written. Required.
Remarks
Security Note
Because the Clipboard can be accessed by other users, do not use it to store sensitive information, such as passwords or conf
idential data.

Example
This example writes the image coolPicture to the Clipboard.
VB
My.Computer.Clipboard.SetImage(coolPicture)

This example depends on the existence of the image coolPicture.


Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Retrieve an Image from the Clipboard in Visual Basic
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsImage Method
My.Computer.Clipboard.GetImage Method
System.Drawing.Image
System.Windows.Forms.Clipboard.SetImage(System.Drawing.Image)
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference

My.Computer.Clipboard.SetText Method
Writes text to the Clipboard.

' Usage
My.Computer.Clipboard.SetText(text)
My.Computer.Clipboard.SetText(text ,format)
' Declaration
Public Sub SetText( _
ByVal text As String _
)
' -or-
Public Sub SetText( _
ByVal text As String, _
ByVal format As System.Windows.Forms.TextDataFormat _
)

Parameters
text
String. Text to be written. Required.
format
TextDataFormat. Format to be used when writing text. Default is UnicodeText. Required.
Exceptions
The following conditions may cause an exception:
text is an empty string (ArgumentException).
text is Nothing (ArgumentNullException).
Remarks
Possible formats are CommaSeparatedValue, Html, Rtf and UnicodeText.
The method requires AllClipboard.
Previous Clipboard formats are not preserved.
Security Note
Because the Clipboard can be accessed by other users, do not use it to store sensitive information, such as passwords or conf
idential data.

Tasks
The following table lists examples of tasks involving the My.Computer.Clipboard.SetText method.
To See
Write text to the Clipboard How to: Write to the Clipboard in Visual Basic
Example
This example writes the string This is a test string. to the Clipboard.

VB
My.Computer.Clipboard.SetText("This is a test string.")

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: ClipboardProxy (provides access to Clipboard)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Clipboard Object
My.Computer.Clipboard.ContainsText Method
My.Computer.Clipboard.GetText Method
System.Windows.Forms.TextDataFormat
System.Windows.Forms.Clipboard.SetText
Other Resources
Storing Data to and Reading From the Clipboard
Visual Basic Language Reference

My.Computer.Clock Object
Provides properties for accessing the current local time and Universal Coordinated Time (equivalent to Greenwich Mean Time)
from the system clock.
Remarks
The My.Computer.Clock object provides properties to find the current local time for the computer and the UTC time. It also
exposes the millisecond count from the computer's system timer.
Example
This example uses the My.Computer.Clock.LocalTime property to display the local time of the computer on which the code
runs.
VB
MsgBox("Current local time: " & My.Computer.Clock.LocalTime)

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Clock
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer.Clock Object Members
My.Computer Object
Microsoft.VisualBasic.Devices.Clock
Visual Basic Language Reference

My.Computer.Clock Object Members


The My.Computer.Clock Object provides properties for accessing the current local time and Universal Coordinated Time
(equivalent to Greenwich Mean Time) from the system clock.
Properties
Property Description
GmtTime Gets a Date object that contains the current local date and time on this computer, expressed as a UTC (GMT) time.

LocalTime Gets a Date object that contains the current local date and time on this computer.

TickCount Gets the millisecond count from the computer's system timer.
See Also
Reference
My.Computer.Clock Object
Visual Basic Language Reference

My.Computer.Clock.GmtTime Property
Gets a Date object that contains the current local date and time on the computer, expressed as a UTC (GMT) time.

' Usage
Dim value As Date = My.Computer.Clock.GmtTime
' Declaration
Public ReadOnly Property GmtTime As Date

Return Value
A Date object that contains the current date and time expressed as UTC (GMT) time.
Remarks
The My.Computer.Clock.GmtTime property has the same behavior as the System.DateTime.UtcNow property.
Example
This example uses the My.Computer.Clock.GmtTime property to display the GMT time of the computer on which the code
runs.
VB
MsgBox("Current GMT time: " & My.Computer.Clock.GmtTime)

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Clock
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer.Clock Object
My.Computer.Clock.LocalTime Property
System.DateTime.UtcNow
Microsoft.VisualBasic.Devices.Clock.GmtTime
Visual Basic Language Reference

My.Computer.Clock.LocalTime Property
Gets a Date object that contains the current local date and time on this computer.

' Usage
Dim value As Date = My.Computer.Clock.LocalTime
' Declaration
Public ReadOnly Property LocalTime As Date

Return Value
A Date object that contains the current local date and time.
Remarks
The My.Computer.Clock.LocalTime property has the same behavior as the System.DateTime.Now property.
Example
This example uses the My.Computer.Clock.LocalTime property to display the local time of the computer on which the code
runs.
VB
MsgBox("Current local time: " & My.Computer.Clock.LocalTime)

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Clock
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer.Clock Object
My.Computer.Clock.GmtTime Property
System.DateTime.Now
Microsoft.VisualBasic.Devices.Clock.LocalTime
Visual Basic Language Reference

My.Computer.Clock.TickCount Property
Gets the millisecond count from the computer's system timer.

' Usage
Dim value As Integer = My.Computer.Clock.TickCount
' Declaration
Public ReadOnly Property TickCount As Integer

Return Value
An Integer containing the millisecond count from the computer's system timer.
Remarks
The TickCount property provides access to the computer's system timer, which runs when the computer is active. The timer
resolution is not less than 500 milliseconds.
You can use this property to make your application's behavior dependent on the length of time it has been running, or you can
use it to label events, both of which are independent of the computer's clock.
Caution
When the value of the TickCount property reaches the maximum integer value (MaxValue), it then jumps to the minimum in
teger value (MinValue), a negative number, and continues to increment.

If the computer runs continuously, TickCount increments from zero to the maximum integer value in approximately 24.9 days.
The TickCount property increments only when the operating system is running; it pauses when the computer goes into
certain power-saving modes, such as standby or hibernation. The TickCount property is unrelated to the computer's clock
setting.
Use the My.Computer.Clock.LocalTime Property or My.Computer.Clock.GmtTime Property to obtain the current local date and
time on this computer.
The My.Computer.Clock.TickCount property has the same behavior as the System.Environment.TickCount property.
Example
The following example uses the My.Computer.Clock.TickCount property to run a task in a loop for a given number of
seconds, even if the computer's system time changes while it runs.
VB
Public Sub LoopTask(ByVal secondsToRun As Integer)
Dim startTicks As Integer = My.Computer.Clock.TickCount
Do While IsTimeUp(startTicks, secondsToRun)
' Code to run for at least secondsToRun seconds goes here.
Loop
End Sub

Private Function IsTimeUp( _


ByVal startTicks As Integer, _
ByVal seconds As Integer _
) As Boolean
' This function throws an overflow exception if the
' tick count difference is greater than 2,147,483,647,
' about 24 days for My.Computer.Clock.TickCount.

' Use UInteger to simplify the code for roll over.


Dim uStart As UInteger = _
CUInt(CLng(startTicks) - Integer.MinValue)
Dim uCurrent As UInteger = _
CUInt(CLng(My.Computer.Clock.TickCount) - Integer.MinValue)
' Calculate the tick count difference.
Dim tickCountDifference As UInteger
If uStart <= uCurrent Then
tickCountDifference = uCurrent - uStart
Else
' Tick count rolled over.
tickCountDifference = UInteger.MaxValue - (uStart - uCurrent)
End If
' Convert seconds to milliseconds and compare.
Return CInt(tickCountDifference) < (seconds * 1000)
End Function

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Clock
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer.Clock Object
System.Environment.TickCount
Microsoft.VisualBasic.Devices.Clock.TickCount
Visual Basic Language Reference

My.Computer.FileSystem Object
Provides properties and methods for working with drives, files, and directories.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem object.
To See
Read from a text file How to: Read From Text Files in Visual Basic

Read from a delimited text file How to: Read From Comma-Delimited Text Files in Visual Basic

Read from a fixed-width text file How to: Read From Fixed-width Text Files in Visual Basic

Read from a text file with multiple formats How to: Read From Text Files with Multiple Formats in Visual Basic

Read from a binary file How to: Read From Binary Files in Visual Basic

Read from text files in the MyDocuments direct How to: Read From Existing Text Files in My Documents (Visual Basic)
ory

Read from a text file with a StreamReader How to: Read Text from Files with a StreamReader (Visual Basic)

Write to a text file How to: Write Text to Files in Visual Basic

Append to a text file How to: Append to Text Files in Visual Basic

Write to a binary file How to: Write to Binary Files in Visual Basic

Write to text files in the MyDocuments director How to: Write Text to Files in the My Documents Directory in Visual Basic
y

Write to a text file with a StreamWriter How to: Write Text to Files with a StreamWriter in Visual Basic

Copy files with a specific pattern How to: Copy Files with a Specific Pattern to a Directory in Visual Basic

Copy a file to the same directory How to: Create a Copy of a File in the Same Directory in Visual Basic

Copy a file to a different directory How to: Create a Copy of a File in a Different Directory in Visual Basic

Create a file How to: Create a File in Visual Basic

Delete a file How to: Delete a File in Visual Basic

Delete all the files in a directory How to: Delete All Files in a Directory in Visual Basic

Find files with a specific pattern How to: Find Files with a Specific Pattern in Visual Basic

Move a file How to: Move a File in Visual Basic

Move a collection of files How to: Move a Collection of Files in Visual Basic

Rename a file How to: Rename a File in Visual Basic


Rename a directory How to: Rename a Directory in Visual Basic

Copy a directory to another directory How to: Copy a Directory to Another Directory in Visual Basic

Create a directory How to: Create a Directory in Visual Basic

Delete a directory How to: Delete a Directory in Visual Basic

Find subdirectories with a specific pattern How to: Find Subdirectories with a Specific Pattern in Visual Basic

Get the collection of files in a directory How to: Get the Collection of Files in a Directory in Visual Basic

Determine how many files are in a directory How to: Determine How Many Files Are in a Directory in Visual Basic

Move a directory How to: Move a Directory in Visual Basic

Move the contents of a directory How to: Move the Contents of a Directory in Visual Basic

Read from the MyDocuments directory How to: Retrieve the Contents of the My Documents Directory in Visual Basic

Parse a file path How to: Parse File Paths in Visual Basic
Example
This example checks to determine whether the folder C:\backup\logs exists and checks its properties.
VB
Dim logInfo As System.IO.DirectoryInfo
If My.Computer.FileSystem.DirectoryExists("C:\backup\logs") Then
logInfo = My.Computer.FileSystem.GetDirectoryInfo _
("C:\backup\logs")
End If

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer.FileSystem Object Members
My.Computer.FileSystem.SpecialDirectories Object
My.Computer Object
Microsoft.VisualBasic.FileIO.FileSystem
Visual Basic Language Reference

My.Computer.FileSystem Object Members


The My.Computer.FileSystem Object provides properties and methods for working with drives, files, and directories.
Properties
Property Description
CurrentDirectory Gets the current directory.

Drives Gets information about drives.

SpecialDirectories Returns the My.Computer.FileSystem.SpecialDirectories Object, which can be used to access special director
ies, such as Temp or MyDocuments.
Methods
Method Description
CombinePath Returns a properly formatted combined path as a String.

CopyDirectory Copies a directory.

CopyFile Copies a file.

CreateDirectory Creates a directory.

DeleteDirectory Deletes a directory.

DeleteFile Deletes a file.

DirectoryExists Returns a Boolean indicating whether a directory exists.

FileExists Returns a Boolean indicating whether a file exists.

My.Computer.FileSystem.FindInFiles Method Returns a read-only collection of strings representing the names of files containi
ng the specified text.

GetDirectories Returns a String collection representing the path names of subdirectories within
a directory.

GetDirectoryInfo Returns a DirectoryInfo object for the specified path.

GetDriveInfo Returns a DriveInfo object for the specified path.

GetFileInfo Returns a FileInfo object for the specified path.

GetFiles Returns a read-only String collection representing the names of files within a dir
ectory.

GetParentPath Returns a String representing the absolute path of the parent of the provided pat
h.

MoveDirectory Moves a directory.

MoveFile Moves a file.


OpenTextFieldParser Opens a TextFieldParser.

OpenTextFileReader Opens a TextReader.

OpenTextFileWriter Opens a TextWriter.

ReadAllBytes Reads from a binary file.

ReadAllText Reads from a text file.

RenameDirectory Renames a directory.

RenameFile Renames a file.

WriteAllBytes Writes to a binary file.

WriteAllText Writes to a text file.


See Also
Tasks
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
My.Computer.FileSystem Object
Concepts
Parsing Text Files with the TextFieldParser Object
Other Resources
Reading from Files in Visual Basic
Writing to Files in Visual Basic
Creating, Deleting, and Moving Files and Directories in Visual Basic
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.CombinePath Method
Combines two paths and returns a properly formatted path.

' Usage
Dim value As String = My.Computer.FileSystem.CombinePath(baseDirectory ,relativePath)
' Declaration
Public Function CombinePath( _
ByVal baseDirectory As String, _
ByVal relativePath As String _
) As String

Parameters
baseDirectory
String. First path to be combined. Required.
relativePath
String. Second path to be combined. Required.
Return Value
String.
Exceptions
The following condition may create an exception:
Path is malformed (ArgumentException).
Remarks
This method trims excess slash-mark characters to create a properly formatted path.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.CombinePath method.
To See
Combine a directory path and file name How to: Parse File Paths in Visual Basic
Example
This example combines a directory path and file name to create a properly formatted path.
VB
Dim fullPath As String
fullPath = My.Computer.FileSystem.CombinePath _
("C:\Documents and Settings\All Users\Documents\My Pictures", "picture.jpg")

This example combines two paths to create a properly formatted path.


VB
Dim fullPath As String
fullPath = My.Computer.FileSystem.CombinePath _
("C:\Dir1\Dir2\Dir3", "..\Dir4\Dir5\File.txt")

This example returns C:\Dir1\Dir2\Dir4\Dir5\File.txt.


Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.GetParentPath Method
CombinePath
Visual Basic Language Reference

My.Computer.FileSystem.CopyDirectory Method
Copies a directory to another directory.

' Usage
My.Computer.FileSystem.CopyDirectory(sourceDirectoryName ,destinationDirectoryName)
My.Computer.FileSystem.CopyDirectory(sourceDirectoryName ,destinationDirectoryName ,overwri
te)
My.Computer.FileSystem.CopyDirectory(sourceDirectoryName ,destinationDirectoryName ,showUI)
My.Computer.FileSystem.CopyDirectory(sourceDirectoryName ,destinationDirectoryName ,showUI
,onUserCancel)
' Declaration
Public Sub CopyDirectory( _
ByVal sourceDirectoryName As String, _
ByVal destinationDirectoryName As String _
)
' -or-
Public Sub CopyDirectory( _
ByVal sourceDirectoryName As String, _
ByVal destinationDirectoryName As String, _
ByVal overwrite As Boolean _
)
' -or-
Public Sub CopyDirectory( _
ByVal sourceDirectoryName As String, _
ByVal destinationDirectoryName As String, _
ByVal showUI As UIOption _
)
' -or-
Public Sub CopyDirectory( _
ByVal sourceDirectoryName As String, _
ByVal destinationDirectoryName As String, _
ByVal showUI As UIOption, _
ByVal onUserCancel As UICancelOption _
)

Parameters
sourceDirectoryName
String. The directory to be copied. Required.
destinationDirectoryName
String. The location to which the directory should be copied. Required.
overwrite
Boolean. Whether or not existing files should be overwritten. Default is False. Required.
showUI
UIOption. Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs. Required.
onUserCancel
UICancelOption. Specifies what should be done if the user clicks Cancel during the operation. Default is ThrowException.
Required.
Exceptions
The following conditions may cause an exception:
The new name specified for the directory contains a colon (:) or slash (\ or /) (ArgumentException).
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
destinationDirectoryName is Nothing or an empty string (ArgumentNullException)
The source directory does not exist (DirectoryNotFoundException).
The source directory is a root directory (IOException).
The combined path points to an existing file (IOException).
The source path and target path are the same (IOException).
ShowUI is set to UIOption.AllDialogs and the user cancels the operation, or one or more files in the directory cannot be
copied (OperationCanceledException).
The operation is cyclic (InvalidOperationException).
The path contains a colon (:) (NotSupportedException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
A destination file exists but cannot be accessed (UnauthorizedAccessException).
Remarks
This method copies the contents of the directory as well as the directory itself. If the target directory does not exist, it is created.
If a directory with the same name exists in the target location, the contents of the two directories are merged. You can specify a
new name for the directory during the operation.
When copying files within a directory, exceptions may be thrown that are caused by a specific file, such as a file existing during
a merge while overwrite is set to False. When such exceptions are thrown, they are consolidated into a single exception whose
Data property holds entries in the form of an IDictionary in which the file or directory path is the key and the specific exception
message is contained in the corresponding value. Use For…Each to enumerate through the entries.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.CopyDirectory method.
To See
Copy a directory How to: Copy a Directory to Another Directory in Visual Basic
Example
The following example copies the directory TestDirectory1 into TestDirectory2, overwriting existing files.

VB
My.Computer.FileSystem.CopyDirectory("C:\TestDirectory1", "C:\TestDirectory2", True)

Replace C:\TestDirectory1 and C:\TestDirectory2 with the path and name of the directory you wish to copy and the
location to which you wish to copy it.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes


Console Application Yes
Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permissions may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration:
SafeSubWindows.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Get the Collection of Files in a Directory in Visual Basic
How to: Move a Directory in Visual Basic
How to: Move the Contents of a Directory in Visual Basic
How to: Parse File Paths in Visual Basic
How to: Determine the Absolute Path of a File in Visual Basic
How to: Determine if a Directory Exists in Visual Basic
Reference
My.Computer.FileSystem Object
UICancelOption Enumeration
Visual Basic Language Reference

My.Computer.FileSystem.CopyFile Method
Copies a file to a new location.

' Usage
My.Computer.FileSystem.CopyFile(sourceFileName ,destinationFileName)
My.Computer.FileSystem.CopyFile(sourceFileName ,destinationFileName ,overwrite)
My.Computer.FileSystem.CopyFile(sourceFileName ,destinationFileName ,showUI)
My.Computer.FileSystem.CopyFile(sourceFileName ,destinationFileName ,showUI ,onUserCancel)
' Declaration
Public Sub CopyFile( _
ByVal sourceFileName As String, _
ByVal destinationFileName As String _
)
' -or-
Public Sub CopyFile( _
ByVal sourceFileName As String, _
ByVal destinationFileName As String, _
ByVal overwrite As Boolean _
)
' -or-
Public Sub CopyFile( _
ByVal sourceFileName As String, _
ByVal destinationFileName As String, _
ByVal showUI As UIOption _
)
' -or-
Public Sub CopyFile( _
ByVal sourceFileName As String, _
ByVal destinationFileName As String, _
ByVal showUI As UIOption, _
ByVal onUserCancel As UICancelOption _
)

Parameters
sourceFileName
String. The file to be copied. Required.
destinationFileName
String. The location to which the file should be copied. Required.
overwrite
Boolean. Whether existing files should be overwritten. Default is False. Required.
showUI
UIOption. Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs. Required.
onUserCancel
UICancelOption. Specifies what should be done if the user clicks Cancel during the operation. Default is ThrowException.
Required.
Exceptions
The following conditions may cause an exception to be thrown:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The system could not retrieve the absolute path (ArgumentException).
destinationFileName contains path information (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
destinationFileName is Nothing or an empty string (ArgumentNullException).
The source file is not valid or does not exist (FileNotFoundException).
The combined path points to an existing directory (IOException).
The destination file exists and overwrite is set to False (IOException).
The user does not have sufficient permissions to access the file (IOException).
A file in the target directory with the same name is in use (IOException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
UICancelOption is set to ThrowException, and the user has canceled the operation (OperationCanceledException).
UICancelOption is set to ThrowException, and an unspecified I/O error occurs (OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
The user does not have required permission (UnauthorizedAccessException).
The user lacks necessary permissions to view the path (SecurityException).
Remarks
CopyFile does not preserve ACEs (Access Control Entries). The newly created file inherits default ACEs from the directory in
which it is created.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.CopyFile method.
To See
Copy a file to the same directory. How to: Create a Copy of a File in the Same Directory in Visual Basic

Copy a file to a different directory. How to: Create a Copy of a File in a Different Directory in Visual Basic
Example
This example copies the file Test.txt to the directory TestFiles2 without overwriting existing files.
VB
My.Computer.FileSystem.CopyFile _
("C:\UserFiles\TestFiles\test.txt", _
"C:\UserFiles\TestFiles2")

Replace the file paths with the paths you want to use in your code.
This example copies the file Test.txt to the directory TestFiles2 and renames it NewFile.txt.

VB
My.Computer.FileSystem.CopyFile _
("C:\UserFiles\TestFiles\test.txt", _
"C:\UserFiles\TestFiles2", "NewFile.txt", FileIO.UICancelOption.DoNothing)

Replace the file paths with the paths you want to use in your code.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permissions may be necessary:
Permission Description
EnvironmentPermission Controls the ability to access all environment variables. Associated enumeration: Unrestricted.

FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

RegistryPermission Controls the ability to access registry variables. Associated enumeration: Unrestricted.

UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration:
SafeSubWindows.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Copy Files with a Specific Pattern to a Directory in Visual Basic
How to: Create a Copy of a File in the Same Directory in Visual Basic
How to: Copy a Directory to Another Directory in Visual Basic
How to: Rename a File in Visual Basic
Reference
My.Computer.FileSystem Object
UICancelOption Enumeration
Visual Basic Language Reference

My.Computer.FileSystem.CreateDirectory Method
Creates a directory.

' Usage
My.Computer.FileSystem.CreateDirectory(directory)
' Declaration
Public Sub CreateDirectory( _
ByVal directory As String _
)

Parameters
directory
String. Name and location of the directory. Required.
Exceptions
The following conditions may cause an exception:
The directory name is malformed. For example, it contains illegal characters or is only white space
(ArgumentException Class).
The parent directory of the directory to be created is read-only (IOException Class).
The directory name is Nothing (ArgumentNullException Class).
The directory name is too long (PathTooLongException Class).
The directory name is only a colon (:). (NotSupportedException Class).
The user does not have permission to create the directory (UnauthorizedAccessException).
A partial-trust situation exists in which the user does not have sufficient permissions (SecurityException).
Remarks
If the directory already exists, no exception is thrown.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.CreateDirectory method.
To See
Create a directory How to: Create a Directory in Visual Basic
Example
This example creates the directory, NewDirectory, in C:\Documents and Settings\All Users\Documents.

VB
My.Computer.FileSystem.CreateDirectory _
("C:\Documents and Settings\All Users\Documents\NewDirectory")

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Determine if a Directory Exists in Visual Basic
Reference
My.Computer.FileSystem Object
CreateDirectory
Visual Basic Language Reference

My.Computer.FileSystem.CurrentDirectory Property
Gets or sets the current directory.

' Usage
Dim value As String = My.Computer.FileSystem.CurrentDirectory
' Declaration
Public Property CurrentDirectory As String

Return Value
String.
Exceptions
The following conditions may cause an exception:
The path is not valid (DirectoryNotFoundException).
The user lacks necessary permissions (UnauthorizedAccessException).
Remarks
CurrentDirectory is a system-wide environment variable.
Example
This example returns the current directory and displays it in a message box.
VB
MsgBox(My.Computer.FileSystem.CurrentDirectory)

This example sets the current directory to C:\TestDirectory.


VB
My.Computer.FileSystem.CurrentDirectory = "C:\TestDirectory"

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes


Web Site Yes
Permissions
Permissions may not be necessary to set CurrentDirectory.
The following permission may be necessary to read CurrentDirectory:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
Microsoft.VisualBasic.FileIO.FileSystem.CurrentDirectory
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.DeleteDirectory Method
Deletes a directory.

' Usage
My.Computer.FileSystem.DeleteDirectory(directory ,onDirectoryNotEmpty)
My.Computer.FileSystem.DeleteDirectory(directory ,showUI ,recycle)
My.Computer.FileSystem.DeleteDirectory(directory ,showUI ,recycle ,onUserCancel)
' Declaration
Public Sub DeleteDirectory( _
ByVal directory As String, _
ByVal onDirectoryNotEmpty As DeleteDirectoryOption _
)
' -or-
Public Sub DeleteDirectory( _
ByVal directory As String, _
ByVal showUI As UIOption, _
ByVal recycle As RecycleOption _
)
' -or-
Public Sub DeleteDirectory( _
ByVal directory As String, _
ByVal showUI As UIOption, _
ByVal recycle As RecycleOption, _
ByVal onUserCancel As UICancelOption _
)

Parameters
directory
String. Directory to be deleted. Required.
onDirectoryNotEmpty
DeleteDirectoryOption Enumeration. Specifies what should be done when a directory that is to be deleted contains files or
directories. Default is DeleteDirectoryOption.DeleteAllContents.
showUI
UIOption Enumeration. Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs.
Required.
recycle
RecycleOption Enumeration. Specifies whether or not the deleted file should be sent to the Recycle Bin. Default is
RecycleOption.DeletePermanently.
onUserCancel
UICancelOption Enumeration. Specifies whether to throw an exception if the user clicks Cancel. Required.
Exceptions
The following conditions may cause an exception:
The path is a zero-length string, is malformed, contains only white space, or contains invalid characters (including
wildcard characters) (ArgumentException).
The path is a device path (starts with \\.\) (ArgumentException).
The path is Nothing (ArgumentNullException).
The directory does not exist or is a file (DirectoryNotFoundException).
The directory is not empty, and onDirectoryNotEmpty is set to ThrowIfDirectoryNonEmpty (IOException).
The user does not have permission to delete the directory or subdirectory (IOException).
A file in the directory or subdirectory is in use (IOException).
A file or directory name contains a colon (:) (NotSupportedException).
The user cancels the operation or the directory cannot be deleted (OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
The user does not have required permissions (SecurityException).
Remarks
The showUI, recycle, and onUserCancel parameters are not supported in applications that are not user interactive, such as
Windows Services.
Tasks
The following table lists an example of a task involving the My.Computer.FileSystem.DeleteDirectory method.
To See
Delete a directory How to: Delete a Directory in Visual Basic
Example
The example deletes the directory OldDirectory only if it is empty.
VB
My.Computer.FileSystem.DeleteDirectory _
("C:\OldDirectory", FileIO.DeleteDirectoryOption.ThrowIfDirectoryNonEmpty)

This example deletes the directory OldDirectory and all of its contents.
VB
My.Computer.FileSystem.DeleteDirectory _
("C:\OldDirectory", FileIO.DeleteDirectoryOption.DeleteAllContents)

This example deletes the directory OldDirectory and all of its contents, asking the user to confirm the deletion, but does not
send the contents to the Recycle Bin.
VB
My.Computer.FileSystem.DeleteDirectory _
("C:\OldDirectory", FileIO.UIOption.AllDialogs, FileIO.RecycleOption.DeletePermanently, Fil
eIO.UICancelOption.ThrowException)

This example deletes the directory OldDirectory and all of its contents, sending them to the Recycle Bin, but does not show
the progress of the operation.
VB
My.Computer.FileSystem.DeleteDirectory("C:\OldDirectory", _
FileIO.UIOption.AllDialogs, FileIO.RecycleOption.SendToRecycleBin, FileIO.UICancelOption.T
hrowException)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permissions may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration:
SafeSubWindows.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Delete a File in Visual Basic
How to: Delete a Directory in Visual Basic
Reference
My.Computer.FileSystem Object
UICancelOption Enumeration
RecycleOption Enumeration
DeleteDirectoryOption Enumeration
UICancelOption Enumeration
UIOption Enumeration
Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory
UICancelOption
Visual Basic Language Reference

My.Computer.FileSystem.DeleteFile Method
Deletes a file.

' Usage
My.Computer.FileSystem.DeleteFile(file)
My.Computer.FileSystem.DeleteFile(file ,showUI ,recycle)
My.Computer.FileSystem.DeleteFile(file ,showUI ,recycle ,onUserCancel)
' Declaration
Public Sub DeleteFile( _
ByVal file As String _
)
' -or-
Public Sub DeleteFile( _
ByVal file As String, _
ByVal showUI As UIOption, _
ByVal recycle As RecycleOption _
)
' -or-
Public Sub DeleteFile( _
ByVal file As String, _
ByVal showUI As UIOption, _
ByVal recycle As RecycleOption, _
ByVal onUserCancel As UICancelOption _
)

Parameters
file
String. Name and path of the file to be deleted. Required.
showUI
UIOption. Whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs. Required.
recycle
RecycleOption. Whether or not the deleted file should be sent to the Recycle Bin. Default is
RecycleOption.DeletePermanently. Required.
onUserCancel
UICancelOption. Specifies whether or not an exception is thrown when the user cancels the operation. Default is
UICancelOption.ThrowException. Required.
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; it has a trailing slash where a file must be specified; or it is a device path (starts with \\.\)
(ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The file is in use (IOException).
The user lacks necessary permissions to view the path (SecurityException).
The file does not exist (FileNotFoundException).
The user does not have permission to delete the file or the file is read-only (UnauthorizedAccessException).
A partial-trust situation in which the user does not have sufficient permissions (SecurityException).
The user cancelled the operation and onUserCancel is set to Microsoft.VisualBasic.FileIO.UICancelOption.ThrowException
(OperationCanceledException).
Remarks
The showUI, recycle, and onUserCancel parameters are not supported in applications that are not user interactive, such as
Windows Services.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.DeleteFile method.
To See
To delete a file How to: Delete a File in Visual Basic

To delete all files in a directory How to: Delete All Files in a Directory in Visual Basic
Example
This example deletes the file Test.txt.

VB
My.Computer.FileSystem.DeleteFile("C:\test.txt")

This example deletes the file Test.txt and allows the user to confirm that the file should be deleted.
VB
My.Computer.FileSystem.DeleteFile _
("C:\test.txt", FileIO.UIOption.AllDialogs, FileIO.RecycleOption.SendToRecycleBin, FileIO.U
ICancelOption.ThrowException)

This example deletes the file Test.txt and sends it to the Recycle Bin.
VB
My.Computer.FileSystem.DeleteFile _
("C:\test.txt", FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.SendToRecycleBin, Fi
leIO.UICancelOption.ThrowException)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes


Windows Service Yes

Web Site Yes


Permissions
The following permissions may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration:
SafeSubWindows.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Delete a Directory in Visual Basic
Reference
My.Computer.FileSystem Object
UIOption Enumeration
RecycleOption Enumeration
UICancelOption Enumeration
My.Computer.FileSystem Object
Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile
Visual Basic Language Reference

My.Computer.FileSystem.DirectoryExists Method
Returns a Boolean indicating whether the specified directory exists.

' Usage
Dim value As Boolean = My.Computer.FileSystem.DirectoryExists(directory)
' Declaration
Public Function DirectoryExists( _
ByVal directory As String _
) As Boolean

Parameters
directory
String. Path of the directory. Required.
Return Value
True if the directory exists; otherwise False.
Exceptions
This method throws no exceptions.
Remarks
The call to DirectoryExists requires FileIOPermission.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.DirectoryExists method.
To See
Determine if a directory exists How to: Determine if a Directory Exists in Visual Basic
Example
This example determines whether the directory C:\backup\logs exists and checks its properties.
VB
If My.Computer.FileSystem.DirectoryExists("C:\backup\logs") Then
Dim logInfo As System.IO.DirectoryInfo
logInfo = My.Computer.FileSystem.GetDirectoryInfo _
("C:\backup\logs")
End If

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes


Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Determine if a File Exists in Visual Basic
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
My.Computer.FileSystem Object
DirectoryExists
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.Drives Property
Returns a read-only collection of all available drive names.

' Usage
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of System.IO.DriveInfo) = My
.Computer.FileSystem.Drives
' Declaration
Public ReadOnly Property Drives As System.Collections.ObjectModel.ReadOnlyCollection(Of Sys
tem.IO.DriveInfo)

Return Value
System.Collections.ObjectModel.ReadOnlyCollection (of System.IO.DriveInfo)
Exceptions
This property throws no exceptions.
Remarks
This property returns all logical drives.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.Drives property.
To See
Determine a drive's volume label How to: Determine a Drive's Volume Label in Visual Basic

Determine a drive's format How to: Determine a Drive's Format in Visual Basic

Determine a drive's type How to: Determine a Drive's Type in Visual Basic

Determine a drive's total space How to: Determine a Drive's Total Space in Visual Basic

Determine a drive's free space How to: Determine a Drive's Physical Free Space in Visual Basic

Determine a drive's root directory How to: Determine a Drive's Root Directory in Visual Basic
Example
This example displays the available drive names in a message box.
VB
Dim getInfo As System.IO.DriveInfo()
getInfo = System.IO.DriveInfo.GetDrives
For Each info As System.IO.DriveInfo In getInfo
MsgBox(info.name)
Next

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
System.Collections.ObjectModel.ReadOnlyCollection
System.IO.DriveInfo
Microsoft.VisualBasic.FileIO.FileSystem.Drives
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.FileExists Method
Returns a Boolean indicating whether the specified file exists.

' Usage
Dim value As Boolean = My.Computer.FileSystem.FileExists(file)
' Declaration
Public Function FileExists( _
ByVal file As String _
) As Boolean

Parameters
file
String. Name and path of the file. Required.
Return Value
Returns True if the file exists; otherwise this method returns False.
Exceptions
The following condition may create an exception:
The name of the file ends with a backslash (\) (ArgumentException).
Remarks
If the application does not have sufficient permissions to read the specified file, the FileExists method returns False, regardless
of the existence of the path; the method does not throw an exception.
Tasks
The following table lists an example of a task involving the My.Computer.FileSystem.FileExists method.
To See
Determine if a file exists How to: Determine if a File Exists in Visual Basic
Example
This example checks to see whether or not the file Check.txt exists and supplies the information in a message box.
VB
If My.Computer.FileSystem.FileExists("c://Check.txt") Then
MsgBox("File found.")
Else
MsgBox("File not found.")
End If

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes


Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Determine if a Directory Exists in Visual Basic
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
My.Computer.FileSystem Object
FileExists
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.FindInFiles Method
Returns a read-only collection of strings representing the names of files containing the specified text.

' Usage
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.Fil
eSystem.FindInFiles(directory ,containsText ,ignoreCase ,searchType)
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.Fil
eSystem.FindInFiles(directory ,containsText ,ignoreCase ,searchType ,fileWildcards)
' Declaration
Public Function FindInFiles( _
ByVal directory As String, _
ByVal containsText As String, _
ByVal ignoreCase As Boolean, _
ByVal searchType As SearchOption _
) As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
' -or-
Public Function FindInFiles( _
ByVal directory As String, _
ByVal containsText As String, _
ByVal ignoreCase As Boolean, _
ByVal searchType As SearchOption, _
ByVal fileWildcards As String() _
) As System.Collections.ObjectModel.ReadOnlyCollection(Of String)

Parameters
directory
String. The directory to be searched. Required.
containsText
String. The search text. Required.
ignoreCase
Boolean. Whether the search should be case-sensitive or not. Default is True. Required.
searchType
SearchOption Enumeration. Whether to include subfolders. Default is SearchOption.SearchTopLevelOnly. Required.
fileWildcards
Array of type String. Pattern to be matched. Required.
Return Value
Read-only collection of type String.
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
directory does not exist (DirectoryNotFoundException).
directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user lacks necessary permissions (UnauthorizedAccessException).
Remarks
An empty collection is returned if no files matching the specified pattern are found.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.FindInFiles method.
To See
Search a directory for files containing a specific string Walkthrough: Manipulating Files and Directories in Visual Basic
Example
This example searches the directory C:\TestDir for any files containing the string "sample string" and displays the results in
ListBox1.

VB
Dim list As System.Collections.ObjectModel.ReadOnlyCollection _
(Of String)
list = My.Computer.FileSystem.FindInFiles("C:\TestDir", _
"sample string", True, FileIO.SearchOption.SearchTopLevelOnly)
For Each name As String In list
ListBox1.Items.Add(name)
Next

In order to work, the project must contain a ListBox named ListBox1.


Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
My.Computer.FileSystem Object
SearchOption Enumeration
System.Collections.ObjectModel.ReadOnlyCollection
Microsoft.VisualBasic.FileIO.FileSystem.FindInFiles
Visual Basic Language Reference

My.Computer.FileSystem.GetDirectories Method
Returns a collection of strings representing the path names of subdirectories within a directory.

' Usage
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.Fil
eSystem.GetDirectories(directory)
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.Fil
eSystem.GetDirectories(directory ,searchType ,wildcards)
' Declaration
Public Function GetDirectories( _
ByVal directory As String _
) As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
' -or-
Public Function GetDirectories( _
ByVal directory As String, _
ByVal searchType As SearchOption, _
ByVal wildcards As String() _
) As System.Collections.ObjectModel.ReadOnlyCollection(Of String)

Parameters
directory
String. Name and path of directory. Required.
searchType
SearchOption Enumeration. Whether to include subfolders. Default is SearchOption.SearchTopLevelOnly. Required.
wildcards
String. Pattern to match names. Required.
Return Value
Read-only collection of String.
Exceptions
The following conditions may produce an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
One or more of the specified wildcard characters is Nothing, an empty string, or contains only spaces
(ArgumentNullException).
directory does not exist (DirectoryNotFoundException).
directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user lacks necessary permissions (UnauthorizedAccessException).
Remarks
You can use the wildcards parameter to specify a specific pattern. If you would like to include the contents of subdirectories in
the search, set the searchType parameter to SearchAllSubDirectories.
An empty collection is returned if no directories matching the specified pattern are found.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.GetDirectories method.
To See
List subdirectories with a specific pattern How to: Find Subdirectories with a Specific Pattern in Visual Basic
Example
The following example returns all the directories in the directory structure that contain the word Logs in their names and adds
them to ListBox1.
VB
For Each foundDirectory As String In _
My.Computer.FileSystem.GetDirectories _
(My.Computer.FileSystem.SpecialDirectories.MyDocuments, _
True, "*Logs*")
ListBox1.Items.Add(foundDirectory)
Next

This example requires that you have a ListBox named ListBox1 on your form.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
SearchOption Enumeration
System.Collections.ObjectModel.ReadOnlyCollection
Microsoft.VisualBasic.FileIO.FileSystem.GetDirectories
Visual Basic Language Reference

My.Computer.FileSystem.GetDirectoryInfo Method
Returns a DirectoryInfo object for the specified path.

' Usage
Dim value As System.IO.DirectoryInfo = My.Computer.FileSystem.GetDirectoryInfo(directory)
' Declaration
Public Function GetDirectoryInfo( _
ByVal directory As String _
) As System.IO.DirectoryInfo

Parameters
directory
String. Path of directory. Required.
Return Value
DirectoryInfo
Exceptions
The following conditions may cause an exception:
The directory path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it
contains invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The directory path is not valid because it is Nothing (ArgumentNullException).
The directory path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the directory path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the directory path (SecurityException).
Remarks
If the directory does not exist, an exception is not thrown until the first time a property on the DirectoryInfo object is accessed.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.GetDirectoryInfo method.
To See
Determine when a directory was created How to: Determine a Directory's Creation Time in Visual Basic

Determine whether a directory is read-only How to: Determine if a Directory is Read-Only in Visual Basic
Example
This example gets a DirectoryInfo object for the directory C:\Documents and Settings and displays the directory's creation
time, last access time, and last write time.
VB
Dim getInfo As System.IO.DirectoryInfo
getInfo = My.Computer.FileSystem.GetDirectoryInfo _
(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
MsgBox("The directory was created at " & getInfo.CreationTime)
MsgBox("The directory was last accessed at " & getInfo.LastAccessTime)
MsgBox("The directory was last written to at " & getInfo.LastWriteTime)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
System.IO.DirectoryInfo
GetDirectoryInfo
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.GetDriveInfo Method
Returns a DriveInfo object for the specified drive.

' Usage
Dim value As System.IO.DriveInfo = My.Computer.FileSystem.GetDriveInfo(drive)
' Declaration
Public Function GetDriveInfo( _
ByVal drive As String _
) As System.IO.DriveInfo

Parameters
drive
String. Drive to be examined. Required.
Return Value
DriveInfo
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
Remarks
The DriveInfo class models a drive and provides methods and properties to query for drive information. Use DriveInfo to
determine what drives are available, and what type of drives they are. You can also query the property to determine the
capacity and available free space on the drive.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.GetDriveInfo method.
To See
Determine a drive's volume label How to: Determine a Drive's Volume Label in Visual Basic

Determine a drive's type How to: Determine a Drive's Type in Visual Basic

Determine a drive's total space How to: Determine a Drive's Total Space in Visual Basic

Determine a drive's physical free space How to: Determine a Drive's Physical Free Space in Visual Basic

Determine a drive's root folder How to: Determine a Drive's Root Directory in Visual Basic
Example
This example obtains a DriveInfo object for the C drive and uses it to display information about the drive.
VB
Dim getInfo As System.IO.DriveInfo
getInfo = My.Computer.FileSystem.GetDriveInfo("C:\")
MsgBox("The drive's type is " & getInfo.DriveType)
MsgBox("The drive has " & getInfo.TotalFreeSpace & " bytes free.")

For information on the different drive types, see DriveType.


Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
System.IO.DriveInfo
GetDriveInfo
DriveType
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.GetFileInfo Method
Returns a FileInfo object for the specified file.

' Usage
Dim value As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(file)
' Declaration
Public Function GetFileInfo( _
ByVal file As String _
) As System.IO.FileInfo

Parameters
file
String. Name and path of the file. Required.
Return Value
FileInfo
Exceptions
The following conditions may cause an exception:
The path name is malformed. For example, it contains invalid characters or is only white space (ArgumentException).
The file name has a trailing slash mark (ArgumentException).
The file does not exist or is Nothing (ArgumentNullException).
The path contains a colon in the middle of the string (NotSupportedException).
The path is too long (PathTooLongException).
The user lacks necessary permissions (SecurityException).
The user lacks ACL (access control list) access to the file (UnauthorizedAccessException).
Remarks
An exception is not thrown if the file does not exist; rather, it will be thrown the first time the object's properties are accessed.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.GetFileInfo method.
To See
To get information about a file How to: Get Information About a File in Visual Basic

Determine a file's name and path How to: Parse File Paths in Visual Basic
Example
This example retrieves a System.IO.FileInfo object for the file MyLogFile.log and uses it to report the file's full name, last
access time, and length.
VB
Dim information As System.IO.FileInfo
information = My.Computer.FileSystem.GetFileInfo("C:\MyLogFile.log")
MsgBox("The file's full name is " & information.FullName & ".")
MsgBox("Last access time is " & information.LastAccessTime & ".")
MsgBox("The length is " & information.Length & ".")

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
My.Computer.FileSystem Object
System.IO.FileInfo
Microsoft.VisualBasic.FileIO.FileSystem.GetFileInfo(System.String)
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.GetFiles Method
Returns a read-only collection of strings representing the names of files within a directory.

' Usage
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.Fil
eSystem.GetFiles(directory)
Dim value As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.Fil
eSystem.GetFiles(directory ,searchType ,wildcards)
' Declaration
Public Function GetFiles( _
ByVal directory As String _
) As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
' -or-
Public Function GetFiles( _
ByVal directory As String, _
ByVal searchType As SearchOption, _
ByVal wildcards As String() _
) As System.Collections.ObjectModel.ReadOnlyCollection(Of String)

Parameters
directory
String. Directory to be searched. Required.
searchType
SearchOption Enumeration. Whether to include subfolders. Default is SearchOption.SearchTopLevelOnly. Required.
wildcards
String. Pattern to be matched. Required.
Return Value
Read-only collection of strings.
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
directory does not exist (DirectoryNotFoundException).
directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user lacks necessary permissions (UnauthorizedAccessException).
Remarks
An empty collection is returned if no files matching the specified pattern are found.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.GetFiles method.
To See
Get the collection of files in a directory How to: Get the Collection of Files in a Directory in Visual Basic

Find files with a specific pattern in a directory How to: Find Files with a Specific Pattern in Visual Basic
Example
The following example returns all files in the directory and adds them to ListBox1.

VB
For Each foundFile As String In My.Computer.FileSystem.GetFiles _
(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
ListBox1.Items.Add(foundFile)
Next

This example requires that you have a ListBox named ListBox1 on your form.
This example returns all files in the directory with the extension .dll and adds them to ListBox1.

VB
For Each foundFile As String In My.Computer.FileSystem.GetFiles _
(My.Computer.FileSystem.SpecialDirectories.MyDocuments, True, "*.dll")
ListBox1.Items.Add(foundFile)
Next

This example requires that you have a ListBox named ListBox1 on your form.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Find Files with a Specific Pattern in Visual Basic
How to: Get the Collection of Files in a Directory in Visual Basic
Reference
My.Computer.FileSystem Object
SearchOption Enumeration
System.Collections.ObjectModel.ReadOnlyCollection
Microsoft.VisualBasic.FileIO.FileSystem.GetFiles
Visual Basic Language Reference

My.Computer.FileSystem.GetName Method
Parses the file name out of the path provided.

' Usage
Dim value As String = My.Computer.FileSystem.GetFileName(path)
' Declaration
Public Function GetFileName( _
ByVal path As String _
) As String

Parameters
path
Required. Path to be parsed. String.
Return Value
String.
Exceptions
This method throws no exceptions.
Remarks
This is a string operation; the FileSystem is not examined.
The GetName method ignores a slash mark occurring at the end of the path.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.GetFileName method.
To See
Parse a file path How to: Parse File Paths in Visual Basic
Example
The following example parses a file path and returns the name of the file.
VB
MsgBox("The filename is: " & _
My.Computer.FileSystem.GetName("C:\testdirectory\testfile"))

Replace the path C:\Testdirectory\Testfile with the path you wish to parse.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes


Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer.FileSystem Object
GetFileName
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.GetParentPath Method
Returns the parent path of the provided path.

' Usage
Dim value As String = My.Computer.FileSystem.GetParentPath(path)
' Declaration
Public Function GetParentPath( _
ByVal path As String _
) As String

Parameters
path
String. Path to be examined. Required.
Return Value
String.
Exceptions
The following conditions may cause an exception to be thrown:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
Path does not have a parent path because it is a root path (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
Remarks
This is a string operation; the file system is not examined.
Example
This example gets the parent path for C:\Backups\Tmp\Test.

VB
Dim strPath As String
strPath = My.Computer.FileSystem.GetParentPath("C:\backups\tmp\test")
MsgBox(strPath)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes


Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Parse File Paths in Visual Basic
Reference
My.Computer.FileSystem Object
GetParentPath
Other Resources
File, Directory, and Drive Properties in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.GetTempFileName Method
Creates a uniquely named zero-byte temporary file on disk and returns the full path of that file.

' Usage
Dim value As String = My.Computer.FileSystem.GetTempFileName()
' Declaration
Public Function GetTempFileName() As String

Return Value
String containing the full path of the temporary file.
Remarks
This method can be used to create a temporary file.
Example
This example creates a temp file and returns its path.
VB
MsgBox("The file is located at " & _
My.Computer.FileSystem.GetTempFileName)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
Microsoft.VisualBasic.FileIO.FileSystem.GetTempFileName
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.MoveDirectory Method
Moves a directory from one location to another.

' Usage
My.Computer.FileSystem.MoveDirectory(sourceDirectoryName ,destinationDirectoryName)
My.Computer.FileSystem.MoveDirectory(sourceDirectoryName ,destinationDirectoryName ,overwri
te)
My.Computer.FileSystem.MoveDirectory(sourceDirectoryName ,destinationDirectoryName ,showUI)
My.Computer.FileSystem.MoveDirectory(sourceDirectoryName ,destinationDirectoryName ,showUI
,onUserCancel)

' Declaration
Public Sub MoveDirectory( _
ByVal sourceDirectoryName As String, _
ByVal destinationDirectoryName As String _
)
' -or-
Public Sub MoveDirectory( _
ByVal sourceDirectoryName As String, _
ByVal destinationDirectoryName As String, _
ByVal overwrite As Boolean _
)
' -or-
Public Sub MoveDirectory( _
ByVal sourceDirectoryName As String, _
ByVal destinationDirectoryName As String, _
ByVal showUI As UIOption _
)
' -or-
Public Sub MoveDirectory( _
ByVal sourceDirectoryName As String, _
ByVal destinationDirectoryName As String, _
ByVal showUI As UIOption, _
ByVal onUserCancel As UICancelOption _
)

Parameters
sourceDirectoryName
String. Path of the directory to be moved. Required.
destinationDirectoryName
String. Path of the directory to which the source directory is being moved. Required.
overwrite
Boolean. Specifies whether existing directories should be overwritten. Default is False. Required.
showUI
UIOption. Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs. Required.
onUserCancel
UICancelOption Enumeration. Specifies whether or not an exception is thrown when the user cancels the operation. Default is
UICancelOption.ThrowException. Required.
Exceptions
The following conditions may cause an exception:
The path is a zero-length string, contains only white space, contains invalid characters, or is a device path (starts with \\.\)
(ArgumentException).
The path is Nothing (ArgumentNullException).
The source is invalid (DirectoryNotFoundException).
The source is a root directory (IOException).
The combined path points to an existing file (IOException).
The source path and the target path are the same (IOException).
The file already exists and overwrite is set to False (IOException).
onUserCancel is set to ThrowException and a subdirectory of the file cannot be copied (IOException).
The operation is cyclic (InvalidOperationException).
A file or directory name in the path contains a colon (:) (NotSupportedException).
UICancelOption is set to ThrowException, and the user cancels the operation, or the operation cannot be
completed(OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
UICancelOption is set to ThrowException, and the user lacks necessary permissions (SecurityException).
The user does not have permission to modify the file (UnauthorizedAccessException).
Remarks
If an attempt is made to move a directory inside a directory that does not exist, the target structure will be created.
Tasks
The following table lists an example of a task involving the My.Computer.FileSystem.MoveDirectory method.
To See
Move a directory How to: Move a Directory in Visual Basic
Example
This example moves Directory1 inside Directory2.

VB
My.Computer.FileSystem.MoveDirectory("C:\Directory1", "C:\Directory2")

This example moves Directory1 inside Directory2, overwriting the directory if it already exists.

VB
My.Computer.FileSystem.MoveDirectory("C:\Directory1", "C:\Directory2", _
True)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes


Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permissions may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration:
SafeSubWindows.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
UIOption Enumeration
UICancelOption Enumeration
My.Computer.FileSystem.MoveFile Method
My.Computer.FileSystem.CopyDirectory Method
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.MoveFile Method
Moves a file to a new location.

' Usage
My.Computer.FileSystem.MoveFile(sourceFileName ,destinationFileName)
My.Computer.FileSystem.MoveFile(sourceFileName ,destinationFileName ,overwrite)
My.Computer.FileSystem.MoveFile(sourceFileName ,destinationFileName ,showUI)
My.Computer.FileSystem.MoveFile(sourceFileName ,destinationFileName ,showUI ,onUserCancel)
' Declaration
Public Sub MoveFile( _
ByVal sourceFileName As String, _
ByVal destinationFileName As String _
)
' -or-
Public Sub MoveFile( _
ByVal sourceFileName As String, _
ByVal destinationFileName As String, _
ByVal overwrite As Boolean _
)
' -or-
Public Sub MoveFile( _
ByVal sourceFileName As String, _
ByVal destinationFileName As String, _
ByVal showUI As UIOption _
)
' -or-
Public Sub MoveFile( _
ByVal sourceFileName As String, _
ByVal destinationFileName As String, _
ByVal showUI As UIOption, _
ByVal onUserCancel As UICancelOption _
)

Parameters
sourceFileName
String. Path of the file to be moved. Required.
destinationFileName
String. Path of the directory into which the file should be moved. Required.
overwrite
Boolean. Specifies whether to overwrite existing files. Default is False. Required.
showUI
UIOption Enumeration. Specifies whether to visually track the operation's progress. Default is UIOption.OnlyErrorDialogs.
Required.
onUserCancel
UICancelOption Enumeration. Specifies whether or not an exception is thrown when the user cancels the operation. Default is
UICancelOption.ThrowException. Required.
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The file name ends with a backslash (\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
destinationFileName is Nothing or an empty string (ArgumentNullException).
The source file is not valid or does not exist (FileNotFoundException).
The combined path points to an existing directory, the destination file exists and overwrite is set to False, a file in the
target directory with the same name is in use, or the user does not have sufficient permissions to access the file
(IOException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
onUserCancel is set to ThrowException, and either the user has cancelled the operation or an unspecified I/O error
occurs (OperationCanceledException).
The path exceeds the system-defined maximum length (PathTooLongException).
The user lacks necessary permissions to view the path (SecurityException).
The user does not have required permission (UnauthorizedAccessException).
Remarks
If the target structure does not exist, it is created.
The MoveFile method preserves ACEs (Access Control Entries) only when moving the file within the same volume. This
includes inherited ACEs, which become direct ACEs when moved (direct ACEs take precedence over inherited ACEs). If a file is
moved between volumes, ACEs will not be copied.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.MoveFile method.
To See
Move a file How to: Move a File in Visual Basic

Move a collection of files How to: Move a Collection of Files in Visual Basic

Move the contents of a directory How to: Move the Contents of a Directory in Visual Basic
Example
This example moves the file Test.txt from TestDir1 to TestDir2.

VB
My.Computer.FileSystem.MoveFile("C:\TestDir1\test.txt", "C:\TestDir2\test.txt")

This example moves the file Test.txt from TestDir1 to TestDir2 and renames it Test2.txt.

VB
My.Computer.FileSystem.MoveFile("C:\TestDir1\test.txt", "C:\TestDir2\test2.txt")

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes


Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permissions may be necessary:
Permission Description
EnvironmentPermission Controls the ability to access all environment variables. Associated enumeration: Unrestricted.

FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

RegistryPermission Controls the ability to access registry variables. Associated enumeration: Unrestricted.

UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration:
SafeSubWindows.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
UIOption Enumeration
UICancelOption Enumeration
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.OpenTextFieldParser Method
The OpenTextFieldParser method allows you to create a TextFieldParser Object, which provides a way to easily and efficiently
parse structured text files, such as logs. The TextFieldParser object can be used to read both delimited and fixed-width files.

' Usage
Dim value As TextFieldParser = My.Computer.FileSystem.OpenTextFieldParser(file)
Dim value As TextFieldParser = My.Computer.FileSystem.OpenTextFieldParser(file ,delimiters)
Dim value As TextFieldParser = My.Computer.FileSystem.OpenTextFieldParser(file ,fieldWidths
)
' Declaration
Public Function OpenTextFieldParser( _
ByVal file As String _
) As TextFieldParser
' -or-
Public Function OpenTextFieldParser( _
ByVal file As String, _
ByVal delimiters As String() _
) As TextFieldParser
' -or-
Public Function OpenTextFieldParser( _
ByVal file As String, _
ByVal fieldWidths As Integer() _
) As TextFieldParser

Parameters
file
String. The file to be opened with the TextFieldParser. Required.
delimiters
String(). Delimiters for the fields. Required.
fieldWidths
Integer(). Widths of the fields. Required.
Return Value
TextFieldParser
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The file name ends with a trailing slash (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
Specified file does not exist (FileNotFoundException).
Specified file is in use (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line
causing the exception, while the TextFieldParser.ErrorLine Property is assigned the text contained in the line.
The user does not have sufficient permissions to access the file (UnauthorizedAccessException).
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.OpenTextFieldParser method.
To See
Read from a delimited text file How to: Read From Comma-Delimited Text Files in Visual Basic

Read from a fixed-width text file How to: Read From Fixed-width Text Files in Visual Basic

Read from a text file with multiple formats How to: Read From Text Files with Multiple Formats in Visual Basic
Example
This example opens the TextFieldParser reader and uses it to read from C:\TestFolder1\Test1.txt.
VB
Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser
reader = My.Computer.FileSystem.OpenTextFieldParser _
("C:\TestFolder1\test1.txt")
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
reader.delimiters = New String() {","}
Dim currentRow As String()
While Not reader.EndOfData
Try
currentRow = reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permissions may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

SecurityPermission Describes a set of security permissions applied to code. Associated enumeration: ControlEvidence.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Read From Text Files in Visual Basic
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Reference
My.Computer.FileSystem Object
TextFieldParser Object
OpenTextFieldParser
Concepts
Parsing Text Files with the TextFieldParser Object
Other Resources
Reading from Files in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.OpenTextFileReader Method
Opens a StreamReader.

' Usage
Dim value As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(file)
Dim value As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(file ,encod
ing)
' Declaration
Public Function OpenTextFileReader( _
ByVal file As String _
) As System.IO.StreamReader
' -or-
Public Function OpenTextFileReader( _
ByVal file As String, _
ByVal encoding As System.Text.Encoding _
) As System.IO.StreamReader

Parameters
file
String. File to be read. Required.
encoding
Encoding. Default is UTF8. Required.
Return Value
StreamReader
Exceptions
The following conditions may create an exception:
The file name ends with a backslash (\) (ArgumentException).
The specified file cannot be found (FileNotFoundException).
The user lacks necessary permissions to read from the file (SecurityException).
Remarks
Only text files can be read with a StreamReader.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.OpenTextFileReader method.
To See
Open a file with a StreamReader How to: Read Text from Files with a StreamReader (Visual Basic)
Example
This example opens the file Testfile.txt, reads a line from it, and displays the line in a MessageBox.
VB
Dim fileReader As System.IO.StreamReader
fileReader = _
My.Computer.FileSystem.OpenTextFileReader("C:\\testfile.txt")
Dim stringReader As String
stringReader = fileReader.ReadLine()
MsgBox("The first line of the file is " & stringReader)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Read Text from Files with a StreamReader (Visual Basic)
Reference
My.Computer.FileSystem Object
System.Text.Encoding
System.IO.StreamReader
Microsoft.VisualBasic.FileIO.FileSystem.OpenTextFileReader
Other Resources
Reading from Files in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.OpenTextFileWriter Method
Opens a StreamWriter.

' Usage
Dim value As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(file ,appen
d)
Dim value As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(file ,appen
d ,encoding)
' Declaration
Public Function OpenTextFileWriter( _
ByVal file As String, _
ByVal append As Boolean _
) As System.IO.StreamWriter
' -or-
Public Function OpenTextFileWriter( _
ByVal file As String, _
ByVal append As Boolean, _
ByVal encoding As System.Text.Encoding _
) As System.IO.StreamWriter

Parameters
file
String. File to be written to. Required.
append
Boolean. Specifies whether to append to or overwrite information in the file. Default is False. Required.
encoding
Encoding. Encoding to be used in writing to the file. Default is UTF8. Required.
Return Value
StreamWriter
Exceptions
The following condition may cause an exception to be thrown:
The file name ends with a trailing slash (ArgumentException).
Tasks
The following table lists an example of a task involving the My.Computer.FileSystem.OpenTextFileWriter method.
To See
Write text to a file with a StreamWriter How to: Write Text to Files with a StreamWriter in Visual Basic
Example
This example opens a StreamWriter with the My.Computer.FileSystem.OpenTextFileWriter method and uses it to write a
string to a text file with the WriteLine method of the StreamWriter class.
VB
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", True)
file.WriteLine("Here is the first string.")
file.Close()

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Write Text to Files with a StreamWriter in Visual Basic
Reference
My.Computer.FileSystem Object
System.Text.Encoding
System.IO.StreamWriter
Microsoft.VisualBasic.FileIO.FileSystem.OpenTextFileWriter
Visual Basic Language Reference

My.Computer.FileSystem.ReadAllBytes Method
Returns the contents of a file as a byte array.

' Usage
Dim value As Byte() = My.Computer.FileSystem.ReadAllBytes(file)
' Declaration
Public Function ReadAllBytes( _
ByVal file As String _
) As Byte()

Parameters
file
String. File to be read. Required.
Return Value
Byte array containing the contents of the file.
Exceptions
The following conditions may cause an exception to be thrown:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The file name ends with a trailing slash (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The file does not exist (FileNotFoundException).
The file is in use by another process or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
There is not enough memory to write the string to buffer (OutOfMemoryException).
The user lacks necessary permissions to view the path (SecurityException).
Remarks
The ReadAllBytes method of the My.Computer.FileSystem object allows you to read from a binary file. The contents of the
file are returned as a byte array.
Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a
Visual Basic source file. Verify all inputs before using the data in your application.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.ReadAllBytes method.
To See
Read from a binary file How to: Read From Binary Files in Visual Basic
Example
This example reads from the file C:/Documents and Settings/selfportrait.jpg.

VB
My.Computer.FileSystem.ReadAllBytes _
("C:/Documents and Settings/selfportrait.jpg")
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
ReadAllBytes
Other Resources
Reading from Files in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.ReadAllText Method
Returns the contents of a text file as a String.

' Usage
Dim value As String = My.Computer.FileSystem.ReadAllText(file)
Dim value As String = My.Computer.FileSystem.ReadAllText(file ,encoding)
' Declaration
Public Function ReadAllText( _
ByVal file As String _
) As String
' -or-
Public Function ReadAllText( _
ByVal file As String, _
ByVal encoding As System.Text.Encoding _
) As String

Parameters
file
String. Name and path of the file to read. Required.
encoding
System.Text.Encoding. Character encoding to use in reading the file. Required. Default is UTF-8.
Return Value
String containing the contents of the file.
Exceptions
The contents of the file may not be what is expected, and methods to read from the file may fail.
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The file name ends with a trailing slash (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The file does not exist (FileNotFoundException).
The file is in use by another process, or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
There is not enough memory to write the string to buffer (OutOfMemoryException).
The user lacks necessary permissions to view the path (SecurityException).
Remarks
The ReadAllText method of the My.Computer.FileSystem object allows you to read from a text file. The contents of the file
are returned as a string.
The file encoding can be specified if the contents of the file are in an encoding such as ASCII or UTF-8. If you are reading from a
file with extended characters, you need to specify the file encoding.
Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a
Visual Basic source file. Verify all inputs before using the data in your application.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.ReadAllText method.
To See
Read from a text file How to: Read From Text Files in Visual Basic
Example
This example reads the contents of Test.txt into a string and then displays it in a message box.
VB
Dim reader As String
reader = My.Computer.FileSystem.ReadAllText("C:\test.txt")
MsgBox(reader)

This example reads the contents of the ASCII file Test.txt into a string and then displays it in a message box.
VB
Dim reader As String
reader = My.Computer.FileSystem.ReadAllText("C:\test.txt", _
System.Text.Encoding.ASCII)
MsgBox(reader)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Read Text from Files with a StreamReader (Visual Basic)
Troubleshooting: Reading from and Writing to Text Files
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
My.Computer.FileSystem Object
System.Text.Encoding
Microsoft.VisualBasic.FileIO.FileSystem.ReadAllText
StreamReader
Concepts
File Encodings
Other Resources
Reading from Files in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.RenameDirectory Method
Renames a directory.

' Usage
My.Computer.FileSystem.RenameDirectory(directory ,newName)
' Declaration
Public Sub RenameDirectory( _
ByVal directory As String, _
ByVal newName As String _
)

Parameters
directory
String. Path and name of directory to be renamed. Required.
newName
String. New name for directory. Required.
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The newName parameter contains path information (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The newName parameter is Nothing or an empty string (ArgumentNullException).
The source directory is not valid or does not exist (DirectoryNotFoundException).
There is an existing file or directory with the name specified in newName (IOException).
The directory is a root directory (IOException).
The path exceeds 248 characters (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user does not have required permission (UnauthorizedAccessException).
Remarks
This method cannot be used to move a directory; use the MoveDirectory method to move and rename the directory.
Tasks
The following table lists an example of a task involving the My.Computer.FileSystem.RenameDirectory method.
To See
Rename a directory How to: Rename a Directory in Visual Basic
Example
This example renames the Test directory to SecondTest.

VB
My.Computer.FileSystem.RenameDirectory("C:MyDocuments\Test", "SecondTest")
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Parse File Paths in Visual Basic
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.MoveDirectory Method
RenameDirectory
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.RenameFile Method
Renames a file.

' Usage
My.Computer.FileSystem.RenameFile(file ,newName)
' Declaration
Public Sub RenameFile( _
ByVal file As String, _
ByVal newName As String _
)

Parameters
file
String. File to be renamed. Required.
newName
String. New name of file. Required.
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The newName parameter contains path information or ends with a backslash (\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The newName parameter is Nothing or an empty string (ArgumentNullException).
The source file is not valid or does not exist (FileNotFoundException).
There is an existing file or directory with the name specified in newName (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
The user does not have the required permission (UnauthorizedAccessException).
Remarks
This method cannot be used to move a file; use the My.Computer.FileSystem.MoveFile Method to move and rename the file.
Tasks
The following table lists an example of a task involving the My.Computer.FileSystem.RenameFile method.
To See
Rename a file How to: Rename a File in Visual Basic
Example
This example renames the file Test.txt to SecondTest.txt.
VB
My.Computer.FileSystem.RenameFile("C:\Test.txt", "SecondTest.txt")

Change "C:\Test.txt" to the path and file name of the file that you want to rename.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(System.String,System.String)
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.SpecialDirectories Property
Gets an object that provides properties for accessing commonly referenced directories.

' Usage
Dim value As Microsoft.VisualBasic.MyServices.SpecialDirectoriesProxy = My.Computer.FileSys
tem.SpecialDirectories
' Declaration
Public ReadOnly Property SpecialDirectories As MyServices.SpecialDirectoriesProxy

Return Value
This property returns the My.Computer.FileSystem.SpecialDirectories Object for the computer.
Remarks
This property provides easy access to the My.Computer.FileSystem.SpecialDirectories Object.
Example
This example returns the file path for the user's Desktop directory and displays it.
VB
Dim filePath As String
filePath = My.Computer.FileSystem.SpecialDirectories.Desktop
MsgBox(filePath)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer.FileSystem Object
My.Computer.FileSystem.SpecialDirectories Object
Visual Basic Language Reference

My.Computer.FileSystem.WriteAllBytes Method
Writes data to a binary file.

' Usage
My.Computer.FileSystem.WriteAllBytes(file ,data ,append)
' Declaration
Public Sub WriteAllBytes( _
ByVal file As String, _
ByVal data As Byte(), _
ByVal append As Boolean _
)

Parameters
file
String. Path and name of the file to be written to. Required.
data
Byte. Data to be written to the file. Required.
append
Boolean. Whether to append or overwrite data. Default is False. Required.
Exceptions
The following conditions may create an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters; or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing or ends with a backslash (\) (ArgumentNullException).
The file parameter points to a path that does not exist (FileNotFoundException or DirectoryNotFoundException).
The file is in use by another process or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
Remarks
If the append parameter is True, it appends the data to the file; otherwise data in the file is overwritten.
If the specified path, excluding the file name, is not valid, a DirectoryNotFoundException exception will be thrown. If the
path is valid but the file does not exist, the file is created.
Tasks
The following table lists an example of a task involving the My.Computer.FileSystem.WriteAllBytes method.
To See
Write to a binary file How to: Write to Binary Files in Visual Basic
Example
This example appends the data array CustomerData to the file CollectedData.

VB
My.Computer.FileSystem.WriteAllBytes _
("C:\MyDocuments\CustomerData", CustomerData, True)
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Write to Binary Files in Visual Basic
Reference
My.Computer.FileSystem Object
WriteAllBytes
Other Resources
Writing to Files in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.WriteAllText Method
Writes text to a file.

' Usage
My.Computer.FileSystem.WriteAllText(file ,text ,append)
My.Computer.FileSystem.WriteAllText(file ,text ,append ,encoding)
' Declaration
Public Sub WriteAllText( _
ByVal file As String, _
ByVal text As String, _
ByVal append As Boolean _
)
' -or-
Public Sub WriteAllText( _
ByVal file As String, _
ByVal text As String, _
ByVal append As Boolean, _
ByVal encoding As System.Text.Encoding _
)

Parameters
file
String. File to be written to. Required.
text
String. Text to be written to file. Required.
append
Boolean. Whether to append text or overwrite existing text. Default is False. Required.
encoding
Encoding. What encoding to use when writing to file. Required. Default is UTF-8.
Exceptions
The following conditions may cause an exception:
The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; it contains
invalid characters, ends with a trailing slash, or is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
file points to a path that does not exist (FileNotFoundException or DirectoryNotFoundException).
The file is in use by another process, or an I/O error occurs (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException).
If you are running in a partial-trust context, the code might throw an exception due to insufficient privileges. For more
information, see Code Access Security Basics.
Remarks
When no encoding is specified, UTF-8 is used. The byte order mark (BOM) for the encoding is written to the file unless you
specify System.Text.Encoding.Default, which uses the system's current ANSI code page.
If the specified file does not exist, it is created.
If append is set to False, existing text in the file is overwritten.
If the specified encoding does not match the existing encoding of the file, the specified coding is ignored.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.WriteAllText method.
To See
Write text to a file How to: Write Text to Files in Visual Basic

Append text to a file How to: Append to Text Files in Visual Basic
Example
This example writes the line "This is new text to be added." to the file Test.txt, overwriting any existing text in the file.

VB
My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt", _
"This is new text to be added.", False)

This example writes the names of the files in the Documents and Settings folder to FileList.txt, inserting a carriage return
between each for better readability.
VB
For Each foundFile As String In _
My.Computer.FileSystem.GetFiles("C:\Documents and Settings")
foundFile = foundFile & vbCrLf
My.Computer.FileSystem.WriteAllText _
("C:\Documents and Settings\FileList.txt", foundFile, True)
Next

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: FileSystemProxy (provides access to FileSystem)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem Object
System.Text.Encoding
Microsoft.VisualBasic.FileIO.FileSystem.WriteAllText
Other Resources
Writing to Files in Visual Basic
Visual Basic Language Reference

My.Computer.FileSystem.SpecialDirectories Object
Provides properties for accessing commonly referenced directories.
Remarks
If the path for the referenced directory is empty, usually due to the operating system not supporting the directory, a
DirectoryNotFoundException exception is thrown.
No backslash (\) appears at the end of the path.
Tasks
The following table lists examples of tasks involving the My.Computer.FileSystem.SpecialDirectories object.
To See
Read from the MyDocuments directory How to: Retrieve the Contents of the My Documents Directory in Visual Basic
Example
This example returns the filePath for the user's Desktop directory and displays it.
VB
Dim filePath As String
filePath = My.Computer.FileSystem.SpecialDirectories.Desktop
MsgBox(filePath)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object Members
My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData Property
My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData Property
My.Computer.FileSystem.SpecialDirectories.Desktop Property
My.Computer.FileSystem.SpecialDirectories.MyDocuments Property
My.Computer.FileSystem.SpecialDirectories.MyMusic Property
My.Computer.FileSystem.SpecialDirectories.MyPictures Property
My.Computer.FileSystem.SpecialDirectories.Programs Property
My.Computer.FileSystem.SpecialDirectories.Temp Property
My.Computer.FileSystem Object
Microsoft.VisualBasic.FileIO.SpecialDirectories
Visual Basic Language Reference

My.Computer.FileSystem.SpecialDirectories Object Members


The My.Computer.FileSystem.SpecialDirectories Property object provides properties for accessing commonly referenced
directories
Properties
AllUsersApplicationData Read-only String representing the pathname pointing to the All Users Application Data directory.

CurrentUserApplicationData Read-only String representing the pathname pointing to the current user's Application Data direc
tory.

Desktop Read-only String representing the pathname pointing to the user's Desktop directory.

MyDocuments Read-only String representing the pathname pointing to the user's MyDocuments directory.

MyMusic Read-only String representing the pathname pointing to the user's MyMusic directory.

MyPictures Read-only String representing the pathname pointing to the user's MyPictures directory.

Programs Read-only String representing the pathname pointing to the user's Programs directory.

Temp Read-only String representing the pathname pointing to the user's Temp directory.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Visual Basic Language Reference

My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData
Property
Gets a path for storing application data that is shared among all users on the computer.

' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData
' Declaration
Public ReadOnly Property AllUsersApplicationData As String

Return Value
String.
Exceptions
The following condition may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object contains paths to commonly referenced directories.
If the path does not exist, it is created with the following format: BasePath\CompanyName\ProductName\Version
A typical BasePath in Windows XP is C:\Documents and Settings\All Users\Application Data. The CompanyName, ProductName, and
Version can be obtained from the My.Application.Info.CompanyName, My.Application.Info.ProductName, and My.Application.Info.Version
properties.
Note
If the Company and Product names are not specified in the Assembly Information dialog box, the CompanyName\ProductName in
the path are replaced with the assembly name. For more information on setting assembly information names, see
How to: Specify Assembly Information.

Example
This example displays the path for shared application data in a MessageBox.
VB
MsgBox _
(My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes


Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.AllUsersApplicationData
Visual Basic Language Reference

My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData
Property
Gets a path for storing the current user's application data.

' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData
' Declaration
Public ReadOnly Property CurrentUserApplicationData As String

Return Value
String.
Exceptions
The following condition may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object contains paths to commonly referenced directories.
If the path does not exist, it is created with the following format: BasePath\CompanyName\ProductName\Version
A typical BasePath in Windows XP is C:\Documents and Settings\username\Application Data. The CompanyName, ProductName, and Version
can be obtained from the My.Application.Info.CompanyName, My.Application.Info.ProductName, and My.Application.Info.Version properties.
Note
If the Company and Product names are not specified in the Assembly Information dialog box, the CompanyName\ProductName in the pat
h are replaced with the assembly name. For more information on setting assembly information names, see
How to: Specify Assembly Information.

Data stored in this path is part of a user profile that is enabled for roaming. A roaming user works on more than one computer in a network. The
user profile for a roaming user is kept on a server on the network and is loaded onto a system when the user logs on. For a user profile to be
eligible for roaming, the operating system must support roaming profiles and the feature must be enabled.
Example
This example displays the path for storing the current user's application data in a MessageBox.
VB
MsgBox(My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes


Web Site Yes
Permissions
The following permission is required:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.CurrentUserApplicationData
Visual Basic Language Reference

My.Computer.FileSystem.SpecialDirectories.Desktop Property
Gets a path name pointing to the Desktop directory.

' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.Desktop
' Declaration
Public ReadOnly Property Desktop As String

Return Value
String.
Exceptions
The following condition may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object contains paths to commonly referenced directories.
Example
This example displays the path for the Desktop directory in a MessageBox.
VB
MsgBox(My.Computer.FileSystem.SpecialDirectories.Desktop)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permission is required:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.Desktop
Visual Basic Language Reference

My.Computer.FileSystem.SpecialDirectories.MyDocuments
Property
Gets a path name pointing to the My Documents directory.

' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
' Declaration
Public ReadOnly Property MyDocuments As String

Return Value
String.
Exceptions
The following condition may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object contains paths to commonly referenced directories.
Example
This example displays the path for the My Documents directory in a MessageBox.
VB
MsgBox(My.Computer.FileSystem.SpecialDirectories.MyDocuments)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permission is required:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.MyDocuments
Visual Basic Language Reference

My.Computer.FileSystem.SpecialDirectories.MyMusic Property
Gets a path name pointing to the My Music directory.

' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.MyMusic
' Declaration
Public ReadOnly Property MyMusic As String

Return Value
String.
Exceptions
The following condition may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object contains paths to commonly referenced directories.
Example
This example displays the path for the My Music directory in a MessageBox.
VB
MsgBox(My.Computer.FileSystem.SpecialDirectories.MyMusic)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permission is required:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.MyMusic
Visual Basic Language Reference

My.Computer.FileSystem.SpecialDirectories.MyPictures
Property
Gets a path name pointing to the My Pictures directory.

' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.MyPictures
' Declaration
Public ReadOnly Property MyPictures As String

Return Value
String.
Exceptions
The following condition may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object class contains paths to commonly referenced directories.
Example
This example displays the path for the My Pictures directory in a MessageBox.
VB
MsgBox(My.Computer.FileSystem.SpecialDirectories.MyPictures)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permission is required:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.MyPictures
Visual Basic Language Reference

My.Computer.FileSystem.SpecialDirectories.ProgramFiles
Property
Gets a path pointing to the Program Files directory.

' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.ProgramFiles
' Declaration
Public ReadOnly Property Programs As String

Return Value
String.
Exceptions
The following condition may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object contains paths to commonly referenced directories. The Program Files
directory contains the computer's program files.
Example
This example displays the path for the Program Files directory in a MessageBox.
VB
MsgBox(My.Computer.FileSystem.SpecialDirectories.ProgramFiles)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.ProgramFiles
Visual Basic Language Reference

My.Computer.FileSystem.SpecialDirectories.Programs Property
Gets a path name pointing to the Programs directory.

' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.Programs
' Declaration
Public ReadOnly Property Programs As String

Return Value
String.
Exceptions
The following conditions may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object contains paths to commonly referenced directories. The Programs
directory contains the user's program groups.
Example
This example displays the path for the Programs directory in a MessageBox.
VB
MsgBox(My.Computer.FileSystem.SpecialDirectories.Programs)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permission is required:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.Programs
Visual Basic Language Reference

My.Computer.FileSystem.SpecialDirectories.Temp Property
Gets a path name pointing to the system's current temporary directory.

' Usage
Dim value As String = My.Computer.FileSystem.SpecialDirectories.Temp
' Declaration
Public ReadOnly Property Temp As String

Return Value
String.
Exceptions
The following condition may cause an exception:
The path is empty, usually because the operating system does not support the directory (DirectoryNotFoundException).
Remarks
The My.Computer.FileSystem.SpecialDirectories Object contains paths to commonly referenced directories.
Example
This example displays the path for the system's current temporary directory in a MessageBox.
VB
MsgBox(My.Computer.FileSystem.SpecialDirectories.Temp)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: SpecialDirectoriesProxy (provides access to SpecialDirectories)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permissions are required:
Permission Description
EnvironmentPermission Controls access to system and user environment variables. Associated enumeration: Unrestricted.

FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.FileSystem.SpecialDirectories Object
Microsoft.VisualBasic.FileIO.SpecialDirectories.Temp
Visual Basic Language Reference

My.Computer.Info Object
Provides properties for getting information about the computer's memory, loaded assemblies, name, and operating system.
Remarks
The properties exposed by the My.Computer.Info object return information about the computer from which the application is
deployed, as determined at run time. Typically, this data differs from what was available on the development computer.
Example
This example uses the My.Computer.Info.AvailablePhysicalMemory property to display the amount of available physical
memory for the computer on which the code runs.
VB
MsgBox("Computer's available physical memory: " & _
My.Computer.Info.AvailablePhysicalMemory)

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer.Info Object Members
Visual Basic Language Reference

My.Computer.Info Object Members


The My.Computer.Info Object provides properties for getting information about the computer's memory, loaded assemblies,
name, and operating system.
Properties
AvailablePhysicalMemory Gets the total amount of free physical memory for the computer.

AvailableVirtualMemory Gets the total amount of free virtual address space available for the computer.

InstalledUICulture Gets the current UI culture installed with the operating system.

OSFullName Gets the full operating-system name.

OSPlatform Gets the platform identifier for the operating system of the computer.

OSVersion Gets the version of the operating system of the computer.

TotalPhysicalMemory Gets the total amount of physical memory for the computer.

TotalVirtualMemory Gets the total amount of virtual address space available for the computer.
See Also
Reference
My.Computer.Info Object
Visual Basic Language Reference

My.Computer.Info.AvailablePhysicalMemory Property
Gets the total amount of free physical memory for the computer.

' Usage
Dim value As ULong = My.Computer.Info.AvailablePhysicalMemory
' Declaration
Public ReadOnly Property AvailablePhysicalMemory As ULong

Return Value
A ULong containing the number of bytes of free physical memory for the computer.
Exceptions
The following condition can cause an exception:
The application cannot obtain the memory status (Win32Exception).
Remarks
The My.Computer.Info.AvailablePhysicalMemory property requires Windows XP, Windows 2000 Professional, Windows
Server 2003, or Windows 2000 Server.
Example
This example uses the My.Computer.Info.AvailablePhysicalMemory property to display the amount of available physical
memory for the computer on which the code runs.
VB
MsgBox("Computer's available physical memory: " & _
My.Computer.Info.AvailablePhysicalMemory)

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer.Info Object
My.Computer.Info.TotalPhysicalMemory Property
My.Computer.Info.AvailableVirtualMemory Property
Microsoft.VisualBasic.Devices.ComputerInfo.AvailablePhysicalMemory
Visual Basic Language Reference

My.Computer.Info.AvailableVirtualMemory Property
Gets the total amount of the computer's free virtual address space.

' Usage
Dim value As ULong = My.Computer.Info.AvailableVirtualMemory
' Declaration
Public ReadOnly Property AvailableVirtualMemory As ULong

Return Value
A ULong containing the number of bytes of the computer's free virtual address space.
Exceptions
The following condition can cause an exception:
The application cannot obtain the memory status (Win32Exception).
Remarks
The My.Computer.Info.AvailableVirtualMemory property requires Windows XP, Windows 2000 Professional, Windows
Server 2003, or Windows 2000 Server.
Example
This example uses the My.Computer.Info.AvailableVirtualMemory property to display the amount of available virtual
memory for the computer on which the code runs.
VB
MsgBox("Computer's available virtual memory: " & _
My.Computer.Info.AvailableVirtualMemory)

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer.Info Object
My.Computer.Info.TotalVirtualMemory Property
My.Computer.Info.AvailablePhysicalMemory Property
Microsoft.VisualBasic.Devices.ComputerInfo.AvailableVirtualMemory
Visual Basic Language Reference

My.Computer.Info.InstalledUICulture Property
Gets the current UI culture installed with the operating system.

' Usage
Dim value As System.Globalization.CultureInfo = My.Computer.Info.InstalledUICulture
' Declaration
Public ReadOnly Property InstalledUICulture As System.Globalization.CultureInfo

Return Value
A CultureInfo object represents the UI culture installed on the computer.
Remarks
The My.Computer.Info.InstalledUICulture property has the same behavior as the InstalledUICulture property.
In a localized operating system, such as Japanese Windows 2000 Professional, this property returns the culture of the
operating system.
Example
This example uses the My.Computer.Info.InstalledUICulture property to display the name of the operating system's UI
culture.
VB
MsgBox("Computer's UI culture name: " & _
My.Computer.Info.InstalledUICulture.DisplayName)

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer.Info Object
System.Globalization.CultureInfo
Microsoft.VisualBasic.Devices.ComputerInfo.InstalledUICulture
Visual Basic Language Reference

My.Computer.Info.OSFullName Property
Gets the full operating system name.

' Usage
Dim value As String = My.Computer.Info.OSFullName
' Declaration
Public ReadOnly Property OSFullName As String

Return Value
A String containing the operating-system name.
Exceptions
The following condition can cause an exception:
The calling code does not have full trust (SecurityException).
Remarks
This property returns detailed information about the operating system name if Windows Management Instrumentation (WMI)
is installed on the computer. Otherwise, this property returns the same string as the My.Computer.Info.OSPlatform
property, which provides less detailed information than WMI can provide.
Example
This example uses the My.Computer.Info.OSFullName property to display the name of the computer's operating system.
VB
MsgBox("Computer's operating system name: " & _
My.Computer.Info.OSFullName)

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.Info Object
My.Computer.Info.OSPlatform Property
Microsoft.VisualBasic.Devices.ComputerInfo.OSFullName
Visual Basic Language Reference

My.Computer.Info.OSPlatform Property
Gets the platform identifier for the operating system of the computer.

' Usage
Dim value As String = My.Computer.Info.OSPlatform
' Declaration
Public ReadOnly Property OSPlatform As String

Return Value
A String containing the platform identifier for the operating system of the computer, chosen from the member names of the
PlatformID enumeration.
Exceptions
The following condition can cause an exception:
The application cannot obtain the operating-system platform information (ExecutionEngineException).
Remarks
The My.Computer.Info.OSPlatform property provides functionality similar to the Platform property of the object returned by
the OSVersion property.
Example
This example uses the My.Computer.Info.OSPlatform property to display the platform of the computer's operating system.
VB
MsgBox("Computer's operating system platform: " & _
My.Computer.Info.OSPlatform)

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer.Info Object
Platform
OSVersion
Microsoft.VisualBasic.Devices.ComputerInfo.OSPlatform
Visual Basic Language Reference

My.Computer.Info.OSVersion Property
Gets the version of the computer's operating system.

' Usage
Dim value As String = My.Computer.Info.OSVersion
' Declaration
Public ReadOnly Property OSVersion As String

Return Value
A String containing the current version number of the operating system.
Exceptions
The following condition can cause an exception:
The application cannot obtain the operating-system version information (ExecutionEngineException).
Remarks
The My.Computer.Info.OSVersion property formats the version as "major.minor.build.revision".
The My.Computer.Info.OSVersion property provides functionality similar to the Version property of the object returned by
the OSVersion property.
Example
This example uses the My.Computer.Info.OSVersion property to display the version of the computer's operating system.
VB
MsgBox("Computer's operating system version: " & _
My.Computer.Info.OSVersion)

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer.Info Object
Microsoft.VisualBasic.Devices.ComputerInfo.OSVersion
Visual Basic Language Reference

My.Computer.Info.TotalPhysicalMemory Property
Gets the total amount of physical memory for the computer.

' Usage
Dim value As ULong = My.Computer.Info.TotalPhysicalMemory
' Declaration
Public ReadOnly Property TotalPhysicalMemory As ULong

Return Value
A ULong containing the number of bytes of physical memory for the computer.
Exceptions
The following condition can cause an exception:
The application cannot obtain the memory status (Win32Exception).
Remarks
The My.Computer.Info.TotalPhysicalMemory property requires Windows XP, Windows 2000 Professional, Windows Server
2003 or Windows 2000 Server.
Example
This example uses the My.Computer.Info.TotalPhysicalMemory property to display the total amount of physical memory
for the computer on which the code runs.
VB
MsgBox("Computer's available physical memory: " & _
My.Computer.Info.TotalPhysicalMemory)

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer.Info Object
My.Computer.Info.AvailablePhysicalMemory Property
My.Computer.Info.TotalVirtualMemory Property
Microsoft.VisualBasic.Devices.ComputerInfo.TotalPhysicalMemory
Visual Basic Language Reference

My.Computer.Info.TotalVirtualMemory Property
Gets the total amount of virtual address space available for the computer.

' Usage
Dim value As ULong = My.Computer.Info.TotalVirtualMemory
' Declaration
Public ReadOnly Property TotalVirtualMemory As ULong

Return Value
A ULong containing the number of bytes of virtual address space available for the computer.
Exceptions
The following condition can cause an exception:
The application cannot obtain the memory status (Win32Exception).
Remarks
The My.Computer.Info.TotalVirtualMemory property requires Windows XP, Windows 2000 Professional, Windows Server
2003 or Windows 2000 Server.
Example
This example uses the My.Computer.Info.TotalVirtualMemory property to display the total amount of virtual memory for
the computer on which the code runs.
VB
MsgBox("Computer's available virtual memory: " & _
My.Computer.Info.TotalVirtualMemory)

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: ComputerInfo
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer.Info Object
My.Computer.Info.AvailableVirtualMemory Property
My.Computer.Info.TotalPhysicalMemory Property
Microsoft.VisualBasic.Devices.ComputerInfo.TotalVirtualMemory
Visual Basic Language Reference

My.Computer.Keyboard Object
Provides properties for accessing the current state of the keyboard, such as what keys are currently pressed, and provides a
method to send keystrokes to the active window.
Remarks
The My.Computer.Keyboard object provides an interface to the computer's keyboard. The properties of the
My.Computer.Keyboard provide information about the state of several special keys. The
My.Computer.Keyboard.SendKeys method lets you send keys to the active window as if they have been typed at the
keyboard.
Task
The following table lists examples of tasks involving the My.Computer.Keyboard object.
To See
Check if CAPS LOCK is on How to: Determine If CapsLock is On in Visual Basic

Send keystrokes to an application How to: Start an Application and Send it Keystrokes (Visual Basic)
Example
This example uses the My.Computer.Keyboard.CtrlKeyDown property to determine if the computer's CTRL key is pressed.
VB
If My.Computer.Keyboard.CtrlKeyDown Then
MsgBox("CTRL key down")
Else
MsgBox("CTRL key up")
End If

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Keyboard
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
See Also
Reference
My.Computer.Keyboard Object Members
My.Computer Object
Microsoft.VisualBasic.Devices.Keyboard
Concepts
Accessing the Keyboard
Visual Basic Language Reference

My.Computer.Keyboard Object Members


The My.Computer.Keyboard Object provides properties for accessing the current state of the keyboard, such as what keys are
currently pressed, and provides a method to send keystrokes to the active window.
Properties
AltKeyDown Gets a Boolean indicating if the ALT key is down.
This property is available only for non-server applications.

CapsLock Gets a Boolean indicating if CAPS LOCK is turned on.


This property is available only for non-server applications.

CtrlKeyDown Gets a Boolean indicating if a CTRL key is down.


This property is available only for non-server applications.

NumLock Gets a Boolean indicating if NUM LOCK is turned on.


This property is available only for non-server applications.

ScrollLock Gets a Boolean indicating if SCROLL LOCK is turned on.


This property is available only for non-server applications.

ShiftKeyDown Gets a Boolean indicating if a SHIFT key is down.


This property is available only for non-server applications.
Methods
SendKeys Sends one or more keystrokes to the active window, as if typed on the keyboard.
This method is available only for non-server applications.
See Also
Reference
My.Computer.Keyboard Object
Visual Basic Language Reference

My.Computer.Keyboard.AltKeyDown Property
Gets a Boolean indicating if the ALT key is down.

' Usage
Dim value As Boolean = My.Computer.Keyboard.AltKeyDown
' Declaration
Public ReadOnly Property AltKeyDown As Boolean

Return Value
A Boolean value: True if the ALT key is down; otherwise False.
Remarks
The My.Computer.Keyboard.AltKeyDown property provides functionality similar to the ModifierKeys property.
Example
This example uses the My.Computer.Keyboard.AltKeyDown property to determine if the computer's ALT key is down.
VB
If My.Computer.Keyboard.AltKeyDown Then
MsgBox("ALT key down")
Else
MsgBox("ALT key up")
End If

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Keyboard
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Keyboard Object
ModifierKeys
Microsoft.VisualBasic.Devices.Keyboard.AltKeyDown
Visual Basic Language Reference

My.Computer.Keyboard.CapsLock Property
Gets a Boolean indicating if CAPS LOCK is turned on.

' Usage
Dim value As Boolean = My.Computer.Keyboard.CapsLock
' Declaration
Public ReadOnly Property CapsLock As Boolean

Return Value
A Boolean value: True if CAPS LOCK is turned on; otherwise False.
Remarks
Only the state of CAPS LOCK is returned.
Example
This example uses the My.Computer.Keyboard.CapsLock property to determine if the computer's CAPS LOCK is turned on.
VB
If My.Computer.Keyboard.CapsLock Then
MsgBox("CAPS LOCK on")
Else
MsgBox("CAPS LOCK off")
End If

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Keyboard
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Keyboard Object
Microsoft.VisualBasic.Devices.Keyboard.CapsLock
Visual Basic Language Reference

My.Computer.Keyboard.CtrlKeyDown Property
Gets a Boolean indicating if a CTRL key is down.

' Usage
Dim value As Boolean = My.Computer.Keyboard.CtrlKeyDown
' Declaration
Public ReadOnly Property CtrlKeyDown As Boolean

Return Value
A Boolean value. True if a CTRL key is down; otherwise False.
Remarks
The My.Computer.Keyboard.CtrlKeyDown property provides functionality similar to the ModifierKeys property.
Example
This example uses the My.Computer.Keyboard.CtrlKeyDown property to determine if the computer's CTRL key is down.
VB
If My.Computer.Keyboard.CtrlKeyDown Then
MsgBox("CTRL key down")
Else
MsgBox("CTRL key up")
End If

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Keyboard
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Keyboard Object
ModifierKeys
Microsoft.VisualBasic.Devices.Keyboard.CtrlKeyDown
Visual Basic Language Reference

My.Computer.Keyboard.NumLock Property
Gets a Boolean indicating if the NUM LOCK key is on.

' Usage
Dim value As Boolean = My.Computer.Keyboard.NumLock
' Declaration
Public ReadOnly Property NumLock As Boolean

Return Value
A Boolean value. True if NUM LOCK is on; otherwise False.
Remarks
Only the state of the NUM LOCK key is returned.
Example
This example uses the My.Computer.Keyboard.NumLock property to determine if the computer's NUM LOCK key is on.
VB
If My.Computer.Keyboard.NumLock Then
MsgBox("NUM LOCK on")
Else
MsgBox("NUM LOCK off")
End If

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Keyboard
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Keyboard Object
Microsoft.VisualBasic.Devices.Keyboard.NumLock
Visual Basic Language Reference

My.Computer.Keyboard.ScrollLock Property
Gets a Boolean indicating whether the SCROLL LOCK key is on.

' Usage
Dim value As Boolean = My.Computer.Keyboard.ScrollLock
' Declaration
Public ReadOnly Property ScrollLock As Boolean

Return Value
A Boolean value. True if SCROLL LOCK is on; otherwise False.
Remarks
Only the state of the SCROLL LOCK key is returned.
Example
This example uses the My.Computer.Keyboard.ScrollLock property to determine if the computer's SCROLL LOCK key is on.
VB
If My.Computer.Keyboard.ScrollLock Then
MsgBox("SCROLL LOCK on")
Else
MsgBox("SCROLL LOCK off")
End If

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Keyboard
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Keyboard Object
Microsoft.VisualBasic.Devices.Keyboard.ScrollLock
Visual Basic Language Reference

My.Computer.Keyboard.SendKeys Method
Sends one or more keystrokes to the active window, as if typed on the keyboard.

' Usage
My.Computer.Keyboard.SendKeys(keys)
My.Computer.Keyboard.SendKeys(keys ,wait)
' Declaration
Public Sub SendKeys( _
ByVal keys As String _
)
' -or-
Public Sub SendKeys( _
ByVal keys As String, _
ByVal wait As Boolean _
)

Parameters
keys
A String that defines the keys to send.
wait
Optional. A Boolean that specifies whether or not to wait for keystrokes to get processed before the application continues.
True by default.
Exceptions
The following condition can cause an exception:
A partial-trust situation exists in which the user lacks necessary permissions (SecurityException).
Remarks
The My.Computer.Keyboard.SendKeys method provides functionality similar to the Send and SendWait methods.
The wait argument is useful if the other application must finish before your application can continue.
Note
Because there is no managed method to activate another application, you can either use this class within the current applicati
on, manually select the window to send the keys to, or use Windows API methods, such as FindWindow and SetForegroun
dWindow, to force focus on other applications. For more information, see Walkthrough: Calling Windows APIs.

The keys argument can specify any single key or any key combined with ALT, CTRL, or SHIFT (or any combination of those
keys). Each key is represented by one or more characters, such as a for the character "a", or {ENTER} for the ENTER key.
To combine a key with SHIFT, precede the key code with + (plus sign). To combine a key with CTRL, precede the key code with ^
(caret). To combine a key with ALT, precede the key code with % (percent sign). To specify repeating keys, use the form {key
number}. You must put a space between key and number. For example, {LEFT 42} means "press the LEFT ARROW key 42
times"; {h 10} means "press 'h' 10 times."
The following table lists the codes that can be used to specify characters that are not displayed when you press the
corresponding key (such as ENTER or TAB).
Key Code
BACKSPACE {BACKSPACE} or {BS}

BREAK {BREAK}

CAPS LOCK {CAPSLOCK}


CLEAR {CLEAR}

DELETE {DELETE} or {DEL}

DOWN ARROW {DOWN}

END {END}

ENTER (numeric keypad) {ENTER}

ENTER ~

ESC {ESCAPE} or {ESC}

HELP {HELP}

HOME {HOME}

INS {INSERT}

LEFT ARROW {LEFT}

NUM LOCK {NUMLOCK}

PAGE DOWN {PGDN}

PAGE UP {PGUP}

RETURN {RETURN}

RIGHT ARROW {RIGHT}

SCROLL LOCK {SCROLLLOCK}

TAB {TAB}

UP ARROW {UP}

F1 through F15 {F1} through {F15}


Example
This example uses the My.Computer.Keyboard.SendKeys method to send keystrokes to an external application, the
Calculator application, started by the Shell function.
VB
Dim ProcID As Integer
' Start the Calculator application, and store the process id.
ProcID = Shell("CALC.EXE", AppWinStyle.NormalFocus)
' Activate the Calculator application.
AppActivate(ProcID)
' Send the keystrokes to the Calculator application.
My.Computer.Keyboard.SendKeys("22", True)
My.Computer.Keyboard.SendKeys("*", True)
My.Computer.Keyboard.SendKeys("44", True)
My.Computer.Keyboard.SendKeys("=", True)
' The result is 22 * 44 = 968.
A ArgumentException exception is raised if an application with the requested process identifier cannot be found.
The call to the Shell function requires full trust (SecurityException class).
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Keyboard
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
The following permissions may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration: AllWindows.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
Walkthrough: Calling Windows APIs
Reference
My.Computer.Keyboard Object
Send
SendWait
Microsoft.VisualBasic.Devices.Keyboard.SendKeys(System.String,System.Boolean)
Visual Basic Language Reference

My.Computer.Keyboard.ShiftKeyDown Property
Gets a Boolean indicating if a SHIFT key is down.

' Usage
Dim value As Boolean = My.Computer.Keyboard.ShiftKeyDown
' Declaration
Public ReadOnly Property ShiftKeyDown As Boolean

Return Value
A Boolean value. True if a SHIFT key is down; otherwise False.
Remarks
The My.Computer.Keyboard.ShiftKeyDown property provides functionality similar to the ModifierKeys property.
Example
This example uses the My.Computer.Keyboard.ShiftKeyDown property to determine if one of the computer's SHIFT keys is
down.
VB
If My.Computer.Keyboard.ShiftKeyDown Then
MsgBox("SHIFT key down")
Else
MsgBox("SHIFT key up")
End If

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Keyboard
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Keyboard Object
ModifierKeys
Microsoft.VisualBasic.Devices.Keyboard.ShiftKeyDown
Visual Basic Language Reference

My.Computer.Mouse Object
Provides properties for getting information about the format and configuration of the mouse installed on the local computer.
Remarks
The My.Computer.Mouse object provides a way to find information about the computer's mouse: whether the mouse
buttons are swapped, and details about the mouse wheel.
Example
This example uses the My.Computer.Mouse.WheelExists and My.Computer.Mouse.WheelScrollLines properties to
determine if the mouse has a scroll wheel and how much to scroll when it rotates.
VB
If My.Computer.Mouse.WheelExists Then
Dim lines As Integer = My.Computer.Mouse.WheelScrollLines
If lines > 0 Then
MsgBox("Application scrolls " & _
lines & " line(s) for each wheel turn.")
Else
MsgBox("Application scrolls " & _
(-lines) & " page(s) for each wheel turn.")
End If
Else
MsgBox("Mouse has no scroll wheel.")
End If

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Mouse
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
See Also
Reference
My.Computer.Mouse Object Members
My.Computer Object
Microsoft.VisualBasic.Devices.Mouse
Visual Basic Language Reference

My.Computer.Mouse Object Members


The My.Computer.Mouse Object provides properties for getting information about the format and configuration of the mouse
installed on the local computer
Properties
Property Description
ButtonsSwapped Gets a Boolean that indicates if the functionality of the left and right mouse buttons has been swapped.
This property is available only for non-server applications.

WheelExists Gets a Boolean that indicates if the mouse has a scroll wheel.
This property is only available for non-server applications.

WheelScrollLines Gets a number that indicates how much to scroll when the mouse wheel is rotated one notch.
This property is available only for non-server applications.
See Also
Reference
My.Computer.Mouse Object
Visual Basic Language Reference

My.Computer.Mouse.ButtonsSwapped Property
Gets a Boolean that indicates if the functionality of the left and right mouse buttons has been swapped.

' Usage
Dim value As Boolean = My.Computer.Mouse.ButtonsSwapped
' Declaration
Public ReadOnly Property ButtonsSwapped As Boolean

Return Value
A Boolean with a value True if the functionality of the left and right mouse buttons has been swapped; otherwise, False.
Exceptions
The following condition can cause an exception:
The computer has no mouse installed (InvalidOperationException).
Remarks
The My.Computer.Mouse.ButtonsSwapped property:
Provides functionality similar to the MouseButtonsSwapped property.
Provides information about the computer that runs the code.
Example
This example uses the My.Computer.Mouse.ButtonsSwapped property to determine if functionality of the left and right
mouse buttons has been swapped.
VB
If My.Computer.Mouse.ButtonsSwapped Then
MsgBox("Functionality of the mouse buttons is swapped.")
Else
MsgBox("Default functionality of the mouse buttons.")
End If

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Mouse
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes


Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Mouse Object
Microsoft.VisualBasic.Devices.Mouse.ButtonsSwapped
Visual Basic Language Reference

My.Computer.Mouse.WheelExists Property
Gets a Boolean that indicates if the mouse has a scroll wheel.

' Usage
Dim value As Boolean = My.Computer.Mouse.WheelExists
' Declaration
Public ReadOnly Property WheelExists As Boolean

Return Value
A Boolean with value True if the mouse has a scroll wheel; otherwise False.
Exceptions
The following condition can cause an exception:
The computer has no mouse installed (InvalidOperationException).
Remarks
The My.Computer.Mouse.WheelExists property provides functionality similar to the MouseWheelPresent property.
You should check the value of the My.Computer.Mouse.WheelExists property before attempting to access the
My.Computer.Mouse.WheelScrollLines Property, which throws an exception if the mouse does not have a scroll wheel.
The My.Computer.Mouse.WheelExists property provides information about the computer that runs the code.
Example
This example uses the My.Computer.Mouse.WheelExists property to determine if the mouse has a scroll wheel and how
much to scroll when the mouse wheel is rotated.
VB
If My.Computer.Mouse.WheelExists Then
Dim lines As Integer = My.Computer.Mouse.WheelScrollLines
If lines > 0 Then
MsgBox("Application scrolls " & _
lines & " line(s) for each wheel turn.")
Else
MsgBox("Application scrolls " & _
(-lines) & " page(s) for each wheel turn.")
End If
Else
MsgBox("Mouse has no scroll wheel.")
End If

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Mouse
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes


Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Mouse Object
My.Computer.Mouse.WheelScrollLines Property
Microsoft.VisualBasic.Devices.Mouse.WheelExists
Visual Basic Language Reference

My.Computer.Mouse.WheelScrollLines Property
Gets a number that indicates how much to scroll when the mouse wheel is rotated one notch.

' Usage
Dim value As Integer = My.Computer.Mouse.WheelScrollLines
' Declaration
Public ReadOnly Property WheelScrollLines As Integer

Return Value
An Integer that indicates how much to scroll when the mouse wheel is rotated one notch. A positive value indicates scrolling
by that number of lines, while a negative value indicates scrolling by one screen at a time.
Exceptions
The following conditions can cause an exception:
The computer has no mouse installed (InvalidOperationException).
The mouse has no scroll wheel (InvalidOperationException).
Remarks
You can use this property to determine how many lines to scroll up or down in a multi-line control that has a scroll bar.
The My.Computer.Mouse.WheelScrollLines property provides functionality similar to the MouseWheelScrollLines property.
Because this property throws an exception if the mouse does not have a scroll wheel, you should make sure a mouse has a
scroll wheel by checking the My.Computer.Mouse.WheelExists property.
This property provides information about the computer that runs the code.
Example
This example determines if the mouse has a scroll wheel and uses the My.Computer.Mouse.WheelExists property to
determine how much to scroll when the mouse wheel is rotated.
VB
If My.Computer.Mouse.WheelExists Then
Dim lines As Integer = My.Computer.Mouse.WheelScrollLines
If lines > 0 Then
MsgBox("Application scrolls " & _
lines & " line(s) for each wheel turn.")
Else
MsgBox("Application scrolls " & _
(-lines) & " page(s) for each wheel turn.")
End If
Else
MsgBox("Mouse has no scroll wheel.")
End If

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Mouse
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Reference
My.Computer.Mouse Object
My.Computer.Mouse.WheelExists Property
Microsoft.VisualBasic.Devices.Mouse.WheelScrollLines
Visual Basic Language Reference

My.Computer.Network Object
Provides a property, event, and methods for interacting with the network to which the computer is connected.
Tasks
The following table lists examples of tasks involving the My.Computer.Network object.
To See
Upload a file How to: Upload a File in Visual Basic

Download a file How to: Download a File in Visual Basic

Check connection status How to: Check Connection Status in Visual Basic

Determine if a remote computer is available How to: Determine if a Remote Computer is Available in Visual Basic
Example
This example uploads the file Order.txt to http://www.cohowinery.com/uploads.
VB
My.Computer.Network.UploadFile ( _
"C:\My Documents\Order.txt", _
"http://www.cohowinery.com/uploads.aspx")

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Network
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.Computer.Network Object Members
My.Computer Object
My.Computer.Network.NetworkAvailabilityChanged Event
Microsoft.VisualBasic.Devices.Network
Visual Basic Language Reference

My.Computer.Network Object Members


Provides a property, event, and methods for getting information about the network as well as uploading and downloading
files.
Properties
Property Description
IsAvailable Indicates whether the network is available.
Methods
Method Description
DownloadFile Downloads a file from a remote location.

Ping Pings a remote machine.

UploadFile Uploads a file to a remote location.


Events
Event Description
NetworkAvailabilityChanged Event Indicates when the status of the network connection changes.
See Also
Reference
My.Computer.Network Object
Other Resources
Performing Network Operations
Visual Basic Language Reference

My.Computer.Network.DownloadFile Method
Downloads the specified remote file and saves it in the specified location.

' Usage
My.Computer.Network.DownloadFile(address ,destinationFileName)
My.Computer.Network.DownloadFile(address ,destinationFileName)
My.Computer.Network.DownloadFile(address ,destinationFileName ,userName ,password)
My.Computer.Network.DownloadFile(address ,destinationFileName ,userName ,password)
My.Computer.Network.DownloadFile(address ,destinationFileName ,userName ,password ,showUI ,
connectionTimeout ,overwrite)
My.Computer.Network.DownloadFile(address ,destinationFileName ,userName ,password ,showUI ,
connectionTimeout ,overwrite ,onUserCancel)
My.Computer.Network.DownloadFile(address ,destinationFileName ,userName ,password ,showUI ,
connectionTimeout ,overwrite)
My.Computer.Network.DownloadFile(address ,destinationFileName ,userName ,password ,showUI ,
connectionTimeout ,overwrite ,onUserCancel)
My.Computer.Network.DownloadFile(address ,destinationFileName ,networkCredentials ,showUI ,
connectionTimeout ,overwrite)
My.Computer.Network.DownloadFile(address ,destinationFileName ,networkCredentials ,showUI ,
connectionTimeout ,overwrite ,onUserCancel)
' Declaration
Public Sub DownloadFile( _
ByVal address As String, _
ByVal destinationFileName As String _
)
' -or-
Public Sub DownloadFile( _
ByVal address As System.Uri, _
ByVal destinationFileName As String _
)
' -or-
Public Sub DownloadFile( _
ByVal address As String, _
ByVal destinationFileName As String, _
ByVal userName As String, _
ByVal password As String _
)
' -or-
Public Sub DownloadFile( _
ByVal address As System.Uri, _
ByVal destinationFileName As String, _
ByVal userName As String, _
ByVal password As String _
)
' -or-
Public Sub DownloadFile( _
ByVal address As String, _
ByVal destinationFileName As String, _
ByVal userName As String, _
ByVal password As String, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal overwrite As Boolean _
)
' -or-
Public Sub DownloadFile( _
ByVal address As String, _
ByVal destinationFileName As String, _
ByVal userName As String, _
ByVal password As String, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal overwrite As Boolean, _
ByVal onUserCancel As UICancelOption _
)
' -or-
Public Sub DownloadFile( _
ByVal address As System.Uri, _
ByVal destinationFileName As String, _
ByVal userName As String, _
ByVal password As String, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal overwrite As Boolean _
)
' -or-
Public Sub DownloadFile( _
ByVal address As System.Uri, _
ByVal destinationFileName As String, _
ByVal userName As String, _
ByVal password As String, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal overwrite As Boolean, _
ByVal onUserCancel As UICancelOption _
)
' -or-
Public Sub DownloadFile( _
ByVal address As System.Uri, _
ByVal destinationFileName As String, _
ByVal networkCredentials As System.Net.ICredentials, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal overwrite As Boolean _
)
' -or-
Public Sub DownloadFile( _
ByVal address As System.Uri, _
ByVal destinationFileName As String, _
ByVal networkCredentials As System.Net.ICredentials, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal overwrite As Boolean, _
ByVal onUserCancel As UICancelOption _
)

Parameters
address
String or Uri. Path of the file to download, including file name and host address. Required.
destinationFileName
String. File name and path of the downloaded file. Required.
userName
String. User name to authenticate. Default is an empty string, "".
password
String.Password to authenticate. Default is an empty string, "".
showUI
Boolean. Specifies whether to display the progress of the operation. Default is False.
connectionTimeout
Int32. Timeout interval, in milliseconds. Default is 100 seconds.
overwrite
Boolean. Specifies whether to overwrite existing files. Default is False.
onUserCancel
UICancelOption. Specifies behavior when the user clicks Cancel or No on the dialog box shown as a result of ShowUI set to
True. Default is ThrowException.
networkCredentials
ICredentials. Credentials to be supplied.
Exceptions
The following conditions may cause an exception to be thrown:
The drive name is not valid (ArgumentException).
destinationFileName ends with a trailing slash (ArgumentException).
overwrite is set to False and the destination file already exists (IOException).
The server does not respond within the specified connectionTimeout (TimeoutException).
The authentication fails (SecurityException).
User lacks necessary permissions (SecurityException).
The request is denied by the website (WebException).
Remarks
If showUI is set to True, a dialog box appears that shows the progress of the operation; the dialog box contains a Cancel
button that can be used to cancel the operation. The dialog box is not modal, and therefore does not block user input to other
windows in the program.
If the server does not respond within the specified connectionTimeout, the operation is cancelled, and an exception is thrown.
DownloadFile outputs trace information when you enable network tracing in your application. For more information, see
Enabling Network Tracing.
Note
The DownloadFile method does not send optional HTTP headers. Some servers may return 500 (Internal Server Error) if the
optional user agent header is missing. To send optional headers, you must construct a request using the WebClient class. For
more information, see Network Operations in the .NET Framework with Visual Basic.

Security Note
The FTP protocol sends information, including passwords, in plain text and should not be used for transmitting sensitive infor
mation.

Tasks
The following table lists an example of a task involving the My.Computer.Network.DownloadFile method.
To See
Download a file How to: Download a File in Visual Basic
Example
This example downloads the file WineList.txt from http://www.cohowinery.com/downloads and saves it to C:\Documents
and Settings\All Users\Documents.

VB
My.Computer.Network.DownloadFile _
("http://www.cohowinery.com/downloads/WineList.txt", _
"C:\Documents and Settings\All Users\Documents\WineList.txt")

This example downloads the file WineList.txt from http://www.cohowinery.com/downloads and saves it to C:\Documents
and Settings\All Users\Documents, specifying a timeout interval of 500 milliseconds.
VB
My.Computer.Network.DownloadFile _
("http://www.cohowinery.com/downloads/", _
"C:\Documents and Settings\All Users\Documents\WineList.txt", _
"", "", False, 500, True)

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Network
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permissions may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration: AllWindows.

WebPermission Controls rights to access HTTP Internet resources. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Download a File in Visual Basic
How to: Determine if a Remote Computer is Available in Visual Basic
How to: Parse File Paths in Visual Basic
Reference
My.Computer.Network Object
System.Uri
System.Net.ICredentials
Microsoft.VisualBasic.Devices.Network.DownloadFile
Visual Basic Language Reference

My.Computer.Network.IsAvailable Property
Indicates whether a computer is connected to a network.

' Usage
Dim value As Boolean = My.Computer.Network.IsAvailable
' Declaration
Public ReadOnly Property IsAvailable As Boolean

Return Value
Boolean.
Remarks
IsAvailable always returns False when called from a Click Once application or if the user does not have
NetworkInformationPermission.
Tasks
The following table lists examples of tasks involving the My.Computer.Network.IsAvailable property.
To See
Check whether a computer is connected to a network How to: Check Connection Status in Visual Basic
Example
This example checks the property's status and reports it.
VB
If My.Computer.Network.IsAvailable = True Then
MsgBox("Computer is connected.")
Else
MsgBox("Computer is not connected.")
End If

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Network
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permissions may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

WebPermission Controls rights to access HTTP Internet resources. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Determine if a Remote Computer is Available in Visual Basic
Reference
My.Computer.Network Object
Microsoft.VisualBasic.Devices.Network.IsAvailable
Visual Basic Language Reference

My.Computer.Network.Ping Method
Pings the specified server.

' Usage
Dim value As Boolean = My.Computer.Network.Ping(hostNameOrAddress)
Dim value As Boolean = My.Computer.Network.Ping(address)
Dim value As Boolean = My.Computer.Network.Ping(hostNameOrAddress ,timeout)
Dim value As Boolean = My.Computer.Network.Ping(address ,timeout)
' Declaration
Public Function Ping( _
ByVal hostNameOrAddress As String _
) As Boolean
' -or-
Public Function Ping( _
ByVal address As System.Uri _
) As Boolean
' -or-
Public Function Ping( _
ByVal hostNameOrAddress As String, _
ByVal timeout As Integer _
) As Boolean
' -or-
Public Function Ping( _
ByVal address As System.Uri, _
ByVal timeout As Integer _
) As Boolean

Parameters
hostNameOrAddress
String. The URL, computer name, or IP number of the server to ping. Required.
address
Uri. The URI of the server to ping. Required.
timeout
Int32. Time threshold in milliseconds for contacting the destination. Default is 500. Required.
Return Value
Boolean indicating whether or not the operation was successful.
Exceptions
The following conditions may cause an exception to be thrown:
No network connection is available (InvalidOperationException).
URL was not valid (PingException).
Remarks
The Ping method is not a fail-safe method for determining the availability of a remote computer: the ping port on the target
computer may be turned off or the ping request may be blocked by a firewall or router.
The address passed to the Ping method must be DNS resolvable and cannot be preceded by "http://".
Tasks
The following table lists examples of tasks involving the My.Computer.Network.Ping method.
To See
Determine whether a remote computer or host is availabl How to: Determine if a Remote Computer is Available in Visual Basic
e
Example
This example reports whether or not the server can be pinged by determining whether the Ping method returns True.
VB
If My.Computer.Network.Ping("198.01.01.01") Then
MsgBox("Server pinged successfully.")
Else
MsgBox("Ping request timed out.")
End If

Replace "198.01.01.01" with the IP address, URL, or computer name of the server to ping.
This example reports whether or not the server can be pinged by determining whether the Ping method returned True and
specifies a timeout interval of 1000 milliseconds.
VB
If My.Computer.Network.Ping("www.cohowinery.com",1000) Then
MsgBox("Server pinged successfully.")
Else
MsgBox("Ping request timed out.")
End If

Replace "www.cohowinery.com" with the IP address, URL, or computer name of the server to ping.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Network
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permissions may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.
SecurityPermission Describes a set of security permissions applied to code. Associated enumeration:
ControlPrincipal.

WebPermission Controls rights to access HTTP Internet resources. Associated enumeration: Unrestricted.

SocketPermission Controls rights to make or accept connections on a transport address. Associated enumeratio
n: Unrestricted.

PerformanceCounterPermission Controls access to a Windows NT performance counter component. Associated enumeration:


Unrestricted.

NetworkInformationPermission Controls access to network information and traffic statistics for the local computer. Associated
enumeration: Ping.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
My.Computer.Network Object
System.Uri
Microsoft.VisualBasic.Devices.Network.Ping
Visual Basic Language Reference

My.Computer.Network.NetworkAvailabilityChanged Event
Occurs when the network availability changes.

' Usage
Public Sub MyComputerNetwork_NetworkAvailabilityChanged( _
ByVal sender As Object, _
ByVal e As Devices.NetworkAvailableEventArgs _
)
End Sub
Sub Handle_NetworkAvailabilityChanged()
AddHandler My.Computer.Network.NetworkAvailabilityChanged, _
AddressOf MyComputerNetwork_NetworkAvailabilityChanged
End Sub
' Declaration
Public Event NetworkAvailabilityChanged( _
ByVal sender As Object, _
ByVal e As Devices.NetworkAvailableEventArgs _
)

Parameters
sender
Required. The Object that raised the event.
e
Required. A NetworkAvailableEventArgs object that contains information about the availability of the network.
Remarks
An application raises the NetworkAvailabilityChanged event every time the availability of the network changes. You can use
the IsNetworkAvailable property of the e parameter to get the new state of the network connection. To get the current state of
the network connection, use the My.Computer.Network.IsAvailable Property.
In a Windows Forms application, this event is raised on the application's main thread with the other user-interface events. This
allows the event handler to directly access the application's user interface. However, if the application is busy handling another
user-interface event when this event is raised, this event cannot be processed until the other event handler finishes or calls the
My.Application.DoEvents Method.
You cannot use the Handles statement to handle the NetworkAvailabilityChanged event; you must use the AddHandler
statement.
In Windows Forms applications, the My.Application object exposes a NetworkAvailabilityChanged event that provides the
same functionality as this event, but you can handle it with the Handles statement. For more information, see
My.Application.NetworkAvailabilityChanged Event.
Note
Many network hubs provide a network connection, even if the hub is disconnected from a larger network. Consequently, for
wired connections, this event indicates a change in the connection between the computer and a hub.

Note
The NetworkAvailabilityChanged event is not raised by applications that run on Windows 95 and Windows 98 or by appli
cations that are run on Windows 2000 by a non-administrator. If your application might run on those platforms, use the
My.Computer.Network.IsAvailable Property to check for network availability.

Example
This example uses the My.Computer.Network.NetworkAvailabilityChanged event to update the user interface of a form
or control.
VB
Private Sub DisplayAvailability(ByVal available As Boolean)
Label1.Text = available.ToString
End Sub

Private Sub MyComputerNetwork_NetworkAvailabilityChanged( _


ByVal sender As Object, _
ByVal e As Devices.NetworkAvailableEventArgs)

DisplayAvailability(e.IsNetworkAvailable)
End Sub

Private Sub Handle_NetworkAvailabilityChanged()


AddHandler My.Computer.Network.NetworkAvailabilityChanged, _
AddressOf MyComputerNetwork_NetworkAvailabilityChanged
DisplayAvailability(My.Computer.Network.IsAvailable)
End Sub

This code should to be in a form or control that has a Label named Label1. You must call the
Handle_NetworkAvailabilityChanged method to initialize the label and hook up the event handler.

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Network
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Reference
My.Computer.Network Object
My.Application.NetworkAvailabilityChanged Event
Microsoft.VisualBasic.Devices.NetworkAvailableEventArgs
Visual Basic Language Reference

My.Computer.Network.UploadFile Method
Sends the specified file to the specified host address.

' Usage
My.Computer.Network.UploadFile(sourceFileName ,address)
My.Computer.Network.UploadFile(sourceFileName ,address)
My.Computer.Network.UploadFile(sourceFileName ,address ,userName ,password)
My.Computer.Network.UploadFile(sourceFileName ,address ,userName ,password)
My.Computer.Network.UploadFile(sourceFileName ,address ,userName ,password ,showUI ,connect
ionTimeout)
My.Computer.Network.UploadFile(sourceFileName ,address ,userName ,password ,showUI ,connect
ionTimeout ,onUserCancel)
My.Computer.Network.UploadFile(sourceFileName ,address ,userName ,password ,showUI ,connect
ionTimeout)
My.Computer.Network.UploadFile(sourceFileName ,address ,userName ,password ,showUI ,connect
ionTimeout ,onUserCancel)
My.Computer.Network.UploadFile(sourceFileName ,address ,networkCredentials ,showUI ,connect
ionTimeout)
My.Computer.Network.UploadFile(sourceFileName ,address ,networkCredentials ,showUI ,connect
ionTimeout ,onUserCancel)
' Declaration
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As String _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As System.Uri _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As String, _
ByVal userName As String, _
ByVal password As String _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As System.Uri, _
ByVal userName As String, _
ByVal password As String _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As String, _
ByVal userName As String, _
ByVal password As String, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As String, _
ByVal userName As String, _
ByVal password As String, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal onUserCancel As UICancelOption _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As System.Uri, _
ByVal userName As String, _
ByVal password As String, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As System.Uri, _
ByVal userName As String, _
ByVal password As String, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal onUserCancel As UICancelOption _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As System.Uri, _
ByVal networkCredentials As System.Net.ICredentials, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer _
)
' -or-
Public Sub UploadFile( _
ByVal sourceFileName As String, _
ByVal address As System.Uri, _
ByVal networkCredentials As System.Net.ICredentials, _
ByVal showUI As Boolean, _
ByVal connectionTimeout As Integer, _
ByVal onUserCancel As UICancelOption _
)

Parameters
sourceFileName
String. Path and name of file to upload. Required.
address
String or Uri. URL, IP address, or URI of destination server. Required.
userName
String. User name to authenticate. Default is an empty string: "".
password
String. Password to authenticate. Default is an empty string: "".
showUI
Boolean. Whether to display progress of the operation. Default is False.
connectionTimeout
Int32. Timeout interval in milliseconds. Default is 100 seconds.
onUserCancel
UICancelOption. Action to be taken when the user clicks Cancel. Default is ThrowException.
networkCredentials
ICredentials. Credentials for authentication.
Exceptions
The following conditions may cause an exception:
The local file path is not valid (ArgumentException).
connectionTimeout is less than or equal to zero (ArgumentException).
address does not include a file name (InvalidOperationException).
Authentication failed (SecurityException).
User lacks necessary permissions (SecurityException).
Connection timed out (TimeoutException).
The website denies the request (WebException).
Remarks
If showUI is set to True, a dialog box shows the progress of the operation and includes a Cancel button that the user can click
to cancel the operation. Because the dialog box is not modal, it does not block user input to other windows in the program.
If the server does not respond within the interval specified in connectionTimeout, the operation is cancelled and an exception is
thrown.
My.Computer.Network.UploadFile outputs trace information when you enable network tracing in your application. For
more information, see Enabling Network Tracing.
Security Note
The FTP protocol sends information, including passwords, in plain text and should not be used for transmitting sensitive infor
mation.

Tasks
The following table lists an example of a task involving the My.Computer.Network.UploadFile method.
To See
Upload a file How to: Upload a File in Visual Basic
Example
This example uploads the file Order.txt to http://www.cohowinery.com/uploads.
VB
My.Computer.Network.UploadFile ( "C:\My Documents\Order.txt", _
"http://www.cohowinery.com/upload.aspx")

This example uploads the file Order.txt to http://www.cohowinery.com/uploads without supplying a user name or password,
shows the progress of the upload, and has a time-out interval of 500 milliseconds.
VB
My.Computer.Network.UploadFile ("C:\My Documents\Order.txt", _
"http://www.cohowinery.com/upload.aspx","","",True,500)

Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Network
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permissions may be necessary:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

UIPermission Controls the permissions related to user interfaces and the clipboard. Associated enumeration: AllWindows.

WebPermission Controls rights to access HTTP Internet resources. Associated enumeration: Unrestricted.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Download a File in Visual Basic
How to: Parse File Paths in Visual Basic
Reference
My.Computer.Network Object
System.Uri
System.Net.ICredentials
Microsoft.VisualBasic.FileIO.UICancelOption
Microsoft.VisualBasic.Devices.Network.UploadFile
Visual Basic Language Reference

My.Computer.Ports Object
Provides a property and a method for accessing the computer's serial ports.
Remarks
The My.Computer.Ports object provides a straightforward entry point for accessing the .NET Framework serial port class,
SerialPort.
Tasks
The following table lists examples of tasks involving the My.Computer.Ports object.
To See
Dial a modem attached to a serial port How to: Dial Modems Attached to Serial Ports in Visual Basic

Send a string to a serial port How to: Send Strings to Serial Ports in Visual Basic

Receive strings from a serial port How to: Receive Strings From Serial Ports in Visual Basic

Show available serial ports How to: Show Available Serial Ports in Visual Basic
Example
This example describes how to send strings to the computer's COM1 serial port.
The Using block allows the application to close the serial port even if it generates an exception. All code that manipulates the
serial port should appear within this block, or within a Try...Catch...Finally block with a call to use the Close method.
The WriteLine method sends the data to the serial port.
VB
Sub SendSerialData(ByVal data As String)
' Send strings to a serial port.
Using com1 As IO.Ports.SerialPort = _
My.Computer.Ports.OpenSerialPort("COM1")
com1.WriteLine(data)
End Using
End Sub

For more information, see How to: Send Strings to Serial Ports in Visual Basic.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Ports
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No


Windows Service Yes

Web Site No
See Also
Tasks
How to: Dial Modems Attached to Serial Ports in Visual Basic
How to: Send Strings to Serial Ports in Visual Basic
How to: Receive Strings From Serial Ports in Visual Basic
How to: Show Available Serial Ports in Visual Basic
Reference
My.Computer.Ports Object Members
My.Computer Object
Microsoft.VisualBasic.Devices.Ports
Visual Basic Language Reference

My.Computer.Ports Object Members


The My.Computer.Ports Object provides a property and a method for accessing the computer's serial ports.
Properties
SerialPortNames Gets a collection of the names of the serial ports on the computer.
This property is not available for Web applications.
Methods
OpenSerialPort Creates and opens a SerialPort object.
This method is not available for Web applications.
See Also
Reference
My.Computer.Ports Object
Visual Basic Language Reference

My.Computer.Ports.OpenSerialPort Method
Creates and opens a SerialPort object.

' Usage
Dim value As System.IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(portName)
Dim value As System.IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(portName ,baudRa
te)
Dim value As System.IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(portName ,baudRa
te ,parity)
Dim value As System.IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(portName ,baudRa
te ,parity ,dataBits)
Dim value As System.IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(portName ,baudRa
te ,parity ,dataBits ,stopBits)
' Declaration
Public Function OpenSerialPort( _
ByVal portName As String _
) As System.IO.Ports.SerialPort
' -or-
Public Function OpenSerialPort( _
ByVal portName As String, _
ByVal baudRate As Integer _
) As System.IO.Ports.SerialPort
' -or-
Public Function OpenSerialPort( _
ByVal portName As String, _
ByVal baudRate As Integer, _
ByVal parity As System.IO.Ports.Parity _
) As System.IO.Ports.SerialPort
' -or-
Public Function OpenSerialPort( _
ByVal portName As String, _
ByVal baudRate As Integer, _
ByVal parity As System.IO.Ports.Parity, _
ByVal dataBits As Integer _
) As System.IO.Ports.SerialPort
' -or-
Public Function OpenSerialPort( _
ByVal portName As String, _
ByVal baudRate As Integer, _
ByVal parity As System.IO.Ports.Parity, _
ByVal dataBits As Integer, _
ByVal stopBits As System.IO.Ports.StopBits _
) As System.IO.Ports.SerialPort

Parameters
portName
String. Required. Name of the port to open.
baudRate
Integer. Baud rate of the port.
parity
Parity. Parity of the port.
dataBits
Integer. Data-bit setting of the port.
stopBits
StopBits. Stop-bit setting of the port.
Return Value
An open SerialPort object, configured with the supplied arguments.
Exceptions
The following conditions can cause an exception:
The portName argument is Nothing or an empty string (ArgumentNullException).
The baudRate or dataBits argument is zero or negative (ArgumentException).
The parity argument type is not one of the Parity enumeration values (InvalidEnumArgumentException).
The stopBits argument type is not one of the StopBits enumeration values (InvalidEnumArgumentException).
Remarks
The My.Computer.Ports.OpenSerialPort method creates and opens a SerialPort object. The arguments to the
OpenSerialPort method determine the settings of the SerialPort object.
Your code should close the SerialPort object when it is finished using the object. You can use the Close method to close the
object explicitly or the Using statement to close it implicitly. See the example in this topic for more information.
Tasks
The following table lists examples of tasks involving the My.Computer.Ports.OpenSerialPort method.
To See
Dial a modem attached to a serial port How to: Dial Modems Attached to Serial Ports in Visual Basic

Send a string to serial port How to: Send Strings to Serial Ports in Visual Basic

Receive strings from a serial port How to: Receive Strings From Serial Ports in Visual Basic
Example
This example describes how to send strings to the computer's COM1 serial port.
The Using block allows the application to close the serial port even if it generates an exception. All code that manipulates the
serial port should appear within this block, or within a Try...Catch...Finally block with a call to use the Close method.
The WriteLine method sends the data to the serial port.
VB
Sub SendSerialData(ByVal data As String)
' Send strings to a serial port.
Using com1 As IO.Ports.SerialPort = _
My.Computer.Ports.OpenSerialPort("COM1")
com1.WriteLine(data)
End Using
End Sub

For more information, see How to: Send Strings to Serial Ports in Visual Basic.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Ports
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes
Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Dial Modems Attached to Serial Ports in Visual Basic
How to: Send Strings to Serial Ports in Visual Basic
How to: Receive Strings From Serial Ports in Visual Basic
Reference
My.Computer.Ports Object
My.Computer.Ports.SerialPortNames Property
Using Statement (Visual Basic)
System.IO.Ports.Parity
System.IO.Ports.StopBits
System.IO.Ports.SerialPort
Microsoft.VisualBasic.Devices.Ports.OpenSerialPort(System.String)
Visual Basic Language Reference

My.Computer.Ports.SerialPortNames Property
Gets a collection of the names of the serial ports on the computer.

' Usage
Dim value As System.Collections.Generic.ReadOnlyCollection`1(Of String) = My.Computer.Ports
.SerialPortNames
' Declaration
Public ReadOnly Property SerialPortNames As System.Collections.Generic.ReadOnlyCollection`1
(Of String)

Return Value
A collection of the names of the serial ports on the computer.
Remarks
The My.Computer.Ports.SerialPortNames property gets a collection of the names of the serial ports on the computer.
Note
The port names returned by My.Computer.Ports.SerialPortNames may be incorrect when run on Windows 98. To prevent
application errors, use exception handling, such as the Try...Catch...Finally statement or the Using statement, when using th
e port names to open ports.

Tasks
The following table lists an example of a task involving the My.Computer.Ports.SerialPortNames property.
To See
Show available serial ports How to: Show Available Serial Ports in Visual Basic
Example
This example loops over all the strings that the My.Computer.Ports.SerialPortNames property returns. These strings are the
names of the available serial ports on the computer.
Typically, a user selects which serial port the application should use from the list of available ports. In this example, the serial
port names are stored in a ListBox control. For more information, see ListBox Control (Windows Forms).
VB
Sub GetSerialPortNames()
' Show all available COM ports.
For Each sp As String In My.Computer.Ports.SerialPortNames
ListBox1.Items.Add(sp)
Next
End Sub

This example requires:


A reference to the System namespace.
That your form have a ListBox control named ListBox1.
For more information, see How to: Show Available Serial Ports in Visual Basic.
Requirements
Namespace: Microsoft.VisualBasic.Devices
Class: Ports
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library No

Windows Service Yes

Web Site No
Permissions
No permissions are required.
See Also
Tasks
How to: Show Available Serial Ports in Visual Basic
Reference
My.Computer.Ports Object
My.Computer.Ports.OpenSerialPort Method
Try...Catch...Finally Statement (Visual Basic)
Using Statement (Visual Basic)
ReadOnlyCollection
Microsoft.VisualBasic.Devices.Ports.SerialPortNames
Visual Basic Language Reference

My.Computer.Registry Object
Provides properties and methods for manipulating the registry.
Remarks
To use these properties, you must have Read and Write permission from the RegistryPermissionAccess Enumeration. Any code
running with full trust (under the default security policy, this is any code installed on the user's local hard drive) has the
necessary permissions to access the registry. For more information, see RegistryPermission Class.
Tasks
The following table lists examples of tasks involving the My.Computer.Registry object.
To See
Create a registry key How to: Create a Registry Key and Set Its Values in Visual Basic

Determine if a value in a registry key exists How to: Determine if a Value Exists in a Registry Key in Visual Basic

Write data to a registry key How to: Set Values in Registry Keys in Visual Basic

Delete a registry key How to: Delete a Registry Key in Visual Basic

Read data from the registry How to: Read a Value from a Registry Key in Visual Basic
Example
This example reads the value Name from HKEY_CURRENT_USER\Software\MyApp and displays it in a message box.
VB
Dim readValue As Object
readValue = My.Computer.Registry.GetValue _
("HKEY_CURRENT_USER\Software\MyApp", "Name", Nothing)
MsgBox("The value is " & CStr(readValue))

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
Walkthrough: Creating a Registry Key and Changing Its Values
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object Members
My.Computer.Registry.ClassesRoot Property
My.Computer.Registry.CurrentConfig Property
My.Computer.Registry.CurrentUser Property
My.Computer.Registry.DynData Property
My.Computer.Registry.LocalMachine Property
My.Computer.Registry.PerformanceData Property
My.Computer.Registry.Users Property
My.Computer.Registry.GetValue Method
My.Computer.Registry.SetValue Method
My.Computer Object
Microsoft.Win32.Registry
Concepts
Common Registry Tasks
Visual Basic Language Reference

My.Computer.Registry Object Members


The My.Computer.Registry object offers properties and methods for working with registry keys.
Properties
ClassesRoot Corresponds to HKEY_CLASSES_ROOT.

CurrentConfig Corresponds to HKEY_CURRENT_CONFIG.

CurrentUser Corresponds to HKEY_CURRENT_USER.

DynData Corresponds to HKEY_DYNAMIC_DATA.

LocalMachine Corresponds to HKEY_LOCAL_MACHINE.

PerformanceData Corresponds to. HKEY_PERFORMANCE_DATA.

Users Corresponds to HKEY_USERS.


Methods
GetValue Gets a value from a registry key.

SetValue Sets a value in a registry key.


See Also
Tasks
Walkthrough: Creating a Registry Key and Changing Its Values
Reference
My.Computer.Registry Object
Concepts
Common Registry Tasks
Visual Basic Language Reference

My.Computer.Registry.ClassesRoot Property
Returns a RegistryKey type which provides access to HKEY_CLASSES_ROOT.

' Usage
Dim value As Microsoft.Win32.RegistryKey = My.Computer.Registry.ClassesRoot
' Declaration
Public ReadOnly Property ClassesRoot As Microsoft.Win32.RegistryKey

Return Value
RegistryKey
Remarks
The My.Computer.Registry object offers methods and properties for working with registry keys. See
My.Computer.Registry Object for more information.
HKEY_CLASSES_ROOT is primarily used to store information about file associations in Windows.
The RegistryPermission class, which is in the System.Security.Permissions namespace, controls access to registry variables.
Registry variables should not be stored in memory locations where code without RegistryPermission can access them.
Similarly, when granting permissions, grant only those privileges necessary to get the job done.
Registry permission access values are defined by the RegistryPermissionAccess enumeration. The following table details its
members.
Value Description
AllAccess Create, read, and write access to registry variables.

Create Create access to registry variables.

NoAccess No access to registry variables.

Read Read access to registry variables.

Write Write access to registry variables.


Tasks
The following table lists examples of tasks involving the My.Computer.Registry object.
To See
Create a registry key How to: Create a Registry Key and Set Its Values in Visual Basic

Delete a registry key How to: Delete a Registry Key in Visual Basic

Determine whether a value exists in a registry key How to: Determine if a Value Exists in a Registry Key in Visual Basic

Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic

Set a value in a registry key How to: Set Values in Registry Keys in Visual Basic
Example
This example gets the names of the subkeys for the ClassesRoot registry key and adds them to ListBox1.
VB
Dim keyList As System.Collections.IEnumerable
keyList = My.Computer.Registry.ClassesRoot.GetSubKeyNames()
For Each keyName As String In keyList
ListBox1.Items.Add(keyName)
Next

This example requires that you have a ListBox named ListBox1 in your project.
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
Microsoft.Win32.RegistryKey
Microsoft.Win32.Registry.ClassesRoot
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Visual Basic Language Reference

My.Computer.Registry.CurrentConfig Property
Returns a RegistryKey type which provides access to HKEY_CURRENT_CONFIG.

' Usage
Dim value As Microsoft.Win32.RegistryKey = My.Computer.Registry.CurrentConfig
' Declaration
Public ReadOnly Property CurrentConfig As Microsoft.Win32.RegistryKey

Return Value
RegistryKey
Remarks
The My.Computer.Registry object offers methods and properties for working with registry keys. See
My.Computer.Registry Object for more information.
HKEY_CURRENT_CONFIG is primarily used to store settings for devices on the computer.
The RegistryPermission class, which is in the System.Security.Permissions namespace, controls access to registry variables.
Registry variables should not be stored in memory locations where code without RegistryPermission can access them.
Similarly, when granting permissions, grant only those privileges necessary to get the job done.
Registry permission access values are defined by the RegistryPermissionAccess enumeration. The following table details its
members.
Value Description
AllAccess Create, read, and write access to registry variables.

Create Create access to registry variables.

NoAccess No access to registry variables.

Read Read access to registry variables.

Write Write access to registry variables.


Tasks
The following table lists examples of tasks involving the My.Computer.Registry object.
To See
Create a registry key How to: Create a Registry Key and Set Its Values in Visual Basic

Delete a registry key How to: Delete a Registry Key in Visual Basic

Determine whether a value exists in a registry key How to: Determine if a Value Exists in a Registry Key in Visual Basic

Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic

Set a value in a registry key How to: Set Values in Registry Keys in Visual Basic
Example
This example creates the subkey MyDeviceSettings.
VB
My.Computer.Registry.CurrentConfig.CreateSubKey("MyDeviceSettings")
Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
Microsoft.Win32.RegistryKey
Microsoft.Win32.Registry.CurrentConfig
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Visual Basic Language Reference

My.Computer.Registry.CurrentUser Property
Returns a RegistryKey type which provides access to HKEY_CURRENT_USER.

' Usage
Dim value As Microsoft.Win32.RegistryKey = My.Computer.Registry.CurrentUser
' Declaration
Public ReadOnly Property CurrentUser As Microsoft.Win32.RegistryKey

Return Value
RegistryKey
Remarks
The My.Computer.Registry object offers methods and properties for working with registry keys. See
My.Computer.Registry Object for more information.
HKEY_CURRENT_USER is primarily used to store per-user settings, such as colors and fonts, in Windows. The key differ
according to the user.
The RegistryPermission class, which is in the System.Security.Permissions namespace, controls access to registry variables.
Registry variables should not be stored in memory locations where code without RegistryPermission can access them.
Similarly, when granting permissions, grant the fewest privileges necessary to get the job done.
Registry permission access values are defined by the RegistryPermissionAccess enumeration. The following table details its
members.
Value Description
AllAccess Create, read, and write access to registry variables.

Create Create access to registry variables.

NoAccess No access to registry variables.

Read Read access to registry variables.

Write Write access to registry variables.


Tasks
The following table lists examples of tasks involving the My.Computer.Registry object.
To See
Create a registry key How to: Create a Registry Key and Set Its Values in Visual Basic

Delete a registry key How to: Delete a Registry Key in Visual Basic

Determine whether a value exists in a registry key How to: Determine if a Value Exists in a Registry Key in Visual Basic

Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic

Set a value in a registry key How to: Set Values in Registry Keys in Visual Basic
Example
This example deletes the subkey Software\MyCompany\Preferences\UserData.
VB
My.Computer.Registry.CurrentUser.DeleteSubKey _
("Software\MyCompany\Preferences\UserData")

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
Microsoft.Win32.RegistryKey
Microsoft.Win32.Registry.CurrentUser
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Visual Basic Language Reference

My.Computer.Registry.DynData Property
Returns a RegistryKey type, which provides access to HKEY_DYNDATA.

' Usage
Dim value As Microsoft.Win32.RegistryKey = My.Computer.Registry.DynData
' Declaration
Public ReadOnly Property DynData As Microsoft.Win32.RegistryKey

Return Value
RegistryKey
Remarks
The My.Computer.Registry object offers methods and properties for working with registry keys. See
My.Computer.Registry Object for more information.
HKEY_DYNDATA is used to store dynamic registry data, such as that used by Virtual Device Drivers and is supported only on
Windows 95/98 systems. On non-Windows 95/98 systems, calling any methods of the key returned by Registry.DynData,
such as CreateSubKey, DeleteSubKey, GetSubKeyCount, GetValueCount, etc., will throw a IOException.
The RegistryPermission class, which is in the System.Security.Permissions namespace, controls access to registry variables.
Registry variables should not be stored in memory locations where code without RegistryPermission can access them.
Similarly, when granting permissions, grant the fewest privileges necessary to get the job done.
Registry permission access values are defined by the RegistryPermissionAccess enumeration. The following table details its
members.
Value Description
AllAccess Create, read, and write access to registry variables.

Create Create access to registry variables.

NoAccess No access to registry variables.

Read Read access to registry variables.

Write Write access to registry variables.


Tasks
The following table lists examples of tasks involving the My.Computer.Registry object.
To See
Create a registry key How to: Create a Registry Key and Set Its Values in Visual Basic

Delete a registry key How to: Delete a Registry Key in Visual Basic

Determine whether a value exists in a registry key How to: Determine if a Value Exists in a Registry Key in Visual Basic

Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic

Set a value in a registry key How to: Set Values in Registry Keys in Visual Basic
Example
This example deletes the subkey tree Software\MyCompany\Preferences.
VB
My.Computer.Registry.DynData.DeleteSubKeyTree("Software\MyCompany\Preferences")

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
Microsoft.Win32.RegistryKey
Microsoft.Win32.Registry.DynData
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Visual Basic Language Reference

My.Computer.Registry.GetValue Method
Gets a value from a registry key.

' Usage
Dim value As Object = My.Computer.Registry.GetValue(keyName ,valueName ,defaultValue)
' Declaration
Public Function GetValue( _
ByVal keyName As String, _
ByVal valueName As String, _
ByVal defaultValue As Object _
) As Object

Parameters
keyName
String. Key from which the value is to be retrieved. Required.
valueName
String. Value to be retrieved. Required.
defaultValue
Object. Default value to be supplied if the value does not exist. Required.
Remarks
valueName is not case-sensitive.
A registry key can contain one value that is not associated with any name. When this unnamed value is displayed in the
registry editor, the string "(Default)" appears instead of a name. To retrieve this unnamed value, specify either null or the empty
string ("") for valueName.
Exceptions
The following conditions may cause an exception:
The name of the key is Nothing (ArgumentNullException).
The user does not have permissions to read from registry keys (SecurityException).
The key name exceeds the 255-character limit (ArgumentException).
Tasks
The following table lists examples of tasks involving the GetValue method.
To See
Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic
Example
This example reads the value Name from HKEY_CURRENT_USER\Software\MyApp and displays it in a MessageBox.
VB
Dim readValue As Object
readValue = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\MyApp", "Name", Nothi
ng)
MsgBox("The value is " & CStr(readValue))

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
GetValue
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Visual Basic Language Reference

My.Computer.Registry.LocalMachine Property
Returns a RegistryKey type, which provides access to HKEY_LOCAL_MACHINE.

' Usage
Dim value As Microsoft.Win32.RegistryKey = My.Computer.Registry.LocalMachine
' Declaration
Public ReadOnly Property LocalMachine As Microsoft.Win32.RegistryKey

Return Value
RegistryKey
Remarks
The My.Computer.Registry object offers methods and properties for working with registry keys. See
My.Computer.Registry Object for more information.
HKEY_LOCAL_MACHINE is usually used to store settings that do not vary from user to user in Windows. All users of the
computer share this key. Its five subkeys (Hardware, SAM, Security, Software, and System) hold configuration data for the
local machine.
The RegistryPermission class, which is in the System.Security.Permissions namespace, controls access to registry variables.
Registry variables should not be stored in memory locations where code without RegistryPermission can access them.
Similarly, when granting permissions, grant the fewest privileges necessary to get the job done.
Registry permission access values are defined by the RegistryPermissionAccess enumeration. The following table details its
members.
Value Description
AllAccess Create, read, and write access to registry variables.

Create Create access to registry variables.

NoAccess No access to registry variables.

Read Read access to registry variables.

Write Write access to registry variables.


Tasks
The following table lists examples of tasks involving the My.Computer.Registry object.
To See
Create a registry key How to: Create a Registry Key and Set Its Values in Visual Basic

Delete a registry key How to: Delete a Registry Key in Visual Basic

Determine whether a value exists in a registry key How to: Determine if a Value Exists in a Registry Key in Visual Basic

Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic

Set a value in a registry key How to: Set Values in Registry Keys in Visual Basic
Example
This example opens the subkey Software\MyCompany\Preferences and sets the value FontColor to "red".
VB
My.Computer.Registry.LocalMachine.OpenSubKey _
("Software\MyCompany\Preferences", True)
My.Computer.Registry.LocalMachine.SetValue("FontColor", "red")

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
Microsoft.Win32.RegistryKey
Microsoft.Win32.Registry.LocalMachine
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Visual Basic Language Reference

My.Computer.Registry.PerformanceData Property
Returns a RegistryKey type, which provides access to HKEY_PERFORMANCE_DATA.

' Usage
Dim value As Microsoft.Win32.RegistryKey = My.Computer.Registry.PerformanceData
' Declaration
Public ReadOnly Property PerformanceData As Microsoft.Win32.RegistryKey

Return Value
RegistryKey
Remarks
HKEY_PERFORMANCE_DATA is used to access performance information for software components. Each software component
creates keys for its objects and counters when it is installed and writes counter data while it is executing. This data is not stored
in the registry, although the registry is used to access it. Instead, calling registry functions via HKEY_PERFORMANCE_DATA
causes the system to collect the data from the appropriate system object managers.
This key does not exist on Windows 98 systems; an attempt to use it other than calling the Name method will throw an
IOException.
This key cannot normally be written to; attempting to create a subkey on it will throw an IOException.
The RegistryPermission class, which is in the System.Security.Permissions namespace, controls access to registry variables.
Registry variables should not be stored in memory locations where code without RegistryPermission can access them.
Similarly, when granting permissions, grant the fewest privileges necessary to get the job done.
Registry permission access values are defined by the RegistryPermissionAccess enumeration. The following table details its
members.
Value Description
AllAccess Create, read, and write access to registry variables.

Create Create access to registry variables.

NoAccess No access to registry variables.

Read Read access to registry variables.

Write Write access to registry variables.


Tasks
The following table lists examples of tasks involving the My.Computer.Registry object.
To See
Create a registry key How to: Create a Registry Key and Set Its Values in Visual Basic

Delete a registry key How to: Delete a Registry Key in Visual Basic

Determine whether a value exists in a registry key How to: Determine if a Value Exists in a Registry Key in Visual Basic

Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic

Set a value in a registry key How to: Set Values in Registry Keys in Visual Basic
Example
This example gets the value ThisSoftware from the MyCompany subkey.
VB
My.Computer.Registry.PerformanceData.GetValue("MyCompany\ThisSoftware")

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
No permissions are required.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
Microsoft.Win32.RegistryKey
Microsoft.Win32.Registry.PerformanceData
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Visual Basic Language Reference

My.Computer.Registry.SetValue Method
Writes a value to a registry key.

' Usage
My.Computer.Registry.SetValue(keyName ,valueName ,value)
My.Computer.Registry.SetValue(keyName ,valueName ,value ,valueKind)
' Declaration
Public Sub SetValue( _
ByVal keyName As String, _
ByVal valueName As String, _
ByVal value As Object _
)
' -or-
Public Sub SetValue( _
ByVal keyName As String, _
ByVal valueName As String, _
ByVal value As Object, _
ByVal valueKind As Microsoft.Win32.RegistryValueKind _
)

Parameters
keyName
String. Name of the key to be written to. Required.
valueName
String. Name of the value to be written. Required.
value
Object. Value to be written. Required.
valueKind
RegistryValueKind. Required.
Remarks
If the specified key or value does not exist, it is created.
Exceptions
The following conditions may cause an exception:
The name of the key is Nothing (ArgumentNullException).
The key name exceeds the 255-character limit (ArgumentException).
The specified hive is not valid (ArgumentException).
The key is closed (IOException).
The path is not valid (IOException).
The registry key is read-only (UnauthorizedAccessException).
Tasks
Here is an example of a task involving the My.Computer.Registry.SetValue method.
To See
Set a value in a registry key How to: Create a Registry Key and Set Its Values in Visual Basic
Example
This example sets the value Name to "Author's Name" in the key HKEY_CURRENT_USER\Software\MyApp.
VB
Dim readValue As Object
readValue = My.Computer.Registry.GetValue _
("HKEY_CURRENT_USER\Software\MyApp", "Name", Nothing)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
Microsoft.Win32.RegistryValueKind
Microsoft.Win32.Registry.SetValue
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Registry Access for Visual Basic 6.0 Users
Visual Basic Language Reference

My.Computer.Registry.Users Property
Returns a RegistryKey type, which provides access to HKEY_USERS.

' Usage
Dim value As Microsoft.Win32.RegistryKey = My.Computer.Registry.Users
' Declaration
Public ReadOnly Property Users As Microsoft.Win32.RegistryKey

Return Value
RegistryKey
Remarks
The My.Computer.Registry object offers methods and properties for working with registry keys. See
My.Computer.Registry Object for more information.
HKEY_USERS is primarily used to store default settings for first-time users.
The RegistryPermission class, which is in the System.Security.Permissions namespace, controls access to registry variables.
Registry variables should not be stored in memory locations where code without RegistryPermission can access them.
Similarly, when granting permissions, grant the fewest privileges necessary to get the job done.
Registry permission access values are defined by the RegistryPermissionAccess enumeration. The following table details its
members.
Value Access to Registry Variables
AllAccess Create, read, and write

Create Create

NoAccess No access.

Read Read

Write Write
Tasks
The following table lists examples of tasks involving the My.Computer.Registry object.
To See
Create a registry key How to: Create a Registry Key and Set Its Values in Visual Basic

Delete a registry key How to: Delete a Registry Key in Visual Basic

Determine whether a value exists in a registry key How to: Determine if a Value Exists in a Registry Key in Visual Basic

Read a value from a registry key How to: Read a Value from a Registry Key in Visual Basic

Set a value in a registry key How to: Set Values in Registry Keys in Visual Basic
Example
This example counts and displays the number of values in the registry key.
VB
Dim keyCount as Integer
keyCount = My.Computer.Registry.Users.ValueCount
MsgBox(keyCount)

Requirements
Namespace: Microsoft.VisualBasic.MyServices
Class: RegistryProxy (provides access to Registry)
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
Troubleshooting: Manipulating the Registry
Reference
My.Computer.Registry Object
Microsoft.Win32.RegistryKey
Microsoft.Win32.Registry.Users
Concepts
Common Registry Tasks
Security and the Registry
Reading from and Writing to the Registry Using My
Visual Basic Language Reference

My.Forms Object
Provides properties for accessing an instance of each Windows form declared in the current project.
Remarks
The My.Forms object provides an instance of each form in the current project. The name of the property is the same as the
name of the form that the property accesses. For information about adding forms to a project, see
How to: Add Windows Forms to a Project.
You can access the forms provided by the My.Forms object by using the name of the form, without qualification. Because the
property name is the same as the form's type name, this allows you to access a form as if it had a default instance. For
example, My.Forms.Form1.Show is equivalent to Form1.Show.
The My.Forms object exposes only the forms associated with the current project. It does not provide access to forms declared
in referenced DLLs. To access a form that a DLL provides, you must use the qualified name of the form, written as
DllName.FormName. For more information, see How to: Access a Form.
You can use the My.Application.OpenForms Property to get a collection of all the application's open forms.
The object and its properties are available only for Windows applications.
Properties
Each property of the My.Forms object provides access to an instance of a form in the current project. The name of the property
is the same as the name of the form that the property accesses, and the property type is the same as the form's type.
Note
If there is a name collision, the property name to access a form is RootNamespace_Namespace_FormName. For example, co
nsider two forms named Form1.If one of these forms is in the root namespace WindowsApplication1 and in the namespace N
amespace1, you would access that form through My.Forms.WindowsApplication1_Namespace1_Form1.

The My.Forms object provides access to the instance of the application's main form that was created on startup. For all other
forms, the My.Forms object creates a new instance of the form when it is accessed and stores it. Subsequent attempts to
access that property return that instance of the form.
You can dispose of a form by assigning Nothing to the property for that form. The property setter calls the Close method of
the form, and then assigns Nothing to the stored value. If you assign any value other than Nothing to the property, the setter
throws an ArgumentException exception.
You can test whether a property of the My.Forms object stores an instance of the form by using the Is or IsNot operator. You
can use those operators to check if the value of the property is Nothing.
Note
Typically, the Is or IsNot operator has to read the value of the property to perform the comparison. However, if the property
currently stores Nothing, the property creates a new instance of the form and then returns that instance. However, the Visua
l Basic compiler treats the properties of the My.Forms object differently and allows the Is or IsNot operator to check the stat
us of the property without altering its value.

Tasks
The following table lists examples of tasks involving the My.Forms object.
To See
Access one form from another form. How to: Access a Form

Control one form from another form. How to: Communicate Between Forms in an Application
Example
This example changes the title of the default SidebarMenu form.
VB
Sub ShowSidebarMenu(ByVal newTitle As String)
If My.Forms.SidebarMenu IsNot Nothing Then
My.Forms.SidebarMenu.Text = newTitle
End If
End Sub

For this example to work, your project must have a form named SidebarMenu. For more information, see
How to: Add Windows Forms to a Project.
This code will work only in a Windows Application project.
Requirements
Availability by Project Type
Project type Available
Windows Application Yes

Class Library No

Console Application No

Windows Control Library No

Web Control Library No

Windows Service No

Web Site No
See Also
Tasks
How to: Add Windows Forms to a Project
How to: Access a Form
Reference
My.Application.OpenForms Property
My.Application.OpenForms Property
Is Operator (Visual Basic)
IsNot Operator
Form
Close
Concepts
Accessing Application Forms
Visual Basic Language Reference

My.Log Object
Provides a property and methods for writing event and exception information to the application's log listeners.
Remarks
The My.Log object provides a straightforward entry point with which to access the .NET Framework's logging services. The
WriteEntry and WriteException methods write messages to the application's log listeners. The listeners can be configured by
the application's configuration file. For more information, see
Walkthrough: Changing Where My.Application.Log Writes Information and Working with Application Logs in Visual Basic.
The My.Log object is only available for ASP.NET applications. For client applications, use My.Application.Log. For more
information, see My.Application.Log Object.
Requirements
Namespace: Microsoft.VisualBasic.Logging
Class: Log
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Write Log Messages
How to: Log Exceptions in Visual Basic
Walkthrough: Determining Where My.Application.Log Writes Information
Reference
My.Log Object Members
My.Application Object
My.Application.Log Object
Microsoft.VisualBasic.Logging.Log
Visual Basic Language Reference

My.Log Object Members


The My.Log Object provides a property and methods for writing event and exception information to the application's log
listeners.
Properties
Property Description
TraceSource Gets to the TraceSource object that underlies the My.Log object.
This is an advanced member; it does not appear in IntelliSense unless you click the All tab.
Methods
Method Description
WriteEntry Writes a message to the application's log listeners.

WriteException Writes exception information to the application's log listeners.


See Also
Reference
My.Log Object
Visual Basic Language Reference

My.Request Object
Gets the HttpRequest object for the requested page.
Remarks
The My.Request object contains information about the current HTTP request.
The My.Request object is available only for ASP.NET applications.
Example
The following example gets the header collection from the My.Request object and uses the My.Response object to write it to
the ASP.NET page.
VB
<script runat="server">
Public Sub ShowHeaders()
' Load the header collection from the Request object.
Dim coll As System.Collections.Specialized.NameValueCollection
coll = My.Request.Headers

' Put the names of all keys into a string array.


For Each key As String In coll.AllKeys
My.Response.Write("Key: " & key & "<br>")

' Get all values under this key.


For Each value As String In coll.GetValues(key)
My.Response.Write("Value: " & _
Server.HtmlEncode(value) & "<br>")
Next
Next
End Sub
</script>

See Also
Reference
My.Response Object
HttpRequest
Visual Basic Language Reference

My.Response Object
Gets the HttpResponse object associated with the Page. This object allows you to send HTTP response data to a client and
contains information about that response.
Remarks
The My.Response object contains the current HttpResponse object associated with the page.
The My.Response object is only available for ASP.NET applications.
Example
The following example gets the header collection from the My.Request object and uses the My.Response object to write it to
the ASP.NET page.
VB
<script runat="server">
Public Sub ShowHeaders()
' Load the header collection from the Request object.
Dim coll As System.Collections.Specialized.NameValueCollection
coll = My.Request.Headers

' Put the names of all keys into a string array.


For Each key As String In coll.AllKeys
My.Response.Write("Key: " & key & "<br>")

' Get all values under this key.


For Each value As String In coll.GetValues(key)
My.Response.Write("Value: " & _
Server.HtmlEncode(value) & "<br>")
Next
Next
End Sub
</script>

See Also
Reference
My.Request Object
HttpResponse
Visual Basic Language Reference

My.Resources Object
Provides properties and classes for accessing the application's resources.
Remarks
The My.Resources object provides access to the application's resources and allows you to dynamically retrieve resources for
your application. For more information, see Managing Application Resources.
The My.Resources object exposes only global resources. It does not provide access to resource files associated with forms.
You must access the form resources from the form. For more information, see Walkthrough: Localizing Windows Forms.
You can access the application's culture-specific resource files from the My.Resources object. By default, the My.Resources
object looks up resources from the resource file that matches the culture in My.Application.UICulture Property. However, you
can override this behavior and specify a particular culture to use for the resources. For more information, see
Resources in Applications.
Properties
The properties of the My.Resources object provide read-only access to your application's resources. To add or remove
resources, use the Project Designer. For more information, see How to: Add or Remove Resources. Resources added through
the Project Designer are accessed using My.Resources.resourceName.
You can also add or remove resource files by selecting your project in Solution Explorer and choosing Add New Item or
Add Existing Item from the Project menu. Resources added this way are available using
My.Resources.resourceFileName.resourceName.
Each resource has a name, category, and value, and these resource settings determine how the property to access the resource
appears in the My.Resources object. For resources added in the Project Designer:
The name determines the name of the property,
The resource data is the value of the property,
The category determines the type of the property:
Categ Property data type
ory
String String
s

Imag Bitmap
es

Icons Icon

Audio UnmanagedMemoryStream
The UnmanagedMemoryStream class derives from the Stream class, so it can be used with methods that take s
treams, such as the My.Computer.Audio.Play Method.

Files String for text files.


Bitmap for image files.
Icon for icon files.
UnmanagedMemoryStream for sound files.

Other Determined by the information in the designer's Type column.

Classes
The My.Resources object exposes each resource file as a class with shared properties. The class name is the same as the name
of the resource file. As described in the previous section, the resources in a resource file are exposed as properties in the class.
Tasks
The following table lists examples of tasks involving the My.Resources object.
To See
Retrieve a string resource How to: Retrieve String Resources in Visual Basic

Retrieve an image resource How to: Retrieve Image Resources in Visual Basic

Retrieve an icon resource How to: Retrieve Icon Resources in Visual Basic

Retrieve an audio resource How to: Retrieve Audio Resources in Visual Basic

Retrieve a localized resource How to: Retrieve Localized Resources in Visual Basic
Example
This example sets the icon of the form to the icon named Form1Icon that is stored in the application's resource file.
VB
Sub SetFormIcon()
Me.Icon = My.Resources.Form1Icon
End Sub

For this example to work, your application must have an icon named Form1Icon in the application's resource file. For more
information, see How to: Add or Remove Resources.
See Also
Tasks
How to: Retrieve String Resources in Visual Basic
How to: Retrieve Image Resources in Visual Basic
How to: Retrieve Icon Resources in Visual Basic
How to: Retrieve Audio Resources in Visual Basic
How to: Retrieve Localized Resources in Visual Basic
How to: Add or Remove Resources
Walkthrough: Localizing Windows Forms
Reference
My.Application.UICulture Property
Concepts
Resources in Applications
Other Resources
Managing Application Resources
Visual Basic Language Reference

My.Settings Object
Provides properties and methods for accessing the application's settings.
Remarks
The My.Settings object provides access to the application's settings and allows you to dynamically store and retrieve property
settings and other information for your application. For more information, see Managing Application Settings.
Properties
The properties of the My.Settings object provide access to your application's settings. To add or remove settings, use the
Settings Designer. For more information, see How to: Add or Remove Application Settings.
Each setting has a Name, Type, Scope, and Value, and these settings determine how the property to access each setting
appears in the My.Settings object:
Name determines the name of the property.
Type determines the type of the property.
Scope indicates if the property is read-only. If the value is Application, the property is read-only; if the value is User, the
property is read-write.
Value is the default value of the property.
Methods
Method Description
Reload Reloads the user settings from the last saved values.

Save Saves the current user settings.

The My.Settings object also provides advanced properties and methods, inherited from the ApplicationSettingsBase class.
Tasks
The following table lists examples of tasks involving the My.Settings object.
To See
Read an application setting How to: Read Application Settings in Visual Basic

Change a user setting How to: Change User Settings in Visual Basic

Persist user settings How to: Persist User Settings in Visual Basic

Create a property grid for user settings How to: Create Property Grids for User Settings in Visual Basic
Example
This example displays the value of the Nickname setting.
VB
Sub ShowNickname()
MsgBox("Nickname is " & My.Settings.Nickname)
End Sub

For this example to work, your application must have a Nickname setting, of type String. For more information, see
How to: Add or Remove Application Settings.
See Also
Tasks
How to: Read Application Settings in Visual Basic
How to: Change User Settings in Visual Basic
How to: Persist User Settings in Visual Basic
How to: Create Property Grids for User Settings in Visual Basic
How to: Add or Remove Application Settings
Reference
ApplicationSettingsBase
Other Resources
Managing Application Settings
Visual Basic Language Reference

My.User Object
Provides access to the information about the current user.
Remarks
The properties and methods exposed by the My.User object provide access to the information about the current user. The
meaning of "current user" differs slightly between Windows and Web applications. In a Windows application, the current user
is the user who runs the application. In a Web application, the current user is the user who accesses the application.
The My.User property also provides access to the IPrincipal for the current user. A principal object represents the user's
security context, including that user's identity and any roles to which the user belongs.
For Windows applications, this property provides the same functionality as the CurrentPrincipal property. For Web
applications, this property provides the same functionality as the User property of the object returned by the Current property.
Note
For Windows applications, only projects built on the Windows Application template initialize the My.User object by defaul
t. In all other Windows project types, you must initialize the My.User object by calling the
My.User.InitializeWithWindowsUser Method explicitly or by assigning a value to CurrentPrincipal.

Note
The My.User object cannot report information about the current Windows user when run under Windows 95 and Windows
98 because those operating systems do not support the concept of a logged-on user. You must implement custom authentic
ation to use the My.User object on those operating systems. For more information, see
Walkthrough: Implementing Custom Authentication and Authorization.

Tasks
The following table lists examples of tasks involving the My.User object.
To See
Get the user's login name How to: Determine a User's Login Name

Get the user's domain name, if the application uses Wi How to: Determine the User's Domain
ndows authentication

Determine the user's role How to: Determine if a User is in a Group

Implement custom authentication Walkthrough: Implementing Custom Authentication and Authorization


Example
This example checks if the application is using Windows or custom authentication, and uses that information to parse the
My.User.Name property.
VB
Function GetUserName() As String
If TypeOf My.User.CurrentPrincipal Is _
Security.Principal.WindowsPrincipal Then
' The application is using Windows authentication.
' The name format is DOMAIN\USERNAME.
Dim parts() As String = Split(My.User.Name, "\")
Dim username As String = parts(1)
Return username
Else
' The application is using custom authentication.
Return My.User.Name
End If
End Function
Requirements
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
My.User Object Members
IPrincipal
CurrentPrincipal
User
Current
Visual Basic Language Reference

My.User Object Members


The My.User Object provides access to the information about the current user.
Properties
Property Description
CurrentPrincipal Gets or sets the current principal (for role-based security).
This is an advanced member; it does not show in IntelliSense unless you click the All tab.

IsAuthenticated Gets a value that indicates whether the user has been authenticated.

Name Gets the name of the current user.


Methods
Method Description
InitializeWithWindowsUser Sets the thread's current principal to the Windows user that started the application.
This is an advanced member; it does not show in IntelliSense unless you click the All tab.

IsInRole Determines whether the current user belongs to the specified role.
See Also
Reference
My.User Object
Visual Basic Language Reference

My.User.CurrentPrincipal Property
Gets or sets the current principal (for role-based security).

' Usage
Dim value As System.Security.Principal.IPrincipal = My.User.CurrentPrincipal
' Declaration
Public Property CurrentPrincipal As System.Security.Principal.IPrincipal

Return Value
A IPrincipal value representing the security context.
Exceptions
The following conditions can cause an exception:
The caller does not have the permission required to set the principal (SecurityException).
Remarks
You can set the My.User.CurrentPrincipal property to an object that implements the IPrincipal interface to enable custom
authentication.
In most project types, this property gets and sets the thread's current principal. In an ASP.NET application, this property gets
and sets the security information for the current HTTP request's user identity.
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
Tasks
To See
Get the user's login name How to: Determine a User's Login Name

Get the user's domain name, if the application uses Wi How to: Determine the User's Domain
ndows authentication

Implement custom authentication Walkthrough: Implementing Custom Authentication and Authorization


Example
This example checks if the application is using Windows or custom authentication, and uses that information to parse
My.User.Name property.
VB
Function GetUserName() As String
If TypeOf My.User.CurrentPrincipal Is _
Security.Principal.WindowsPrincipal Then
' The application is using Windows authentication.
' The name format is DOMAIN\USERNAME.
Dim parts() As String = Split(My.User.Name, "\")
Dim username As String = parts(1)
Return username
Else
' The application is using custom authentication.
Return My.User.Name
End If
End Function

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: User, WebUser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
SecurityPermission Describes a set of security permissions applied to code. Associated enumeration: ControlPrincipal.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Determine a User's Login Name
How to: Determine the User's Domain
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User Object
System.Security.Principal.IPrincipal
Microsoft.VisualBasic.ApplicationServices.User.CurrentPrincipal
Visual Basic Language Reference

My.User.InitializeWithWindowsUser Method
Sets the thread's current principal to the Windows user that started the application.

' Usage
My.User.InitializeWithWindowsUser()
' Declaration
Public Sub InitializeWithWindowsUser()

Remarks
You can use the My.User.InitializeWithWindowsUser method to set the thread's current principal to the Windows user that
started the application. The Visual Basic Application Model in a Windows application calls this method at startup by default. In
other project types, you must set the thread's current principal by calling this method explicitly or by assigning a value to
System.Threading.Thread.CurrentPrincipal.
In Windows projects, the My.User object is based on the thread's current principal; therefore, this method can change the
information My.User returns. In an ASP.NET application, the My.User object is based on the current HTTP request's user
identity, and is unaffected by this method.
Note
The exact behavior of the My.User object depends on the type of application and on the operating system on which the appli
cation runs. For more information, see My.User Object.

This is an advanced member; it does not show in IntelliSense unless you click the All tab.
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: User, WebUser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
SecurityPermission Describes a set of security permissions applied to code. Associated enumeration: ControlPrincipal.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User Object
Microsoft.VisualBasic.ApplicationServices.User.InitializeWithWindowsUser
Visual Basic Language Reference

My.User.IsAuthenticated Property
Gets a value that indicates whether the user has been authenticated.

' Usage
Dim value As Boolean = My.User.IsAuthenticated
' Declaration
Public ReadOnly Property IsAuthenticated As Boolean

Return Value
True if the user was authenticated; otherwise, False.
Remarks
The My.User.IsAuthenticated property allows your code to determine if the current user has been authenticated.
Note
The exact behavior of My.User object depends on the type of the application and on the operating system on which the appli
cation runs. For more information, see My.User Object.

Tasks
To See
Implement custom authentication Walkthrough: Implementing Custom Authentication and Authorization
Example
This example verifies that the user has been authenticated before accessing a resource.
VB
If My.User.IsAuthenticated Then
' Insert code to access a resource here.
End If

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: User, WebUser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes


Web Site Yes
Permissions
The following permission may be necessary:
Permission Description
SecurityPermission Describes a set of security permissions applied to code. Associated enumeration: ControlPrincipal.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User Object
Microsoft.VisualBasic.ApplicationServices.User.IsAuthenticated
Visual Basic Language Reference

My.User.IsInRole Method
Determines whether the current user belongs to the specified role.

' Usage
Dim value As Boolean = My.User.IsInRole(role)
Dim value As Boolean = My.User.IsInRole(role)
' Declaration
Public Function IsInRole( _
ByVal role As String _
) As Boolean
' -or-
Public Function IsInRole( _
ByVal role As BuiltInRole _
) As Boolean

Parameters
role
String or BuiltInRole Enumeration. The role for which to check membership.
Return Value
True if the current user is a member of the specified role; otherwise, False.
Remarks
The My.User.IsInRole method allows your code to determine if the current user is a member of the specified role.
The overload of the My.User.IsInRole method that takes a string provides easy access to the IsInRole method of the current
principal.
The overload of the My.User.IsInRole method that takes a BuiltInRole enumeration behaves differently, depending on the
current principal. If it is a Windows user principal (WindowsPrincipal), this function converts role to the equivalent
WindowsBuiltInRole enumeration and returns the result of calling IsInRole. If the current principal is any other principal, this
function passes the name of the enumeration value in role to the principal's IsInRole method.
Note
The exact behavior of the My.User object depends on the type of the application and on the operating system on which the a
pplication runs. For more information, see My.User Object.

Tasks
To See
Determine the user's role How to: Determine if a User is in a Group
Example
This example checks if the user is an administrator before accessing a resource.
VB
If My.User.IsInRole( _
ApplicationServices.BuiltInRole.Administrator) Then
' Insert code to access a resource here.
End If

Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: User, WebUser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
SecurityPermission Describes a set of security permissions applied to code. Associated enumeration: ControlPrincipal.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Determine if a User is in a Group
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User Object
BuiltInRole Enumeration
Microsoft.VisualBasic.ApplicationServices.BuiltInRole
Microsoft.VisualBasic.ApplicationServices.User.IsInRole(System.String)
Visual Basic Language Reference

My.User.Name Property
Gets the name of the current user.

' Usage
Dim value As String = My.User.Name
' Declaration
Public ReadOnly Property Name As String

Return Value
String. The name of the current user.
Remarks
You can use the My.User object to get information about the current user.
The principal that authenticates the user also controls the format of the user name. By default, an application uses Windows
authentication, and the user name has the format DOMAIN\USERNAME. A custom implementation of the principal does not
necessarily use the same format.
Note
The My.User.Name property returns an empty string when run under Windows 95 and Windows 98 because those operati
ng systems do not recognize user names.

Note
The exact behavior of the My.User object depends on the type of the application and on the operating system on which the a
pplication runs. For more information, see My.User Object.

Tasks
The following table lists examples of tasks involving the My.User.Name property.
To See
Get the user's login name How to: Determine a User's Login Name

Get the user's domain name, if the application uses Wi How to: Determine the User's Domain
ndows authentication

Implement custom authentication Walkthrough: Implementing Custom Authentication and Authorization


Example
This example checks if the application is using Windows or custom authentication, and uses that information to parse the
My.User.Name property.
VB
Function GetUserName() As String
If TypeOf My.User.CurrentPrincipal Is _
Security.Principal.WindowsPrincipal Then
' The application is using Windows authentication.
' The name format is DOMAIN\USERNAME.
Dim parts() As String = Split(My.User.Name, "\")
Dim username As String = parts(1)
Return username
Else
' The application is using custom authentication.
Return My.User.Name
End If
End Function
Requirements
Namespace: Microsoft.VisualBasic.ApplicationServices
Class: User, WebUser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site Yes


Permissions
The following permission may be necessary:
Permission Description
SecurityPermission Describes a set of security permissions applied to code. Associated enumeration: ControlPrincipal.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Determine a User's Login Name
How to: Determine the User's Domain
Walkthrough: Implementing Custom Authentication and Authorization
Reference
My.User Object
Microsoft.VisualBasic.ApplicationServices.User.Name
Visual Basic Language Reference

My.WebServices Object
Provides properties for creating and accessing a single instance of each XML Web service referenced by the current project.
Remarks
The My.WebServices object provides an instance of each Web service referenced by the current project. Each instance is
instantiated on demand. You can access these Web services through the properties of the My.WebServices object. The name
of the property is the same as the name of the Web service that the property accesses. Any class that inherits from
SoapHttpClientProtocol is a Web service. For information about adding Web services to a project, see
How to: Access an XML Web Service in Managed Code.
The My.WebServices object exposes only the Web services associated with the current project. It does not provide access to
Web services declared in referenced DLLs. To access a Web service that a DLL provides, you must use the qualified name of the
Web service, in the form DllName.WebServiceName. For more information, see
Accessing XML Web Services in Managed Code.
The object and its properties are not available for Web applications.
Properties
Each property of the My.WebServices object provides access to an instance of a Web service referenced by the current
project. The name of the property is the same as the name of the Web service that the property accesses, and the property type
is the same as the Web service's type.
Note
If there is a name collision, the property name to access a Web service is RootNamespace_Namespace_ServiceName. For exa
mple, consider two Web services named Service1.If one of these services is in the root namespace WindowsApplication1 an
d in the namespace Namespace1, you would access that service through My.WebServices.WindowsApplication1_Namespace1_
Service1.

When you first access one of the My.WebServices object's properties, it creates a new instance of the Web service and stores
it. Subsequent accesses of that property return that instance of the Web service.
You can dispose of a Web service by assigning Nothing to the property for that Web service. The property setter assigns
Nothing to the stored value. If you assign any value other than Nothing to the property, the setter throws an
ArgumentException exception.
You can test whether a property of the My.WebServices object stores an instance of the Web service by using the Is or IsNot
operator. You can use those operators to check if the value of the property is Nothing.
Note
Typically, the Is or IsNot operator has to read the value of the property to perform the comparison. However, if the property
currently stores Nothing, the property creates a new instance of the Web service and then returns that instance. However, th
e Visual Basic compiler treats the properties of the My.WebServices object specially, and allows the Is or IsNot operator to
check the status of the property without altering its value.

Tasks
The following table lists an example of a task involving the My.Forms object.
To See
Call a Web Service asynchronously and handle an event when it completes How to: Call a Web Service Asynchronously
Example
This example calls the FahrenheitToCelsius method of the TemperatureConverter XML Web service, and returns the result.
VB
Function ConvertFromFahrenheitToCelsius( _
ByVal dFahrenheit As Double) _
As Double
Return My.WebServices.TemperatureConverter.FahrenheitToCelsius(dFahrenheit)
End Function

For this example to work, your project must reference a Web service named Converter, and that Web service must expose the
ConvertTemperature method. For more information, see How to: Access an XML Web Service in Managed Code.

This code does not work in a Web application project.


Requirements
Availability by Project Type
Project type Available
Windows Application Yes

Class Library Yes

Console Application Yes

Windows Control Library Yes

Web Control Library Yes

Windows Service Yes

Web Site No
See Also
Tasks
How to: Access an XML Web Service in Managed Code
Reference
SoapHttpClientProtocol
ArgumentException
Concepts
Accessing Application Web Services
Other Resources
Accessing XML Web Services in Managed Code
Visual Basic Language Reference

TextFieldParser Object
Provides methods and properties for parsing structured text files.

Public Class TextFieldParser

Exceptions
The following condition may cause an exception:
A text field does not match the specified format. For example, in a fixed-width file, one of the fields does not match the
specified width. (MalformedLineException).
Remarks
The TextFieldParser object provides methods and properties for parsing structured text files. Parsing a text file with the
TextFieldParser is similar to iterating over a text file, while the ReadFields method to extract fields of text is similar to
splitting the strings.
The TextFieldParser can parse two types of files: delimited or fixed-width. Some properties, such as Delimiters and
HasFieldsEnclosedInQuotes are meaningful only when working with delimited files, while the FieldWidths property is
meaningful only when working with fixed-width files.
Tasks
The following table lists examples of tasks involving the Microsoft.VisualBasic.FileIO.TextFieldParser object.
To See
Read from a delimited text file How to: Read From Comma-Delimited Text Files in Visual Basic

Read from a fixed-width text file How to: Read From Fixed-width Text Files in Visual Basic

Read from a text file with multiple formats How to: Read From Text Files with Multiple Formats in Visual Basic
Example
This example parses through a tab-delimited text file, Bigfile.
VB
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser _
("c:\logs\bigfile")
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {vbTab}
Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
' Include code here to handle the row.
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
" is invalid. Skipping")
End Try
End While
End Using

This example depends on the existence of a function, processFields, which processes the fields as they are read.
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
TextFieldParser Object Members
TextFieldParser.CommentTokens Property
TextFieldParser.Delimiters Property
TextFieldParser.EndOfData Property
TextFieldParser.ErrorLine Property
TextFieldParser.ErrorLineNumber Property
TextFieldParser.FieldWidths Property
TextFieldParser.HasFieldsEnclosedInQuotes Property
TextFieldParser.LineNumber Property
TextFieldParser.TextFieldType Property
TextFieldParser.TrimWhiteSpace Property
TextFieldParser.Close Method
TextFieldParser.PeekChars Method
TextFieldParser.ReadFields Method
TextFieldParser.ReadLine Method
TextFieldParser.ReadToEnd Method
TextFieldParser.SetDelimiters Method
TextFieldParser.SetFieldWidths Method
My.Computer.FileSystem.OpenTextFieldParser Method
Microsoft.VisualBasic.FileIO.TextFieldParser
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference

TextFieldParser Object Members


The TextFieldParser object provides methods and properties for parsing structured text files as shown in the following table.
Properties
CommentTokens String. Lines beginning with the specified comment token are skipped by the parser.

Delimiters String. The delimiters for the text file. Valid only for delimited files.

EndOfData Boolean. Returns True if there are no non-blank, non-comment lines between the current cursor
position and the end of the file.

ErrorLine String. Returns the line that caused the most recent MalformedLineException. Default is "".

ErrorLineNumber Long. Returns the line number that caused the most recent MalformedLineException. Default is
-1.

FieldWidths Integer. Denotes the width of each column in the text file. Valid only for fixed-width files.

HasFieldsEnclosedInQuotes Boolean. Returns True if fields can be enclosed in quotation marks. Valid only for delimited files.
Default is True.

LineNumber Integer. Returns the current line number, or -1 if no more characters are available.

TextFieldType FieldType. The type of file, delimited or fixed-width. Default is Delimited.

TrimWhiteSpace Boolean. Indicates whether leading and trailing white spaces should be trimmed from field values
.
Methods
Close Closes the underlying stream.

PeekChars Reads the specified number of characters without advancing the cursor.

ReadFields Reads all fields on the current line, returns them as an array of strings, and advances cursor to the next line.

ReadLine Returns the current line as a String and advances the cursor to the next line.

ReadToEnd Reads the remainder of the stream and returns it as a String.

SetDelimiters Sets the delimiters for the reader to the specified values and the field type to Delimited.

SetFieldWidths Sets the delimiters for the reader to the specified values and the field type to FixedWidth.
See Also
Reference
TextFieldParser Object
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference

TextFieldParser Constructor
Initializes a new instance of the TextFieldParser class.

' Usage
Dim value As New TextFieldParser(path)
Dim value As New TextFieldParser(path, defaultEncoding)
Dim value As New TextFieldParser(path, defaultEncoding, detectEncoding)
Dim value As New TextFieldParser(stream)
Dim value As New TextFieldParser(stream, defaultEncoding)
Dim value As New TextFieldParser(stream, defaultEncoding, detectEncoding)
Dim value As New TextFieldParser(stream, defaultEncoding, detectEncoding, leaveOpen)
Dim value As New TextFieldParser(reader)
' Declaration
Public Sub New( _
ByVal path As String _
)
' -or-
Public Sub New( _
ByVal path As String, _
ByVal defaultEncoding As System.Text.Encoding _
)
' -or-
Public Sub New( _
ByVal path As String, _
ByVal defaultEncoding As System.Text.Encoding, _
ByVal detectEncoding As Boolean _
)
' -or-
Public Sub New( _
ByVal stream As Stream _
)
' -or-
Public Sub New( _
ByVal stream As Stream, _
ByVal defaultEncoding As System.Text.Encoding _
)
' -or-
Public Sub New( _
ByVal stream As Stream, _
ByVal defaultEncoding As System.Text.Encoding, _
ByVal detectEncoding As Boolean _
)
' -or-
Public Sub New( _
ByVal stream As Stream, _
ByVal defaultEncoding As System.Text.Encoding, _
ByVal detectEncoding As Boolean, _
ByVal leaveOpen As Boolean _
)
' -or-
Public Sub New( _
ByVal reader As TextReader _
)

Parameters
path
String. The complete path of the file to be parsed.
stream
Stream. The stream to be parsed.
defaultEncoding
Encoding. The character encoding to use if encoding is not determined from file. Default is UTF8.
detectEncoding
Boolean. Indicates whether to look for byte order marks at the beginning of the file. Default is True.
leaveOpen
Boolean. Indicates whether to leave stream open when the TextFieldParser object is closed. Default is False.
reader
TextReader. The TextReader stream to be parsed.
Remarks
Creates a new TextFieldParser object to parse the file or stream represented by the path, stream, or reader parameters.
If the defaultEncoding parameter is specified, this constructor uses it as the default encoding.
If the detectEncoding parameter is True, this constructor attempts to detect the encoding by looking at the first three bytes of
the file or stream. It automatically recognizes UTF-8, little-endian Unicode, and big-endian Unicode text if the file starts with the
appropriate byte-order marks. Otherwise, the encoding specified by defaultEncoding is used.
Caution
When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cul
tural setting, the characters might not be interpretable and could cause an exception to be thrown.

Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Reference
TextFieldParser Object
Microsoft.VisualBasic.FileIO.TextFieldParser.#ctor(System.IO.Stream)
Visual Basic Language Reference

TextFieldParser.Close Method
Closes the current TextFieldParser object.

' Usage
TextFieldParserObject.Close()
' Declaration
Public Sub Close()

Remarks
This method closes a TextFieldParser object.
Example
This example closes the TextFieldParser FileReader.
VB
FileReader.Close()

Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Reference
TextFieldParser Object
Microsoft.VisualBasic.FileIO.TextFieldParser.Close
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference

TextFieldParser.CommentTokens Property
Defines comment tokens. A comment token is a string that, when placed at the beginning of a line, indicates that the line is a
comment and should be ignored by the parser.

' Usage
Dim value As String() = TextFieldParserObject.CommentTokens
' Declaration
Public Property CommentTokens As String()

Return Value
String ().
Exceptions
The following condition may produce an exception:
A comment token includes white space (ArgumentException).
Remarks
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
Zero-length comment tokens are ignored.
Example
This example specifies that for the TextFieldParser, FileReader lines beginning with a single quotation mark (') should be
ignored.
VB
FileReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
FileReader.CommentTokens = New String() {"'"}

Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Reference
TextFieldParser Object
Microsoft.VisualBasic.FileIO.TextFieldParser.CommentTokens
Visual Basic Language Reference

TextFieldParser.Delimiters Property
Defines the delimiters for a text file.

' Usage
Dim value As String() = TextFieldParserObject.Delimiters
' Declaration
Public Property Delimiters As String()

Return Value
String ().
Exceptions
The following condition may result in an exception:
An attempt to use a newline character, an empty string, or Nothing as a delimiter (ArgumentException).
Remarks
This property is meaningful only if TextFieldType = FieldType.Delimited.
Defining the delimiters for a text file can also be accomplished with the SetDelimiters method. For more information, see
TextFieldParser.SetDelimiters Method.
Tasks
The following table lists an example of a task involving the Delimiters property.
To See
Read from a delimited text file How to: Read From Comma-Delimited Text Files in Visual Basic
Example
This example specifies that the delimiter for the TextFieldParser object, FileReader, is a comma (,).
VB
FileReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
FileReader.Delimiters = New String() {","}

Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Reference
TextFieldParser Object
TextFieldParser.SetDelimiters Method
Microsoft.VisualBasic.FileIO.TextFieldParser.Delimiters
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference

TextFieldParser.EndOfData Property
Returns True if there are no non-blank, non-comment lines between the current cursor position and the end of the file.

' Usage
Dim value As Boolean = TextFieldParserObject.EndOfData
' Declaration
Public ReadOnly Property EndOfData As Boolean

Return Value
Boolean.
Remarks
This property can be used when reading from files to determine the end of the data being read.
Tasks
The following table lists examples of tasks involving the EndOfData property.
To See
Read from a delimited file How to: Read From Comma-Delimited Text Files in Visual Basic

Read from a fixed-width file How to: Read From Fixed-width Text Files in Visual Basic
Example
This example uses the EndofData property to loop through all the fields in the file with the TextFieldReader, FileReader.
VB
Dim StdFormat As Integer() = {5, 10, 11, -1}
Dim ErrorFormat As Integer() = {5, 5, -1}
Using FileReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
FileReader.TextFieldType = FileIO.FieldType.FixedWidth
FileReader.FieldWidths = StdFormat
Dim CurrentRow As String()
While Not FileReader.EndOfData
Try
Dim RowType As String = FileReader.PeekChars(3)
If String.Compare(RowType, "Err") = 0 Then
' If this line describes an error, the format of the row will be different.
FileReader.SetFieldWidths(ErrorFormat)
CurrentRow = FileReader.ReadFields
FileReader.SetFieldWidths(StdFormat)
Else
' Otherwise parse the fields normally
CurrentRow = FileReader.ReadFields
For Each newString As String In CurrentRow
My.Computer.FileSystem.WriteAllText("newFile.txt", newString, True)
Next
End If
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using

Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permissions are required:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

SecurityPermission Describes a set of security permissions applied to code. Associated enumeration: ControlEvidence.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
TextFieldParser Object
Microsoft.VisualBasic.FileIO.TextFieldParser.EndOfData
Visual Basic Language Reference

TextFieldParser.ErrorLine Property
Returns the line that caused the most recent MalformedLineException exception.

' Usage
Dim value As String = TextFieldParserObject.ErrorLine
' Declaration
Public ReadOnly Property ErrorLine As String

Return Value
String.
Remarks
If no MalformedLineException exceptions have been thrown, an empty string is returned.
The TextFieldParser.ErrorLineNumber Property can be used to display the number of the line causing the exception.
Tasks
The following table lists examples of tasks involving the ErrorLine property.
To See
Read from a delimited file How to: Read From Comma-Delimited Text Files in Visual Basic

Read from a fixed-width file How to: Read From Fixed-width Text Files in Visual Basic
Example
This example uses the ErrorLine property to display the line causing the current MalformedLineException exception.
VB
Dim FileReader As Microsoft.VisualBasic.FileIO.TextFieldParser
FileReader = My.Computer.FileSystem.OpenTextFieldParser("C:\test.txt")
Dim currentRow As String()
While Not FileReader.EndOfData
Try
currentRow = FileReader.ReadFields
For Each currentField As String In currentRow
My.Computer.FileSystem.WriteAllText _
("C://testfile.txt", currentField, True)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & FileReader.ErrorLine & " is not valid.")
End Try
End While

Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
How to: Read From Text Files with Multiple Formats in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Test Code with a Try…Catch Block in Visual Basic
Reference
TextFieldParser Object
Microsoft.VisualBasic.FileIO.TextFieldParser.ErrorLine
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference

TextFieldParser.ErrorLineNumber Property
Returns the number of the line that caused the most recent MalformedLineException exception.

' Usage
Dim value As Long = TextFieldParserObject.ErrorLineNumber
' Declaration
Public ReadOnly Property ErrorLineNumber As Long

Return Value
Long.
Exceptions
This property throws no exceptions.
Remarks
If no MalformedLineException exceptions have been thrown, -1 is returned.
The TextFieldParser.ErrorLine Property can be used to display the number of the line causing the exception. Blank lines and
comments are not ignored when determining the line number.
Tasks
The following table lists examples of tasks involving the ErrorLineNumber property.
To See
Read from a delimited file How to: Read From Comma-Delimited Text Files in Visual Basic

Read from a fixed-width file How to: Read From Fixed-width Text Files in Visual Basic
Example
This example uses the ErrorLineNumber property to display the location of the line causing the current
MalformedLineException exception.
VB
Dim FileReader As Microsoft.VisualBasic.FileIO.TextFieldParser
FileReader = My.Computer.FileSystem.OpenTextFieldParser("C:\test.txt")
Dim currentRow As String()
While Not FileReader.EndOfData
Try
currentRow = FileReader.ReadFields
For Each currentField As String In currentRow
My.Computer.FileSystem.WriteAllText _
("C://testfile.txt", currentField, True)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & FileReader.ErrorLineNumber & " is not valid.")
End Try
End While

Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
How to: Read From Text Files with Multiple Formats in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Test Code with a Try…Catch Block in Visual Basic
Reference
TextFieldParser Object
Microsoft.VisualBasic.FileIO.TextFieldParser.ErrorLineNumber
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference

TextFieldParser.FieldWidths Property
Denotes the width of each column in the text file being parsed.

' Usage
Dim value As Integer() = TextFieldParserObject.FieldWidths
' Declaration
Public Property FieldWidths As Integer()

Return Value
Integer ().
Exceptions
The following condition may produce an exception:
A width value in any place other than the last entry of the array is less than or equal to zero (ArgumentException).
Remarks
This property is meaningful only if TextFieldParser.TextFieldType Property = FieldType.FixedWidth. If the last entry in the
array is less than or equal to zero, the field is assumed to be of variable width.
The SetFieldWidths method can also be used to set field widths. For more information, see
TextFieldParser.SetFieldWidths Method.
Tasks
The following table lists examples of tasks involving the FieldWidths property.
To See
Read from a fixed-width text file How to: Read From Fixed-width Text Files in Visual Basic
Example
This example reads the file ParserText.txt, specifying the widths; the first column is 5 characters wide, the second is 10, the
third is 11, and the fourth is of variable width
VB
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.txt")
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
MyReader.FieldWidths = New Integer() {5, 10, 11, -1}
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
End Using

Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
TextFieldParser Object
FieldType Enumeration
Microsoft.VisualBasic.FileIO.TextFieldParser.FieldWidths
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference

TextFieldParser.HasFieldsEnclosedInQuotes Property
Denotes whether fields are enclosed in quotation marks when parsing a delimited file.

' Usage
Dim value As Boolean = TextFieldParserObject.HasFieldsEnclosedInQuotes
' Declaration
Public Property HasFieldsEnclosedInQuotes As Boolean

Return Value
Boolean.
Remarks
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
If the property is True, the parser assumes that fields are enclosed in quotation marks (" ") and may contain line endings.
If a field is enclosed in quotation marks, for example, abc, “field2a,field2b”, field3 and this property is True, then all text
enclosed in quotation marks will be returned as is; this example would return abc|field2a,field2b|field3. Setting this
property to False would make this example return abc|”field2a|field2b”|field3.
Example
This example sets the HasFieldsEnclosedInQuotes property to True for myReader.
VB
FileReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
FileReader.Delimiters = New String() {","}
FileReader.CommentTokens = New String() {""}
FileReader.HasFieldsEnclosedInQuotes = True

Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Reference
TextFieldParser Object
Microsoft.VisualBasic.FileIO.TextFieldParser.HasFieldsEnclosedInQuotes
Visual Basic Language Reference

TextFieldParser.LineNumber Property
Returns the current line number, or returns -1 if no more characters are available in the stream.

' Usage
Dim value As Long = TextFieldParserObject.LineNumber
' Declaration
Public ReadOnly Property LineNumber As Long

Return Value
Integer.
Remarks
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
Blank lines and comments are not ignored when determining the line number.
Example
This example searches for the name "Jones" in the text file and reports what line(s) it occurs on.
VB
Using FileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.txt")
FileReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
FileReader.Delimiters = New String() {","}
Dim currentRow As String()
While Not FileReader.EndOfData
Try
currentRow = FileReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
If currentField = "Jones" Then
MsgBox("The name Jones occurs on line " & _
FileReader.LineNumber)
End If
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
End Using

Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Reference
TextFieldParser Object
Microsoft.VisualBasic.FileIO.TextFieldParser.LineNumber
Visual Basic Language Reference

TextFieldParser.PeekChars Method
Reads the specified number of characters without advancing the cursor.

' Usage
Dim value As String = TextFieldParserObject.PeekChars(numberOfChars)
' Declaration
Public Function PeekChars( _
ByVal numberOfChars As Integer _
) As String

Parameters
numberOfChars
Int32. Number of characters to read. Required.
Return Value
String.
Exceptions
The following condition may cause an exception to be thrown:
numberOfChars is less than 0 (ArgumentException).
Remarks
The numberOfChars value must be less than the total number of characters in the line. If it is not, the string returned by
PeekChars will be truncated to the length of the line.
Blank lines are ignored.
End-of-line characters are not returned.
The PeekChars method performs no parsing; an end-of- line character within a delimited field is interpreted as the actual end
of the line.
Tasks
The following table lists examples of tasks involving the PeekChars method.
To See
Determine the format of a field before parsing it How to: Read From Text Files with Multiple Formats in Visual Basic
Example
This example uses PeekChars to find the end of the data and stop parsing the file at that point.
VB
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.txt")
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
MyReader.CommentTokens = New String() {"'"}
Dim currentRow As String()
While (MyReader.PeekChars(1) IsNot "")
Try
currentRow = MyReader.ReadFields()
For Each currentField As String In currentRow
My.Computer.FileSystem.WriteAllText _
("C://testfile.txt", currentField, True)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using

Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permissions are required:
Permission Description
FileIOPermission Controls the ability to access files and folders. Associated enumeration: Unrestricted.

SecurityPermission Describes a set of security permissions applied to code. Associated enumeration: ControlEvidence.

For more information, see Code Access Security and Requesting Permissions.
See Also
Reference
TextFieldParser Object
PeekChars
Concepts
Parsing Text Files with the TextFieldParser Object
Other Resources
Reading from Files in Visual Basic
Visual Basic Language Reference

TextFieldParser.ReadFields Method
Reads all fields on the current line, returns them as an array of strings, and advances the cursor to the next line containing data.

' Usage
Dim value As String() = TextFieldParserObject.ReadFields()
' Declaration
Public Function ReadFields() As String()

Return Value
String ().
Exceptions
The following condition may cause an exception to be thrown:
A field cannot be parsed using the specified format (MalformedLineException).
Remarks
In order to allow users to parse text files in multiple formats, the ReadFields method examines the values of TextFieldType,
Delimiters, and FieldWidths, if they are specified, each time it is called. Users need to correctly configure the TextFieldType
and FieldWidths or Delimiters properties, as appropriate. If TextFieldType is set to Delimited, and Delimiters is not set, or
if TextFieldType is set to FixedWidth and FieldWidths, an exception is thrown.
If ReadFields encounters blank lines, they are skipped and the next non-blank line is returned.
Tasks
The following table lists examples of tasks involving the ReadFields method.
To See
Read from a delimited file How to: Read From Comma-Delimited Text Files in Visual Basic

Read from a fixed-width file How to: Read From Fixed-width Text Files in Visual Basic
Example
This example uses the ReadFields method to read from the file ParserText.txt and write the fields to Testfile.txt.
VB
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.txt")
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
For Each currentField As String In currentRow
My.Computer.FileSystem.WriteAllText _
("C://testfile.txt", currentField, True)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using

Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
The following permissions are required:
Permission Description
FileIOPermission Associated enumeration: Unrestricted.

SecurityPermission Associated enumeration: ControlEvidence.

For more information, see Code Access Security and Requesting Permissions.
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Reference
TextFieldParser Object
TextFieldParser.TextFieldType Property
TextFieldParser.FieldWidths Property
TextFieldParser.Delimiters Property
TextFieldParser.ReadLine Method
Microsoft.VisualBasic.FileIO.TextFieldParser.ReadFields
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference

TextFieldParser.ReadLine Method
Returns the current line as a string and advances the cursor to the next line.

' Usage
Dim value As String = TextFieldParserObject.ReadLine()
' Declaration
Public Function ReadLine() As String

Return Value
String
Exceptions
The following condition may cause an exception to be thrown:
Target file does not exist (FileNotFoundException).
Remarks
The ReadLine method performs no parsing; an end-of-line character within a delimited field is interpreted as the actual end of
the line.
Nothing is returned if the end of the file is reached.
Example
This example reads through the file ParserText.txt and writes it to Testfile.txt.
VB
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.txt")
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
Dim currentRow As String
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadLine()
My.Computer.FileSystem.WriteAllText _
("C://testfile.txt", currentRow, True)
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using

If Testfile.txt does not exist, it is created by the WriteAllText method.


This example writes the fields as a single string; to have each line display on its own line in the destination file, a VbCrLf
character should be appended at the end of each line.
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Reference
TextFieldParser Object
TextFieldParser.ReadFields Method
TextFieldParser.ReadToEnd Method
Microsoft.VisualBasic.FileIO.TextFieldParser.ReadLine
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference

TextFieldParser.ReadToEnd Method
Reads the remainder of the text file and returns it as a string.

' Usage
Dim value As String = TextFieldParserObject.ReadToEnd()
' Declaration
Public Function ReadToEnd() As String

Return Value
String.
Remarks
This is an advanced member; it does not show in IntelliSense unless you click the All tab.
If there is nothing more to read because the end of the file has been reached, Nothing is returned.
The ReadToEnd method does not ignore blank lines and comments.
Example
This example uses the ReadToEnd method to read the entire file ParserText.txt and write it to the file Testfile.txt.
VB
Using FileReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.txt")
Dim allText As String = FileReader.ReadToEnd
My.Computer.FileSystem.WriteAllText("C://testfile.txt", allText, True)
End Using

If Testfile.txt does not exist, it is created by the WriteAllText method.


Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Reference
TextFieldParser Object
TextFieldParser.ReadFields Method
TextFieldParser.ReadLine Method
Microsoft.VisualBasic.FileIO.TextFieldParser.ReadToEnd
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference

TextFieldParser.SetDelimiters Method
Sets the delimiters for the reader to the specified values, and sets the field type to Delimited.

' Usage
TextFieldParserObject.SetDelimiters(delimiters)
' Declaration
Public Sub SetDelimiters( _
ByVal delimiters As String() _
)

Parameters
delimiters
Array of type String.
Exceptions
The following condition may cause an exception to be thrown.
A delimiter is zero-length (ArgumentException).
Remarks
The existing contents of the Delimiters property are cleared when this method is set.
This method provides a way to set delimiters without creating an array.
Tasks
The following table lists an example of a task involving the SetDelimiters method.
To See
Parse a text file Parsing Text Files with the TextFieldParser Object
Example
This example opens a text field parser and defines the delimiter as vbTab.
VB
Using FileReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\logs\test.log")
FileReader.SetDelimiters(vbTab)
End Using

Replace the path C:\logs\test.log with the path and name of the file you wish to parse.
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
Reference
TextFieldParser Object
TextFieldParser.SetFieldWidths Method
SetDelimiters
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference

TextFieldParser.SetFieldWidths Method
Sets the delimiters for the reader to the specified values and the field type to FixedWidth.

' Usage
TextFieldParserObject.SetFieldWidths(fieldWidths)
' Declaration
Public Sub SetFieldWidths( _
ByVal fieldWidths As Integer() _
)

Parameters
fieldWidths
Array of Integer.
Exceptions
The following condition may cause an exception to be thrown:
A delimiter is not an integer (ArgumentException).
Remarks
The existing contents of the Delimiters property are cleared when this is set.
This method provides a way to set delimiters without creating an array.
Tasks
The following table lists example of tasks involving the SetFieldWidths method.
To See
Parse a text file. Parsing Text Files with the TextFieldParser Object
Example
This example opens a text-field parser and defines the field width as 5.
VB
Using FileReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\logs\test.log")
FileReader.SetFieldWidths(5)
End Using

Replace the path C:\logs\test.log with the path and name of the file you wish to parse.
The following example opens a text-field parser and defines the field widths as 5, 10, and variable.
VB
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\logs\test.log")
MyReader.SetFieldWidths(5, 10, -1)
End Using

Replace the path C:\logs\test.log with the path and name of the file you wish to parse.
Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Reference
TextFieldParser Object
TextFieldParser.SetDelimiters Method
SetFieldWidths
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference

TextFieldParser.TextFieldType Property
Indicates whether the file to be parsed is delimited or fixed-width.

' Usage
Dim value As FieldType = TextFieldParserObject.TextFieldType
' Declaration
Public Property TextFieldType As FieldType

Return Value
TextFieldType.
Remarks
The default value of this property is delimited.
Tasks
The following table lists examples of tasks involving the TextFieldType property.
To See
Read from a delimited text file How to: Read From Comma-Delimited Text Files in Visual Basic

Read from a fixed-width text file How to: Read From Fixed-width Text Files in Visual Basic

Read from a text file with multiple formats How to: Read From Text Files with Multiple Formats in Visual Basic
Example
This example creates a TextFieldParser, FileReader, and specifies that it is delimited.
VB
Using FileReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.txt")
FileReader.TextFieldType = _
Microsoft.VisualBasic.FileIO.FieldType.Delimited
FileReader.SetDelimiters(",")
End Using

This example creates a TextFieldParser, FileReader, and specifies that it is fixed-width.


VB
Using FileReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.txt")
FileReader.TextFieldType = _
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
FileReader.FieldWidths = New Integer() {5, 10, 11, -1}
End Using

Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
TextFieldParser Object
FieldType Enumeration
FieldType Enumeration
TextFieldParser
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference

TextFieldParser.TrimWhiteSpace Property
Indicates whether leading and trailing white space should be trimmed from field values.

' Usage
Dim value As Boolean = TextFieldParserObject.TrimWhiteSpace
' Declaration
Public Property TrimWhiteSpace As Boolean

Return Value
Boolean.
Remarks
The default value for this property is True.
Example
This example creates a TextFieldParser, FileReader, and sets the TrimWhiteSpace property to True.

VB
Using FileReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\ParserText.txt")
FileReader.TextFieldType = _
Microsoft.VisualBasic.FileIO.FieldType.Delimited
FileReader.SetDelimiters(",")
FileReader.TrimWhiteSpace = True
End Using

Requirements
Namespace: Microsoft.VisualBasic.FileIO
Class: TextFieldParser
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Permissions
No permissions are required.
See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Reference
TextFieldParser Object
My.Computer.FileSystem.OpenTextFieldParser Method
Microsoft.VisualBasic.FileIO.TextFieldParser.TrimWhiteSpace
Concepts
Parsing Text Files with the TextFieldParser Object
Visual Basic Language Reference

Operators (Visual Basic)


In This Section
Operator Precedence in Visual Basic
Operators Listed by Functionality
Data Types of Operator Results
Arithmetic Operators
Assignment Operators
Bit Shift Operators
Comparison Operators
Concatenation Operators
Logical/Bitwise Operators
Miscellaneous Operators
Related Sections
Visual Basic Reference
Visual Basic
Visual Basic Language Reference

Operator Precedence in Visual Basic


When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator
precedence.
Precedence Rules
When expressions contain operators from more than one category, they are evaluated according to the following rules:
The arithmetic and concatenation operators have the order of precedence described below, and all have higher
precedence than the comparison, logical, and bitwise operators.
All comparison operators have equal precedence, and all have higher precedence than the logical and bitwise operators,
but lower precedence than the arithmetic and concatenation operators.
The logical and bitwise operators have the order of precedence described below, and all have lower precedence than the
arithmetic, concatenation, and comparison operators.
Operators with equal precedence are evaluated left to right in the order in which they appear in the expression.
Precedence Order
Operators are evaluated in the following order of precedence:
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)
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 if two object variables refer to the same object instance.
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 (resulting in 12) and then the division 12 / 4, resulting in 3. Because the
compiler evaluates the operations for n1 from left to right, the evaluation is exactly the same when that order is explicitly
indicated for n2. Both n1 and n2 have a result of 3. 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 within parentheses before those outside.
Within parentheses, however, it maintains normal 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
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.

See Also
Reference
= Operator (Visual Basic)
Is Operator (Visual Basic)
IsNot Operator
Like Operator
TypeOf Operator (Visual Basic)
Operators Listed by Functionality
Concepts
Operators and Expressions in Visual Basic
Visual Basic Language Reference

Operators Listed by Functionality


See one of the categories listed below, or open this portion of the Help table of contents to see an alphabetical list of Visual
Basic operators.
Categories of Operators
Operators Description
Arithmetic Operators These operators perform mathematical calculations.

Assignment Operators These operators perform assignment operations.

Comparison Operators These operators perform comparisons.

Concatenation Operators These operators combine strings.

Logical/Bitwise Operators These operators perform logical operations.

Bit Shift Operators These operators perform arithmetic shifts on bit patterns.

Miscellaneous Operators These operators perform miscellaneous operations.


See Also
Reference
Operator Precedence in Visual Basic
Concepts
Operators and Expressions in Visual Basic
Visual Basic Language Reference

& Operator (Visual Basic)


Generates a string concatenation of two expressions.

result = expression1 & expression2

Parts
result
Required. Any String or Object variable.
expression1
Required. Any expression with a data type that widens to String.
expression2
Required. Any expression with a data type that widens to String.
Remarks
If the data type of expression1 or expression2 is not String but widens to String, it is converted to String. If either of the data
types does not widen to String, the compiler generates an error.
The data type of result is String. If one or both expressions evaluate to Nothing or have a value of System.DBNull.Value, they
are treated as a string with a value of "".
Note
The & operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the
type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefine
d behavior. For more information, see Operator Procedures.

Example
This example uses the & operator to force string concatenation. The result is a string value representing the concatenation of
the two string operands.
VB
Dim sampleStr As String
sampleStr = "Hello" & " World"
' The preceding statement sets sampleStr to "Hello World".

See Also
Reference
&= Operator (Visual Basic)
Concatenation Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Concatenation Operators in Visual Basic
Visual Basic Language Reference

* Operator (Visual Basic)


Multiplies two numbers.

number1 * number2

Parts
number1
Required. Any numeric expression.
number2
Required. Any numeric expression.
Result
The result is the product of number1 and number2.
Supported Types
All numeric types, including the unsigned and floating-point types and Decimal.
Remarks
The data type of the result depends on the types of the operands. The following table shows how the data type of the result is
determined.
Operand data types Result data type
Both expressions are integral data types (SByte, Byte, Short, A numeric data type appropriate for the data types of number1 an
UShort, Integer, UInteger, Long, ULong) d number2. See the "Integer Arithmetic" tables in
Data Types of Operator Results.

Both expressions are Decimal Decimal

Both expressions are Single Single

Either expression is a floating-point data type (Single or Double


Double) but not both Single (note Decimal is not a floatin
g-point data type)

If an expression evaluates to Nothing, it is treated as zero.


Overloading
The * operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the
type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefined
behavior. For more information, see Operator Procedures.
Example
This example uses the * operator to multiply two numbers. The result is the product of the two operands.
VB
Dim testValue As Double
testValue = 2 * 2
' The preceding statement sets testValue to 4.
testValue = 459.35 * 334.9
' The preceding statement sets testValue to 153836.315.

See Also
Reference
*= Operator (Visual Basic)
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference

*= Operator (Visual Basic)


Multiplies the value of a variable or property by the value of an expression and assigns the result to the variable or property.

variableorproperty *= expression

Parts
variableorproperty
Required. Any numeric variable or property.
expression
Required. Any numeric expression.
Remarks
The element on the left side of the *= operator can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The *= operator assigns the value on its right to the variable or
property on its left.
Overloading
The * Operator (Visual Basic) can be overloaded, which means that a class or structure can redefine its behavior when an
operand has the type of that class or structure. Overloading the * operator affects the behavior of the *= operator. If your code
uses *= on a class or structure that overloads *, be sure you understand its redefined behavior. For more information, see
Operator Procedures.
Example
The following example uses the *= operator to multiply one Integer variable by a second and assign the result to the first
variable.
VB
Dim var1 As Integer = 10
Dim var2 As Integer = 3
var1 *= var2
' The value of var1 is now 30.

See Also
Reference
* Operator (Visual Basic)
Assignment Operators
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference

+ Operator (Visual Basic)


Adds two numbers or returns the positive value of a numeric expression. Can also be used to concatenate two string
expressions.

expression1 + expression2
- or -
+ expression1

Parts
expression1
Required. Any numeric or string expression.
expression2
Required unless the + operator is calculating a negative value. Any numeric or string expression.
Result
If expression1 and expression2 are both numeric, the result is their arithmetic sum.
If expression2 is absent, the + operator is the unary identity operator for the unchanged value of an expression. In this sense,
the operation consists of retaining the sign of expression1, so the result is negative if expression1 is negative.
If expression1 and expression2 are both strings, the result is the concatenation of their values.
If expression1 and expression2 are of mixed types, the action taken depends on their types, their contents, and the setting of the
Option Strict Statement. For more information, see the tables in "Remarks."
Supported Types
All numeric types, including the unsigned and floating-point types and Decimal, and String.
Remarks
In general, + performs arithmetic addition when possible, and concatenates only when both expressions are strings.
If neither expression is an Object, Visual Basic takes the following actions.
Data types of expressions Action by compiler
Both expressions are numeric data types (SByte, Byte, Add. The result data type is a numeric type appropriate for the data typ
Short, UShort, Integer, UInteger, Long, ULong, Dec es of expression1 and expression2. See the "Integer Arithmetic" tables i
imal, Single, or Double) n Data Types of Operator Results.

Both expressions are of type String Concatenate.

One expression is a numeric data type and the other is If Option Strict is On, then generate a compiler error.
a string
If Option Strict is Off, then implicitly convert the String to Double an
d add.
If the String cannot be converted to Double, then throw an
InvalidCastException exception.

One expression is a numeric data type, and the other is Add, with Nothing valued as zero.
Nothing (Visual Basic)

One expression is a string, and the other is Nothing Concatenate, with Nothing valued as "".

If one expression is an Object expression, Visual Basic takes the following actions.
Data types of expressions Action by compiler
Object expression holds a numeric value and the othe If Option Strict is On, then generate a compiler error.
r is a numeric data type
If Option Strict is Off, then add.

Object expression holds a numeric value and the othe If Option Strict is On, then generate a compiler error.
r is of type String
If Option Strict is Off, then implicitly convert the String to Double an
d add.
If the String cannot be converted to Double, then throw an InvalidCa
stException exception.

Object expression holds a string and the other is a nu If Option Strict is On, then generate a compiler error.
meric data type
If Option Strict is Off, then implicitly convert the string Object to Dou
ble and add.
If the string Object cannot be converted to Double, then throw an Inv
alidCastException exception.

Object expression holds a string and the other is of ty If Option Strict is On, then generate a compiler error.
pe String
If Option Strict is Off, then implicitly convert Object to String and co
ncatenate.

If both expressions are Object expressions, Visual Basic takes the following actions (Option Strict Off only).
Data types of expressions Action by compiler
Both Object expressions hold numeric values Add.

Both Object expressions are of type String Concatenate.

One Object expression holds a numeric value and Implicitly convert the string Object to Double and add.
the other holds a string
If the string Object cannot be converted to a numeric value, then throw an
InvalidCastException exception.

If either Object expression evaluates to Nothing or DBNull, the + operator treats it as a String with a value of "".
Note
When you use the + operator, you might not be able to determine whether addition or string concatenation will occur. Use t
he & operator for concatenation to eliminate ambiguity and to provide self-documenting code.

Overloading
The + operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the
type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefined
behavior. For more information, see Operator Procedures.
Example
The following example uses the + operator to add numbers. If the operands are both numeric, Visual Basic computes the
arithmetic result. The arithmetic result represents the sum of the two operands.
VB
Dim sumNumber As Integer
sumNumber = 2 + 2
sumNumber = 4257.04 + 98112
' The preceding statements set sumNumber to 4 and 102369.

You can also use the + operator to concatenate strings. If the operands are both strings, Visual Basic concatenates them. The
concatenation result represents a single string consisting of the contents of the two operands one after the other.
If the operands are of mixed types, the result depends on the setting of the Option Strict Statement. The following example
illustrates the result when Option Strict is On.
VB
Option Strict On

VB
Dim var1 As String = "34"
Dim var2 As Integer = 6
Dim concatenatedNumber As Integer = var1 + var2
... ' The preceding statement generates a COMPILER ERROR.

The following example illustrates the result when Option Strict is Off.
VB
Option Strict Off

VB
Dim var1 As String = "34"
Dim var2 As Integer = 6
Dim concatenatedNumber As Integer = var1 + var2
... ' The preceding statement returns 40 after the string in var1 is
' converted to a numeric value. This might be an unexpected result.
' We do not recommend use of Option Strict Off for these operations.

To eliminate ambiguity, you should use the & operator instead of + for concatenation.
See Also
Reference
& Operator (Visual Basic)
Concatenation Operators (Visual Basic)
Arithmetic Operators (Visual Basic)
Operators Listed by Functionality
Operator Precedence in Visual Basic
Option Strict Statement
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference

+= Operator (Visual Basic)


Adds the value of a numeric expression to the value of a numeric variable or property and assigns the result to the variable or
property. Can also be used to concatenate a String expression to a String variable or property and assign the result to the
variable or property.

variableorproperty += expression

Parts
variableorproperty
Required. Any numeric or String variable or property.
expression
Required. Any numeric or String expression.
Remarks
The element on the left side of the += operator can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The += operator assigns the value on its right to the variable or
property on its left.
This assignment operator implicitly performs widening but not narrowing conversions if the compilation environment
enforces strict semantics. For more information on these conversions, see Widening and Narrowing Conversions. For more
information on strict and permissive semantics, see Option Strict Statement.
If permissive semantics are allowed, the += operator implicitly performs a variety of string and numeric conversions identical
to those performed by the + operator. For details on these conversions, see + Operator (Visual Basic).
Note
When you use the += operator, you might not be able to determine whether addition or string concatenation will occur. Use
the &= operator for concatenation to eliminate ambiguity and to provide self-documenting code.

Overloading
The + operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the
type of that class or structure. Overloading the + operator affects the behavior of the += operator. If your code uses += on a
class or structure that overloads +, be sure you understand its redefined behavior. For more information, see
Operator Procedures.
Example
The following example uses the += operator to combine the value of one variable with another. The first part uses += with
numeric variables to add one value to another. The second part uses += with String variables to concatenate one value with
another. In both cases, the result is assigned to the first variable.
VB
' This part uses numeric variables.
Dim num1 As Integer = 10
Dim num2 As Integer = 3
num1 += num2

VB
' This part uses string variables.
Dim str1 As String = "10"
Dim str2 As String = "3"
str1 += str2
The value of num1 is now 13, and the value of str1 is now "103".
See Also
Reference
+ Operator (Visual Basic)
Assignment Operators
Arithmetic Operators (Visual Basic)
Concatenation Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference

= Operator (Visual Basic)


Assigns a value to a variable or property.

variableorproperty = value

Parts
variableorproperty
Any writable variable or any property.
value
Any literal, constant, or expression.
Remarks
The element on the left side of the equal sign (=) can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The = operator assigns the value on its right to the variable or property
on its left.
Note
The = operator is also used as a comparison operator. For details, see Comparison Operators (Visual Basic).

Overloading
The = operator can be overloaded only as a relational comparison operator, not as an assignment operator. For more
information, see Operator Procedures.
Example
The following example demonstrates the assignment operator. The value on the right is assigned to the variable on the left.
VB
Dim testInt As Integer
Dim testString As String
Dim testButton As System.Windows.Forms.Button
Dim testObject As Object
testInt = 42
testString = "This is an example of a string literal."
testButton = New System.Windows.Forms.Button()
testObject = testInt
testObject = testString
testObject = testButton

See Also
Reference
&= Operator (Visual Basic)
*= Operator (Visual Basic)
+= Operator (Visual Basic)
-= Operator (Visual Basic)
/= Operator (Visual Basic)
\= Operator
^= Operator (Visual Basic)
Comparison Operators (Visual Basic)
ReadOnly (Visual Basic)
Concepts
Assignment Statements
Visual Basic Language Reference

- Operator (Visual Basic)


Returns the difference between two numeric expressions or the negative value of a numeric expression.

expression1 – expression2
- or -
– expression1

Parts
expression1
Required. Any numeric expression.
expression2
Required unless the – operator is calculating a negative value. Any numeric expression.
Result
The result is the difference between expression1 and expression2, or the negated value of expression1.
The result data type is a numeric type appropriate for the data types of expression1 and expression2. See the "Integer
Arithmetic" tables in Data Types of Operator Results.
Supported Types
All numeric types, including the unsigned and floating-point types and Decimal.
Remarks
In the first usage shown in the preceding syntax, the – operator is the binary arithmetic subtraction operator for the difference
between two numeric expressions.
In the second usage shown in the preceding syntax, the – operator is the unary negation operator for the negative value of an
expression. In this sense, the negation consists of reversing the sign of expression1, so the result is positive if expression1 is
negative.
If either expression evaluates to Nothing, the – operator treats it as zero.
Note
The – operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the t
ype of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefine
d behavior. For more information, see Operator Procedures.

Example
The following example uses the – operator to calculate and return the difference between two numbers, and then to negate a
number.
VB
Dim binaryResult As Double = 459.35 - 334.9
Dim unaryResult As Double = -334.9

Following the execution of these statements, binaryResult contains 124.45 and unaryResult contains –334.90.
See Also
Reference
-= Operator (Visual Basic)
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference

-= Operator (Visual Basic)


Subtracts the value of an expression from the value of a variable or property and assigns the result to the variable or property.

variableorproperty -= expression

Parts
variableorproperty
Required. Any numeric variable or property.
expression
Required. Any numeric expression.
Remarks
The element on the left side of the -= operator can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The -= operator assigns the value on its right to the variable or
property on its left.
Overloading
The - Operator (Visual Basic) can be overloaded, which means that a class or structure can redefine its behavior when an
operand has the type of that class or structure. Overloading the - operator affects the behavior of the -= operator. If your code
uses -= on a class or structure that overloads -, be sure you understand its redefined behavior. For more information, see
Operator Procedures.
Example
The following example uses the -= operator to subtract one Integer variable from another and assign the result to the latter
variable.
VB
Dim var1 As Integer = 10
Dim var2 As Integer = 3
var1 -= var2
' The value of var1 is now 7.

See Also
Reference
- Operator (Visual Basic)
Assignment Operators
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference

<< Operator (Visual Basic)


Performs an arithmetic left shift on a bit pattern.

result = pattern << amount

Parts
result
Required. Integral numeric value. The result of shifting the bit pattern. The data type is the same as that of pattern.
pattern
Required. Integral numeric expression. The bit pattern to be shifted. The data type must be an integral type (SByte, Byte,
Short, UShort, Integer, UInteger, Long, or ULong).
amount
Required. Numeric expression. The number of bits to shift the bit pattern. The data type must be Integer or widen to
Integer.
Remarks
Arithmetic shifts are not circular, which means the bits shifted off one end of the result are not reintroduced at the other end. In
an arithmetic left shift, the bits shifted beyond the range of the result data type are discarded, and the bit positions vacated on
the right are set to zero.
To prevent shifting by more bits than the result can hold, Visual Basic masks the value of amount with a size mask
corresponding to the data type of pattern. The binary AND of these values is used for the shift amount. The size masks are as
follows:
Data type of pattern Size mask (decimal) Size mask (hexadecimal)
SByte, Byte 7 &H00000007

Short, UShort 15 &H0000000F

Integer, UInteger 31 &H0000001F

Long, ULong 63 &H0000003F

If amount is zero, the value of result is identical to the value of pattern. If amount is negative, it is taken as an unsigned value
and masked with the appropriate size mask.
Arithmetic shifts never generate overflow exceptions.
Note
The << operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has th
e type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefi
ned behavior. For more information, see Operator Procedures.

Example
The following example uses the << operator to perform arithmetic left shifts on integral values. The result always has the same
data type as that of the expression being shifted.
VB
Dim pattern As Short = 192
' The bit pattern is 0000 0000 1100 0000.
Dim result1, result2, result3, result4, result5 As Short
result1 = pattern << 0
result2 = pattern << 4
result3 = pattern << 9
result4 = pattern << 17
result5 = pattern << -1

The results of the preceding example are as follows:


result1 is 192 (0000 0000 1100 0000).

result2 is 3072 (0000 1100 0000 0000).

result3 is -32768 (1000 0000 0000 0000).

result4 is 384 (0000 0001 1000 0000).

result5 is 0 (shifted 15 places to the left).

The shift amount for result4 is calculated as 17 AND 15, which equals 1.
See Also
Reference
Bit Shift Operators
Assignment Operators
<<= Operator (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference

<<= Operator (Visual Basic)


Performs an arithmetic left shift on the value of a variable or property and assigns the result back to the variable or property.

variableorproperty <<= amount

Parts
variableorproperty
Required. Variable or property of an integral type (SByte, Byte, Short, UShort, Integer, UInteger, Long, or ULong).
amount
Required. Numeric expression of a data type that widens to Integer.
Remarks
The element on the left side of the <<= operator can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The <<= operator assigns the value on its right to the variable or
property on its left.
Arithmetic shifts are not circular, which means the bits shifted off one end of the result are not reintroduced at the other end. In
an arithmetic left shift, the bits shifted beyond the range of the result data type are discarded, and the bit positions vacated on
the right are set to zero.
Overloading
The << Operator (Visual Basic) can be overloaded, which means that a class or structure can redefine its behavior when an
operand has the type of that class or structure. Overloading the << operator affects the behavior of the <<= operator. If your
code uses <<= on a class or structure that overloads <<, be sure you understand its redefined behavior. For more information,
see Operator Procedures.
Example
The following example uses the <<= operator to shift the bit pattern of an Integer variable left by the specified amount and
assign the result to the variable.
VB
Dim var As Integer = 10
Dim shift As Integer = 3
var <<= shift
' The value of var is now 80.

See Also
Reference
<< Operator (Visual Basic)
Assignment Operators
Bit Shift Operators
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference

>> Operator (Visual Basic)


Performs an arithmetic right shift on a bit pattern.

result = pattern >> amount

Parts
result
Required. Integral numeric value. The result of shifting the bit pattern. The data type is the same as that of pattern.
pattern
Required. Integral numeric expression. The bit pattern to be shifted. The data type must be an integral type (SByte, Byte,
Short, UShort, Integer, UInteger, Long, or ULong).
amount
Required. Numeric expression. The number of bits to shift the bit pattern. The data type must be Integer or widen to
Integer.
Remarks
Arithmetic shifts are not circular, which means the bits shifted off one end of the result are not reintroduced at the other end. In
an arithmetic right shift, the bits shifted beyond the rightmost bit position are discarded, and the leftmost (sign) bit is
propagated into the bit positions vacated at the left. This means that if pattern has a negative value, the vacated positions are
set to one; otherwise they are set to zero.
Note that the data types Byte, UShort, UInteger, and ULong are unsigned, so there is no sign bit to propagate. If pattern is of
any unsigned type, the vacated positions are always set to zero.
To prevent shifting by more bits than the result can hold, Visual Basic masks the value of amount with a size mask
corresponding to the data type of pattern. The binary AND of these values is used for the shift amount. The size masks are as
follows:
Data type of pattern Size mask (decimal) Size mask (hexadecimal)
SByte, Byte 7 &H00000007

Short, UShort 15 &H0000000F

Integer, UInteger 31 &H0000001F

Long, ULong 63 &H0000003F

If amount is zero, the value of result is identical to the value of pattern. If amount is negative, it is taken as an unsigned value
and masked with the appropriate size mask.
Arithmetic shifts never generate overflow exceptions.
Overloading
The >> operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the
type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefined
behavior. For more information, see Operator Procedures.
Example
The following example uses the >> operator to perform arithmetic right shifts on integral values. The result always has the
same data type as that of the expression being shifted.
VB
Dim pattern As Short = 2560
' The bit pattern is 0000 1010 0000 0000.
Dim result1, result2, result3, result4, result5 As Short
result1 = pattern >> 0
result2 = pattern >> 4
result3 = pattern >> 10
result4 = pattern >> 18
result5 = pattern >> -1

The results of the preceding example are as follows:


result1 is 2560 (0000 1010 0000 0000).

result2 is 160 (0000 0000 1010 0000).

result3 is 2 (0000 0000 0000 0010).

result4 is 640 (0000 0010 1000 0000).

result5 is 0 (shifted 15 places to the right).

The shift amount for result4 is calculated as 18 AND 15, which equals 2.
The following example shows arithmetic shifts on a negative value.
VB
Dim negPattern As Short = -8192
' The bit pattern is 1110 0000 0000 0000.
Dim negResult1, negResult2 As Short
negResult1 = negPattern >> 4
negResult2 = negPattern >> 13

The results of the preceding example are as follows:


negresult1 is -512 (1111 1110 0000 0000).

negresult2 is -1 (the sign bit is propagated).

See Also
Reference
Bit Shift Operators
Assignment Operators
>>= Operator (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference

>>= Operator (Visual Basic)


Performs an arithmetic right shift on the value of a variable or property and assigns the result back to the variable or property.

variableorproperty >>= amount

Parts
variableorproperty
Required. Variable or property of an integral type (SByte, Byte, Short, UShort, Integer, UInteger, Long, or ULong).
amount
Required. Numeric expression of a data type that widens to Integer.
Remarks
The element on the left side of the >>= operator can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The >>= operator assigns the value on its right to the variable or
property on its left.
Arithmetic shifts are not circular, which means the bits shifted off one end of the result are not reintroduced at the other end. In
an arithmetic right shift, the bits shifted beyond the rightmost bit position are discarded, and the leftmost bit is propagated into
the bit positions vacated at the left. This means that if variableorproperty has a negative value, the vacated positions are set to
one. If variableorproperty is positive, or if its data type is an unsigned type, the vacated positions are set to zero.
Overloading
The >> Operator (Visual Basic) can be overloaded, which means that a class or structure can redefine its behavior when an
operand has the type of that class or structure. Overloading the >> operator affects the behavior of the >>= operator. If your
code uses >>= on a class or structure that overloads >>, be sure you understand its redefined behavior. For more information,
see Operator Procedures.
Example
The following example uses the >>= operator to shift the bit pattern of an Integer variable right by the specified amount and
assign the result to the variable.
VB
Dim var As Integer = 10
Dim shift As Integer = 2
var >>= shift
' The value of var is now 2 (one bit was lost off the right end).

See Also
Reference
>> Operator (Visual Basic)
Assignment Operators
Bit Shift Operators
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference

/ Operator (Visual Basic)


Divides two numbers and returns a floating-point result.

expression1 / expression2

Parts
expression1
Required. Any numeric expression.
expression2
Required. Any numeric expression.
Supported Types
All numeric types, including the unsigned and floating-point types and Decimal.
Result
The result is the full quotient of expression1 divided by expression2, including any remainder.
The \ Operator returns the integer quotient, which drops the remainder.
Remarks
The data type of the result depends on the types of the operands. The following table shows how the data type of the result is
determined.
Operand data types Result data typ
e
Both expressions are integral data types (SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong) Double

Both expressions are of the Decimal data type Decimal

Both expressions are of the Single Data Type (Visual Basic) Single

Either expression is a floating-point data type (Single Data Type (Visual Basic) or Double
Double Data Type (Visual Basic))

Before division is performed, any integral numeric expressions are widened to Double. If you assign the result to an integral
data type, Visual Basic attempts to convert the result from Double to that type. This can throw an exception if the result does
not fit in that type. In particular, see "Attempted Division by Zero" on this Help page.
If expression1 or expression2 evaluates to Nothing, it is treated as zero.
Attempted Division by Zero
If expression2 evaluates to zero, the / operator behaves differently for different operand data types. The following table shows
the possible behaviors.
Operand data types Behavior if expression2 is zero
Floating-point (Single Returns infinity (PositiveInfinity or NegativeInfinity), or NaN (not a number) if expression1 is also zero
or Double)

Decimal Throws DivideByZeroException

Integral (signed or uns Attempted conversion back to integral type throws OverflowException because integral types cannot a
igned) ccept PositiveInfinity, NegativeInfinity, or NaN
Note
The / operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the t
ype of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefine
d behavior. For more information, see Operator Procedures.

Example
This example uses the / operator to perform floating-point division. The result is the quotient of the two operands.
VB
Dim resultValue As Double
resultValue = 10 / 4
resultValue = 10 / 3

The expressions in the preceding example return values of 2.5 and 3.333333. Note that the result is always floating-point
(Double), even though both operands are integer constants.
See Also
Reference
/= Operator (Visual Basic)
\ Operator
Data Types of Operator Results
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference

/= Operator (Visual Basic)


Divides the value of a variable or property by the value of an expression and assigns the floating-point result to the variable or
property.

variableorproperty /= expression

Parts
variableorproperty
Required. Any numeric variable or property.
expression
Required. Any numeric expression.
Remarks
The element on the left side of the /= operator can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The /= operator assigns the value on its right to the variable or
property on its left.
This statement assigns a Double value to the variable or property on the left hand side. If Option Strict is On,
variableorproperty must be a Double. If Option Strict is Off, Visual Basic performs an implicit conversion and assigns the
resulting value to variableorproperty, with a possible error at run time. For more information, see
Widening and Narrowing Conversions and Option Strict Statement.
Overloading
The / Operator (Visual Basic) can be overloaded, which means that a class or structure can redefine its behavior when an
operand has the type of that class or structure. Overloading the / operator affects the behavior of the /= operator. If your code
uses /= on a class or structure that overloads /, be sure you understand its redefined behavior. For more information, see
Operator Procedures.
Example
The following example uses the /= operator to divide one Integer variable by a second and assign the quotient to the first
variable.
VB
Dim var1 As Integer = 12
Dim var2 As Integer = 3
var1 /= var2
' The value of var1 is now 4.

See Also
Reference
/ Operator (Visual Basic)
\= Operator
Assignment Operators
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference

\ Operator
Divides two numbers and returns an integer result.

expression1 \ expression2

Parts
expression1
Required. Any numeric expression.
expression2
Required. Any numeric expression.
Supported Types
All numeric types, including the unsigned and floating-point types and Decimal.
Result
The result is the integer quotient of expression1 divided by expression2, which discards any remainder and retains only the
integer portion. This is known as truncation.
The result data type is a numeric type appropriate for the data types of expression1 and expression2. See the "Integer
Arithmetic" tables in Data Types of Operator Results.
The / Operator (Visual Basic) returns the full quotient, which retains the remainder in the fractional portion.
Remarks
Before performing the division, Visual Basic attempts to convert any floating-point numeric expression to Long. If Option
Strict is On, a compiler error results. If Option Strict is Off, an OverflowException is possible if the value is outside the range
of the Long Data Type (Visual Basic). The conversion to Long is also subject to banker's rounding. For more information, see
"Fractional Parts" in Type Conversion Functions.
If expression1 or expression2 evaluates to Nothing, it is treated as zero.
Attempted Division by Zero
If expression2 evaluates to zero, the \ operator throws a DivideByZeroException exception. This is true for all numeric data
types of the operands.
Note
The \ operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the t
ype of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefine
d behavior. For more information, see Operator Procedures.

Example
The following example uses the \ operator to perform integer division. The result is an integer representing the integer
quotient of the two operands, with the remainder discarded.
VB
Dim resultValue As Integer
resultValue = 11 \ 4
resultValue = 9 \ 3
resultValue = 100 \ 3
resultValue = 67 \ -3

The expressions in the preceding example return values of 2, 3, 33, and -22, respectively.
See Also
Reference
\= Operator
/ Operator (Visual Basic)
Option Strict Statement
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference

\= Operator
Divides the value of a variable or property by the value of an expression and assigns the integer result to the variable or
property.

variableorproperty \= expression

Parts
variableorproperty
Required. Any numeric variable or property.
expression
Required. Any numeric expression.
Remarks
The element on the left side of the \= operator can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The \= operator assigns the value on its right to the variable or
property on its left.
For further information on integer division, see \ Operator.
Overloading
The \ operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the
type of that class or structure. Overloading the \ operator affects the behavior of the \= operator. If your code uses \= on a
class or structure that overloads \, be sure you understand its redefined behavior. For more information, see
Operator Procedures.
Example
The following example uses the \= operator to divide one Integer variable by a second and assign the integer result to the first
variable.
VB
Dim var1 As Integer = 10
Dim var2 As Integer = 3
var1 \= var2
' The value of var1 is now 3.

See Also
Reference
\ Operator
/= Operator (Visual Basic)
Assignment Operators
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference

^ Operator (Visual Basic)


Raises a number to the power of another number.

number ^ exponent

Parts
number
Required. Any numeric expression.
exponent
Required. Any numeric expression.
Result
The result is number raised to the power of exponent, always as a Double value.
Supported Types
Double. Operands of any different type are converted to Double.
Remarks
Visual Basic always performs exponentiation in the Double Data Type (Visual Basic).
The value of exponent can be fractional, negative, or both.
When more than one exponentiation is performed in a single expression, the ^ operator is evaluated as it is encountered from
left to right.
Note
The ^ operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the t
ype of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefine
d behavior. For more information, see Operator Procedures.

Example
The following example uses the ^ operator to raise a number to the power of an exponent. The result is the first operand raised
to the power of the second.
VB
Dim exp1, exp2, exp3, exp4, exp5, exp6 As Double
exp1 = 2 ^ 2
exp2 = 3 ^ 3 ^ 3
exp3 = (-5) ^ 3
exp4 = (-5) ^ 4
exp5 = 8 ^ (1.0 / 3.0)
exp6 = 8 ^ (-1.0 / 3.0)

The preceding example produces the following results:


exp1 is set to 4 (2 squared).

exp2 is set to 19683 (3 cubed, then that value cubed).

exp3 is set to -125 (-5 cubed).

exp4 is set to 625 (-5 to the fourth power).

exp5 is set to 2 (cube root of 8).

exp6 is set to 0.5 (1.0 divided by the cube root of 8).


Note the importance of the parentheses in the expressions in the preceding example. Because of operator precedence, Visual
Basic normally performs the ^ operator before any others, even the unary – operator. If exp4 and exp6 had been calculated
without parentheses, they would have produced the following results:
exp4 = -5 ^ 4 would be calculated as –(5 to the fourth power), which would result in –625.

exp6 = 8 ^ -1.0 / 3.0 would be calculated as (8 to the –1 power, or 0.125) divided by 3.0, which would result in
0.041666666666666666666666666666667.
See Also
Reference
^= Operator (Visual Basic)
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference

^= Operator (Visual Basic)


Raises the value of a variable or property to the power of an expression and assigns the result back to the variable or property.

variableorproperty ^= expression

Parts
variableorproperty
Required. Any numeric variable or property.
expression
Required. Any numeric expression.
Remarks
The element on the left side of the ^= operator can be a simple scalar variable, a property, or an element of an array. The
variable or property cannot be ReadOnly (Visual Basic). The ^= operator assigns the value on its right to the variable or
property on its left.
Visual Basic always performs exponentiation in the Double Data Type (Visual Basic). Operands of any different type are
converted to Double, and the result is always Double.
The value of expression can be fractional, negative, or both.
Overloading
The ^ Operator (Visual Basic) can be overloaded, which means that a class or structure can redefine its behavior when an
operand has the type of that class or structure. Overloading the ^ operator affects the behavior of the ^= operator. If your
code uses ^= on a class or structure that overloads ^, be sure you understand its redefined behavior. For more information,
see Operator Procedures.
Example
The following example uses the ^= operator to raise the value of one Integer variable to the power of a second variable and
assign the result to the first variable.
VB
Dim var1 As Integer = 10
Dim var2 As Integer = 3
var1 ^= var2
' The value of var1 is now 1000.

See Also
Reference
^ Operator (Visual Basic)
Assignment Operators
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference

AddressOf Operator
Creates a procedure delegate instance that references the specific procedure.

AddressOf procedurename

Parts
procedurename
Required. Specifies the procedure to be referenced by the newly created procedure delegate.
Remarks
The AddressOf operator creates a function delegate that points to the function specified by procedurename. When the
specified procedure is an instance method then the function delegate refers to both the instance and the method. Then, when
the function delegate is invoked the specified method of the specified instance is called.
The AddressOf operator can be used as the operand of a delegate constructor or it can be used in a context in which the type
of the delegate can be determined by the compiler.
Example
This example uses the AddressOf operator to designate a delegate to handle the Click event of a button.
VB
' Add the following line to Sub Form1_Load().
AddHandler Button1.Click, AddressOf Button1_Click

The following example uses the AddressOf operator to designate the startup function for a thread.
VB
Public Sub CountSheep()
Dim i As Integer = 1 ' Sheep do not count from 0.
Do While (True) ' Endless loop.
Console.WriteLine("Sheep " & i & " Baah")
i = i + 1
System.Threading.Thread.Sleep(1000) 'Wait 1 second.
Loop
End Sub
Sub UseThread()
Dim t As New System.Threading.Thread(AddressOf CountSheep)
t.Start()
End Sub

See Also
Reference
Declare Statement
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
Concepts
Delegates and the AddressOf Operator
Visual Basic Language Reference

And Operator (Visual Basic)


Performs a logical conjunction on two Boolean expressions, or a bitwise conjunction on two numeric expressions.

result = expression1 And expression2

Parts
result
Required. Any Boolean or numeric expression. For Boolean comparison, result is the logical conjunction of two Boolean
values. For bitwise operations, result is a numeric value representing the bitwise conjunction of two numeric bit patterns.
expression1
Required. Any Boolean or numeric expression.
expression2
Required. Any Boolean or numeric expression.
Remarks
For Boolean comparison, result is True if and only if both expression1 and expression2 evaluate to True. The following table
illustrates how result is determined.
If expression1 is And expression2 is The value of result is
True True True

True False False

False True False

False False False


Note
In a Boolean comparison, the And operator always evaluates both expressions, which could include making procedure calls.
The AndAlso Operator performs short-circuiting, which means that if expression1 is False, then expression2 is not evaluated.

When applied to numeric values, the And operator performs a bitwise comparison of identically positioned bits in two numeric
expressions and sets the corresponding bit in result according to the following table.
If bit in expression1 is And bit in expression2 is The bit in result is
1 1 1

1 0 0

0 1 0

0 0 0
Note
Since the logical and bitwise operators have a lower precedence than other arithmetic and relational operators, any bitwise o
perations should be enclosed in parentheses to ensure accurate results.

Data Types
If the operands consist of one Boolean expression and one numeric expression, Visual Basic converts the Boolean expression
to a numeric value (–1 for True and 0 for False) and performs a bitwise operation.
For a Boolean comparison, the data type of the result is Boolean. For a bitwise comparison, the result data type is a numeric
type appropriate for the data types of expression1 and expression2. See the "Relational and Bitwise Comparisons" table in
Data Types of Operator Results.
Note
The And operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has t
he type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redef
ined behavior. For more information, see Operator Procedures.

Example
The following example uses the And operator to perform a logical conjunction on two expressions. The result is a Boolean
value that represents whether both of the expressions are True.
VB
Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstCheck, secondCheck As Boolean
firstCheck = a > b And b > c
secondCheck = b > a And b > c

The preceding example produces results of True and False, respectively.


The following example uses the And operator to perform logical conjunction on the individual bits of two numeric expressions.
The bit in the result pattern is set if the corresponding bits in the operands are both set to 1.
VB
Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstPattern, secondPattern, thirdPattern As Integer
firstPattern = (a And b)
secondPattern = (a And c)
thirdPattern = (b And c)

The preceding example produces results of 8, 2, and 0, respectively.


See Also
Reference
Logical/Bitwise Operators
Operator Precedence in Visual Basic
Operators Listed by Functionality
AndAlso Operator
Concepts
Logical and Bitwise Operators in Visual Basic
Visual Basic Language Reference

AndAlso Operator
Performs short-circuiting logical conjunction on two expressions.

result = expression1 AndAlso expression2

Parts
result
Required. Any Boolean expression. The result is the Boolean result of comparison of the two expressions.
expression1
Required. Any Boolean expression.
expression2
Required. Any Boolean expression.
Remarks
A logical operation is said to be short-circuiting if the compiled code can bypass the evaluation of one expression depending
on the result of another expression. If the result of the first expression evaluated determines the final result of the operation,
there is no need to evaluate the second expression, because it cannot change the final result. Short-circuiting can improve
performance if the bypassed expression is complex, or if it involves procedure calls.
If both expressions evaluate to True, result is True. The following table illustrates how result is determined.
If expression1 is And expression2 is The value of result is
True True True

True False False

False (not evaluated) False

One use of the AndAlso operator is to test for the existence of an object instance before attempting to access one of its
members. The following code line illustrates this.
If newObject AndAlso newObject.initFinished Then

The access to the initFinished property in the preceding code line could throw a NullReferenceException exception if the
newObject variable did not have an object instance assigned to it. However, the AndAlso operator causes the compiler to
bypass the access to initFinished if newObject is Nothing, because Nothing evaluates to False.
Data Types
The AndAlso operator is defined only for the Boolean Data Type (Visual Basic). Visual Basic converts each operand as
necessary to Boolean and performs the operation entirely in Boolean. If you assign the result to a numeric type, Visual Basic
converts it from Boolean to that type. This could produce unexpected behavior. For example, 5 AndAlso 12 results in –1 when
converted to Integer.
Overloading
The And Operator (Visual Basic) and the IsFalse Operator can be overloaded, which means that a class or structure can redefine
their behavior when an operand has the type of that class or structure. Overloading the And and IsFalse operators affects the
behavior of the AndAlso operator. If your code uses AndAlso on a class or structure that overloads And and IsFalse, be sure
you understand their redefined behavior. For more information, see Operator Procedures.
Example
The following example uses the AndAlso operator to perform a logical conjunction on two expressions. The result is a
Boolean value that represents whether the entire conjoined expression is true. If the first expression is False, the second is not
evaluated.
VB
Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstCheck, secondCheck, thirdCheck As Boolean
firstCheck = a > b AndAlso b > c
secondCheck = b > a AndAlso b > c
thirdCheck = a > b AndAlso c > b

The preceding example produces results of True, False, and False, respectively. In the calculation of secondCheck, the second
expression is not evaluated because the first is already False. However, the second expression is evaluated in the calculation of
thirdCheck.

The following example shows a Function procedure that searches for a given value among the elements of an array. If the
array is empty, or if the array length has been exceeded, the While statement does not test the array element against the
search value.
VB
Public Function findValue(ByVal arr() As Double, _
ByVal searchValue As Double) As Double
Dim i As Integer = 0
While i <= UBound(arr) AndAlso arr(i) <> searchValue
' If i is greater than UBound(arr), searchValue is not checked.
i += 1
End While
If i > UBound(arr) Then i = -1
Return i
End Function

See Also
Reference
Logical/Bitwise Operators
Operator Precedence in Visual Basic
Operators Listed by Functionality
And Operator (Visual Basic)
IsFalse Operator
Concepts
Logical and Bitwise Operators in Visual Basic
Visual Basic Language Reference

GetType Operator
Returns a Type object for the specified type. The Type object provides information about the type such as its properties,
methods, and events.

GetType(typename)

Parameters
typename
The name of the type for which you desire information.
Remarks
The GetType operator returns the Type object for the specified typename. You can pass the name of any defined type in
typename. This includes the following:
Any Visual Basic data type, such as Boolean or Date.
Any .NET Framework class, structure, module, or interface, such as System.ArgumentException or System.Double.
Any class, structure, module, or interface defined by your application.
Any array defined by your application.
Any delegate defined by your application.
Any enumeration defined by Visual Basic, the .NET Framework, or your application.
If you want to get the type object of an object variable, use the System.Type.GetType method.
The GetType operator can be useful in the following circumstances:
You need to access the metadata for a type at run time. The Type object supplies metadata such as type members and
deployment information. You need this, for example, to reflect over an assembly. For more information, see
System.Reflection.
You want to compare two object references to see if they refer to instances of the same type. If they do, GetType returns
references to the same Type object.
Example
The following examples show the GetType operator in use.
VB
' The following statement returns the Type object for Integer.
MsgBox(GetType(Integer).ToString())
' The following statement returns the Type object for one-dimensional string arrays.
MsgBox(GetType(String()).ToString())

See Also
Reference
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Operators and Expressions in Visual Basic
Visual Basic Language Reference

Is Operator (Visual Basic)


Compares two object reference variables.

result = object1 Is object2

Parts
result
Required. Any Boolean value.
object1
Required. Any Object name.
object2
Required. Any Object name.
Remarks
The Is operator determines if two object references refer to the same object. However, it does not perform value comparisons.
If object1 and object2 both refer to the exact same object instance, result is True; if they do not, result is False.
Is can also be used with the TypeOf keyword to make a TypeOf...Is expression, which tests whether an object variable is
compatible with a data type.
Example
The following example uses the Is operator to compare pairs of object references. The results are assigned to a Boolean value
representing whether the two objects are identical.
VB
Dim myObject As New Object
Dim otherObject As New Object
Dim yourObject, thisObject, thatObject As Object
Dim myCheck As Boolean
yourObject = myObject
thisObject = myObject
thatObject = otherObject
' The following statement sets myCheck to True.
myCheck = yourObject Is thisObject
' The following statement sets myCheck to False.
myCheck = thatObject Is thisObject
' The following statement sets myCheck to False.
myCheck = myObject Is thatObject
thatObject = myObject
' The following statement sets myCheck to True.
myCheck = thisObject Is thatObject

As the preceding example demonstrates, you can use the Is operator to test both early bound and late bound objects.
See Also
Reference
TypeOf Operator (Visual Basic)
IsNot Operator
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Comparison Operators in Visual Basic
Operators and Expressions in Visual Basic
Visual Basic Language Reference

IsFalse Operator
Determines whether an expression is False.
You cannot call IsFalse explicitly in your code, but the Visual Basic compiler can use it to generate code from AndAlso clauses.
If you define a class or structure and then use a variable of that type in an AndAlso clause, you must define IsFalse on that
class or structure.
The compiler considers the IsFalse and IsTrue operators as a matched pair. This means that if you define one of them, you
must also define the other one.
Note
The IsFalse operator can be overloaded, which means that a class or structure can redefine its behavior when its operand ha
s the type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its re
defined behavior. For more information, see Operator Procedures.

Example
The following code example defines the outline of a structure that includes definitions for the IsFalse and IsTrue operators.
VB
Public Structure p
Dim a As Double
Public Shared Operator IsFalse(ByVal w As p) As Boolean
Dim b As Boolean
' Insert code to calculate IsFalse of w.
Return b
End Operator
Public Shared Operator IsTrue(ByVal w As p) As Boolean
Dim b As Boolean
' Insert code to calculate IsTrue of w.
Return b
End Operator
End Structure

See Also
Tasks
How to: Define an Operator
Reference
IsTrue Operator
AndAlso Operator
Visual Basic Language Reference

IsNot Operator
Compares two object reference variables.

result = object1 IsNot object2

Parts
result
Required. A Boolean value.
object1
Required. Any Object variable or expression.
object2
Required. Any Object variable or expression.
Remarks
The IsNot operator determines if two object references refer to different objects. However, it does not perform value
comparisons. If object1 and object2 both refer to the exact same object instance, result is False; if they do not, result is True.
IsNot is the opposite of the Is operator. The advantage of IsNot is that you can avoid awkward syntax with Not and Is, which
can be difficult to read.
You can use the Is and IsNot operators to test both early-bound and late-bound objects.
Example
The following code example uses both the Is operator and the IsNot operator to accomplish the same comparison.
VB
Dim o1, o2 As New Object
If Not o1 Is o2 Then MsgBox("o1 and o2 do not refer to the same instance.")
If o1 IsNot o2 Then MsgBox("o1 and o2 do not refer to the same instance.")

See Also
Tasks
How to: Test Whether Two Objects Are the Same
Reference
Is Operator (Visual Basic)
Operator Precedence in Visual Basic
Visual Basic Language Reference

IsTrue Operator
Determines whether an expression is True.
You cannot call IsTrue explicitly in your code, but the Visual Basic compiler can use it to generate code from OrElse clauses. If
you define a class or structure and then use a variable of that type in an OrElse clause, you must define IsTrue on that class or
structure.
The compiler considers the IsTrue and IsFalse operators as a matched pair. This means that if you define one of them, you
must also define the other one.
Compiler Use of IsTrue
When you have defined a class or structure, you can use a variable of that type in a For, If, Else If, or While statement, or in a
When clause. If you do this, the compiler requires an operator that converts your type into a Boolean value so it can test a
condition. It searches for a suitable operator in the following order:
1. A widening conversion operator from your class or structure to Boolean.
2. The IsTrue operator on your class or structure.
3. A narrowing conversion operator from your class or structure to Boolean.
If you have not defined any conversion to Boolean or an IsTrue operator, the compiler signals an error.
Note
The IsTrue operator can be overloaded, which means that a class or structure can redefine its behavior when its operand has
the type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its rede
fined behavior. For more information, see Operator Procedures.

Example
The following code example defines the outline of a structure that includes definitions for the IsFalse and IsTrue operators.
VB
Public Structure p
Dim a As Double
Public Shared Operator IsFalse(ByVal w As p) As Boolean
Dim b As Boolean
' Insert code to calculate IsFalse of w.
Return b
End Operator
Public Shared Operator IsTrue(ByVal w As p) As Boolean
Dim b As Boolean
' Insert code to calculate IsTrue of w.
Return b
End Operator
End Structure

See Also
Tasks
How to: Define an Operator
Reference
IsFalse Operator
OrElse Operator
Visual Basic Language Reference

Like Operator
Compares a string against a pattern.

result = string Like pattern

Parts
result
Required. Any Boolean variable. The result is a Boolean value indicating whether or not the string satisfies the pattern.
string
Required. Any String expression.
pattern
Required. Any String expression conforming to the pattern-matching conventions described in "Remarks."
Remarks
If the value in string satisfies the pattern contained in pattern, result is True. If the string does not satisfy the pattern, result is
False. If both string and pattern are empty strings, the result is True.
Comparison Method
The behavior of the Like operator depends on the Option Compare Statement. The default string comparison method for each
source file is Option Compare Binary.
Pattern Options
Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching features allow you to match
each character in string against a specific character, a wildcard character, a character list, or a character range. The following
table shows the characters allowed in pattern and what they match.
Characters in pattern Matches in string
? Any single character

* Zero or more characters

# Any single digit (0–9)

[ charlist ] Any single character in charlist

[! charlist ] Any single character not in charlist


Character Lists
A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in string and
can include almost any character code, including digits.
An exclamation point (!) at the beginning of charlist means that a match is made if any character except the characters in
charlist is found in string. When used outside brackets, the exclamation point matches itself.
Special Characters
To match the special characters left bracket ([), question mark (?), number sign (#), and asterisk (*), enclose them in brackets.
The right bracket (]) cannot be used within a group to match itself, but it can be used outside a group as an individual
character.
The character sequence [] is considered a zero-length string (""). However, it cannot be part of a character list enclosed in
brackets. If you want to check whether a position in string contains one of a group of characters or no character at all, you can
use Like twice. For an example, see How to: Match a String against a Pattern.
Character Ranges
By using a hyphen (–) to separate the lower and upper bounds of the range, charlist can specify a range of characters. For
example, [A–Z] results in a match if the corresponding character position in string contains any character within the range A–Z,
and [!H–L] results in a match if the corresponding character position contains any character outside the range H–L.
When you specify a range of characters, they must appear in ascending sort order, that is, from lowest to highest. Thus, [A–Z]
is a valid pattern, but [Z–A] is not.
Multiple Character Ranges
To specify multiple ranges for the same character position, put them within the same brackets without delimiters. For example,
[A–CX–Z] results in a match if the corresponding character position in string contains any character within either the range A–C
or the range X–Z.
Usage of the Hyphen
A hyphen (–) can appear either at the beginning (after an exclamation point, if any) or at the end of charlist to match itself. In
any other location, the hyphen identifies a range of characters delimited by the characters on either side of the hyphen.
Collating Sequence
The meaning of a specified range depends on the character ordering at run time, as determined by Option Compare and the
locale setting of the system the code is running on. With Option Compare Binary, the range [A–E] matches A, B, C, D, and E.
With Option Compare Text, [A–E] matches A, a, À, à, B, b, C, c, D, d, E, and e. The range does not match Ê or ê because accented
characters collate after unaccented characters in the sort order.
Digraph Characters
In some languages, there are alphabetic characters that represent two separate characters. For example, several languages use
the character æ to represent the characters a and e when they appear together. The Like operator recognizes that the single
digraph character and the two individual characters are equivalent.
When a language that uses a digraph character is specified in the system locale settings, an occurrence of the single digraph
character in either pattern or string matches the equivalent two-character sequence in the other string. Similarly, a digraph
character in pattern enclosed in brackets (by itself, in a list, or in a range) matches the equivalent two-character sequence in
string.
Overloading
The Like operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the
type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefined
behavior. For more information, see Operator Procedures.
Example
This example uses the Like operator to compare strings to various patterns. The results go into a Boolean variable indicating
whether each string satisfies the pattern.
VB
Dim testCheck As Boolean
' The following statement returns True (does "F" satisfy "F"?)
testCheck = "F" Like "F"
' The following statement returns False for Option Compare Binary
' and True for Option Compare Text (does "F" satisfy "f"?)
testCheck = "F" Like "f"
' The following statement returns False (does "F" satisfy "FFF"?)
testCheck = "F" Like "FFF"
' The following statement returns True (does "aBBBa" have an "a" at the
' beginning, an "a" at the end, and any number of characters in
' between?)
testCheck = "aBBBa" Like "a*a"
' The following statement returns True (does "F" occur in the set of
' characters from "A" through "Z"?)
testCheck = "F" Like "[A-Z]"
' The following statement returns False (does "F" NOT occur in the
' set of characters from "A" through "Z"?)
testCheck = "F" Like "[!A-Z]"
' The following statement returns True (does "a2a" begin and end with
' an "a" and have any single-digit number in between?)
testCheck = "a2a" Like "a#a"
' The following statement returns True (does "aM5b" begin with an "a",
' followed by any character from the set "L" through "P", followed
' by any single-digit number, and end with any character NOT in
' the character set "c" through "e"?)
testCheck = "aM5b" Like "a[L-P]#[!c-e]"
' The following statement returns True (does "BAT123khg" begin with a
' "B", followed by any single character, followed by a "T", and end
' with zero or more characters of any type?)
testCheck = "BAT123khg" Like "B?T*"
' The following statement returns False (does "CAT123khg"?) begin with
' a "B", followed by any single character, followed by a "T", and
' end with zero or more characters of any type?)
testCheck = "CAT123khg" Like "B?T*"

See Also
Tasks
How to: Match a String against a Pattern
Reference
Comparison Operators (Visual Basic)
InStr Function (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Option Compare Statement
StrComp Function (Visual Basic)
Concepts
Operators and Expressions in Visual Basic
Visual Basic Language Reference

Mod Operator (Visual Basic)


Divides two numbers and returns only the remainder.

number1 Mod number2

Parts
number1
Required. Any numeric expression.
number2
Required. Any numeric expression.
Supported Types
All numeric types, including the unsigned and floating-point types and Decimal.
Result
The result is the remainder after number1 is divided by number2. For example, the expression 14 Mod 4 evaluates to 2.

Remarks
If either number1 or number2 is a floating-point value, the floating-point remainder of the division is returned. The data type
of the result is the smallest data type that can hold all possible values resulting from division with the data types of number1
and number2.
If number1 or number2 evaluates to Nothing, it is treated as zero.
Related operators include the following:
The \ Operator returns the integer quotient of a division. For example, the expression 14 \ 4 evaluates to 3.

The / Operator (Visual Basic) returns the full quotient, including the remainder, as a floating-point number. For example,
the expression 14 / 4 evaluates to 3.5.
Attempted Division by Zero
If number2 evaluates to zero, the behavior of the Mod operator depends on the data type of the operands. An integral division
throws a DivideByZeroException exception. A floating-point division returns NaN.
Equivalent Formula
The expression a Mod b is equivalent to either of the following formulas:
a - (b * (a \ b))
a - (b * Fix(a / b))
Floating-point Imprecision
When you work with floating-point numbers, keep in mind that they do not always have a precise representation in memory.
This could lead to unexpected results from certain operations, such as value comparison and the Mod operator. For more
information, see Troubleshooting Data Types.
Overloading
The Mod operator can be overloaded, which means that a class or structure can redefine its behavior. If your code applies
Mod to an instance of a class or structure that includes such an overload, be sure you understand its redefined behavior. For
more information, see Operator Procedures.
Example
The following example uses the Mod operator to divide two numbers and return only the remainder. If either number is a
floating-point number, the result is a floating-point number representing the remainder.
VB
Dim testResult As Double
testResult = 10 Mod 5
testResult = 10 Mod 3
testResult = 12 Mod 4.3
testResult = 12.6 Mod 5
testResult = 47.9 Mod 9.35

The expressions in the preceding example return values of 0, 1, 3.4, 2.6, and 1.15.
The following example demonstrates the potential imprecision of floating-point operands. In the first statement, the operands
are Double, and 0.2 is an infinitely repeating binary fraction with a stored value of 0.20000000000000001. In the second
statement, the literal type character D forces both operands to Decimal, and 0.2 has a precise representation.
VB
firstResult = 2.0 Mod 0.2
' Double operation returns 0.2, not 0.
secondResult = 2D Mod 0.2D
' Decimal operation returns 0.

See Also
Tasks
Troubleshooting Data Types
Reference
Arithmetic Operators (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Int, Fix Functions (Visual Basic)
\ Operator
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference

Not Operator (Visual Basic)


Performs logical negation on a Boolean expression, or bitwise negation on a numeric expression.

result = Not expression

Parts
result
Required. Any Boolean or numeric expression.
expression
Required. Any Boolean or numeric expression.
Remarks
For Boolean expressions, the following table illustrates how result is determined.
If expression is The value of result is
True False

False True

For numeric expressions, the Not operator inverts the bit values of any numeric expression and sets the corresponding bit in
result according to the following table.
If bit in expression is The bit in result is
1 0

0 1
Note
Since the logical and bitwise operators have a lower precedence than other arithmetic and relational operators, any bitwise o
perations should be enclosed in parentheses to ensure accurate execution.

Data Types
For a Boolean negation, the data type of the result is Boolean. For a bitwise negation, the result data type is the same as that of
expression. However, if expression is Decimal, the result is Long.
Overloading
The Not operator can be overloaded, which means that a class or structure can redefine its behavior when its operand has the
type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefined
behavior. For more information, see Operator Procedures.
Example
The following example uses the Not operator to perform logical negation on a Boolean expression. The result is a Boolean
value that represents the reverse of the value of the expression.
VB
Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstCheck, secondCheck As Boolean
firstCheck = Not (a > b)
secondCheck = Not (b > a)
The preceding example produces results of False and True, respectively.
The following example uses the Not operator to perform logical negation of the individual bits of a numeric expression. The bit
in the result pattern is set to the reverse of the corresponding bit in the operand pattern, including the sign bit.
VB
Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstPattern, secondPattern, thirdPattern As Integer
firstPattern = (Not a)
secondPattern = (Not b)
thirdPattern = (Not c)

The preceding example produces results of –11, –9, and –7, respectively.
See Also
Reference
Logical/Bitwise Operators
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Logical and Bitwise Operators in Visual Basic
Visual Basic Language Reference

Or Operator (Visual Basic)


Performs a logical disjunction on two Boolean expressions, or a bitwise disjunction on two numeric expressions.

result = expression1 Or expression2

Parts
result
Required. Any Boolean or numeric expression. For Boolean comparison, result is the inclusive logical disjunction of two
Boolean values. For bitwise operations, result is a numeric value representing the inclusive bitwise disjunction of two
numeric bit patterns.
expression1
Required. Any Boolean or numeric expression.
expression2
Required. Any Boolean or numeric expression.
Remarks
For Boolean comparison, result is False if and only if both expression1 and expression2 evaluate to False. The following table
illustrates how result is determined.
If expression1 is And expression2 is The value of result is
True True True

True False True

False True True

False False False


Note
In a Boolean comparison, the Or operator always evaluates both expressions, which could include making procedure calls. T
he OrElse Operator performs short-circuiting, which means that if expression1 is True, then expression2 is not evaluated.

For bitwise operations, the Or operator performs a bitwise comparison of identically positioned bits in two numeric
expressions and sets the corresponding bit in result according to the following table.
If bit in expression1 is And bit in expression2 is The bit in result is
1 1 1

1 0 1

0 1 1

0 0 0
Note
Since the logical and bitwise operators have a lower precedence than other arithmetic and relational operators, any bitwise o
perations should be enclosed in parentheses to ensure accurate execution.

Data Types
If the operands consist of one Boolean expression and one numeric expression, Visual Basic converts the Boolean expression
to a numeric value (–1 for True and 0 for False) and performs a bitwise operation.
For a Boolean comparison, the data type of the result is Boolean. For a bitwise comparison, the result data type is a numeric
type appropriate for the data types of expression1 and expression2. See the "Relational and Bitwise Comparisons" table in
Data Types of Operator Results.
Overloading
The Or operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the
type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefined
behavior. For more information, see Operator Procedures.
Example
The following example uses the Or operator to perform an inclusive logical disjunction on two expressions. The result is a
Boolean value that represents whether either of the two expressions is True.
VB
Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstCheck, secondCheck, thirdCheck As Boolean
firstCheck = a > b Or b > c
secondCheck = b > a Or b > c
thirdCheck = b > a Or c > b

The preceding example produces results of True, True, and False, respectively.
The following example uses the Or operator to perform inclusive logical disjunction on the individual bits of two numeric
expressions. The bit in the result pattern is set if either of the corresponding bits in the operands is set to 1.
VB
Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstPattern, secondPattern, thirdPattern As Integer
firstPattern = (a Or b)
secondPattern = (a Or c)
thirdPattern = (b Or c)

The preceding example produces results of 10, 14, and 14, respectively.
See Also
Reference
Logical/Bitwise Operators
Operator Precedence in Visual Basic
Operators Listed by Functionality
OrElse Operator
Concepts
Logical and Bitwise Operators in Visual Basic
Visual Basic Language Reference

OrElse Operator
Performs short-circuiting inclusive logical disjunction on two expressions.

result = expression1 OrElse expression2

Parts
result
Required. Any Boolean expression.
expression1
Required. Any Boolean expression.
expression2
Required. Any Boolean expression.
Remarks
A logical operation is said to be short-circuiting if the compiled code can bypass the evaluation of one expression depending
on the result of another expression. If the result of the first expression evaluated determines the final result of the operation,
there is no need to evaluate the second expression, because it cannot change the final result. Short-circuiting can improve
performance if the bypassed expression is complex, or if it involves procedure calls.
If either or both expressions evaluate to True, result is True. The following table illustrates how result is determined.
If expression1 is And expression2 is The value of result is
True (not evaluated) True

False True True

False False False


Data Types
The OrElse operator is defined only for the Boolean Data Type (Visual Basic). Visual Basic converts each operand as necessary
to Boolean and performs the operation entirely in Boolean. If you assign the result to a numeric type, Visual Basic converts it
from Boolean to that type. This could produce unexpected behavior. For example, 5 OrElse 12 results in –1 when converted
to Integer.
Overloading
The Or Operator (Visual Basic) and the IsTrue Operator can be overloaded, which means that a class or structure can redefine
their behavior when an operand has the type of that class or structure. Overloading the Or and IsTrue operators affects the
behavior of the OrElse operator. If your code uses OrElse on a class or structure that overloads Or and IsTrue, be sure you
understand their redefined behavior. For more information, see Operator Procedures.
Example
The following example uses the OrElse operator to perform logical disjunction on two expressions. The result is a Boolean
value that represents whether either of the two expressions is true. If the first expression is True, the second is not evaluated.
VB
Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstCheck, secondCheck, thirdCheck As Boolean
firstCheck = a > b OrElse b > c
secondCheck = b > a OrElse b > c
thirdCheck = b > a OrElse c > b
The preceding example produces results of True, True, and False respectively. In the calculation of firstCheck, the second
expression is not evaluated because the first is already True. However, the second expression is evaluated in the calculation of
secondCheck.

The following example shows an If...Then statement containing two procedure calls. If the first call returns True, the second
procedure is not called. This could produce unexpected results if the second procedure performs important tasks that should
always be performed when this section of the code runs.
VB
If testFunction(5) = True OrElse otherFunction(4) = True Then
' If testFunction(5) is True, otherFunction(4) is not called.
' Insert code to be executed.
End If

See Also
Reference
Logical/Bitwise Operators
Operator Precedence in Visual Basic
Operators Listed by Functionality
Or Operator (Visual Basic)
IsTrue Operator
Concepts
Logical and Bitwise Operators in Visual Basic
Visual Basic Language Reference

TypeOf Operator (Visual Basic)


Compares an object reference variable to a data type.

result = TypeOf objectexpression Is typename

Parts
result
Returned. A Boolean value.
objectexpression
Required. Any expression that evaluates to a reference type.
typename
Required. Any data type name.
Remarks
The TypeOf operator determines whether the run-time type of objectexpression is compatible with typename. The
compatibility depends on the type category of typename. The following table shows how compatibility is determined.
Type category of typename Compatibility criterion
Class objectexpression is of type typename or inherits from typename

Structure objectexpression is of type typename

Interface objectexpression implements typename or inherits from a class that implements typename

If the run-time type of objectexpression satisfies the compatibility criterion, result is True. Otherwise, result is False.
TypeOf is always used with the Is keyword to construct a TypeOf...Is expression.
Example
The following example uses TypeOf...Is expressions to test the type compatibility of two object reference variables with various
data types.
VB
Dim refInteger As Object = 2
MsgBox("TypeOf Object[Integer] Is Integer? " & TypeOf refInteger Is Integer)
MsgBox("TypeOf Object[Integer] Is Double? " & TypeOf refInteger Is Double)
Dim refForm As Object = New System.Windows.Forms.Form
MsgBox("TypeOf Object[Form] Is Form? " & TypeOf refForm Is System.Windows.Forms.Form)
MsgBox("TypeOf Object[Form] Is Label? " & TypeOf refForm Is System.Windows.Forms.Label)
MsgBox("TypeOf Object[Form] Is Control? " & TypeOf refForm Is System.Windows.Forms.Control)
MsgBox("TypeOf Object[Form] Is IComponent? " & TypeOf refForm Is System.ComponentModel.ICom
ponent)

The variable refInteger has a run-time type of Integer. It is compatible with Integer but not with Double. The variable
refForm has a run-time type of Form. It is compatible with Form because that is its type, with Control because Form inherits
from Control, and with IComponent because Form inherits from Component, which implements IComponent. However,
refForm is not compatible with Label.

See Also
Reference
Is Operator (Visual Basic)
IsNot Operator
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Comparison Operators in Visual Basic
Operators and Expressions in Visual Basic
Visual Basic Language Reference

Xor Operator (Visual Basic)


Performs a logical exclusion on two Boolean expressions, or a bitwise exclusion on two numeric expressions.

result = expression1 Xor expression2

Parts
result
Required. Any Boolean or numeric variable. For Boolean comparison, result is the logical exclusion (exclusive logical
disjunction) of two Boolean values. For bitwise operations, result is a numeric value representing the bitwise exclusion
(exclusive bitwise disjunction) of two numeric bit patterns.
expression1
Required. Any Boolean or numeric expression.
expression2
Required. Any Boolean or numeric expression.
Remarks
For Boolean comparison, result is True if and only if exactly one of expression1 and expression2 evaluates to True, that is, if and
only if expression1 and expression2 evaluate to opposite Boolean values. The following table illustrates how result is
determined.
If expression1 is And expression2 is The value of result is
True True False

True False True

False True True

False False False


Note
In a Boolean comparison, the Xor operator always evaluates both expressions, which could include making procedure calls. T
here is no short-circuiting counterpart to Xor, since the result always depends on both operands. For short-circuiting logical
operators, see AndAlso Operator and OrElse Operator.

For bitwise operations, the Xor operator performs a bitwise comparison of identically positioned bits in two numeric
expressions and sets the corresponding bit in result according to the following table.
If bit in expression1 is And bit in expression2 is The bit in result is
1 1 0

1 0 1

0 1 1

0 0 0
Note
Since the logical and bitwise operators have a lower precedence than other arithmetic and relational operators, any bitwise o
perations should be enclosed in parentheses to ensure accurate execution.
For example, 5 Xor 3 is 6. To see why this is so, convert 5 and 3 to their binary representations, 101 and 011. Then use the
preceding table to determine that 101 Xor 011 is 110, which is the binary representation of the decimal number 6.
Data Types
If the operands consist of one Boolean expression and one numeric expression, Visual Basic converts the Boolean expression
to a numeric value (–1 for True and 0 for False) and performs a bitwise operation.
For a Boolean comparison, the data type of the result is Boolean. For a bitwise comparison, the result data type is a numeric
type appropriate for the data types of expression1 and expression2. See the "Relational and Bitwise Comparisons" table in
Data Types of Operator Results.
Overloading
The Xor operator can be overloaded, which means that a class or structure can redefine its behavior when an operand has the
type of that class or structure. If your code uses this operator on such a class or structure, be sure you understand its redefined
behavior. For more information, see Operator Procedures.
Example
The following example uses the Xor operator to perform logical exclusion (exclusive logical disjunction) on two expressions.
The result is a Boolean value that represents whether exactly one of the expressions is True.
VB
Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstCheck, secondCheck, thirdCheck As Boolean
firstCheck = a > b Xor b > c
secondCheck = b > a Xor b > c
thirdCheck = b > a Xor c > b

The preceding example produces results of False, True, and False, respectively.
The following example uses the Xor operator to perform logical exclusion (exclusive logical disjunction) on the individual bits
of two numeric expressions. The bit in the result pattern is set if exactly one of the corresponding bits in the operands is set to
1.
VB
Dim a As Integer = 10 ' 1010 in binary
Dim b As Integer = 8 ' 1000 in binary
Dim c As Integer = 6 ' 0110 in binary
Dim firstPattern, secondPattern, thirdPattern As Integer
firstPattern = (a Xor b) ' 2, 0010 in binary
secondPattern = (a Xor c) ' 12, 1100 in binary
thirdPattern = (b Xor c) ' 14, 1110 in binary

The preceding example produces results of 2, 12, and 14, respectively.


See Also
Reference
Logical/Bitwise Operators
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Logical and Bitwise Operators in Visual Basic
Visual Basic Language Reference

Data Types of Operator Results


Visual Basic determines the result data type of an operation based on the data types of the operands. In some cases this might
be a data type with a greater range than that of either operand.
Data Type Ranges
The ranges of the relevant data types, in order from smallest to largest, are as follows:
Boolean — two possible values
SByte, Byte — 256 possible integral values
Short, UShort — 65,536 (6.5...E+4) possible integral values
Integer, UInteger — 4,294,967,296 (4.2...E+9) possible integral values
Long, ULong — 18,446,744,073,709,551,615 (1.8...E+19) possible integral values
Decimal — 1.5...E+29 possible integral values, maximum range 7.9...E+28 (absolute value)
Single — maximum range 3.4...E+38 (absolute value)
Double — maximum range 1.7...E+308 (absolute value)
For more information on Visual Basic data types, see Data Type Summary (Visual Basic).
If an operand evaluates to Nothing, the Visual Basic arithmetic operators treat it as zero.
Decimal Arithmetic
Note that the Decimal data type is neither floating-point nor integer.
If either operand of a +, –, *, /, or Mod operation is Decimal and the other is not Single or Double, Visual Basic widens the
other operand to Decimal. It performs the operation in Decimal, and the result data type is Decimal.
Floating-Point Arithmetic
Visual Basic performs most floating-point arithmetic in Double, which is the most efficient data type for such operations.
However, if one operand is Single and the other is not Double, Visual Basic performs the operation in Single. It widens each
operand as necessary to the appropriate data type before the operation, and the result has that data type.
/ and ^ Operators
The / operator is defined only for the Decimal, Single, and Double data types. Visual Basic widens each operand as necessary to
the appropriate data type before the operation, and the result has that data type.
The following table shows the result data types for the / operator. Note that this table is symmetric; for a given combination of
operand data types, the result data type is the same regardless of the order of the operands.

Decimal Single Double Any integer type

Decimal Decimal Single Double Double

Single Single Single Double Double

Double Double Double Double Double

Any integer type Double Double Double Double

The ^ operator is defined only for the Double data type. Visual Basic widens each operand as necessary to Double before the
operation, and the result data type is always Double.
Integer Arithmetic
The result data type of an integer operation depends on the data types of the operands. In general, Visual Basic uses the
following policies for determining the result data type:
If both operands of a binary operator have the same data type, the result has that data type. An exception is Boolean,
which is forced to Short.
If an unsigned operand participates with a signed operand, the result has a signed type with at least as large a range as
either operand.
Otherwise, the result usually has the larger of the two operand data types.
Note that the result data type might not be the same as either operand data type.
Note
The result data type is not always large enough to hold all possible values resulting from the operation. An
OverflowException exception can occur if the value is too large for the result data type.

Unary + and – Operators


The following table shows the result data types for the two unary operators, + and –.

Boolean SByte Byte Short UShort Integer UInteger Long ULong

Unary + Short SByte Byte Short UShort Integer UInteger Long ULong

Unary – Short SByte Short Short Integer Integer Long Long Decimal
<< and >> Operators
The following table shows the result data types for the two bit-shift operators, << and >>. Visual Basic treats each bit-shift
operator as a unary operator on its left operand (the bit pattern to be shifted).

Boolean SByte Byte Short UShort Integer UInteger Long ULong

<<, >> Short SByte Byte Short UShort Integer UInteger Long ULong

If the left operand is Decimal, Single, Double, or String, Visual Basic attempts to convert it to Long before the operation, and
the result data type is Long. The right operand (the number of bit positions to shift) must be Integer or a type that widens to
Integer.
Binary +, –, *, and Mod Operators
The following table shows the result data types for the binary + and – operators and the * and Mod operators. Note that this
table is symmetric; for a given combination of operand data types, the result data type is the same regardless of the order of
the operands.

Boolean SByte Byte Short UShort Integer UInteger Long ULong

Boolean Short SByte Short Short Integer Integer Long Long Decimal

SByte SByte SByte Short Short Integer Integer Long Long Decimal

Byte Short Short Byte Short UShort Integer UInteger Long ULong

Short Short Short Short Short Integer Integer Long Long Decimal

UShort Integer Integer UShort Integer UShort Integer UInteger Long ULong

Integer Integer Integer Integer Integer Integer Integer Long Long Decimal

UInteger Long Long UInteger Long UInteger Long UInteger Long ULong

Long Long Long Long Long Long Long Long Long Decimal
ULong Decimal Decimal ULong Decimal ULong Decimal ULong Decimal ULong
\ Operator
The following table shows the result data types for the \ operator. Note that this table is symmetric; for a given combination of
operand data types, the result data type is the same regardless of the order of the operands.

Boolean SByte Byte Short UShort Integer UInteger Long ULong

Boolean Short SByte Short Short Integer Integer Long Long Long

SByte SByte SByte Short Short Integer Integer Long Long Long

Byte Short Short Byte Short UShort Integer UInteger Long ULong

Short Short Short Short Short Integer Integer Long Long Long

UShort Integer Integer UShort Integer UShort Integer UInteger Long ULong

Integer Integer Integer Integer Integer Integer Integer Long Long Long

UInteger Long Long UInteger Long UInteger Long UInteger Long ULong

Long Long Long Long Long Long Long Long Long Long

ULong Long Long ULong Long ULong Long ULong Long ULong

If either operand of the \ operator is Decimal, Single, or Double, Visual Basic attempts to convert it to Long before the
operation, and the result data type is Long.
Relational and Bitwise Comparisons
The result data type of a relational operation (=, <>, <, >, <=, >=) is always BooleanBoolean Data Type (Visual Basic). The
same is true for logical operations (And, AndAlso, Not, Or, OrElse, Xor) on Boolean operands.
The result data type of a bitwise logical operation depends on the data types of the operands. Note that AndAlso and OrElse
are defined only for Boolean, and Visual Basic converts each operand as necessary to Boolean before performing the
operation.
=, <>, <, >, <=, and >= Operators
If both operands are Boolean, Visual Basic considers True to be less than False. If a numeric type is compared with a String,
Visual Basic attempts to convert the String to Double before the operation. A Char or Date operand can be compared only
with another operand of the same data type. The result data type is always Boolean.
Bitwise Not Operator
The following table shows the result data types for the bitwise Not operator.

Boolean SByte Byte Short UShort Integer UInteger Long ULong

Not Boolean SByte Byte Short UShort Integer UInteger Long ULong

If the operand is Decimal, Single, Double, or String, Visual Basic attempts to convert it to Long before the operation, and the
result data type is Long.
Bitwise And, Or, and Xor Operators
The following table shows the result data types for the bitwise And, Or, and Xor operators. Note that this table is symmetric;
for a given combination of operand data types, the result data type is the same regardless of the order of the operands.
Boolean SByte Byte Short UShort Integer UInteger Long ULong

Boolean Boolean SByte Short Short Integer Integer Long Long Long

SByte SByte SByte Short Short Integer Integer Long Long Long

Byte Short Short Byte Short UShort Integer UInteger Long ULong

Short Short Short Short Short Integer Integer Long Long Long

UShort Integer Integer UShort Integer UShort Integer UInteger Long ULong

Integer Integer Integer Integer Integer Integer Integer Long Long Long

UInteger Long Long UInteger Long UInteger Long UInteger Long ULong

Long Long Long Long Long Long Long Long Long Long

ULong Long Long ULong Long ULong Long ULong Long ULong

If an operand is Decimal, Single, Double, or String, Visual Basic attempts to convert it to Long before the operation, and the
result data type is the same as if that operand had already been Long.
Miscellaneous Operators
The & operator is defined only for concatenation of String operands. Visual Basic converts each operand as necessary to
String before the operation, and the result data type is always String. For the purposes of the & operator, all conversions to
String are considered to be widening, even if Option Strict is On.
The Is and IsNot operators require both operands to be of a reference type. The TypeOf...Is expression requires the first
operand to be of a reference type and the second operand to be the name of a data type. In all these cases the result data type
is Boolean.
The Like operator is defined only for pattern matching of String operands. Visual Basic attempts to convert each operand as
necessary to String before the operation. The result data type is always Boolean.
See Also
Reference
Data Type Summary (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
Arithmetic Operators (Visual Basic)
Comparison Operators (Visual Basic)
Option Strict Statement
Concepts
Operators and Expressions in Visual Basic
Arithmetic Operators in Visual Basic
Comparison Operators in Visual Basic
Other Resources
Operators (Visual Basic)
Visual Basic Language Reference

Arithmetic Operators (Visual Basic)


The following are the arithmetic operators defined in Visual Basic.
^ Operator
* Operator
/ Operator
\ Operator
Mod Operator
+ Operator (unary and binary)
- Operator (unary and binary)
See Also
Reference
Operator Precedence in Visual Basic
Concepts
Arithmetic Operators in Visual Basic
Visual Basic Language Reference

Assignment Operators
The following are the assignment operators defined in Visual Basic.
= Operator
^= Operator
*= Operator
/= Operator
\= Operator
+= Operator
-= Operator
<<= Operator
>>= Operator
&= Operator
See Also
Reference
Operator Precedence in Visual Basic
Operators Listed by Functionality
Concepts
Assignment Statements
Visual Basic Language Reference

Bit Shift Operators


The following are the bit shift operators defined in Visual Basic.
<< Operator
>> Operator
See Also
Reference
Operators Listed by Functionality
Visual Basic Language Reference

Comparison Operators (Visual Basic)


The following are the comparison operators defined in Visual Basic.
< operator
<= operator
> operator
>= operator
= operator
<> operator
Is Operator (Visual Basic)
IsNot Operator
Like Operator
These operators compare two expressions to determine whether or not they are equal, and if not, how they differ. Is, IsNot,
and Like are discussed in detail on separate Help pages. The relational comparison operators are discussed in detail on this
page.

result = expression1 comparisonoperator expression2


result = object1 [Is | IsNot] object2
result = string Like pattern

Parts
result
Required. A Boolean value representing the result of the comparison.
expression
Required. Any expression.
comparisonoperator
Required. Any relational comparison operator.
object1, object2
Required. Any reference object names.
string
Required. Any String expression.
pattern
Required. Any String expression or range of characters.
Remarks
The following table contains a list of the relational comparison operators and the conditions that determine whether result is
True or False.
Operator True if False if
< (Less than) expression1 < expression2 expression1 >= expression2

<= (Less than or equal to) expression1 <= expression2 expression1 > expression2

> (Greater than) expression1 > expression2 expression1 <= expression2


>= (Greater than or equal to) expression1 >= expression2 expression1 < expression2

= (Equal to) expression1 = expression2 expression1 <> expression2

<> (Not equal to) expression1 <> expression2 expression1 = expression2


Note
The = Operator (Visual Basic) is also used as an assignment operator.

The Is operator, the IsNot operator, and the Like operator have specific comparison functionalities that differ from the
operators in the preceding table.
Comparing Numbers
When you compare an expression of type Single to one of type Double, the Single expression is converted to Double. This
behavior is opposite to the behavior found in Visual Basic 6.
Similarly, when you compare an expression of type Decimal to an expression of type Single or Double, the Decimal
expression is converted to Single or Double. For Decimal expressions, any fractional value less than 1E-28 might be lost.
Such fractional value loss may cause two values to compare as equal when they are not. For this reason, you should take care
when using equality (=) to compare two floating-point variables. It is safer to test whether the absolute value of the difference
between the two numbers is less than a small acceptable tolerance.
Floating-point Imprecision
When you work with floating-point numbers, keep in mind that they do not always have a precise representation in memory.
This could lead to unexpected results from certain operations, such as value comparison and the Mod Operator (Visual Basic).
For more information, see Troubleshooting Data Types.
Comparing Strings
When you compare strings, the string expressions are evaluated based on their alphabetical sort order, which depends on the
Option Compare setting.
Option Compare Binary bases string comparisons on a sort order derived from the internal binary representations of the
characters. The sort order is determined by the code page. The following example shows a typical binary sort order.
A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø

Option Compare Text bases string comparisons on a case-insensitive, textual sort order determined by your application's
locale. When you set Option Compare Text and sort the characters in the preceding example, the following text sort order
applies:
(A=a) < (À= à) < (B=b) < (E=e) < (Ê= ê) < (Ø = ø) < (Z=z)
Locale Dependence
When you set Option Compare Text, the result of a string comparison can depend on the locale in which the application is
running. Two characters might compare as equal in one locale but not in another. If you are using a string comparison to make
important decisions, such as whether to accept an attempt to log on, you should be alert to locale sensitivity. Consider either
setting Option Compare Binary or calling the StrComp Function (Visual Basic), which takes the locale into account.
Typeless Programming with Relational Comparison Operators
The use of relational comparison operators with Object expressions is not allowed under Option Strict On. When Option
Strict is Off, and either expression1 or expression2 is an Object expression, the run-time types determine how they are
compared. The following table shows how the expressions are compared and the result from the comparison, depending on
the runtime type of the operands.
If operands are Comparison is
Both String Sort comparison based on string sorting characteristics.

Both numeric Objects converted to Double, numeric comparison.


One numeric and one String The String is converted to a Double and numeric comparison is performed. If the String cann
ot be converted to Double, an InvalidCastException is thrown.

Either or both are reference ty An InvalidCastException is thrown.


pes other than String
Numeric comparisons treat Nothing as 0. String comparisons treat Nothing as "" (an empty string).
Overloading
The relational comparison operators (<. <=, >, >=, =, <>) can be overloaded, which means that a class or structure can
redefine their behavior when an operand has the type of that class or structure. If your code uses any of these operators on
such a class or structure, be sure you understand the redefined behavior. For more information, see Operator Procedures.
Notice that the = Operator (Visual Basic) can be overloaded only as a relational comparison operator, not as an assignment
operator.
Example
The following example shows various uses of relational comparison operators, which you use to compare expressions.
Relational comparison operators return a Boolean result that represents whether or not the stated expression evaluates to
True. When you apply the > and < operators to strings, the comparison is made using the normal alphabetical sorting order of
the strings. This order can be dependent on your locale setting. Whether the sort is case-sensitive or not depends on the
Option Compare setting.
VB
Dim testResult As Boolean
testResult = 45 < 35
testResult = 45 = 45
testResult = 4 <> 3
testResult = "5" > "4444"

In the preceding example, the first comparison returns False and the remaining comparisons return True.
See Also
Tasks
Troubleshooting Data Types
Reference
= Operator (Visual Basic)
Operator Precedence in Visual Basic
Operators Listed by Functionality
InvalidCastException
Concepts
Comparison Operators in Visual Basic
Visual Basic Language Reference

Concatenation Operators (Visual Basic)


The following are the concatenation operators defined in Visual Basic.
& Operator
+ Operator
See Also
Reference
Operator Precedence in Visual Basic
System.Text
StringBuilder
Concepts
Concatenation Operators in Visual Basic
Visual Basic Language Reference

Logical/Bitwise Operators
The following are the logical/bitwise operators defined in Visual Basic.
And Operator (Visual Basic)
Not Operator (Visual Basic)
Or Operator (Visual Basic)
Xor Operator (Visual Basic)
AndAlso Operator
OrElse Operator
IsFalse Operator
IsTrue Operator
See Also
Reference
Operator Precedence in Visual Basic
Concepts
Logical and Bitwise Operators in Visual Basic
Visual Basic Language Reference

Miscellaneous Operators
The following are miscellaneous operators defined in Visual Basic.
AddressOf Operator
GetType Operator
TypeOf Operator (Visual Basic)
See Also
Reference
Operators Listed by Functionality
Visual Basic Language Reference

Properties (Visual Basic)


This page lists the properties that are members of Visual Basic modules. Other properties that are members of specific Visual
Basic objects are listed elsewhere in the Help table of contents. To see these properties, go to the Objects (Visual Basic) page
and sync to the table of contents. Open the "Objects" node in the contents and you will see a list of Visual Basic objects. The
properties are listed under their respective objects.
In This Section
DateString Property
Now Property
ScriptEngine Property
ScriptEngineBuildVersion Property
ScriptEngineMajorVersion Property
ScriptEngineMinorVersion Property
TimeOfDay Property
Timer Property
TimeString Property
Today Property
Related Sections
Visual Basic Reference
Visual Basic
Visual Basic Language Reference

DateString Property
Returns or sets a String value representing the current date according to your system.

Public Property DateString As String

Exceptions
Exception type Error number Condition
InvalidCastException 5 Invalid format used to set value of DateString.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
DateString always returns the system date as "MM-dd-yyyy", which uses the abbreviated month name. The accepted formats
for setting the date are "M-d-yyyy", "M-d-y", "M/d/yyyy", and "M/d/y". These formats are culture-invariant, which means they
do not change even if you change the Regional Options in Control Panel.
To get or set the current system time as a String, use the TimeString Property.
To get the current system date or time in the format of your locale, or in a custom format, supply the Now Property to the
Format Function, specifying either Predefined Date/Time Formats (Format Function) or
User-Defined Date/Time Formats (Format Function). The following example demonstrates this.

MsgBox("The formatted date is " & Format(Now, "dddd, d MMM yyyy"))

To access the current system date as a Date, use the Today Property.
Security Note
Setting the system date or time requires unmanaged code permission, which might affect its execution in partial-trust situati
ons. For more information, see SecurityPermission and Code Access Permissions.

Example
The following example uses the DateString property to display the current system date.
VB
MsgBox("The current date is " & DateString)

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Because DateString is a member of a module, rather than of a class, you do not need to create an object on which to access
DateString.
Smart Device Developer Notes
You can get, but not set, the system date using the DateString property.
See Also
Reference
Now Property
TimeString Property
Today Property
Date Data Type (Visual Basic)
DateTime
Visual Basic Language Reference

Now Property
Returns a Date value containing the current date and time according to your system.

ReadOnly Public Property Now() As DateTime

Remarks
To set the system date, use the Today Property. To set the system time, use the TimeOfDay Property.
Example
The following example uses the Now property to return the current system date and time.
VB
Dim ThisMoment As Date
' The following statement calls the Get procedure of the Visual Basic Now property.
ThisMoment = Now

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Because Now is a member of a module, rather than of a class, you do not need to create an object on which to access Now.
See Also
Reference
Day Function (Visual Basic)
Hour Function (Visual Basic)
Minute Function
Month Function (Visual Basic)
Second Function (Visual Basic)
Weekday Function (Visual Basic)
Year Function (Visual Basic)
Date Data Type (Visual Basic)
DateTime
Visual Basic Language Reference

ScriptEngine Property
Returns a String representing the runtime currently in use.

ReadOnly Public Property ScriptEngine As String

Remarks
The ScriptEngine property returns the string "VB".
You can use ScriptEngine when your application is running as a standalone program, in a script, or in a host application.
Example
The following example uses the ScriptEngine property and related properties to return a string describing the current run-
time information:
VB
Function getRuntimeInfo() As String
Dim runtime As String = ScriptEngine & " Version "
runtime &= CStr(ScriptEngineMajorVersion) & "."
runtime &= CStr(ScriptEngineMinorVersion) & "."
runtime &= CStr(ScriptEngineBuildVersion)
' Return the current runtime information.
Return runtime
End Function

Smart Device Developer Notes


This property is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Globals
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Because ScriptEngine is a member of a module, rather than of a class, you do not need to create an object on which to access
ScriptEngine.
See Also
Reference
ScriptEngineBuildVersion Property
ScriptEngineMajorVersion Property
ScriptEngineMinorVersion Property
Visual Basic Language Reference

ScriptEngineBuildVersion Property
Returns an Integer containing the build version number of the runtime currently in use.

ReadOnly Public Property ScriptEngineBuildVersion As Integer

Remarks
The returned value corresponds directly to the version information contained in the DLL for the current runtime.
You can use ScriptEngineBuildVersion when your application is running as a standalone program, in a script, or in a host
application.
Example
The following example uses the ScriptEngineBuildVersion property and related properties to return a string describing the
current run-time information:
VB
Function getRuntimeInfo() As String
Dim runtime As String = ScriptEngine & " Version "
runtime &= CStr(ScriptEngineMajorVersion) & "."
runtime &= CStr(ScriptEngineMinorVersion) & "."
runtime &= CStr(ScriptEngineBuildVersion)
' Return the current runtime information.
Return runtime
End Function

Smart Device Developer Notes


This property is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Globals
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Because ScriptEngineBuildVersion is a member of a module, rather than of a class, you do not need to create an object on
which to access ScriptEngineBuildVersion.
See Also
Reference
ScriptEngine Property
ScriptEngineMajorVersion Property
ScriptEngineMinorVersion Property
Visual Basic Language Reference

ScriptEngineMajorVersion Property
Returns an Integer containing the major version number of the runtime currently in use.

ReadOnly Public Property ScriptEngineMajorVersion As Integer

Remarks
The returned value corresponds directly to the version information contained in the DLL for the current runtime.
You can use ScriptEngineMajorVersion when your application is running as a standalone program, in a script, or in a host
application.
Example
The following example uses the ScriptEngineMajorVersion property and related properties to return a string describing the
current run-time information:
VB
Function getRuntimeInfo() As String
Dim runtime As String = ScriptEngine & " Version "
runtime &= CStr(ScriptEngineMajorVersion) & "."
runtime &= CStr(ScriptEngineMinorVersion) & "."
runtime &= CStr(ScriptEngineBuildVersion)
' Return the current runtime information.
Return runtime
End Function

Smart Device Developer Notes


This property is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Globals
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Because ScriptEngineMajorVersion is a member of a module, rather than of a class, you do not need to create an object on
which to access ScriptEngineMajorVersion.
See Also
Reference
ScriptEngine Property
ScriptEngineBuildVersion Property
ScriptEngineMinorVersion Property
Visual Basic Language Reference

ScriptEngineMinorVersion Property
Returns an Integer containing the minor version number of the runtime currently in use.

ReadOnly Public Property ScriptEngineMinorVersion As Integer

Remarks
The returned value corresponds directly to the version information contained in the DLL for the current runtime.
You can use ScriptEngineMinorVersion when your application is running as a standalone program, in a script, or in a host
application.
Example
The following example uses the ScriptEngineMinorVersion property and related properties to return a string describing the
current run-time information:
VB
Function getRuntimeInfo() As String
Dim runtime As String = ScriptEngine & " Version "
runtime &= CStr(ScriptEngineMajorVersion) & "."
runtime &= CStr(ScriptEngineMinorVersion) & "."
runtime &= CStr(ScriptEngineBuildVersion)
' Return the current runtime information.
Return runtime
End Function

Smart Device Developer Notes


This property is not supported.
Requirements
Namespace: Microsoft.VisualBasic
Module: Globals
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Because ScriptEngineMinorVersion is a member of a module, rather than of a class, you do not need to create an object on
which to access ScriptEngineMinorVersion.
See Also
Reference
ScriptEngine Property
ScriptEngineBuildVersion Property
ScriptEngineMajorVersion Property
Visual Basic Language Reference

TimeOfDay Property
Returns or sets a Date value containing the current time of day according to your system.

Public Property TimeOfDay() As DateTime

Remarks
The Date data type includes date components. When returning the system time, TimeOfDay sets these all to 1, so the
returned value represents the first day of the year 1. When setting the system time, TimeOfDay ignores the date components.
To access the current system time as a String, use the TimeString Property.
To get or set the current system date, use the Today Property.
Security Note
Setting the system date or time requires unmanaged code permission, which might affect its execution in partial-trust situati
ons. For more information, see SecurityPermission and Code Access Permissions.

Example
This example uses the TimeOfDay property to return the current system time.
VB
Dim currentTime As Date
currentTime = TimeOfDay

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Because TimeOfDay is a member of a module, rather than of a class, you do not need to create an object on which to access
TimeOfDay.
Smart Device Developer Notes
You can get, but not set, the current time of day using the TimeOfDay property.
See Also
Reference
Timer Property
Date Data Type (Visual Basic)
DateTime
Visual Basic Language Reference

Timer Property
Returns a Double value representing the number of seconds elapsed since midnight.

ReadOnly Public Property Timer() As Double

Remarks
The Timer property returns both the seconds and the milliseconds since the most recent midnight. The seconds are in the
integral part of the return value, and the milliseconds are in the fractional part.
Example
This example uses the Timer property to pause the application. It can perform other processing during the pause.
VB
Public Sub waitFiveSeconds()
If TimeOfDay >= #11:59:55 PM# Then
MsgBox("The current time is within 5 seconds of midnight" & _
vbCrLf & "The timer returns to 0.0 at midnight")
Return
End If
Dim start, finish, totalTime As Double
If (MsgBox("Press Yes to pause for 5 seconds", MsgBoxStyle.YesNo)) _
= MsgBoxResult.Yes Then
start = Microsoft.VisualBasic.DateAndTime.Timer
' Set end time for 5-second duration.
finish = start + 5.0
Do While Microsoft.VisualBasic.DateAndTime.Timer < finish
' Do other processing while waiting for 5 seconds to elapse.
Loop
totalTime = Microsoft.VisualBasic.DateAndTime.Timer - start
MsgBox("Paused for " & totalTime & " seconds")
End If
End Sub

Note that you must qualify the Timer property with the Microsoft.VisualBasic namespace, because Timer is also a defined
class in the System.Threading, System.Timers, and System.Windows.Forms namespaces.
Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Because Timer is a member of a module, rather than of a class, you do not need to create an object on which to access Timer.
See Also
Reference
Randomize Function (Visual Basic)
TimeOfDay Property
Today Property
System
System.Windows.Forms
DateTime
ArgumentException
ArgumentOutOfRangeException
Visual Basic Language Reference

TimeString Property
Returns or sets a String value representing the current time of day according to your system.

Public Property TimeString As String

Exceptions
Exception type Error number Condition
InvalidCastException 5 Invalid format used to set value of TimeString.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
TimeString always returns the system time as "HH:mm:ss", which is a 24-hour format. This format is culture-invariant, which
means it does not change even if you change the Regional Options in Control Panel.
To get or set the current system date as a String, use the DateString Property.
To get the current system date or time in the format of your locale, or in a custom format, supply the Now Property to the
Format Function, specifying either Predefined Date/Time Formats (Format Function) or
User-Defined Date/Time Formats (Format Function). The following example demonstrates this.

MsgBox("The formatted time is " & Format(Now, "hh.mm.ss.fff tt"))

To access the current system time as a Date, use the TimeOfDay Property.
Security Note
Setting the system date or time requires unmanaged code permission, which might affect its execution in partial trust situati
ons. For more information, see SecurityPermission and Code Access Permissions.

Example
This example uses the TimeString property to display the current system time.
VB
MsgBox("The current time is " & TimeString)

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Because TimeString is a member of a module, rather than of a class, you do not need to create an object on which to access
TimeString.
Smart Device Developer Notes
You can get, but not set, the system time using the TimeString property.
See Also
Reference
Now Property
DateString Property
TimeOfDay Property
Date Data Type (Visual Basic)
DateTime
Visual Basic Language Reference

Today Property
Returns or sets a Date value containing the current date according to your system.

Public Property Today() As DateTime

Remarks
The Date data type includes time components. When returning the system date, Today sets all of these to 0, so the returned
value represents midnight (00:00:00). When setting the system date, Today ignores the time components.
To access the current system date as a String, use the DateString Property.
To get or set the current system time, use the TimeOfDay Property.
Security Note
Setting the system date or time requires unmanaged code permission, which might affect its execution in partial-trust situati
ons. For more information, see SecurityPermission and Code Access Permissions.

Example
This example uses the Today property to return the current system date.
VB
Dim thisDate As Date
thisDate = Today

Requirements
Namespace: Microsoft.VisualBasic
Module: DateAndTime
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Because Today is a member of a module, rather than of a class, you do not need to create an object on which to access Today.
Smart Device Developer Notes
You can get but not set the current system date using the Today property.
See Also
Reference
Format Function
Now Property
Date Data Type (Visual Basic)
DateTime
Visual Basic Language Reference

Statements (Visual Basic)


The topics in this section contain tables of the Visual Basic declaration and executable statements, and of important lists that
apply to many statements.
In This Section
A-E Statements
F-P Statements
Q-Z Statements
Declaration Contexts and Default Access Levels
Attribute List
Parameter List
Type List
Related Sections
Visual Basic Reference
Visual Basic
Visual Basic Language Reference

A-E Statements
The following table contains a listing of Visual Basic language statements.

AddHandler Call Class Const

Continue Declare Delegate Dim

Do...Loop End Enum Erase

Error Event Exit


See Also
Reference
F-P Statements
Q-Z Statements
Other Resources
Visual Basic Reference
Visual Basic Language Reference

AddHandler Statement
Associates an event with an event handler at run time.

AddHandler event, AddressOf eventhandler

Parts
event
The name of the event to handle.
eventhandler
The name of a procedure that handles the event.
Remarks
The AddHandler and RemoveHandler statements allow you to start and stop event handling at any time during program
execution.
The signature of the eventhandler procedure must match the signature of the event event.
The Handles keyword and the AddHandler statement both allow you to specify that particular procedures handle particular
events, but there are differences. The AddHandler statement connects procedures to events at run time. Use the Handles
keyword when defining a procedure to specify that it handles a particular event. For more information, see Handles.
For custom events, the AddHandler statement invokes the event's AddHandler accessor. For more information on custom
events, see Event Statement.
Example
VB
Sub TestEvents()
Dim Obj As New Class1
' Associate an event handler with an event.
AddHandler Obj.Ev_Event, AddressOf EventHandler
' Call the method to raise the event.
Obj.CauseSomeEvent()
' Stop handling events.
RemoveHandler Obj.Ev_Event, AddressOf EventHandler
' This event will not be handled.
Obj.CauseSomeEvent()
End Sub
Sub EventHandler()
' Handle the event.
MsgBox("EventHandler caught event.")
End Sub
Public Class Class1
' Declare an event.
Public Event Ev_Event()
Sub CauseSomeEvent()
' Raise an event.
RaiseEvent Ev_Event()
End Sub
End Class

See Also
Reference
RemoveHandler Statement
Handles
Event Statement
Concepts
Events and Event Handlers
AddHandler and RemoveHandler
Visual Basic Language Reference

Call Statement (Visual Basic)


Transfers control to a Function, Sub, or dynamic-link library (DLL) procedure.

[ Call ] procedureName [ (argumentList) ]

Parts
procedureName
Required. Name of the procedure to call.
argumentList
Optional. List of variables or expressions representing arguments that are passed to the procedure when it is called. Multiple
arguments are separated by commas. If you include argumentList, you must enclose it in parentheses.
Remarks
You normally use the Call statement to call a procedure that does not return a value. If the procedure returns a value, the Call
statement discards it.
You are not required to use the Call statement when calling a procedure. However, it improves the readability of your code.
Example
This example illustrates how the Call statement is used to transfer control to a Sub procedure, an intrinsic function, and a
dynamic-link library (DLL) procedure.
VB
' (1) Call a Sub procedure.
Call printToDebugWindow("Hello World")
...
' The above statement passes control to the following Sub procedure.
Sub printToDebugWindow(ByVal anyString As String)
Debug.WriteLine(anyString)
End Sub

VB
' (2) Call a Visual Basic run-time function (Shell), discard the return value.
Call Shell("C:\WINNT\system32\calc.exe", AppWinStyle.NormalFocus)
' The preceding path is for Windows 2000;
' The Windows XP path is C:\Windows\system32\calc.exe.

VB
' (3) Call a Microsoft Windows DLL procedure. The Declare statement
' must be Private in a class, not in a module.
Private Declare Sub MessageBeep Lib "User32" (ByVal N As Integer)
Sub callBeepDll()
Call MessageBeep(-1)
End Sub

See Also
Reference
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
Declare Statement
Visual Basic Language Reference

Class Statement (Visual Basic)


Declares the name of a class and introduces the definition of the variables, properties, events, and procedures that the class
comprises.

[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Parti


al ] _
Class name [ ( Of typelist ) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class

Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional. Can be one of the following:
Public
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
Shadows
Optional. See Shadows.
MustInherit
Optional. See MustInherit.
NotInheritable
Optional. See NotInheritable.
Partial
Optional. Indicates a partial definition of the class. See Partial (Visual Basic).
name
Required. Name of this class. See Declared Element Names.
Of
Optional. Specifies that this is a generic class.
typelist
Required if you use the Of keyword. List of type parameters for this class. See Type List.
Inherits
Optional. Indicates that this class inherits the members of another class. See Inherits Statement.
classname
Required if you use the Inherits statement. The name of the class from which this class derives.
Implements
Optional. Indicates that this class implements the members of one or more interfaces. See Implements Statement.
interfacenames
Required if you use the Implements statement. The names of the interfaces this class implements.
statements
Optional. Statements which define the members of this class.
End Class
Required. Terminates the Class definition.
Remarks
A Class statement defines a new data type. A class is a fundamental building block of object-oriented programming (OOP). For
more information, see Object-Oriented Programming in Visual Basic and Classes: Blueprints for Objects.
You can use Class only at namespace or module level. This means the declaration context for a class must be a source file,
namespace, class, structure, module, or interface, and cannot be a procedure or block. For more information, see
Declaration Contexts and Default Access Levels.
Each instance of a class has a lifetime independent of all other instances. This lifetime begins when it is created by a
New (Visual Basic) clause or by a function such as CreateObject Function (Visual Basic). It ends when all variables pointing to
the instance have been set to Nothing (Visual Basic) or to instances of other classes.
Classes default to Friend (Visual Basic) access. You can adjust their access levels with the access modifiers. For more
information, see Access Levels in Visual Basic.
Rules
Nesting. You can define one class within another. The outer class is called the containing class, and the inner class is
called a nested class.
Inheritance. If the class uses the Inherits Statement, you can specify only one base class or interface. A class cannot
inherit from more than one element.
A class cannot inherit from another class with a more restrictive access level. For example, a Public class cannot inherit
from a Friend class.
A class cannot inherit from a class nested within it.
Implementation. If the class uses the Implements Statement, you must implement every member defined by every
interface you specify in interfacenames. An exception to this is reimplementation of a base class member. For more
information, see "Reimplementation" in Implements (Visual Basic).
Default Property. A class can specify at most one property as its default property. For more information, see
Default Properties.
Behavior
Access Level. Within a class, you can declare each member with its own access level. Class members default to
Public (Visual Basic) access, except variables and constants, which default to Private (Visual Basic) access. When a class
has more restricted access than one of its members, the class access level takes precedence.
Scope. A class is in scope throughout its containing namespace, class, structure, or module.
The scope of every class member is the entire class.
Lifetime. Visual Basic does not support static classes. The functional equivalent of a static class is provided by a module.
For more information, see Module Statement.
Class members have lifetimes depending on how and where they are declared. For more information, see
Lifetime in Visual Basic.
Qualification. Code outside a class must qualify a member's name with the name of that class.
If code inside a nested class makes an unqualified reference to a programming element, Visual Basic searches for the
element first in the nested class, then in its containing class, and so on out to the outermost containing element. For more
information, see Resolving a Reference When Multiple Variables Have the Same Name.
Classes and Modules
These elements have many similarities, but there are some important differences as well.
Terminology. Previous versions of Visual Basic recognize two types of modules: class modules (.cls files) and standard
modules (.bas files). The current version calls these classes and modules, respectively.
Shared Members. You can control whether a member of a class is a shared or instance member.
Object Orientation. Classes are object-oriented, but modules are not. You can create one or more instances of a class.
For more information, see Classes vs. Modules.
Example
The following example uses a Class statement to define a class and several members.
VB
Class bankAccount
Shared interestRate As Decimal
Private accountNumber As String
Private accountBalance As Decimal
Public holdOnAccount As Boolean = False

Public ReadOnly Property balance() As Decimal


Get
Return accountBalance
End Get
End Property

Public Sub postInterest()


accountBalance = accountBalance * (1 + interestRate)
End Sub

Public Sub postDeposit(ByVal amountIn As Decimal)


accountBalance = accountBalance + amountIn
End Sub

Public Sub postWithdrawal(ByVal amountOut As Decimal)


accountBalance = accountBalance - amountOut
End Sub
End Class

See Also
Tasks
How to: Use a Generic Class
Reference
Interface Statement (Visual Basic)
Module Statement
Property Statement
Concepts
Structures and Classes
Object Lifetime: How Objects Are Created and Destroyed
Generic Types in Visual Basic
Other Resources
Understanding Classes
Visual Basic Language Reference

Const Statement (Visual Basic)


Declares and defines one or more constants.

[ <attributelist> ] [ accessmodifier ] [ Shadows ]


Const constantlist

Parts
attributelist
Optional. List of attributes that apply to all the constants declared in this statement. See Attribute List in angle brackets ("<"
and ">").
accessmodifier
Optional. Use this to specify what code can access these constants. Can be Public (Visual Basic), Protected (Visual Basic),
Friend (Visual Basic), Protected Friend, or Private (Visual Basic).
Shadows
Optional. Use this to redeclare and hide a programming element in a base class. See Shadows.
constantlist
Required. List of constants being declared in this statement.
constant [ , constant ... ]

Each constant has the following syntax and parts:


constantname [ As datatype ] = initializer

Part Description
constantname Required. Name of the constant. See Declared Element Names.

datatype Required if Option Strict is On. Data type of the constant.

initializer Required. Expression that is evaluated at compile time and assigned to the constant.

Remarks
If you have a value that never changes in your application, you can define a named constant and use it in place of a literal
value. A name is easier to remember than a value. You can define the constant just once and use it in many places in your code.
If in a later version you need to redefine the value, the Const statement is the only place you need to make a change.
You can use Const only at module or procedure level. This means the declaration context for a variable must be a class,
structure, module, procedure, or block, and cannot be a source file, namespace, or interface. For more information, see
Declaration Contexts and Default Access Levels.
Local constants (inside a procedure) default to public access, and you cannot use any access modifiers on them. Class and
module member constants (outside any procedure) default to private access, and structure member constants default to public
access. You can adjust their access levels with the access modifiers.
Rules
Declaration Context. A constant declared at module level, outside any procedure, is a member constant; it is a member
of the class, structure, or module that declares it.
A constant declared at procedure level is a local constant; it is local to the procedure or block that declares it.
Attributes. You can apply attributes only to member constants, not to local constants. An attribute contributes
information to the assembly's metadata, which is not meaningful for temporary storage such as local constants.
Modifiers. By default, all constants are Shared, Static, and ReadOnly. You cannot use any of these keywords when
declaring a constant.
At procedure level, you cannot use Shadows or any access modifiers to declare local constants.
Multiple Constants. You can declare several constants in the same declaration statement, specifying the constantname
part for each one. Multiple constants are separated by commas.
Data Type Rules
Data Types. The Const statement can declare the data type of a variable. You can specify any data type or the name of
an enumeration.
Default Type. If you do not specify datatype, the constant takes the data type of initializer. If you specify both datatype
and initializer, the data type of initializer must be convertible to datatype. If neither datatype nor initializer is present, the
data type defaults to Object.
Different Types. You can specify different data types for different constants by using a separate As clause for each
variable you declare. However, you cannot declare several constants to be of the same type by using a common As
clause.
Initialization. You must initialize the value of every constant in constantlist. You use initializer to supply an expression
to be assigned to the constant. The expression can be any combination of literals, other constants that are already
defined, and enumeration members that are already defined. You can use arithmetic and logical operators to combine
such elements.
You cannot use variables or functions in initializer. However, you can use conversion keywords such as CByte and
CShort. You can also use AscW if you call it with a constant String or Char argument, since that can be evaluated at
compile time.
Behavior
Scope. Local constants are accessible only from within their procedure or block. Member constants are accessible from
anywhere within their class, structure, or module.
Qualification. Code outside a class, structure, or module must qualify a member constant's name with the name of that
class, structure, or module. Code outside a procedure or block cannot refer to any local constants within that procedure
or block.
Example
The following example uses the Const statement to declare constants for use in place of literal values.
VB
' The following statements declare constants.
Const maximum As Long = 459
Public Const helpString As String = "HELP"
Private Const startValue As Integer = 5

If you define a constant with data type Object, the Visual Basic compiler gives it the type of initializer, instead of Object. In the
following example, the constant naturalLogBase has the run-time type Decimal.
VB
Const naturalLogBase As Object = CDec(2.7182818284)
MsgBox("Run-time type of constant naturalLogBase is " & _
naturalLogBase.GetType.ToString())

The preceding example uses the ToString method on the Type object returned by the GetType Operator, because Type cannot
be converted to String using CStr.
See Also
Reference
Enum Statement (Visual Basic)
#Const Directive
Dim Statement (Visual Basic)
ReDim Statement (Visual Basic)
Type Conversion Functions
Asc, AscW Functions
Concepts
Implicit and Explicit Conversions
Intrinsic Constants and Enumerations
Other Resources
Constants and Enumerations in Visual Basic
Visual Basic Language Reference

Continue Statement (Visual Basic)


Transfers control immediately to the next iteration of a loop.

Continue { Do | For | While }

Remarks
You can transfer from inside a Do, For, or While loop to the next iteration of that loop. Control passes immediately to the loop
condition test, which is equivalent to transferring to the For or While statement, or to the Do or Loop statement that contains
the Until or While clause.
You can use Continue at any place in the loop that permits transfers. The rules allowing transfer of control are the same as
with the GoTo Statement.
For example, if a loop is totally contained within a Try block, a Catch block, or a Finally block, you can use Continue to
transfer out of the loop. If, on the other hand, the Try...End Try structure is contained within the loop, you cannot use
Continue to transfer control out of the Finally block, and you can use it to transfer out of a Try or Catch block only if you
transfer completely out of the Try...End Try structure.
If you have nested loops of the same type, for example a Do loop within another Do loop, a Continue Do statement skips to
the next iteration of the innermost Do loop that contains it. You cannot use Continue to skip to the next iteration of a
containing loop of the same type.
If you have nested loops of different types, for example a Do loop within a For loop, you can skip to the next iteration of either
loop by using either Continue Do or Continue For.
Example
The following code example uses the Continue While statement to skip to the next column of an array if a divisor is zero. The
Continue While is inside a For loop. It transfers to the While col < lastcol statement, which is the next iteration of the
innermost While loop that contains the For loop.
VB
Dim row, col As Integer
Dim lastrow As Integer = 6
Dim lastcol As Integer = 10
Dim a(,) As Double = New Double(lastrow, lastcol) {}
Dim b(7) As Double
row = -1
While row < lastrow
row += 1
col = -1
While col < lastcol
col += 1
a(row, col) = 0
For i As Integer = 0 To b.GetUpperBound(0)
If b(i) = col Then
Continue While
Else
a(row, col) += (row + b(i)) / (col - b(i))
End If
Next i
End While
End While

See Also
Tasks
How to: Skip to the Next Iteration of a Loop
Reference
Do...Loop Statement (Visual Basic)
For...Next Statement (Visual Basic)
While...End While Statement (Visual Basic)
Try...Catch...Finally Statement (Visual Basic)
Visual Basic Language Reference

Declare Statement
Declares a reference to a procedure implemented in an external file.

[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ Overloads ] _


Declare [ charsetmodifier ] [ Sub ] name Lib "libname" _
[ Alias "aliasname" ] [ ([ parameterlist ]) ]
' -or-
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ Overloads ] _
Declare [ charsetmodifier ] [ Function ] name Lib "libname" _
[ Alias "aliasname" ] [ ([ parameterlist ]) ] [ As returntype ]

Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional. Can be one of the following:
Public
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
Shadows
Optional. See Shadows.
charsetmodifier
Optional. Specifies character set and file search information. Can be one of the following:
Ansi (default)
Unicode (Visual Basic)
Auto
Sub
Optional, but either Sub or Function must appear. Indicates that the external procedure does not return a value.
Function
Optional, but either Sub or Function must appear. Indicates that the external procedure returns a value.
name
Required. Name of this external reference. For more information, see Declared Element Names.
Lib
Required. Introduces a Lib clause, which specifies the file that contains the procedure being declared.
libname
Required. Name of the file that contains the declared procedure.
Alias
Optional. Indicates that the procedure being declared cannot be identified within its file by the name specified in name. You
specify its identification in aliasname.
aliasname
Required if you use the Alias keyword. String that identifies the procedure in one of two ways:
The entry point name of the procedure within its file, within quotes ("")
-or-
A number sign (#) followed by an integer specifying the ordinal number of the procedure's entry point within its file
parameterlist
Required if the procedure takes parameters. See Parameter List.
returntype
Required if Function is specified and Option Strict is On. Data type of the value returned by the procedure.
Remarks
Sometimes you need to call a procedure defined in a file (such as a DLL or code resource) outside your project. When you do
this, the Visual Basic compiler does not have access to the information it needs to call the procedure correctly, such as where
the procedure is located, how it is identified, its calling sequence and return type, and the string character set it uses. The
Declare statement creates a reference to an external procedure and supplies this necessary information.
You can use Declare only at module level. This means the declaration context for an external reference must be a class,
structure, or module, and cannot be a source file, namespace, interface, procedure, or block. For more information, see
Declaration Contexts and Default Access Levels.
External references default to Public (Visual Basic) access. You can adjust their access levels with the access modifiers.
Rules
Attributes. You can apply attributes to an external reference. Any attribute you apply has effect only in your project, not
in the external file.
Modifiers. External procedures are implicitly Shared (Visual Basic). You cannot use the Shared keyword when declaring
an external reference, and you cannot alter its shared status.
An external procedure cannot participate in overriding, implement interface members, or handle events. Accordingly, you
cannot use the Overrides, Overridable, NotOverridable, MustOverride, Implements, or Handles keyword in a
Declare statement.
External Procedure Name. You do not have to give this external reference the same name (in name) as the procedure's
entry-point name within its external file (aliasname). You can use an Alias clause to specify the entry-point name. This
can be useful if the external procedure has the same name as a Visual Basic reserved modifier or a variable, procedure, or
any other programming element in the same scope.
Note
Entry-point names in most DLLs are case-sensitive.

External Procedure Number. Alternatively, you can use an Alias clause to specify the ordinal number of the entry
point within the export table of the external file. To do this, you begin aliasname with a number sign (#). This can be
useful if any character in the external procedure name is not allowed in Visual Basic, or if the external file exports the
procedure without a name.
Data Type Rules
Parameter Data Types. If Option Strict is On, you must specify the data type of each parameter in parameterlist. This
can be any data type or the name of an enumeration, structure, class, or interface. Within parameterlist, you use an As
clause to specify the data type of the argument to be passed to each parameter.
Note
If the external procedure was not written for the .NET Framework, you must take care that the data types correspond. F
or example, if you declare an external reference to a Visual Basic 6.0 procedure with an Integer parameter (16 bits in Vi
sual Basic 6.0), you must identify the corresponding argument as Short in the Declare statement, because that is the 1
6-bit integer type in Visual Basic. Similarly, Long has a different data width in Visual Basic 6.0, and Date is implemente
d differently.

Return Data Type. If the external procedure is a Function and Option Strict is On, you must specify the data type of
the value returned to the calling code. This can be any data type or the name of an enumeration, structure, class, or
interface.
Note
The Visual Basic compiler does not verify that your data types are compatible with those of the external procedure. If th
ere is a mismatch, the common language runtime generates a MarshalDirectiveException exception at run time.

Default Data Types. If Option Strict is Off and you do not specify the data type of a parameter in parameterlist, the
Visual Basic compiler converts the corresponding argument to the Object Data Type. Similarly, if you do not specify
returntype, the compiler takes the return data type to be Object.
Note
Because you are dealing with an external procedure that might have been written on a different platform, it is dangero
us to make any assumptions about data types or to allow them to default. It is much safer to specify the data type of ev
ery parameter and of the return value, if any. This also improves the readability of your code.

Behavior
Scope. An external reference is in scope throughout its class, structure, or module.
Lifetime. An external reference has the same lifetime as the class, structure, or module in which it is declared.
Calling an External Procedure. You call an external procedure the same way you call a Function or Sub procedure—
by using it in an expression if it returns a value, or by specifying it in a Call Statement (Visual Basic) if it does not return a
value.
You pass arguments to the external procedure exactly as specified by parameterlist in the Declare statement. Do not
take into account how the parameters were originally declared in the external file. Similarly, if there is a return value, use
it exactly as specified by returntype in the Declare statement.
Character Sets. You can specify in charsetmodifier how Visual Basic should marshal strings when it calls the external
procedure. The Ansi modifier directs Visual Basic to marshal all strings to ANSI values, and the Unicode modifier directs
it to marshal all strings to Unicode values. The Auto modifier directs Visual Basic to marshal strings according to .NET
Framework rules based on the external reference name, or aliasname if specified. The default value is Ansi.
charsetmodifier also specifies how Visual Basic should look up the external procedure within its external file. Ansi and
Unicode both direct Visual Basic to look it up without modifying its name during the search. Auto directs Visual Basic to
determine the base character set of the run-time platform and possibly modify the external procedure name, as follows:
On an ANSI platform, such as Windows 95, Windows 98, or Windows Millennium Edition, first look up the
external procedure with no name modification. If that fails, append "A" to the end of the external procedure name
and look it up again.
On a Unicode platform, such as Windows NT, Windows 2000, or Windows XP, first look up the external
procedure with no name modification. If that fails, append "W" to the end of the external procedure name and
look it up again.
Mechanism. Visual Basic uses the .NET Framework platform invoke (PInvoke) mechanism to resolve and access external
procedures. The Declare statement and the DllImportAttribute class both use this mechanism automatically, and you do
not need any knowledge of PInvoke. For more information, see Walkthrough: Calling Windows APIs.
Security Note
If the external procedure runs outside the common language runtime (CLR), it is unmanaged code. When you call such a pro
cedure, for example a Win32 API function or a COM method, you might expose your application to security risks. For more in
formation, see Unmanaged Code.

Example
The following example declares an external reference to a Function procedure that returns the current user name. It then calls
the external procedure GetUserNameA as part of the getUser procedure.
VB
Declare Function getUserName Lib "advapi32.dll" Alias "GetUserNameA" _
(ByVal lpBuffer As String, ByRef nSize As Integer) As Integer
Sub getUser()
Dim buffer As String = New String(CChar(" "), 25)
Dim retVal As Integer = getUserName(buffer, 25)
Dim userName As String = Strings.Left(buffer, InStr(buffer, Chr(0)) - 1)
MsgBox(userName)
End Sub

The DllImportAttribute provides an alternative way of using functions in unmanaged code. The following example declares
an imported function without using a Declare statement.
VB
' Add an Imports statement at the top of the class, structure, or
' module that uses the DllImport attribute.
Imports System.Runtime.InteropServices

VB
<DllImportAttribute("kernel32.dll", EntryPoint:="MoveFileW", _
SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function moveFile(ByVal src As String, _
ByVal dst As String) As Boolean
' This function copies a file from the path src to the path dst.
' Leave this function empty. The DLLImport attribute forces calls
' to moveFile to be forwarded to MoveFileW in KERNEL32.DLL.
End Function

See Also
Tasks
Walkthrough: Calling Windows APIs
Reference
Imports Statement
AddressOf Operator
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
Parameter List
Call Statement (Visual Basic)
LastDllError Property (Err Object)
Concepts
Data Type Changes for Visual Basic 6.0 Users
Integer Data Type for Visual Basic 6.0 Users
Visual Basic Language Reference

Delegate Statement
Used to declare a delegate. A delegate is a reference type that refers to a Shared method of a type or to an instance method of
an object. Any procedure with matching parameter types and return type may be used to create an instance of this delegate
class. The procedure can then later be invoked by means of the delegate instance.

[ <attrlist> ] [ accessmodifier ] _
[ Shadows ] Delegate [ Sub | Function ] name [( Of typeparamlist )] [([ parameterlist ])] [
As type ]

Parts
attrlist
Optional. List of attributes that apply to this delegate. Multiple attributes are separated by commas. You must enclose the
Attribute List in angle brackets ("<" and ">").
accessmodifier
Optional. Specifies what code can access the delegate. Can be one of the following:
Public. Any code that can access the element that declares the delegate can access it.
Protected. Only code within the delegate's class or a derived class can access it.
Friend. Only code within the same assembly can access the delegate.
Private. Only code within the element that declares the delegate can access it.
You can specify Protected Friend to allow access from code within the delegate's class, a derived class, or the same
assembly.
Shadows
Optional. Indicates that this delegate redeclares and hides an identically named programming element, or set of overloaded
elements, in a base class. You can shadow any kind of declared element with any other kind.
A shadowed element is unavailable from within the derived class that shadows it, except from where the shadowing element
is inaccessible. For example, if a Private element shadows a base class element, code that does not have permission to
access the Private element accesses the base class element instead.
Sub
Optional, but either Sub or Function must appear. Declares this procedure as a delegate Sub procedure that does not return
a value.
Function
Optional, but either Sub or Function must appear. Declares this procedure as a delegate Function procedure that returns a
value.
name
Required. Name of the delegate type; follows standard variable naming conventions.
typeparamlist
Optional. List of type parameters for this delegate. Multiple type parameters are separated by commas. You must enclose the
Type List in parentheses and introduce it with the Of keyword.
parameterlist
Optional. List of parameters that are passed to the procedure when it is called. You must enclose the Parameter List in
parentheses.
type
Required if you specify a Function procedure. Data type of the return value.
Remarks
The Delegate statement defines the parameter types and return type of a delegate class. Any procedure with matching
parameters types and return type may be used to create an instance of this delegate class. The procedure can then later be
invoked by means of the delegate instance, by calling the delegate's Invoke method.
Delegates can be declared at the namespace, module, class, or structure level, but not within a procedure.
Each delegate class defines a constructor that is passed the specification of an object method. An argument to a delegate
constructor must be an expression of the form:
AddressOf [expression.]methodname
The compile-time type of the expression must be the name of a class or an interface that contains a method of the specified
name whose signature matches the signature of the delegate class. The methodname can be either a shared method or an
instance method. The methodname is not optional, even if you create a delegate for the default method of the class.
Example
The following example uses the Delegate statement to declare a delegate for operating on two numbers and returning a
number. The DelegateTest method takes an instance of a delegate of this type and uses it to operate on pairs of numbers.
VB
Delegate Function MathOperator( _
ByVal x As Double, _
ByVal y As Double _
) As Double

Function AddNumbers( _
ByVal x As Double, _
ByVal y As Double _
) As Double
Return x + y
End Function

Function SubtractNumbers( _
ByVal x As Double, _
ByVal y As Double _
) As Double
Return x - y
End Function
Sub DelegateTest( _
ByVal x As Double, _
ByVal op As MathOperator, _
ByVal y As Double _
)
Dim ret As Double
ret = op.Invoke(x, y) ' Call the method.
MsgBox(ret)
End Sub

Protected Sub Test()


DelegateTest(5, AddressOf AddNumbers, 3)
DelegateTest(9, AddressOf SubtractNumbers, 3)
End Sub

See Also
Tasks
How to: Use a Generic Class
Reference
AddressOf Operator
Of
Concepts
Generic Types in Visual Basic
Other Resources
Delegates in Visual Basic
Visual Basic Language Reference

Dim Statement (Visual Basic)


Declares and allocates storage space for one or more variables.

[ <attributelist> ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]] [ ReadOnly ]


Dim [ WithEvents ] variablelist

Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional. Can be one of the following:
Public
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
Shared
Optional. See Shared.
Shadows
Optional. See Shadows.
Static
Optional. See Static.
ReadOnly
Optional. See ReadOnly.
WithEvents
Optional. Specifies that these are object variables that refer to instances of a class that can raise events. See WithEvents.
variablelist
Required. List of variables being declared in this statement.
variable [ , variable ... ]

Each variable has the following syntax and parts:


variablename[ ( [ boundslist ] ) ] [ As [ New ] datatype ] [ = initializer ]

Part Description
variablename Required. Name of the variable. See Declared Element Names.

boundslist Optional. List of bounds of each dimension of an array variable.

New Optional. Creates a new instance of the class when the Dim statement runs.

datatype Required if Option Strict is On. Data type of the variable.


initializer Optional if New is not specified. Expression that is evaluated and assigned to the variable when it is created.

Remarks
You should declare every variable you use in your program, to tell the Visual Basic compiler the variable's data type and other
information such as what code can access it. The following example declares a variable to hold an Integer value.

Dim numberOfStudents As Integer

You can use Dim only at module or procedure level. This means the declaration context for a variable must be a class,
structure, module, procedure, or block, and cannot be a source file, namespace, or interface. For more information, see
Declaration Contexts and Default Access Levels.
If Option Explicit is On (the default), the compiler requires a declaration for every variable you use. If you turn Option
Explicit Off, every undeclared variable defaults to the Object Data Type, which might not be your intention.
You can specify each variable's data type in the Dim statement. You can also specify an initial value. If you do not, Visual Basic
uses default settings. For more information, see "Data Type Rules" and "Default Values" under "Detailed Information" on this
Help page. The following example declares and initializes a String variable.

Dim summary As String = "Summary of results"

You can specify what code can access a variable by supplying an accessmodifier in the Dim statement. For more information,
see "Modifiers" and "Access Level" under "Detailed Information" on this Help page.
You can declare a variable to hold an array, which can hold multiple values. For more information, see "Array Rules" under
"Detailed Information" on this Help page. For more information on arrays, see Arrays in Visual Basic. The following example
declares an Integer array variable.

Dim days() As Integer

In general, you should put all your Dim statements at the beginning of the code region in which you use the variables. For
more information, see "Troubleshooting" under "Detailed Information" on this Help page.
Detailed Information
This section covers the following areas in detail:
Declaration
Data types
Arrays
Behavior
Troubleshooting
Declaration Rules
Declaration Context. A variable declared at module level, outside any procedure, is a member variable or field; it is a
member of the class, structure, or module that declares it.
A variable declared at procedure level is a local variable; it is local to the procedure or block that declares it.
Attributes. You can apply attributes only to member variables, not to local variables. An attribute contributes
information to the assembly's metadata, which is not meaningful for temporary storage such as local variables.
Implicit Use of Dim. If you specify any of the modifiers Public, Protected, Friend, Protected Friend, Private, Shared,
Shadows, Static, ReadOnly, or WithEvents, you can optionally omit the Dim keyword.

Public maximumAllowed As Double


Protected Friend currentUserName As String
Private salary As Decimal
Static runningTotal As Integer
At module level, you cannot use the Static modifier to declare member variables. At procedure level, you cannot use
Shared, Shadows, ReadOnly, WithEvents, or any access modifiers to declare local variables.
WithEvents Variables. You can specify WithEvents only on member variables, not on local variables inside a
procedure.
If you specify WithEvents, the data type of the variables must be a specific class type and not Object. You cannot
declare an array with WithEvents.
For more information on events, see Events and Event Handlers.
Multiple Variables. You can declare several variables in the same declaration statement, specifying the variablename
part for each one and following each array name with parentheses. Multiple variables are separated by commas.

Dim lastTime, nextTime, allTimes() As Date

Data Type Rules


Data Types. The Dim statement can declare the data type of a variable. You can specify any data type or the name of an
enumeration, structure, class, or interface.

Dim finished As Boolean


Dim monitorBox As System.Windows.Forms.Form

Default Type. If you do not specify datatype, the variable takes the data type of initializer. If neither datatype nor
initializer is present, the data type defaults to the Object Data Type. If you specify both datatype and initializer, the data
type of initializer must be convertible to datatype.
Different Types. You can specify different data types for different variables by using a separate As clause for each
variable you declare. Alternatively, you can declare several variables to be of the same type by using a common As
clause. Each variable takes the data type specified in the first As clause encountered after its variablename part.

Dim a, b, c As Single, x, y As Double, i As Integer


' a, b, and c are all Single; x and y are both Double

Initialization. The Dim statement can initialize the contents of selected variables in variablelist. For a value type, you
use initializer to supply an expression to be assigned to the variable. The expression must evaluate to a constant that can
be calculated at compile time.

Dim quantity As Integer = 10


Dim message As String = "Just started"

For a reference type, you use the New keyword to create a new instance of the class or structure specified by datatype. If
you use New, you do not use an initializer expression. Instead, you supply arguments, if required, to the constructor of
the class from which you are creating the variable.

Dim bottomLabel As New System.Windows.Forms.Label

If you declare more than one variable with the same As clause, you cannot supply an initializer for that group of
variables.
Array Rules
Array Variables. To specify that a variable in variablelist is an array, you follow its variablename immediately with
parentheses. If the array has more than one dimension, you must include commas between the parentheses to indicate
the number of dimensions.

Dim oneDimension(), twoDimensions(,), threeDimensions(,,) As Byte


An array can have from 1 to 32 dimensions.
For more information, see Arrays in Visual Basic.
Array Bounds. You can specify the lower and upper bound of each dimension. To do this, you include a boundslist inside
the parentheses. For each dimension, the boundslist specifies the upper bound and optionally the lower bound. The lower
bound is always zero, whether you specify it or not. Each index can vary from zero through its upper bound value.
The following two statements are equivalent. Each statement declares an array of 21 Integer elements. When you access
the array, the index can vary from 0 through 20.

Dim totals(20) As Integer


Dim totals(0 To 20) As Integer

The following statement declares a two-dimensional array of type Double. The array has 4 rows (3 + 1) of 6 columns (5
+ 1) each.

Dim matrix2(3, 5) As Double

Note that an upper bound represents the highest possible value for that index, not the length of that dimension, which is
the upper bound plus one.
Blank Array Bounds. You can leave all the bounds blank in an array declaration. If you do this, the array has the number
of dimensions you specify, but it is uninitialized, so it has a value of Nothing until you initialize at least some of its
elements. The Dim statement must specify bounds either for all dimensions or for none of them.

Dim messages() As String

Empty Arrays. It is possible to use -1 to declare the upper bound of an array dimension. This signifies that the array is
empty but not Nothing, a distinction required by certain common language runtime functions. However, Visual Basic
code cannot successfully access such an array. If you attempt to do so, an IndexOutOfRangeException error occurs during
execution. For more information, see How to: Create an Array with No Elements.
Array Initialization. You can initialize the values of an array by surrounding the initialization values with braces ({}).

Dim longArray() As Long = {0, 1, 2, 3}

For multidimensional arrays, the initialization for each separate dimension is surrounded by braces within the outer
dimension. The elements are specified in row-major order.

Dim twoDimensions(,) As Integer = {{0, 1, 2}, {10, 11, 12}}

Behavior
Default Values. If you do not specify initializer for a variable, Visual Basic initializes it to the default value for its data
type. The following table shows the default initialization values.
Data type Default value
All numeric types (including Byte and SByte) 0

Char Binary 0

All reference types (including Object, String, and all array Nothing
s)

Boolean False
Date 12:00 AM of January 1 of the year 1 (01/01/0001 12:00:00 A
M)

Each element of a structure is initialized as if it were a separate variable. If you declare the length of an array but do not
initialize its elements, each element is initialized as if it were a separate variable.
Access Level. Local variables (inside a procedure) default to public access, and you cannot use any access modifiers on
them.
Class and module member variables (outside any procedure) default to private access, and structure member variables
default to public access. You can adjust their access levels with the access modifiers.
Scope. Local variables are in scope only within their procedure or block. Member variables are in scope throughout their
class, structure, or module.
Qualification. Code outside a class, structure, or module must qualify a member variable's name with the name of that
class, structure, or module. Code outside a procedure or block cannot refer to any local variables within that procedure or
block.
Lifetime. A Static local variable has a longer lifetime than that of the procedure in which it is declared. The boundaries
of the variable's lifetime depend on where the procedure is declared and whether or not it is Shared.
Procedure declarat Variable initialized Variable ceases to exist
ion
In a module The first time the procedure is called When your program terminates exe
cution

In a class or structure The first time the procedure is called either on a specific insta When your program terminates exe
, Shared nce or on the class or structure itself cution

In a class or structure The first time the procedure is called on a specific instance When the instance is released for ga
, not Shared rbage collection (GC)

Troubleshooting
Execution Order. The Dim statement is not itself an executable statement. However, if it initializes one or more
variables, the initializations are treated as assignment statements. This means that a variable's value undergoes the
following steps:
1. On the first entry into the code element declaring the variable, Visual Basic initializes it to the default value for its
data type.
2. When execution arrives at the variable's Dim statement, Visual Basic initializes it to the value supplied in the Dim
statement.
3. Whenever execution returns to the variable's Dim statement, Visual Basic sets it once again to the value supplied in
the Dim statement.
This has the following implications when you use a Dim statement to initialize a variable:
If you use the variable before executing the Dim statement, its value is the default for its data type, not the value
supplied in the Dim statement.
If execution never reaches the Dim statement, the variable is never initialized to the value supplied in the Dim
statement.
If you alter the value but then return to the Dim statement, your altered value is replaced by the value supplied in
the Dim statement.
If you put all your Dim statements at the beginning of the code region in which they appear, for example a module or a
procedure, your code initializes them as you intend.
Example
The following example declares variables using the Dim statement with various options.
VB
' The following statement declares and initializes a Long variable.
Dim startingAmount As Long = 500

VB
' The following statement declares a variable that refers to a Button
' object, creates a new Button object, and assigns it to the variable.
Dim switchButton As New System.Windows.Forms.Button

VB
' The following statement declares a variable that can only be
' accessed by code in the same class, structure, or module.
Private homeTelephone As String = ""

VB
' The following statement declares a local variable that always retains
' its value, even after its procedure returns to the calling code.
Static totalSales As Double

VB
' The following statement declares a variable that refers to an array.
Dim highTemperature(31) As Integer

VB
' The following statement declares and initializes an array variable
' that holds 4 Boolean check values.
Dim checkValues() As Boolean = {False, False, True, False}

See Also
Tasks
How to: Declare an Array Variable
How to: Declare an Array Variable
Reference
Const Statement (Visual Basic)
ReDim Statement (Visual Basic)
Option Explicit Statement (Visual Basic)
Concepts
Variable Declaration in Visual Basic
Visual Basic Language Reference

Do...Loop Statement (Visual Basic)


Repeats a block of statements while a Boolean condition is True or until the condition becomes True.

Do { While | Until } condition


[ statements ]
[ Exit Do ]
[ statements ]
Loop
-or-
Do
[ statements ]
[ Exit Do ]
[ statements ]
Loop { While | Until } condition

Parts
While
Required unless Until is used. Repeat the loop until condition is False.
Until
Required unless While is used. Repeat the loop until condition is True.
condition
Optional. Boolean expression. If condition is Nothing, Visual Basic treats it as False.
statements
Optional. One or more statements that are repeated while, or until, condition is True.
Exit Do
Optional. Transfers control out of the Do loop.
Loop
Required. Terminates the definition of the Do loop.
Remarks
Use a Do...Loop structure when you want to repeat a set of statements an indefinite number of times, until a condition is
satisfied. If you want to repeat the statements a set number of times, the For...Next Statement is usually a better choice.
The Do...Loop structure gives you more flexibility than the While...End While Statement (Visual Basic) because it allows you to
choose whether to end the loop when condition stops being True or when it first becomes True. It also allows you to test
condition at either the beginning or the end of the loop.
Rules
Nature of Condition. The condition usually results from a comparison of two values, but it can be any expression that
evaluates to a Boolean Data Type (Visual Basic) value (True or False). This includes values of other data types, such as
numeric types, that have been converted to Boolean.
Testing the Condition. You can test condition only once, at either the beginning or the end of the loop. You can use
either While or Until to specify condition, but not both.
Number of Iterations. If you test condition at the beginning of the loop (in the Do statement), the loop might never run
even once. If you test at the end of the loop (in the Loop statement), the loop always runs at least once.
Nesting Loops. You can nest Do loops by placing one loop within another. You can also nest different kinds of control
structures within one another. For more information, see Nested Control Structures.
Transferring Out of the Loop. The Exit Statement (Visual Basic) transfers control immediately to the statement
following the Loop statement. You might want to exit a loop if you detect a condition that makes it unnecessary or
impossible to continue iterating, such as an erroneous value or a termination request. You can place any number of Exit
Do statements anywhere in the Do loop. Exit Do is often used after evaluating some condition, for example in an
If...Then...Else structure.
Endless Loops
One use of Exit Do is to test for a condition that could cause an endless loop, which is a loop that could run an extremely large
or even infinite number of times. If you detect such a condition, you can use Exit Do to escape the loop. Otherwise, the loop
continues running.
In the following example, number is assigned a value that could cause the loop to run more than 2 ^ 31 times. The If statement
checks for this condition and exits if it exists, preventing endless looping.
VB
Sub exitDoExample()
Dim counter As Integer = 0
Dim number As Integer = 8
Do Until number = 10
If number <= 0 Then Exit Do
number -= 1
counter += 1
Loop
MsgBox("The loop ran " & counter & " times.")
End Sub

Note
To stop an endless loop, press ESC or CTRL+BREAK.

Example
The following example illustrates nested Do...Loop structures, as well as the use of While and Until, and testing at the
beginning (Do statement) and end (Loop statement) of the loop.
VB
Dim check As Boolean = True
Dim counter As Integer = 0
Do
Do While counter < 20
counter += 1
If counter = 10 Then
check = False
Exit Do
End If
Loop
Loop Until check = False
End Sub

In the preceding example, the inner Do...Loop structure loops 10 times, sets the value of the flag to False, and exits
prematurely using the Exit Do statement. The outer loop exits immediately upon checking the value of the flag.
See Also
Tasks
How to: Improve the Performance of a Loop
Reference
For...Next Statement (Visual Basic)
Boolean Data Type (Visual Basic)
Exit Statement (Visual Basic)
While...End While Statement (Visual Basic)
Concepts
Loop Structures
Nested Control Structures
Visual Basic Language Reference

End Statement
Terminates execution immediately.

End

Remarks
You can place the End statement anywhere in a procedure to force the entire application to stop running. End closes any files
opened with an Open statement and clears all the application's variables. The application closes as soon as there are no other
programs holding references to its objects and none of its code is running.
Note
The End statement stops code execution abruptly, without invoking the Dispose or Finalize method, or any other Visual Bas
ic code. Object references held by other programs are invalidated. If an End statement is encountered within a Try or Catch
block, control does not pass to the corresponding Finally block.

The Stop statement suspends execution, but unlike End, it does not close any files or clear any variables, unless it is
encountered in a compiled executable (.exe) file.
Because End terminates your application without attending to any resources that might be open, you should try to close down
cleanly before using it. For example, if your application has any forms open, you should close them before control reaches the
End statement.
You should use End sparingly, and only when you need to stop immediately. The normal ways to terminate a procedure
(Return Statement (Visual Basic) and Exit Statement (Visual Basic)) not only close down the procedure cleanly but also give the
calling code the opportunity to close down cleanly. A console application, for example, can simply Return from the Main
procedure.
Security Note
The End statement calls the Exit method of the Environment class in the System namespace. Exit requires that you have
UnmanagedCode permission. If you do not, a SecurityException error occurs.

When followed by an additional keyword, End (Visual Basic) delineates the end of the definition of the appropriate procedure
or block. For example, End Function terminates the definition of a Function procedure.
Example
The following example uses the End statement to terminate code execution if the user requests it.
VB
Sub Form_Load()
Dim answer As MsgBoxResult
answer = MsgBox("Do you want to quit now?", MsgBoxStyle.YesNo)
If answer = MsgBoxResult.Yes Then
MsgBox("Terminating program")
End
End If
End Sub

Smart Device Developer Notes


This statement is not supported.
See Also
Tasks
How to: Request Permission to Access Unmanaged Code
Reference
Stop Statement (Visual Basic)
End (Visual Basic)
SecurityPermissionFlag
Visual Basic Language Reference

Enum Statement (Visual Basic)


Declares an enumeration and defines the values of its members.

[ <attribute list> ] [ access modifier ] [ Shadows ]


Enum enumeration name [ As data type ]
member list
End Enum

Parts
attribute list
Optional. List of attributes that apply to this enumeration. You must enclose the Attribute List in angle brackets ("<" and ">").
access modifier
Optional. Specifies what code can access this enumeration. Can be one of the following:
Public
Protected
Friend
Private
You can specify Protected Friend to allow access from code within the enumeration's class, a derived class, or the same
assembly.
Shadows
Optional. Specifies that this enumeration redeclares and hides an identically named programming element, or set of
overloaded elements, in a base class. You can specify Shadows only on the enumeration itself, not on any of its members.
enumeration name
Required. Name of the enumeration. For information on valid names, see Declared Element Names.
data type
Required if Option Strict is On. Data type of the enumeration and all its members.
member list
Required. List of member constants being declared in this statement. Multiple members appear on individual source code
lines.
Each member has the following syntax and parts: [<attribute list>] member name [ = initializer ]

Part Description
member name Required. Name of this member.

initializer Optional. Expression that is evaluated at compile time and assigned to this member.

End Enum
Terminates the Enum block.
Remarks
If you have a set of unchanging values that are logically related to each other, you can define them together in an enumeration.
This provides meaningful names for the enumeration and its members, which are easier to remember than their values. You
can then use the enumeration members in many places in your code. This also improves the readability of your code because
all the related values use the same enumeration name.
You can use Enum only at namespace or module level. This means the declaration context for an enumeration must be a
source file, namespace, class, structure, module, or interface, and cannot be a procedure. For more information, see
Declaration Contexts and Default Access Levels.
The Enum statement can declare the data type of an enumeration. Each member takes the enumeration's data type. You can
specify Byte, Integer, Long, SByte, Short, UInteger, ULong, or UShort.
If you do not specify initializer for a member, Visual Basic initializes it either to zero (if it is the first member in member list), or
to a value greater by one than that of the immediately preceding member.
Class, structure, module, and interface member enumerations default to public access. You can adjust their access levels with
the access modifiers. Namespace member enumerations default to friend access. You can adjust their access levels to public,
but not to private or protected. For more information, see Access Levels in Visual Basic.Rules
Declaration Context. An enumeration declared at module level, outside any procedure, is a member enumeration; it is
a member of the class, structure, module, or interface that declares it.
An enumeration declared at namespace level, outside any class, structure, module, or interface, is a member only of the
namespace in which it appears.
Attributes. You can apply attributes to an enumeration as a whole, but not to its members individually. An attribute
contributes information to the assembly's metadata.
Modifiers. By default, all enumerations are types and their fields are constants. Therefore the Shared, Static, and
ReadOnly keywords cannot be used when declaring an enumeration or its members.
Data Type Rules
Default Type. If you do not specify data type for the enumeration, each member takes the data type of its initializer. If
you specify both data type and initializer, the data type of initializer must be convertible to data type. If neither data type
nor initializer is present, the data type defaults to Integer.
Initialization. The Enum statement can initialize the contents of selected members in member list. You use initializer to
supply an expression to be assigned to the member.
The expression supplied in each initializer can be any combination of literals, other constants that are already defined,
and enumeration members that are already defined, including a previous member of this enumeration. You can use
arithmetic and logical operators to combine such elements.
You cannot use variables or functions in initializer. However, you can use conversion keywords such as CByte and
CShort. You can also use AscW if you call it with a constant String or Char argument, since that can be evaluated at
compile time.
Behavior
Access Level. All enumeration members have public access, and you cannot use any access modifiers on them.
However, if the enumeration itself has a more restricted access level, the specified enumeration access level takes
precedence..
Scope. Member enumerations are accessible from anywhere within their class, structure, module, or interface.
Namespace member enumerations are accessible from any code within that namespace.
Qualification. Code outside a class, structure, or module must qualify a member enumeration's name with the name of
that class, structure, or module.
Invalid Values. If the value of a member exceeds the allowable range for the underlying data type, or if you initialize any
member to the maximum value allowed by the underlying data type, the compiler reports an error.
Enumeration variables are variables declared to be of an Enum type. Declaring a variable in this way helps you to control the
values you assign to it. However, you can still assign a value that is not an enumeration member, provided its data type can be
converted to the enumeration's data type. This is useful when the enumeration is a flag field and you assign a combination of
flags to the enumeration variable. The following example shows an assignment of multiple flags to an enumeration variable.
VB
Enum filePermissions
create = 1
read = 2
write = 4
delete = 8
End Enum

VB
Dim file1Perm As filePermissions
file1Perm = filePermissions.create Or filePermissions.read

You must qualify every reference to an enumeration member, either with the name of an enumeration variable or with the
enumeration name itself. For example, in the preceding example, you can refer to the first member asfilePermissions.create,
but not as create.
Example
The following example uses the Enum statement to define a related set of named constant values. In this case, the values are
colors you might choose to design data entry forms for a database.
VB
Public Enum InterfaceColors
MistyRose = &HE1E4FF&
SlateGray = &H908070&
DodgerBlue = &HFF901E&
DeepSkyBlue = &HFFBF00&
SpringGreen = &H7FFF00&
ForestGreen = &H228B22&
Goldenrod = &H20A5DA&
Firebrick = &H2222B2&
End Enum

The following example shows values that include both positive and negative numbers.
VB
Enum SecurityLevel
IllegalEntry = -1
MinimumSecurity = 0
MaximumSecurity = 1
End Enum

See Also
Reference
Const Statement (Visual Basic)
Dim Statement (Visual Basic)
Type Conversion Functions
Asc, AscW Functions
Concepts
Implicit and Explicit Conversions
Intrinsic Constants and Enumerations
Other Resources
Constants and Enumerations in Visual Basic
Visual Basic Language Reference

Erase Statement (Visual Basic)


Used to release array variables and deallocate the memory used for their elements.

Erase arraylist

Parts
arraylist
Required. List of array variables to be erased. Multiple variables are separated by commas.
Remarks
The Erase statement can appear only at procedure level. This means you can release arrays inside a procedure but not at class
or module level.
The Erase statement is equivalent to assigning Nothing to each array variable.
Example
The following example uses the Erase statement to clear two arrays and free their memory (1000 and 100 storage elements,
respectively). The ReDim statement then assigns a new array instance to the three-dimensional array.
VB
Dim threeDimArray(9, 9, 9), twoDimArray(9, 9) As Integer
Erase threeDimArray, twoDimArray
ReDim threeDimArray(4, 4, 9)

See Also
Reference
Nothing (Visual Basic)
ReDim Statement (Visual Basic)
Visual Basic Language Reference

Error Statement
Simulates the occurrence of an error.

Error errornumber

Parts
errornumber
Required. Can be any valid error number.
Remarks
The Error statement is supported for backward compatibility. In new code, especially when creating objects, use the Err object's
Raise method to generate run-time errors.
If errornumber is defined, the Error statement calls the error handler after the properties of the Err object are assigned the
following default values:
Propert Value
y
Numbe Value specified as argument to Error statement. Can be any valid error number.
r

Source Name of the current Visual Basic project.

Descrip String expression corresponding to the return value of the Error function for the specified Number, if this string exist
tion s. If the string does not exist, Description contains a zero-length string ("").

HelpFil The fully qualified drive, path, and file name of the appropriate Visual Basic Help file.
e

HelpCo The appropriate Visual Basic Help file context ID for the error corresponding to the Number property.
ntext

LastDL Zero.
LError

If no error handler exists, or if none is enabled, an error message is created and displayed from the Err object properties.
Note
Some Visual Basic host applications cannot create objects. See your host application's documentation to determine whether i
t can create classes and objects.

Example
This example uses the Error statement to generate error number 11.

On Error Resume Next ' Defer error handling.


Error 11 ' Simulate the "Division by zero" error.

Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Get Information about Visual Basic Run-Time Errors
Reference
Clear Method (Err Object)
Err Object (Visual Basic)
On Error Statement (Visual Basic)
Raise Method (Err Object)
Resume Statement
Visual Basic Language Reference

Event Statement
Declares a user-defined event.

[ <attrlist> ] [ accessmodifier ] _
[ Shared ] [ Shadows ] Event eventname[(parameterlist)] _
[ Implements implementslist ]
' -or-
[ <attrlist> ] [ accessmodifier ] _
[ Shared ] [ Shadows ] Event eventname As delegatename _
[ Implements implementslist ]
' -or-
[ <attrlist> ] [ accessmodifier ] _
[ Shared ] [ Shadows ] Custom Event eventname As delegatename _
[ Implements implementslist ]
[ <attrlist> ] AddHandler(ByVal value As delegatename)
[ statements ]
End AddHandler
[ <attrlist> ] RemoveHandler(ByVal value As delegatename)
[ statements ]
End RemoveHandler
[ <attrlist> ] RaiseEvent(delegatesignature)
[ statements ]
End RaiseEvent
End Event

Parts
Part Description
attrlist Optional. List of attributes that apply to this event. Multiple attributes are separated by commas. You must enclose the
Attribute List in angle brackets ("<" and ">").

accessm Optional. Specifies what code can access the event. Can be one of the following:
odifier
Public—any code that can access the element that declares it can access it.
Protected—only code within its class or a derived class can access it.
Friend—only code within the same assembly can access it.
Private—only code within the element that declares it can access it.
You can specify Protected Friend to allow access from code within the event's class, a derived class, or the same ass
embly.

Shared Optional. Specifies that this event is not associated with a specific instance of a class or structure.

Shado Optional. Indicates that this event redeclares and hides an identically named programming element, or set of overloa
ws ded elements, in a base class. You can shadow any kind of declared element with any other kind.
A shadowed element is unavailable from within the derived class that shadows it, except from where the shadowing e
lement is inaccessible. For example, if a Private element shadows a base-class element, code that does not have perm
ission to access the Private element accesses the base-class element instead.

eventna Required. Name of the event; follows standard variable naming conventions.
me

parame Optional. List of local variables representing the parameters of this event. You must enclose the Parameter List in pare
terlist ntheses.
Imple Optional. Indicates that this event implements an event of an interface.
ments

implem Required if Implements is supplied. List of Sub procedures being implemented. Multiple procedures are separated b
entslist y commas:
implementedprocedure [ , implementedprocedure ... ]
Each implementedprocedure has the following syntax and parts:
interface.definedname
Part Description
interfac Required. Name of an interface that this procedure's containing class or structure is implementing.
e

defined Required. Name by which the procedure is defined in interface. This does not have to be the same as name, t
name he name that this procedure is using to implement the defined procedure.

Custo Required. Events declared as Custom must define custom AddHandler, RemoveHandler, and RaiseEvent accessor
m s.

delegat Optional. The name of a delegate that specifies the event-handler signature.
ename

AddHa Required. Declares an AddHandler accessor, which specifies the statements to execute when an event handler is add
ndler ed, either explicitly using the AddHandler statement or implicitly using the Handles clause.

End Ad Required. Terminates the AddHandler block.


dHandl
er

value Required. Parameter name.

Remov Required. Declares a RemoveHandler accessor, which specifies the statements to execute when an event handler is r
eHandl emoved using the RemoveHander statement.
er

End Re Required. Terminates the RemoveHandler block.


moveH
andler

RaiseE Required. Declares a RaiseEvent accessor, which specifies the statements to execute when the event is raised using t
vent he RaiseEvent statement. Typically, this invokes a list of delegates maintained by the AddHandler and RemoveHan
dler accessors.

End Rai Required. Terminates the RaiseEvent block.


seEven
t

delegat Required. List of parameters that matches the parameters required by the delegatename delegate. You must enclose t
esignat he Parameter List in parentheses.
ure

stateme Optional. Statements that contain the bodies of the AddHandler, RemoveHander, and RaiseEvent methods.
nts
End Ev Required. Terminates the Event block.
ent
Remarks
Once the event has been declared, use the RaiseEvent statement to raise the event. A typical event might be declared and
raised as shown in the following fragments:
VB
Public Class EventSource
' Declare an event.
Public Event LogonCompleted(ByVal UserName As String)
Sub CauseEvent()
' Raise an event on successful logon.
RaiseEvent LogonCompleted("AustinSteele")
End Sub
End Class

Note
You can declare event arguments just as you do arguments of procedures, with the following exceptions: events cannot have
named arguments, ParamArray arguments, or Optional arguments. Events do not have return values.

To handle an event, you must associate it with an event handler subroutine using either the Handles or AddHandler
statement. The signatures of the subroutine and the event must match. To handle a shared event, you must use the
AddHandler statement.
You can use Event only at module level. This means the declaration context for an event must be a class, structure, module, or
interface, and cannot be a source file, namespace, procedure, or block. For more information, see
Declaration Contexts and Default Access Levels.
In most circumstances, you can use the first syntax in the Syntax section of this topic for declaring events. However, some
scenarios require that you have greater control over the detailed behavior of the event. The last syntax in the Syntax section of
this topic, which uses the Custom keyword, provides that control by allowing you to define custom events. In a custom event,
you specify exactly what happens when code adds or removes an event handler to or from the event, or when code raises the
event. For examples, see How to: Declare Events That Conserve Memory Use and How to: Declare Events That Avoid Blocking.
Example
The following example uses events to count down seconds from 10 to 0. The code illustrates several of the event-related
methods, properties, and statements, including the RaiseEvent statement.
The class that raises an event is the event source, and the methods that process the event are the event handlers. An event
source can have multiple handlers for the events it generates. When the class raises the event, that event is raised on every
class that has elected to handle events for that instance of the object.
The example also uses a form (Form1) with a button (Button1) and a text box (TextBox1). When you click the button, the first
text box displays a countdown from 10 to 0 seconds. When the full time (10 seconds) has elapsed, the first text box displays
"Done".
The code for Form1 specifies the initial and terminal states of the form. It also contains the code executed when events are
raised.
To use this example, open a new Windows Forms project. Then add a button named Button1 and a text box named TextBox1 to
the main form, named Form1. Then right-click the form and click View Code to open the code editor.
Add a WithEvents variable to the declarations section of the Form1 class:
VB
Private WithEvents mText As TimerState

Add the following code to the code for Form1. Replace any duplicate procedures that may exist, such as Form_Load or
Button_Click.
VB
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Button1.Text = "Start"
mText = New TimerState
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
mText.StartCountdown(10.0, 0.1)
End Sub

Private Sub mText_ChangeText() Handles mText.Finished


TextBox1.Text = "Done"
End Sub

Private Sub mText_UpdateTime(ByVal Countdown As Double) _


Handles mText.UpdateTime
TextBox1.Text = Format(Countdown, "##0.0")
' Use DoEvents to allow the display to refresh.
My.Application.DoEvents()
End Sub

Class TimerState
Public Event UpdateTime(ByVal Countdown As Double)
Public Event Finished()
Public Sub StartCountdown(ByVal Duration As Double, _
ByVal Increment As Double)
Dim Start As Double = DateAndTime.Timer
Dim ElapsedTime As Double = 0

Dim SoFar As Double = 0


Do While ElapsedTime < Duration
If ElapsedTime > SoFar + Increment Then
SoFar += Increment
RaiseEvent UpdateTime(Duration - SoFar)
End If
ElapsedTime = DateAndTime.Timer - Start
Loop
RaiseEvent Finished()
End Sub
End Class

Press F5 to run the preceding example, and click the button labeled Start. The first text box starts to count down the seconds.
When the full time (10 seconds) has elapsed, the first text box displays "Done".
Note
The My.Application.DoEvents method does not process events in exactly the same way the form does. To allow the form t
o handle the events directly, you can use multithreading. For more information, see Multithreading in Visual Basic.

See Also
Tasks
How to: Add Events to a Class
How to: Declare Events That Conserve Memory Use
How to: Declare Events That Avoid Blocking
Reference
RaiseEvent Statement
Implements Statement
AddHandler Statement
RemoveHandler Statement
Handles
Delegate Statement
Shared (Visual Basic)
Shadows
Other Resources
Events in Visual Basic
Visual Basic Language Reference

Exit Statement (Visual Basic)


Exits a procedure or block and transfers control immediately to the statement following the procedure call or the block
definition.

Exit { Do | For | Function | Property | Select | Sub | Try | While }

Parts
Do
Immediately exits the Do loop in which it appears. Execution continues with the statement following the Loop statement.
Exit Do can be used only inside a Do loop. When used within nested Do loops, Exit Do exits the innermost loop and
transfers control to the next higher level of nesting.
For
Immediately exits the For loop in which it appears. Execution continues with the statement following the Next statement.
Exit For can be used only inside a For...Next or For Each...Next loop. When used within nested For loops, Exit For exits the
innermost loop and transfers control to the next higher level of nesting.
Function
Immediately exits the Function procedure in which it appears. Execution continues with the statement following the
statement that called the Function procedure. Exit Function can be used only inside a Function procedure.
Property
Immediately exits the Property procedure in which it appears. Execution continues with the statement that called the
Property procedure, that is, with the statement requesting or setting the property's value. Exit Property can be used only
inside a property's Get or Set procedure.
Select
Immediately exits the Select Case block in which it appears. Execution continues with the statement following the End
Select statement. Exit Select can be used only inside a Select Case statement.
Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement
that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.
Try
Immediately exits the Try or Catch block in which it appears. Execution continues with the Finally block if there is one, or
with the statement following the End Try statement otherwise. Exit Try can be used only inside a Try or Catch block, and
not inside a Finally block.
While
Immediately exits the While loop in which it appears. Execution continues with the statement following the End While
statement. Exit While can be used only inside a While loop. When used within nested While loops, Exit While transfers
control to the loop that is one nested level above the loop where Exit While occurs.
Remarks
Do not confuse Exit statements with End statements. Exit does not define the end of a statement.
Example
The following example uses the Exit statement to exit a For...Next loop, a Do loop, and a Sub procedure.
VB
Sub exitStatementDemo()
Dim demoNum As Single
' Set up an infinite loop.
Do
For i As Integer = 1 To 10000000
demoNum = Int(Rnd() * 100)
Select Case demoNum
Case 7 : Exit For
Case 29 : Exit Do
Case 54 : Exit Sub
End Select
Next i
Loop
End Sub

See Also
Reference
Do...Loop Statement (Visual Basic)
End Statement
For Each...Next Statement (Visual Basic)
For...Next Statement (Visual Basic)
Function Statement (Visual Basic)
Stop Statement (Visual Basic)
Sub Statement (Visual Basic)
Try...Catch...Finally Statement (Visual Basic)
For Each...Next Statement (Visual Basic)
Visual Basic Language Reference

F-P Statements
The following table contains a listing of Visual Basic language statements.

For Each...Next For...Next Function Get

GoTo If...Then...Else Implements Imports

Inherits Interface Mid Module

Namespace On Error Operator Option Compare

Option Explicit Option Strict Property


See Also
Reference
A-E Statements
Q-Z Statements
Other Resources
Visual Basic Reference
Visual Basic Language Reference

For Each...Next Statement (Visual Basic)


Repeats a group of statements for each element in a collection.

For Each element [ As datatype ] In group


[ statements ]
[ Exit For ]
[ statements ]
Next [ element ]

Parts
element
Required in the For Each statement. Optional in the Next statement. Variable. Used to iterate through the elements of the
collection.
datatype
Required if element is not already declared. Data type of element.
group
Required. Object variable. Refers to the collection over which the statements are to be repeated.
statements
Optional. One or more statements between For Each and Next that run on each item in group.
Exit For
Optional. Transfers control out of the For Each loop.
Next
Required. Terminates the definition of the For Each loop.
Remarks
Use a For Each...Next loop when you want to repeat a set of statements for each element of a collection or array.
A For...Next Statement (Visual Basic) works well when you can associate each iteration of a loop with a control variable and
determine that variable's initial and final values. However, when you are dealing with a collection, the concept of initial and
final values is not meaningful, and you do not necessarily know how many elements the collection has. In this case, a For
Each...Next loop is a better choice.
Rules
Data Types. The data type of element must be such that the data type of the elements of group can be converted to it.
The data type of group must be a reference type that refers to a collection or an array. This means that group must refer
to an object that implements the IEnumerable interface of the System.Collections namespace or the IEnumerable
interface of the System.Collections.Generic namespace. IEnumerable defines the GetEnumerator method, which returns
an enumerator object for the collection. The enumerator object implements the IEnumerator interface of the
System.Collections namespace and exposes the Current property and the Reset and MoveNext methods. Visual Basic
uses these to traverse the collection.
The elements of group are usually of type Object but can have any run-time data type.
Declaration. If element has not been declared outside this loop, you must declare it within the For Each statement. In
this case, the scope of element is the body of the loop. However, you cannot declare element both outside and inside the
loop.
Number of Iterations. Visual Basic evaluates the collection only once, before the loop begins. If your statement block
changes element or group, these changes do not affect the iteration of the loop.
Nesting Loops. You can nest For Each loops by placing one loop within another. However, each loop must have a
unique element variable.
You can also nest different kinds of control structures within one another. For more information, see
Nested Control Structures.
Note
If a Next statement of an outer nesting level is encountered before the Next of an inner level, the compiler signals an e
rror. However, the compiler can detect this overlapping error only if you specify element in every Next statement.

Identifying the Control Variable. You can optionally specify element in the Next statement. This improves the
readability of your program, especially if you have nested For Each loops. You must specify the same variable as the one
that appears in the corresponding For Each statement.
Transferring Out of the Loop. The Exit Statement (Visual Basic) transfers control immediately to the statement
following the Next statement. You might want to exit a loop if you detect a condition that makes it unnecessary or
impossible to continue iterating, such as an erroneous value or a termination request. Also, if you catch an exception in a
Try...Catch...Finally statement, you can use Exit For at the end of the Finally block.
You can place any number of Exit For statements anywhere in the For Each loop. Exit For is often used after evaluating
some condition, for example in an If...Then...Else structure.
Endless Loops. One use of Exit For is to test for a condition that could cause an endless loop, which is a loop that could
run an extremely large or even infinite number of times. If you detect such a condition, you can use Exit For to escape
the loop. For more information, see Do...Loop Statement (Visual Basic).
Behavior
Entry into the Loop. When execution of the For Each...Next loop begins, Visual Basic verifies that group refers to a
valid collection object. If not, it throws an exception. Otherwise, it calls the MoveNext method and the Current property
of the enumerator object to return the first element. If MoveNext indicates that there is no next element, that is, if the
collection is empty, then the For Each loop terminates and control passes to the statement following the Next statement.
Otherwise, Visual Basic sets element to the first element and runs the statement block.
Iterations of the Loop. Each time Visual Basic encounters the Next statement, it returns to the For Each statement.
Again it calls MoveNext and Current to return the next element, and again it either runs the block or terminates the
loop depending on the result. This process continues until MoveNext indicates that there is no next element or an Exit
For statement is encountered.
Termination of the Loop. When all the elements in the collection have been successively assigned to element, the For
Each loop terminates and control passes to the statement following the Next statement.
Changing Iteration Values. Changing the value of element while inside a loop can make it more difficult to read and
debug your code. Changing the value of group does not affect the collection or its elements, which were determined
when the loop was first entered.
Traversal Order. When you execute a For Each...Next loop, traversal of the collection is under the control of the
enumerator object returned by the GetEnumerator method. The order of traversal is not determined by Visual Basic, but
rather by the MoveNext method of the enumerator object. This means that you might not be able to predict which
element of the collection is the first to be returned in element, or which is the next to be returned after a given element.
If your code depends on traversing a collection in a particular order, a For Each...Next loop is not the best choice unless
you know the characteristics of the enumerator object the collection exposes. You might achieve more reliable results
using a different loop structure, such as For...Next or Do...Loop.
Modifying the Collection. The enumerator object returned by GetEnumerator normally does not allow you to alter
the collection by adding, deleting, replacing, or reordering any elements. If you alter the collection after you have initiated
a For Each...Next loop, the enumerator object becomes invalid, and the next attempt to access an element results in an
InvalidOperationException exception.
However, this blocking of modification is not determined by Visual Basic, but rather by the implementation of the
IEnumerable interface. It is possible to implement IEnumerable in such a way as to allow modification during iteration.
If you are considering doing such dynamic modification, be sure you understand the characteristics of the IEnumerable
implementation on the collection you are using.
Modifying Collection Elements. The Current property of the enumerator object is ReadOnly (Visual Basic), and it
returns a local copy of each collection element. This means that you cannot modify the elements themselves in a For
Each...Next loop. Any modification you make affects only the local copy from Current and is not reflected back into the
underlying collection. However, if an element is a reference type, you can modify the members of the instance to which it
points. The following example illustrates this.

Sub lightBlueBackground(ByVal thisForm As System.Windows.Forms.Form)


For Each thisControl As System.Windows.Forms.Control In thisForm.Controls
thisControl.BackColor = System.Drawing.Color.LightBlue
Next thisControl
End Sub

The preceding example can modify the BackColor member of each thisControl element, although it cannot modify
thisControl itself.

Traversing Arrays. Because the Array class implements the IEnumerable interface, all arrays expose the GetEnumerator
method. This means that you can iterate through an array with a For Each...Next loop. However, you can only read the
array elements, not change them. For an illustration, see
How to: Run Several Statements for Each Element in a Collection or Array.
Example
The following example uses the For Each...Next statement to search all elements in a collection for the string "Hello". The
example assumes that the collection thisCollection has already been created and that its elements are of type String.
VB
Dim found As Boolean = False
Dim thisCollection As New Collection
For Each thisObject As String In thisCollection
If thisObject = "Hello" Then
found = True
Exit For
End If
Next thisObject

See Also
Tasks
How to: Run Several Statements for Each Element in a Collection or Array
How to: Improve the Performance of a Loop
Reference
While...End While Statement (Visual Basic)
Do...Loop Statement (Visual Basic)
Concepts
Loop Structures
Collections in Visual Basic
Visual Basic Language Reference

For...Next Statement (Visual Basic)


Repeats a group of statements a specified number of times.

For counter [ As datatype ] = start To end [ Step step ]


[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]

Parts
counter
Required in the For statement. Numeric variable. The control variable for the loop.
datatype
Required if counter is not already declared. Data type of counter.
start
Required. Numeric expression. The initial value of counter.
end
Required. Numeric expression. The final value of counter.
step
Optional. Numeric expression. The amount by which counter is incremented each time through the loop.
statements
Optional. One or more statements between For and Next that run the specified number of times.
Exit For
Optional. Transfers control out of the For loop.
Next
Required. Terminates the definition of the For loop.
Remarks
Use a For...Next structure when you want to repeat a set of statements a set number of times.
A While...End While Statement (Visual Basic) or Do...Loop Statement (Visual Basic) works well when you do not know in
advance how many times you need to run the statements in the loop. However, when you expect to run the loop a specific
number of times, a For...Next loop is a better choice. You determine the number of iterations when you first enter the loop.
The value of step can be either positive or negative. It determines loop processing as follows:
Step value Loop executes if
Positive or zero counter <= end

Negative counter >= end

If not specified, step defaults to 1.


Rules
Data Types. The data type of counter is usually Integer but can be any type that supports the greater than or equal to
(>=), less than or equal to (<=), addition (+), and subtraction (-) operators. It can even be a user-defined type provided it
supports all these operators.
The start, end, and step expressions usually evaluate to type Integer but can evaluate to any data type that widens to the
type of counter. If you use a user-defined type for counter, this means you might have to define the CType conversion
operator to convert the types of start, end, or step to the type of counter.
Declaration. If counter has not been declared outside this loop, you must declare it within the For statement. In this
case, the scope of counter is the body of the loop. However, you cannot declare counter both outside and inside the loop.
Number of Iterations. Visual Basic evaluates the iteration values start, end, and step only once, before the loop begins.
If your statement block changes end or step, these changes do not affect the iteration of the loop.
Nesting Loops. You can nest For loops by placing one loop within another. However, each loop must have a unique
counter variable. The following construction is valid.

For i As Integer = 1 To 10
For j As Integer = 1 To 10
For k As Integer = 1 To 10
' Insert statements to operate with current values of i, j, and k.
Next k
Next j
Next i

You can also nest different kinds control structures within one another. For more information, see
Nested Control Structures.
Note
If a Next statement of an outer nesting level is encountered before the Next of an inner level, the compiler signals an e
rror. However, the compiler can detect this overlapping error only if you specify counter in every Next statement.

Identifying the Control Variable. You can optionally specify counter in the Next statement. This improves the
readability of your program, especially if you have nested For loops. You must specify the same variable as the one that
appears in the corresponding For statement.
Transferring Out of the Loop. The Exit Statement (Visual Basic) transfers control immediately to the statement
following the Next statement. You might want to exit a loop if you detect a condition that makes it unnecessary or
impossible to continue iterating, such as an erroneous value or a termination request. Also, if you catch an exception in a
Try...Catch...Finally, you can use Exit For at the end of the Finally block.
You can place any number of Exit For statements anywhere in the For loop. Exit For is often used after evaluating some
condition, for example in an If...Then...Else structure.
Endless Loops. One use of Exit For is to test for a condition that could cause an endless loop, which is a loop that could
run an extremely large or even infinite number of times. If you detect such a condition, you can use Exit For to escape
the loop. For more information, see Do...Loop Statement (Visual Basic).
Behavior
Entry into the Loop. When execution of the For...Next loop begins, Visual Basic evaluates start, end, and step for the
only time. It then assigns start to counter. Before it runs the statement block, it compares counter to end. If counter is
already past the end value, the For loop terminates and control passes to the statement following the Next statement.
Otherwise the statement block runs.
Iterations of the Loop. Each time Visual Basic encounters the Next statement, it increments counter by step and returns
to the For statement. Again it compares counter to end, and again it either runs the block or terminates the loop
depending on the result. This process continues until counter passes end or an Exit For statement is encountered.
Termination of the Loop. The loop does not terminate until counter has passed end. If counter is equal to end, the loop
continues. The comparison that determines whether to run the block is counter <= end if step is positive and
counter >= end if step is negative.
Changing Iteration Values. Changing the value of counter while inside a loop can make it more difficult to read and
debug your code. Changing the value of start, end, or step does not affect the iteration values determined when the loop
was first entered.
Example
The following example demonstrates nested For...Next structures with different step values.
VB
Dim words, digit As Integer
Dim thisString As String = ""
For words = 10 To 1 Step -1
For digit = 0 To 9
thisString &= CStr(digit)
Next digit
thisString &= " "
Next words

The preceding example creates a string that contains 10 instances of the numbers 0 through 9, each string separated from the
other by a single space. The outer loop decrements a loop counter variable each time through the loop.
See Also
Tasks
How to: Improve the Performance of a Loop
Reference
While...End While Statement (Visual Basic)
Do...Loop Statement (Visual Basic)
Exit Statement (Visual Basic)
For Each...Next Statement (Visual Basic)
Concepts
Loop Structures
Nested Control Structures
Visual Basic Language Reference

Function Statement (Visual Basic)


Declares the name, parameters, and code that define a Function procedure.

[ <attributelist> ] [ accessmodifier ] [ proceduremodifiers ] [ Shared ] [ Shadows ]


Function name [ (Of typeparamlist) ] [ (parameterlist) ] [ As returntype ] [ Implements imp
lementslist | Handles eventlist ]
[ statements ]
[ Exit Function ]
[ statements ]
End Function

Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional. Can be one of the following:
Public
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
proceduremodifiers
Optional. Can be one of the following:
Overloads
Overrides
Overridable
NotOverridable
MustOverride
MustOverride Overrides
NotOverridable Overrides
Shared
Optional. See Shared.
Shadows
Optional. See Shadows.
name
Required. Name of the procedure. See Declared Element Names.
typeparamlist
Optional. List of type parameters for a generic procedure. See Type List.
parameterlist
Optional. List of local variable names representing the parameters of this procedure. See Argument List.
returntype
Required if Option Strict is On. Data type of the value returned by this procedure.
Implements
Optional. Indicates that this procedure implements one or more Function procedures, each one defined in an interface
implemented by this procedure's containing class or structure. See Implements Statement.
implementslist
Required if Implements is supplied. List of Function procedures being implemented.
implementedprocedure [ , implementedprocedure ... ]

Each implementedprocedure has the following syntax and parts:


interface.definedname

Part Description
interface Required. Name of an interface implemented by this procedure's containing class or structure.

definedname Required. Name by which the procedure is defined in interface.

Handles
Optional. Indicates that this procedure can handle one or more specific events. See Handles.
eventlist
Required if Handles is supplied. List of events this procedure handles.
eventspecifier [ , eventspecifier ... ]

Each eventspecifier has the following syntax and parts:


eventvariable.event

Part Description
eventvariable Required. Object variable declared with the data type of the class or structure that raises the event.

event Required. Name of the event this procedure handles.

statements
Optional. Block of statements to be executed within this procedure.
End Function
Terminates the definition of this procedure.
Remarks
All executable code must be inside a procedure. Each procedure in turn is declared within a class, structure, or module, which is
called the containing class, structure, or module.
Use a Function procedure when you need to return a value to the calling code. Use a Sub procedure when you do not need to
return a value.
You can use Function only at module level. This means the declaration context for a function must be a class, structure,
module, or interface, and cannot be a source file, namespace, procedure, or block. For more information, see
Declaration Contexts and Default Access Levels.
Function procedures default to public access. You can adjust their access levels with the access modifiers.
You can use a Function procedure on the right side of an expression when you want to use the value returned by the function.
You use the Function procedure the same way you use any library function such as Sqrt, Cos, or ChrW.
You call a Function procedure by using the procedure name, followed by the argument list in parentheses, in an expression.
You can omit the parentheses only if you are not supplying any arguments. However, your code is more readable if you always
include the parentheses.
A function can also be called using the Call statement, in which case the return value is ignored.
Rules
Return Type. The Function statement can declare the data type of the value it returns. You can specify any data type or
the name of an enumeration, structure, class, or interface.
If you do not specify returntype, the procedure returns Object.
Implementation. If this procedure uses the Implements keyword, the containing class or structure must also have an
Implements statement immediately following its Class or Structure statement. The Implements statement must
include each interface specified in implementslist. However, the name by which an interface defines the Function (in
definedname) does not have to be the same as the name of this procedure (in name).
Behavior
Returning from a Procedure. When the Function procedure returns to the calling code, execution continues with the
statement following the statement that called it.
The Exit Function and Return statements cause an immediate exit from a Function procedure. Any number of Exit
Function and Return statements can appear anywhere in the procedure, and you can mix Exit Function and Return
statements.
Return Value. To return a value from a function, you can either assign the value to the function name or include it in a
Return statement. The following example assigns the return value to the function name myFunction and then uses the
Exit Function statement to return.
VB
Function myFunction(ByVal j As Integer) As Double
myFunction = 3.87 * j
Exit Function
End Function

If you use Exit Function without assigning a value to name, the procedure returns the default value for the data type
specified in returntype. If returntype is not specified, the procedure returns Nothing, the default value for Object.
The Return statement simultaneously assigns the return value and exits the function. The following example shows this.
VB
Function myFunction(ByVal j As Integer) As Double
Return 3.87 * j
End Function

Troubleshooting
Order of Execution. Visual Basic sometimes rearranges arithmetic expressions to increase internal efficiency. For that
reason, avoid using a Function procedure in an arithmetic expression when the function changes the value of variables
in the same expression.
Example
The following example uses the Function statement to declare the name, parameters, and code that form the body of a
Function procedure. The ParamArray modifier enables the function to accept a variable number of arguments.
VB
Public Function calcSum(ByVal ParamArray args() As Double) As Double
calcSum = 0
If args.Length <= 0 Then Exit Function
For i As Integer = 0 To UBound(args, 1)
calcSum += args(i)
Next i
End Function
The following example invokes the function declared in the preceding example.
VB
Dim returnedValue As Double = calcSum(4, 3, 2, 1)
' The function's local variables are assigned the following values:
' args(0) = 4, args(1) = 3, and so on.

See Also
Tasks
How to: Use a Generic Class
Troubleshooting Procedures
Reference
Sub Statement (Visual Basic)
Parameter List
Dim Statement (Visual Basic)
Call Statement (Visual Basic)
Of
Concepts
Parameter Arrays
Visual Basic Language Reference

Get Statement
Declares a Get property procedure used to retrieve the value of a property.

[ <attributelist> ] [ accessmodifier ] Get()


[ statements ]
End Get

Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional on at most one of the Get and Set statements in this property. Can be one of the following:
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
statements
Optional. One or more statements that run when the Get property procedure is called.
End Get
Required. Terminates the definition of the Get property procedure.
Remarks
Every property must have a Get property procedure unless the property is marked WriteOnly. The Get procedure is used to
return the current value of the property.
Visual Basic automatically calls a property's Get procedure when an expression requests the property's value.
The body of the property declaration can contain only the property's Get and Set procedures between the Property Statement
and the End Property statement. It cannot store anything other than those procedures. In particular, it cannot store the
property's current value. You must store this value outside the property, because if you store it inside either of the property
procedures, the other property procedure cannot access it. The usual approach is to store the value in a Private (Visual Basic)
variable declared at the same level as the property. You must define a Get procedure inside the property to which it applies.
The Get procedure defaults to the access level of its containing property unless you use accessmodifier in the Get statement.
Rules
Mixed Access Levels. If you are defining a read-write property, you can optionally specify a different access level for
either the Get or the Set procedure, but not both. If you do this, the procedure access level must be more restrictive than
the property's access level. For example, if the property is declared Friend, you can declare the Get procedure Private,
but not Public.
If you are defining a ReadOnly property, the Get procedure represents the entire property. You cannot declare a
different access level for Get, because that would set two access levels for the property.
Return Type. The Property Statement can declare the data type of the value it returns. The Get procedure automatically
returns that data type. You can specify any data type or the name of an enumeration, structure, class, or interface.
If the Property statement does not specify returntype, the procedure returns Object.
Behavior
Returning from a Procedure. When the Get procedure returns to the calling code, execution continues within the
statement that requested the property value.
Get property procedures can return a value using either the Return Statement (Visual Basic) or by assigning the return
value to the property name. For more information, see "Return Value" in Function Statement (Visual Basic).
The Exit Property and Return statements cause an immediate exit from a property procedure. Any number of Exit
Property and Return statements can appear anywhere in the procedure, and you can mix Exit Property and Return
statements.
Return Value. To return a value from a Get procedure, you can either assign the value to the property name or include it
in a Return Statement (Visual Basic). The Return statement simultaneously assigns the Get procedure return value and
exits the procedure.
If you use Exit Property without assigning a value to the property name, the Get procedure returns the default value for
the property's data type. For more information, see "Return Value" in Function Statement (Visual Basic).
The following example illustrates two ways the read-only property quoteForTheDay can return the value held in the
private variable quoteValue.
VB
Private quoteValue As String = "No quote assigned yet."

VB
ReadOnly Property quoteForTheDay() As String
Get
quoteForTheDay = quoteValue
Exit Property
End Get
End Property

VB
ReadOnly Property quoteForTheDay() As String
Get
Return quoteValue
End Get
End Property

Example
The following example uses the Get statement to return the value of a property.
VB
Class propClass
' Define a private local variable to store the property value.
Private currentTime As String
' Define the read-only property.
Public ReadOnly Property dateAndTime() As String
Get
' The Get procedure is called automatically when the
' value of the property is retrieved.
currentTime = CStr(Now)
' Return the date and time As a string.
Return currentTime
End Get
End Property
End Class
See Also
Tasks
How to: Add Fields and Properties to a Class
Reference
Set Statement (Visual Basic)
Property Statement
Exit Statement (Visual Basic)
Visual Basic Language Reference

GoTo Statement
Branches unconditionally to a specified line within a procedure.

GoTo line

Part
line
Required. Any line label.
Remarks
The GoTo statement can branch only to lines within the procedure in which it appears. The line must have a line label that
GoTo can refer to. For more information, see How to: Label Statements.
Note
GoTo statements can make code difficult to read and maintain. Whenever possible, use a control structure instead. For more
information, see Control Flow in Visual Basic.

You cannot use a GoTo statement to branch from outside a For...Next, For Each...Next, SyncLock...End SyncLock,
Try...Catch...Finally, With...End With, or Using...End Using construction to a label inside.
Branching and Try Constructions
Within a Try...Catch...Finally construction, the following rules apply to branching with the GoTo statement.
Block or reg Branching in from outside Branching out from inside
ion
Try block Only from a Catch block of the same con Only to outside the entire construction
struction 1

Catch block Never allowed Only to outside the entire construction, or to the Try block of the sam
e construction 1

Finally block Never allowed Never allowed

1 If one Try...Catch...Finally construction is nested within another, a Catch block can branch into the Try block at its own
nesting level, but not into any other Try block. A nested Try...Catch...Finally construction must be contained entirely within a
Try or Catch block of the construction within which it is nested.
The following illustration shows one Try construction nested within another. Various branches among the blocks of the two
constructions are indicated as valid or invalid.
Valid and invalid branches in Try constructions
Example
The following example uses the GoTo statement to branch to line labels within a procedure.
VB
Sub gotoStatementDemo()
Dim number As Integer = 1
Dim sampleString As String
' Evaluate number and branch to appropriate label.
If number = 1 Then GoTo Line1 Else GoTo Line2
Line1:
sampleString = "Number equals 1"
GoTo LastLine
Line2:
' The following statement never gets executed because number = 1.
sampleString = "Number equals 2"
LastLine:
' Write "Number equals 1" in the Debug window.
Debug.WriteLine(sampleString)
End Sub

See Also
Reference
Do...Loop Statement (Visual Basic)
For...Next Statement (Visual Basic)
For Each...Next Statement (Visual Basic)
If...Then...Else Statement (Visual Basic)
Select...Case Statement (Visual Basic)
Try...Catch...Finally Statement (Visual Basic)
While...End While Statement (Visual Basic)
With...End With Statement (Visual Basic)
Visual Basic Language Reference

If...Then...Else Statement (Visual Basic)


Conditionally executes a group of statements, depending on the value of an expression.

If condition [ Then ]
[ statements ]
[ ElseIf elseifcondition [ Then ]
[ elseifstatements ] ]
[ Else
[ elsestatements ] ]
End If
-or-
If condition Then [ statements ] [ Else [ elsestatements ] ]

Parts
condition
Required. Expression. Must evaluate to True or False, or to a data type that is implicitly convertible to Boolean.
Then
Required in the single-line form, optional in the multiple-line form.
statements
Optional. One or more statements following If...Then that are executed if condition evaluates to True.
elseifcondition
Required if ElseIf is present. Expression. Must evaluate to True or False, or to a data type that is implicitly convertible to
Boolean.
elseifstatements
Optional. One or more statements following ElseIf...Then that are executed if elseifcondition evaluates to True.
elsestatements
Optional. One or more statements that are executed if no previous condition or elseifcondition expression evaluates to True.
End If
Terminates the If...Then...Else block.
Remarks
You can use the single-line form for short, simple tests. However, the multiple-line form provides more structure and flexibility
than the single-line form and is usually easier to read, maintain, and debug.
When a multiple-line If...Then...Else is encountered, condition is tested. If condition is True, the statements following Then are
executed. If condition is False, each ElseIf statement is evaluated in order. When a True elseifcondition is found, the statements
immediately following the associated Then are executed. If no elseifcondition evaluates to True, or if there are no ElseIf
statements, the statements following Else are executed. After executing the statements following Then, ElseIf, or Else,
execution continues with the statement following End If.
Tip
The Select...Case Statement (Visual Basic) might be more useful when evaluating a single expression that has several possible
values.

In the single-line form, it is possible to have multiple statements executed as the result of an If...Then decision. All statements
must be on the same line and be separated by colons. The following example demonstrates this.

If A > 10 Then A = A + 1 : B = B + A : C = C + B
In the multiple-line form, the If statement must be the only statement on the first line. The ElseIf, Else, and End If statements
can be preceded only by a line label. The multiple-line If...Then...Else block must end with an End If statement.
To determine whether or not an If statement introduces a multiple-line form, examine what follows the Then keyword. If
anything other than a comment appears after Then in the same statement, the statement is treated as a single-line If
statement. If Then is absent, it must be the beginning of a multiple-line If...Then...Else.
The ElseIf and Else clauses are both optional. You can have as many ElseIf clauses as you want in a multiple-line
If...Then...Else, but none can appear after an Else clause. Multiple-line forms can be nested within one another.
Example
The following example shows both the multiple- and single-line forms of the If...Then...Else statement.
VB
Dim number, digits As Integer
Dim myString As String
number = 53
If number < 10 Then
digits = 1
ElseIf number < 100 Then
digits = 2
Else
digits = 3
End If
If digits = 1 Then myString = "One" Else myString = "More than one"

In the preceding example, the ElseIf condition evaluates to True, and digits is assigned a value of 2. The last statement then
assigns a value of "More than one" to myString.
See Also
Reference
#If...Then...#Else Directives
Choose Function
Select...Case Statement (Visual Basic)
Switch Function
Visual Basic Language Reference

Implements Statement
Specifies one or more interfaces, or interface members, that must be implemented in the class or structure definition in which
it appears.

Implements interfacename [, ...]


-or-
Implements interfacename.interfacemember [, ...]

Parts
interfacename
Required. An interface whose properties, procedures, and events are to be implemented by corresponding members in the
class or structure.
interfacemember
Required. The member of an interface that is being implemented.
Remarks
An interface is a collection of prototypes representing the members (properties, procedures, and events) the interface
encapsulates. Interfaces contain only the declarations for members; classes and structures implement these members.
The Implements statement must immediately follow the Class or Structure statement.
When you implement an interface, you must implement all the members declared in the interface. Omitting any member is
considered to be a syntax error. To implement an individual member, you specify the Implements (Visual Basic) keyword
(which is separate from the Implements statement) when you declare the member in the class or structure. For more
information, see Implements Keyword and Implements Statement.
Classes can use Private (Visual Basic) implementations of properties and procedures, but these members are accessible only by
casting an instance of the implementing class into a variable declared to be of the type of the interface.
Example
The following example shows how to use the Implements statement to implement members of an interface. It defines an
interface named ICustomerInfo with an event, a property, and a procedure. The class customerInfo implements all the
members defined in the interface.
VB
Public Interface ICustomerInfo
Event updateComplete()
Property customerName() As String
Sub updateCustomerStatus()
End Interface

Public Class customerInfo


Implements ICustomerInfo
' Storage for the property value.
Private customerNameValue As String
Public Event updateComplete() Implements ICustomerInfo.updateComplete
Public Property CustomerName() As String Implements _
ICustomerInfo.customerName
Get
Return customerNameValue
End Get
Set(ByVal value As String)
' The value parameter is passed to the Set procedure
' when the contents of this property are modified.
customerNameValue = value
End Set
End Property
Public Sub updateCustomerStatus() Implements _
ICustomerInfo.updateCustomerStatus
' Add code here to update the status of this account.
' Raise an event to indicate that this procedure is done.
RaiseEvent updateComplete()
End Sub
End Class

Note that the class customerInfo uses the Implements statement on a separate source code line to indicate that the class
implements all the members of the ICustomerInfo interface. Then each member in the class uses the Implements keyword as
part of its member declaration to indicate that it implements that interface member.
The following two procedures show how you could use the interface implemented in the preceding example. To test the
implementation, add these procedures to your project and call the testImplements procedure.
VB
Public Sub testImplements()
' This procedure tests the interface implementation by
' creating an instance of the class that implements ICustomerInfo.
Dim cust As ICustomerInfo = New customerInfo()
' Associate an event handler with the event that is raised by
' the cust object.
AddHandler cust.updateComplete, AddressOf handleUpdateComplete
' Set the customerName Property
cust.customerName = "Fred"
' Retrieve and display the customerName property.
MsgBox("Customer name is: " & cust.customerName)
' Call the updateCustomerStatus procedure, which raises the
' updateComplete event.
cust.updateCustomerStatus()
End Sub

Sub handleUpdateComplete()
' This is the event handler for the updateComplete event.
MsgBox("Update is complete.")
End Sub

See Also
Reference
Implements (Visual Basic)
Interface Statement (Visual Basic)
Concepts
How Visual Basic Provides Polymorphism
Other Resources
Interfaces in Visual Basic
Polymorphism
Visual Basic Language Reference

Imports Statement
Imports namespaces or programming elements defined in referenced projects and assemblies. Also imports namespaces or
elements defined within the same project.

Imports [ aliasname = ] namespace


-or-
Imports [ aliasname = ] namespace.element

Parts
aliasname
Optional. An import alias or name by which code can refer to namespace instead of the full qualification string. See
Declared Element Names.
namespace
Required. The fully qualified name of the namespace being imported. Can be a string of namespaces nested to any level.
element
Optional. The name of a programming element declared in the namespace. Can be any container element.
Remarks
Each source file can contain any number of Imports statements. These must follow any option declarations such as the Option
Strict statement, and they must precede any programming element declarations such as Module or Class statements.
You can use Imports only at file level. This means the declaration context for importation must be a source file, and cannot be
a namespace, class, structure, module, interface, procedure, or block.
Import aliases are useful when you need to use items with the same name that are declared in one or more namespaces. For
more information and an example, see "Classes with the Same Name" in
Resolving a Reference When Multiple Variables Have the Same Name.
Note that the Imports statement does not make elements from other projects and assemblies available to your project.
Importing does not take the place of setting a reference. It only removes the need to qualify names that are already available to
your project. For more information, see "Importing Containing Elements" in
Resolving a Reference When Multiple Variables Have the Same Name.
Rules
Alias Name. You should not declare a member at module level with the same name as aliasname. If you do, the Visual
Basic compiler uses aliasname only for the declared member and no longer recognizes it as an import alias.
Namespace Name. You can supply a single namespace name or a string of nested namespaces. Each nested
namespace is separated from the next higher level namespace by a period (.), as the following example illustrates.
Imports System.Collections.Generic

Element Type. If you supply element, it must represent a container element, that is, a programming element that can
contain other elements. Container elements include classes, structures, modules, interfaces, and enumerations.
Behavior
Scope. The scope of the elements made available by an Imports statement depends on whether you specify element. If
you specify only namespace, all uniquely named members of that namespace, and members of container elements
within that namespace, are available without qualification. If you specify both namespace and element, only the members
of that element are available without qualification.
Qualification. Code outside a namespace or container element must normally qualify a member's name with the name
of that namespace of container element. The Imports statement makes such qualification unnecessary unless your
project has access to another member with the same name. In such a case you can specify an aliasname in each Imports
statement. Then you need only the import aliases to qualify the members with the same name.
Example
The following example imports the Microsoft.VisualBasic.Strings class and assigns an alias, str, that can be used to access the
Left method.
VB
' Place Imports statements at the top of your program.
Imports str = Microsoft.VisualBasic.Strings

VB
Class testClass1
Sub showHello()
' Display only the word "Hello"
MsgBox(str.Left("Hello World", 5))
End Sub
End Class

Notice that the preceding example imports a nested namespace, Strings within VisualBasic within Microsoft. When the
MsgBox Function (Visual Basic) accesses the Left method, it can use the alias str instead of the entire qualification string
Microsoft.VisualBasic.Strings.

See Also
Reference
Namespace Statement
Concepts
Introduction to the .NET Framework Class Library in Visual Studio
Namespaces in Visual Basic
Other Resources
Visual Basic and the .NET Framework
Visual Basic Language Reference

Inherits Statement
Causes the current class or interface to inherit the attributes, variables, properties, procedures, and events from another class
or set of interfaces.

Inherits basetypenames

Parts
basetypenames
Required. The name of the class from which this class derives.
-or-
The names of the interfaces from which this interface derives. Use commas to separate multiple names.
Remarks
If used, the Inherits statement must be the first non-blank, non-comment line in a class or interface definition. It should
immediately follow the Class or Interface statement.
You can use Inherits only in a class or interface. This means the declaration context for an inheritance cannot be a source file,
namespace, structure, module, procedure, or block.
Rules
Class Inheritance. If a class uses the Inherits statement, you can specify only one base class.
A class cannot inherit from a class nested within it.
Interface Inheritance. If an interface uses the Inherits statement, you can specify one or more base interfaces. You can
inherit from two interfaces even if they each define a member with the same name. If you do so, the implementing code
must use name qualification to specify which member it is implementing.
An interface cannot inherit from another interface with a more restrictive access level. For example, a Public interface
cannot inherit from a Friend interface.
An interface cannot inherit from an interface nested within it.
An example of class inheritance in the .NET Framework is the ArgumentException class, which inherits from the
SystemException class. This provides to ArgumentException all the predefined properties and procedures required by
system exceptions, such as the Message property and the ToString method.
An example of interface inheritance in the .NET Framework is the ICollection interface, which inherits from the IEnumerable
interface. This causes ICollection to inherit the definition of the enumerator required to traverse a collection.
Example
The following example uses the Inherits statement to show how a class named thisClass can inherit all the members of a
base class named anotherClass.
VB
Public Class thisClass
Inherits anotherClass
' Add code to override, overload, or extend members
' inherited from the base class.
' Add new variable, property, procedure, and event declarations.
End Class

The following example shows inheritance of multiple interfaces.


VB
Public Interface thisInterface
Inherits IComparable, IDisposable, IFormattable
' Add new property, procedure, and event definitions.
End Interface

The interface named thisInterface now includes all the definitions in the IComparable, IDisposable, and IFormattable
interfaces The inherited members provide respectively for type-specific comparison of two objects, releasing allocated
resources, and expressing the value of an object as a String. A class that implements thisInterface must implement every
member of every base interface.
See Also
Reference
MustInherit
NotInheritable
MyBase
MyClass
Concepts
Interface Implementation Examples in Visual Basic
Other Resources
Inheritance in Visual Basic
Visual Basic Language Reference

Interface Statement (Visual Basic)


Declares the name of an interface and introduces the definitions of the members that the interface comprises.

[ <attributelist> ] [ accessmodifier ] [ Shadows ] _


Interface name [ ( Of typelist ) ]
[ Inherits interfacenames ]
[ [ modifiers ] Property membername ]
[ [ modifiers ] Function memberame ]
[ [ modifiers ] Sub memberame ]
[ [ modifiers ] Event memberame ]
[ [ modifiers ] Interface memberame ]
[ [ modifiers ] Class memberame ]
[ [ modifiers ] Structure memberame ]
End Interface

Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional. Can be one of the following:
Public
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
Shadows
Optional. See Shadows.
name
Required. Name of this interface. See Declared Element Names.
Of
Optional. Specifies that this is a generic interface.
typelist
Required if you use the Of keyword. List of type parameters for this interface. See Type List.
Inherits
Optional. Indicates that this interface inherits the attributes and members of another interface or interfaces. See
Inherits Statement.
interfacenames
Required if you use the Inherits statement. The names of the interfaces from which this interface derives.
modifiers
Optional. Appropriate modifiers for the interface member being defined.
Property
Optional. Defines a property that is a member of the interface.
Function
Optional. Defines a Function procedure that is a member of the interface.
Sub
Optional. Defines a Sub procedure that is a member of the interface.
Event
Optional. Defines an event that is a member of the interface.
Interface
Optional. Defines an interface that is a nested within this interface. The nested interface definition must terminate with an
End Interface statement.
Class
Optional. Defines a class that is a member of the interface. The member class definition must terminate with an End Class
statement.
Structure
Optional. Defines a structure that is a member of the interface. The member structure definition must terminate with an End
Structure statement.
membername
Required for each property, procedure, event, interface, class, or structure defined as a member of the interface. The name of
the member.
End Interface
Terminates the Interface definition.
Remarks
An interface defines a set of members, such as properties and procedures, that classes and structures can implement. The
interface defines only the signatures of the members and not their internal workings.
A class or structure implements the interface by supplying code for every member defined by the interface. Finally, when the
application creates an instance from that class or structure, an object exists and runs in memory. For more information, see
Object-Oriented Programming in Visual Basic and Interfaces in Visual Basic.
For a comparison of interfaces and classes, see Interfaces Overview.
You can use Interface only at namespace or module level. This means the declaration context for an interface must be a
source file, namespace, class, structure, module, or interface, and cannot be a procedure or block. For more information, see
Declaration Contexts and Default Access Levels.
Interfaces default to Friend (Visual Basic) access. You can adjust their access levels with the access modifiers. For more
information, see Access Levels in Visual Basic.
Rules
Nesting Interfaces. You can define one interface within another. The outer interface is called the containing interface,
and the inner interface is called a nested interface.
Member Declaration. When you declare a property or procedure as a member of an interface, you are defining only
the signature of that property or procedure. This includes the element type (property or procedure), its parameters and
parameter types, and its return type. Because of this, the member definition uses only one line of code, and terminating
statements such as End Function or End Property are not valid in an interface.
In contrast, when you define an enumeration or structure, or a nested class or interface, it is necessary to include their
data members.
Member Modifiers. You cannot use any access modifiers when defining module members, nor can you specify
Shared (Visual Basic) or any procedure modifier except Overloads. You can declare any member with Shadows, and you
can use Default (Visual Basic) when defining a property, as well as ReadOnly (Visual Basic) or WriteOnly.
Inheritance. If the interface uses the Inherits Statement, you can specify one or more base interfaces. You can inherit
from two interfaces even if they each define a member with the same name. If you do so, the implementing code must
use name qualification to specify which member it is implementing.
An interface cannot inherit from another interface with a more restrictive access level. For example, a Public interface
cannot inherit from a Friend interface.
An interface cannot inherit from an interface nested within it.
Implementation. When a class uses the Implements (Visual Basic) statement to implement this interface, it must
implement every member defined within the interface. Furthermore, each signature in the implementing code must
exactly match the corresponding signature defined in this interface. However, the name of the member in the
implementing code does not have to match the member name as defined in the interface.
When a class is implementing a procedure, it cannot designate the procedure as Shared.
Default Property. An interface can specify at most one property as its default property, which can be referenced without
using the property name. You specify such a property by declaring it with the Default (Visual Basic) modifier. For more
information, see Default Properties.
Notice that this means that an interface can define a default property only if it inherits none.
Behavior
Access Level. All interface members implicitly have Public (Visual Basic) access. You cannot use any access modifier
when defining a member. However, a class implementing the interface can declare an access level for each implemented
member.
If you assign a class instance to a variable, the access level of its members can depend on whether the data type of the
variable is the underlying interface or the implementing class. The following example illustrates this.
VB
Public Interface IDemo
Sub doSomething()
End Interface
Public Class implementIDemo
Implements IDemo
Private Sub doSomething() Implements IDemo.doSomething
End Sub
End Class
Dim varAsInterface As IDemo = New implementIDemo()
Dim varAsClass As implementIDemo = New implementIDemo()

If you access class members through varAsInterface, they all have public access. However, if you access members
through varAsClass, the Sub procedure doSomething has private access.
Scope. An interface is in scope throughout its namespace, class, structure, or module.
The scope of every interface member is the entire interface.
Lifetime. An interface does not itself have a lifetime, nor do its members. When a class implements an interface and an
object is created as an instance of that class, the object has a lifetime within the application in which it is running. For
more information, see "Lifetime" in Class Statement (Visual Basic).
Example
The following example uses the Interface statement to define an interface named thisInterface, which must be implemented
with a Property statement and a Function statement.
VB
Public Interface thisInterface
Property thisProp(ByVal thisStr As String) As Char
Function thisFunc(ByVal thisInt As Integer) As Integer
End Interface
Note that the Property and Function statements do not introduce blocks ending with End Property and End Function
within the interface. The interface defines only the signatures of its members. The full Property and Function blocks appear in
a class that implements thisInterface.
See Also
Reference
Class Statement (Visual Basic)
Module Statement
Structure Statement
Property Statement
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
Concepts
Generic Types in Visual Basic
Other Resources
Interfaces in Visual Basic
Visual Basic Language Reference

Mid Statement
Replaces a specified number of characters in a String variable with characters from another string.

Mid( _
ByRef Target As String, _
ByVal Start As Integer, _
Optional ByVal Length As Integer _
) = StringExpression

Parts
Target
Required. Name of the String variable to modify.
Start
Required. Integer expression. Character position in Target where the replacement of text begins. Start uses a one-based
index.
Length
Optional. Integer expression. Number of characters to replace. If omitted, all of String is used.
StringExpression
Required. String expression that replaces part of Target.
Exceptions
Exception type Error number Condition
ArgumentException 5 Start <= 0 or Length < 0.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You
can compare the error number against the Number Property (Err Object).) However, when possible, you should consider
replacing such error control with Structured Exception Handling Overview for Visual Basic.
Remarks
The number of characters replaced is always less than or equal to the number of characters in Target.
Visual Basic has a Mid Function (Visual Basic) and a Mid statement. These elements both operate on a specified number of
characters in a string, but the Mid function returns the characters while the Mid statement replaces the characters. For more
information, see Mid Function (Visual Basic).
Note
The MidB statement of earlier versions of Visual Basic replaces a substring in bytes, rather than characters. It is used primaril
y for converting strings in double-byte character set (DBCS) applications. All Visual Basic strings are in Unicode, and MidB is
no longer supported.

Example
This example uses the Mid statement to replace a specified number of characters in a string variable with characters from
another string.
VB
Dim TestString As String
' Initializes string.
TestString = "The dog jumps"
' Returns "The fox jumps".
Mid(TestString, 5, 3) = "fox"
' Returns "The cow jumps".
Mid(TestString, 5) = "cow"
' Returns "The cow jumpe".
Mid(TestString, 5) = "cow jumped over"
' Returns "The duc jumpe".
Mid(TestString, 5, 3) = "duck"

Requirements
Namespace: Microsoft.VisualBasic
Module: Strings
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Mid Function (Visual Basic)
Other Resources
Strings in Visual Basic
Introduction to Strings in Visual Basic
Visual Basic Language Reference

Module Statement
Declares the name of a module and introduces the definition of the variables, properties, events, and procedures that the
module comprises.

[ <attributelist> ] [ accessmodifier ] Module name


[ statements ]
End Module

Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional. Can be one of the following:
Public
Friend
See Access Levels in Visual Basic.
name
Required. Name of this module. See Declared Element Names.
statements
Optional. Statements which define the variables, properties, events, procedures, and nested types of this module.
End Module
Terminates the Module definition.
Remarks
A Module statement defines a reference type available throughout its namespace. A module (sometimes called a standard
module) is similar to a class but with some important distinctions. Every module has exactly one instance and does not need to
be created or assigned to a variable. Modules do not support inheritance or implement interfaces. Notice that a module is not a
type in the sense that a class or structure is — you cannot declare a programming element to have the data type of a module.
You can use Module only at namespace level. This means the declaration context for a module must be a source file or
namespace, and cannot be a class, structure, module, interface, procedure, or block. You cannot nest a module within another
module, or within any type. For more information, see Declaration Contexts and Default Access Levels.
A module has the same lifetime as your program. Because its members are all Shared, they also have lifetimes equal to that of
the program.
Modules default to Friend (Visual Basic) access. You can adjust their access levels with the access modifiers. For more
information, see Access Levels in Visual Basic.
All members of a module are implicitly Shared.
Classes and Modules
These elements have many similarities, but there are some important differences as well.
Terminology. Previous versions of Visual Basic recognize two types of modules: class modules (.cls files) and standard
modules (.bas files). The current version calls these classes and modules, respectively.
Shared Members. You can control whether a member of a class is a shared or instance member.
Object Orientation. Classes are object-oriented, but modules are not. So only classes can be instantiated as objects. For
more information, see Classes vs. Modules.
Rules
Modifiers. All module members are implicitly Shared (Visual Basic). You cannot use the Shared keyword when
declaring a member, and you cannot alter the shared status of any member.
Inheritance. A module cannot inherit from any type other than Object, from which all modules inherit. In particular, one
module cannot inherit from another.
You cannot use the Inherits Statement in a module definition, even to specify Object.
Default Property. You cannot define any Default Properties in a module.
Behavior
Access Level. Within a module, you can declare each member with its own access level. Module members default to
Public (Visual Basic) access, except variables and constants, which default to Private (Visual Basic) access. When a module
has more restricted access than one of its members, the specified module access level takes precedence.
Scope. A module is in scope throughout its namespace.
The scope of every module member is the entire module. Notice that all members undergo type promotion, which
causes their scope to be promoted to the namespace containing the module. For more information, see Type Promotion.
Qualification. You can have multiple modules in a project, and you can declare members with the same name in two or
more modules. However, you must qualify any reference to such a member with the appropriate module name if the
reference is from outside that module. For more information, see
Resolving a Reference When Multiple Variables Have the Same Name.
Example
VB
Public Module thisModule
Sub Main()
Dim userName As String = InputBox("What is your name?")
MsgBox("User name is" & userName)
End Sub
' Insert variable, property, procedure, and event declarations.
End Module

See Also
Reference
Class Statement (Visual Basic)
Namespace Statement
Structure Statement
Interface Statement (Visual Basic)
Property Statement
Concepts
Type Promotion
Visual Basic Language Reference

Namespace Statement
Declares the name of a namespace and causes the source code following the declaration to be compiled within that
namespace.

Namespace { name | name.name }


[ componenttypes ]
End Namespace

Parts
name
Required. A unique name that identifies the namespace. Must be a valid Visual Basic identifier. For more information, see
Declared Element Names.
componenttypes
Optional. Elements that make up the namespace. These include (but are not limited to) enumerations, structures, interfaces,
classes, modules, delegates, and other namespaces.
End Namespace
Terminates a Namespace block.
Remarks
Namespaces are used as an organizational system. They provide a way of classifying and presenting programming elements
that are exposed to other programs and applications. Note that a namespace is not a type in the sense that a class or structure
is — you cannot declare a programming element to have the data type of a namespace.
You can use a Namespace statement only at the file or namespace level. This means the declaration context for a namespace
must be a source file or another namespace, and cannot be a class, structure, module, interface, or procedure. For more
information, see Declaration Contexts and Default Access Levels.
Namespaces are treated as if they had a Public access level. A namespace can be accessed from code anywhere within the
same project, from other projects that reference the project, and from any assembly built from the project.
Rules
Attributes. You cannot apply attributes to a namespace. An attribute contributes information to the assembly's
metadata, which is not meaningful for source classifiers such as namespaces.
Modifiers. You cannot apply any access or procedure modifiers, or any other modifiers, to a namespace. Because it is
not a type, these modifiers are not meaningful.
Nesting. You can declare one namespace within another. There is no strict limit to the levels of nesting you can declare,
but keep in mind that when other code accesses the elements declared in the innermost namespace, it must use a
qualification string containing all the namespace names in the nesting hierarchy.
Behavior
Access Level. Programming elements declared at namespace level, meaning within a namespace but not inside any
other element, can have Public or Friend access. If not specified, the access level of such an element defaults to Friend.
Elements you can declare at namespace level include classes, structures, modules, interfaces, enumerations, and
delegates. For more information, see Declaration Contexts and Default Access Levels.
Compilation. All programming elements declared following a Namespace statement belong to that namespace. Visual
Basic continues to compile elements into the last declared namespace until it encounters either an End Namespace
statement or another Namespace statement.
Adding to a Namespace. If a namespace is already defined, even outside your project, you can add programming
elements to it. To do this, you use a Namespace statement to direct Visual Basic to compile the following elements into
that namespace.
The following example defines the skeleton of a new generic list class and adds it to the System.Collections.Generic
namespace.

Namespace System.Collections.Generic
Class specialSortedList(Of T)
Inherits List(Of T)
' Insert code to define the special generic list class.
End Class
End Namespace

Root Namespace. All namespace names in your project are based on a root namespace. Visual Studio assigns your
project name as the default root namespace for all code in your project. For example, if your project is named Payroll, its
programming elements belong to namespace Payroll. If you declare Namespace funding, the full name of that
namespace is Payroll.funding.
If you wish to specify an existing namespace in a Namespace statement, such as in the generic list class example, you
can set your root namespace to a null value. You do this by choosing Project Properties from the Project menu and
then clearing the Root namespace entry so that the box is empty. If you did not do this in the generic list class example,
the Visual Basic compiler would take System.Collections.Generic as a new namespace within project Payroll, with the
full name of Payroll.System.Collections.Generic.
Alternatively, you can use the Global keyword to refer to elements of namespaces defined outside your project. Doing so
allows you to retain your project name as the root namespace. This reduces the chance of unintentionally merging your
programming elements with those of existing namespaces.
Troubleshooting
Undefined Types. The root namespace can lead to unexpected concatenations of namespace names. If you make
reference to namespaces defined outside your project, the Visual Basic compiler can construe them as nested
namespaces within your root namespace. In such a case, the compiler does not recognize any types that have been
already defined in the external namespaces. To avoid this, either set your root namespace to a null value as described in
"Root Namespace", or use the Global keyword to access elements of external namespaces.
Example
The following example declares two namespaces, one nested within the other.
VB
Namespace n1
Namespace n2
Class a
' Insert class definition.
End Class
End Namespace
End Namespace

The following example declares multiple nested namespaces on a single line, and it is equivalent to the previous example.
VB
Namespace n1.n2
Class a
' Insert class definition.
End Class
End Namespace

The following example accesses the class defined in the previous examples.
VB
Dim instance As New n1.n2.a
See Also
Reference
Imports Statement
Global
Concepts
Declared Element Names
Namespaces in Visual Basic
Visual Basic Language Reference

On Error Statement (Visual Basic)


Enables an error-handling routine and specifies the location of the routine within a procedure; can also be used to disable an
error-handling routine.
Without an On Error statement, any run-time error that occurs is fatal: an error message is displayed, and execution stops.
Whenever possible, we suggest you use structured exception handling in your code, rather than resorting to unstructured
exception handling and the On Error statement. For more information, see Structured Exception Handling in Visual Basic.

On Error { GoTo [ line | 0 | -1 ] | Resume Next }

Parts
GoTo line
Enables the error-handling routine that starts at the line specified in the required line argument. The line argument is any line
label or line number. If a run-time error occurs, control branches to the specified line, making the error handler active. The
specified line must be in the same procedure as the On Error statement, or a compile-time error will occur.
GoTo 0
Disables enabled error handler in the current procedure and resets it to Nothing.
GoTo -1
Disables enabled exception in the current procedure and resets it to Nothing.
Resume Next
Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the
error occurred, and execution continues from that point. Use this form rather than On Error GoTo when accessing objects.
Remarks
An "enabled" error handler is one that is turned on by an On Error statement. An "active" error handler is an enabled handler
that is in the process of handling an error.
If an error occurs while an error handler is active (between the occurrence of the error and a Resume, Exit Sub, Exit
Function, or Exit Property statement), the current procedure's error handler cannot handle the error. Control returns to the
calling procedure.
If the calling procedure has an enabled error handler, it is activated to handle the error. If the calling procedure's error handler
is also active, control passes back through previous calling procedures until an enabled, but inactive, error handler is found. If
no such error handler is found, the error is fatal at the point at which it actually occurred.
Each time the error handler passes control back to a calling procedure, that procedure becomes the current procedure. Once an
error is handled by an error handler in any procedure, execution resumes in the current procedure at the point designated by
the Resume statement.
Note
An error-handling routine is not a Sub procedure or a Function procedure. It is a section of code marked by a line label or a
line number.

Number Property
Error-handling routines rely on the value in the Number property of the Err object to determine the cause of the error. The
routine should test or save relevant property values in the Err object before any other error can occur or before a procedure
that might cause an error is called. The property values in the Err object reflect only the most recent error. The error message
associated with Err.Number is contained in Err.Description.
Throw Statement
An error that is raised with the Err.Raise method sets the Exception property to a newly created instance of the Exception
class. In order to support the raising of exceptions of derived exception types, a Throw statement is supported in the language.
This takes a single parameter that is the exception instance to be thrown. The following example shows how these features can
be used with the existing exception handling support:
VB
On Error GoTo Handler
Throw New DivideByZeroException()
Handler:
If (TypeOf Err.GetException() Is DivideByZeroException) Then
' Code for handling the error is entered here.
End If

Notice that the On Error GoTo statement traps all errors, regardless of the exception class.
On Error Resume Next
On Error Resume Next causes execution to continue with the statement immediately following the statement that caused the
run-time error, or with the statement immediately following the most recent call out of the procedure containing the On Error
Resume Next statement. This statement allows execution to continue despite a run-time error. You can place the error-
handling routine where the error would occur rather than transferring control to another location within the procedure. An On
Error Resume Next statement becomes inactive when another procedure is called, so you should execute an On Error
Resume Next statement in each called routine if you want inline error handling within that routine.
Note
The On Error Resume Next construct may be preferable to On Error GoTo when handling errors generated during access t
o other objects. Checking Err after each interaction with an object removes ambiguity about which object was accessed by th
e code. You can be sure which object placed the error code in Err.Number, as well as which object originally generated the e
rror (the object specified in Err.Source).

On Error GoTo 0
On Error GoTo 0 disables error handling in the current procedure. It doesn't specify line 0 as the start of the error-handling
code, even if the procedure contains a line numbered 0. Without an On Error GoTo 0 statement, an error handler is
automatically disabled when a procedure is exited.
On Error GoTo -1
On Error GoTo -1 disables the exception in the current procedure. It does not specify line -1 as the start of the error-handling
code, even if the procedure contains a line numbered -1. Without an On Error GoTo -1 statement, an exception is
automatically disabled when a procedure is exited.
To prevent error-handling code from running when no error has occurred, place an Exit Sub, Exit Function, or Exit Property
statement immediately before the error-handling routine, as in the following fragment:
VB
Public Sub InitializeMatrix(ByVal Var1 As Object, ByVal Var2 As Object)
On Error GoTo ErrorHandler
' Insert code that might generate an error here
Exit Sub
ErrorHandler:
' Insert code to handle the error here
Resume Next
End Sub

Here, the error-handling code follows the Exit Sub statement and precedes the End Sub statement to separate it from the
procedure flow. You can place error-handling code anywhere in a procedure.
Untrapped Errors
Untrapped errors in objects are returned to the controlling application when the object is running as an executable file. Within
the development environment, untrapped errors are returned to the controlling application only if the proper options are set.
See your host application's documentation for a description of which options should be set during debugging, how to set
them, and whether the host can create classes.
If you create an object that accesses other objects, you should try to handle any unhandled errors they pass back. If you cannot,
map the error codes in Err.Number to one of your own errors and then pass them back to the caller of your object. You
should specify your error by adding your error code to the VbObjectError constant. For example, if your error code is 1052,
assign it as follows:
VB
Err.Number = vbObjectError + 1052

Caution
System errors during calls to Windows dynamic-link libraries (DLLs) do not raise exceptions and cannot be trapped with Visu
al Basic error trapping. When calling DLL functions, you should check each return value for success or failure (according to th
e API specifications), and in the event of a failure, check the value in the Err object's LastDLLError property.

Example
This example first uses the On Error GoTo statement to specify the location of an error-handling routine within a procedure. In
the example, an attempt to divide by zero generates error number 6. The error is handled in the error-handling routine, and
control is then returned to the statement that caused the error. The On Error GoTo 0 statement turns off error trapping. Then
the On Error Resume Next statement is used to defer error trapping so that the context for the error generated by the next
statement can be known for certain. Note that Err.Clear is used to clear the Err object's properties after the error is handled.
VB
Public Sub OnErrorDemo()
On Error GoTo ErrorHandler ' Enable error-handling routine.
Dim x As Integer = 32
Dim y As Integer = 0
Dim z As Integer
z = x / y ' Creates a divide by zero error
On Error GoTo 0 ' Turn off error trapping.
On Error Resume Next ' Defer error trapping.
z = x / y ' Creates a divide by zero error again
If Err.Number = 6 Then
' Tell user what happened. Then clear the Err object.
Dim Msg As String
Msg = "There was an error attempting to divide by zero!"
MsgBox(Msg, , "Divide by zero error")
Err.Clear() ' Clear Err object fields.
End If
Exit Sub ' Exit to avoid handler.
ErrorHandler: ' Error-handling routine.
Select Case Err.Number ' Evaluate error number.
Case 6 ' Divide by zero error
MsgBox("You attempted to divide by zero!")
' Insert code to handle this error
Case Else
' Insert code to handle other situations here...
End Select
Resume Next ' Resume execution at same line
' that caused the error.
End Sub

Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Get Information about Visual Basic Run-Time Errors
Reference
End Statement
Err Object (Visual Basic)
Exit Statement (Visual Basic)
LastDllError Property (Err Object)
Resume Statement
Visual Basic Language Reference

Operator Statement
Declares the operator symbol, operands, and code that define an operator procedure on a class or structure.

[ <attrlist> ] Public [ Overloads ] Shared [ Shadows ] [ Widening | Narrowing ]


Operator operatorsymbol ( operand1 [, operand2 ]) [ As [ <attrlist> ] type ]
[ statements ]
[ statements ]
Return returnvalue
[ statements ]
End Operator

Parts
attrlist
Optional. See Attribute List.
Public
Required. Indicates that this operator procedure has Public (Visual Basic) access.
Overloads
Optional. See Overloads.
Shared
Required. Indicates that this operator procedure is a Shared (Visual Basic) procedure.
Shadows
Optional. See Shadows.
Widening
Required for a conversion operator unless you specify Narrowing. Indicates that this operator procedure defines a
Widening conversion. See "Widening and Narrowing Conversions" on this Help page.
Narrowing
Required for a conversion operator unless you specify Widening. Indicates that this operator procedure defines a
Narrowing conversion. See "Widening and Narrowing Conversions" on this Help page.
operatorsymbol
Required. The symbol or identifier of the operator that this operator procedure defines.
operand1
Required. The name and type of the single operand of a unary operator (including a conversion operator) or the left operand
of a binary operator.
operand2
Required for binary operators. The name and type of the right operand of a binary operator.
operand1 and operand2 have the following syntax and parts:
[ ByVal ] operandname [ As operandtype ]

Part Description
ByVal Optional, but the passing mechanism must be ByVal.

operandname Required. Name of the variable representing this operand. See Declared Element Names.

operandtype Optional unless Option Strict is On. Data type of this operand.
type
Optional unless Option Strict is On. Data type of the value the operator procedure returns.
statements
Optional. Block of statements that the operator procedure runs.
returnvalue
Required. The value that the operator procedure returns to the calling code.
End Operator
Required. Terminates the definition of this operator procedure.
Remarks
You can use Operator only in a class or structure. This means the declaration context for an operator cannot be a source file,
namespace, module, interface, procedure, or block. For more information, see Declaration Contexts and Default Access Levels.
All operators must be Public Shared. You cannot specify ByRef, Optional, or ParamArray for either operand.
You cannot use the operator symbol or identifier to hold a return value. You must use the Return statement, and it must
specify a value. Any number of Return statements can appear anywhere in the procedure.
Defining an operator in this way is called operator overloading, whether or not you use the Overloads keyword. The following
table lists the operators you can define.
Type Operators
Unary +, -, IsFalse, IsTrue, Not

Binary +, -, *, /, \, &, ^, >>, <<, =, <>, >, >=, <, <=, And, Like, Mod, Or, Xor

Conversion (unary) CType

Note that the = operator in the binary list is the comparison operator, not the assignment operator.
When you define CType, you must specify either Widening or Narrowing.
Matched Pairs
You must define certain operators as matched pairs. If you define either operator of such a pair, you must define the other as
well. The matched pairs are the following:
= and <>
> and <
>= and <=
IsTrue and IsFalse
Data Type Restrictions
Every operator you define must involve the class or structure on which you define it. This means that the class or structure
must appear as the data type of the following:
The operand of a unary operator.
At least one of the operands of a binary operator.
Either the operand or the return type of a conversion operator.
Certain operators have additional data type restrictions, as follows:
If you define the IsTrue and IsFalse operators, they must both return the Boolean type.
If you define the << and >> operators, they must both specify the Integer type for the operandtype of operand2.
The return type does not have to correspond to the type of either operand. For example, a comparison operator such as = or
<> can return Boolean even if neither operand is Boolean.
Logical and Bitwise Operators
The And, Or, Not, and Xor operators can perform either logical or bitwise operations in Visual Basic. However, if you define
one of these operators on a class or structure, you can define only its bitwise operation.
You cannot define the AndAlso operator directly with an Operator statement. However, you can use AndAlso if you have
fulfilled the following conditions:
You have defined And on the same operand types you want to use for AndAlso.
Your definition of And returns the same type as the class or structure on which you have defined it.
You have defined the IsFalse operator on the class or structure on which you have defined And.
Similarly, you can use OrElse if you have defined Or on the same operands, with the return type of the class or structure, and
you have defined IsTrue on the class or structure.
Widening and Narrowing Conversions
A widening conversion always succeeds at run time, while a narrowing conversion can fail at run time. For more information,
see Widening and Narrowing Conversions.
If you declare a conversion procedure to be Widening, your procedure code must not generate any failures. This means the
following:
It must always return a valid value of type type.
It must handle all possible exceptions and other error conditions.
It must handle any error returns from any procedures it calls.
If there is any possibility that a conversion procedure might not succeed, or that it might cause an unhandled exception, you
must declare it to be Narrowing.
Example
The following code example uses the Operator statement to define the outline of a structure that includes operator procedures
for the And, Or, IsFalse, and IsTrue operators. And and Or each take two operands of type abc and return type abc. IsFalse
and IsTrue each take a single operand of type abc and return Boolean. These definitions allow the calling code to use And,
AndAlso, Or, and OrElse with operands of type abc.
VB
Public Structure abc
Dim d As Date
Public Shared Operator And(ByVal x As abc, ByVal y As abc) As abc
Dim r As New abc
' Insert code to calculate And of x and y.
Return r
End Operator
Public Shared Operator Or(ByVal x As abc, ByVal y As abc) As abc
Dim r As New abc
' Insert code to calculate Or of x and y.
Return r
End Operator
Public Shared Operator IsFalse(ByVal z As abc) As Boolean
Dim b As Boolean
' Insert code to calculate IsFalse of z.
Return b
End Operator
Public Shared Operator IsTrue(ByVal z As abc) As Boolean
Dim b As Boolean
' Insert code to calculate IsTrue of z.
Return b
End Operator
End Structure

See Also
Tasks
How to: Define an Operator
How to: Define a Conversion Operator
How to: Call an Operator Procedure
How to: Use a Class that Defines Operators
Reference
IsFalse Operator
IsTrue Operator
Widening
Narrowing
Concepts
Widening and Narrowing Conversions
Operator Procedures
Visual Basic Language Reference

Option Compare Statement


Declares the default comparison method to use when comparing string data.

Option Compare { Binary | Text }

Parts
Binary
Optional. Results in string comparisons based on a sort order derived from the internal binary representations of the
characters.
Text
Optional. Results in string comparisons based on a case-insensitive text sort order determined by your system's locale.
Remarks
If used, the Option Compare statement must appear in a file before any other source code statements.
The Option Compare statement specifies the string comparison method (Binary or Text) for a class, module or structure. If
an Option Compare statement is not included, the default text comparison method is Binary.
In Microsoft Windows, sort order is determined by the code page. For more information, see Code Pages.
In the following example, characters in the English/European code page (ANSI 1252) are sorted using Option Compare
Binary, which produces a typical binary sort order.
A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø

When the same characters in the same code page are sorted using Option Compare Text, the following text sort order is
produced.
(A=a) < (À = à) < (B=b) < (E=e) < (Ê = ê) < (Z=z) < (Ø = ø)

You can also set Option Compare in the Visual Studio integrated development environment (IDE) or on a command line.
To set Option Compare in the integrated development environment (IDE)
1. On the Tools menu, choose Options.
2. Open the Projects and Solutions node.
3. Choose VB Defaults.
4. Modify the Option Compare setting.
To set Option Compare on the command line
Include the /optioncompare compiler option in the vbc command.
Example
The following example uses the Option Compare statement to set the binary comparison as the default string comparison
method.
VB
' Set the string comparison method to Binary ("AAA" < "aaa").
Option Compare Binary

The following example uses the Option Compare statement to set the case-insensitive text sort order as the default string
comparison method.
VB
' Set the string comparison method to Text ("AAA" = "aaa").
Option Compare Text

See Also
Reference
Comparison Operators (Visual Basic)
InStr Function (Visual Basic)
InStrRev Function (Visual Basic)
Replace Function (Visual Basic)
Split Function (Visual Basic)
StrComp Function (Visual Basic)
/optioncompare
Option Explicit Statement (Visual Basic)
Option Strict Statement
/optionexplicit
/optionstrict
Visual Basic Defaults, Projects, Options Dialog Box
Visual Basic Language Reference

Option Explicit Statement (Visual Basic)


Forces explicit declaration of all variables in a file.

Option Explicit { On | Off }

Parts
On
Optional. Enables Option Explicit checking. If On or Off is not specified, the default is On.
Off
Optional. Disables Option Explicit checking.
Remarks
If used, the Option Explicit statement must appear in a file before any other source code statements.
When Option Explicit appears in a file, you must explicitly declare all variables using the Dim or ReDim statements. If you
attempt to use an undeclared variable name, an error occurs at compile time.
Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope
of the variable is not clear. If you do not use the Option Explicit statement, all undeclared variables are of Object type.
Note
The compiler default is Option Explicit On if you do not specify Option Explicit in your code.

You can also set Option Explicit in the Visual Studio integrated development environment (IDE) or on a command line.
To set Option Explicit in the integrated development environment (IDE)
1. On the Tools menu, choose Options.
2. Open the Projects and Solutions node.
3. Choose VB Defaults.
4. Modify the Option Explicit setting.

To set Option Explicit on the command line


Include the /optionexplicit compiler option in the vbc command.
Example
The following example uses the Option Explicit statement to force explicit declaration of all variables. Attempting to use an
undeclared variable causes an error at compile time.
VB
' Force explicit variable declaration.
Option Explicit On

VB
Dim thisVar As Integer
thisVar = 10
' The following assignment produces a COMPILER ERROR because
' the variable is not declared and Option Explicit is On.
thisInt = 10 ' causes ERROR
See Also
Reference
Dim Statement (Visual Basic)
ReDim Statement (Visual Basic)
Option Compare Statement
Option Strict Statement
/optioncompare
/optionexplicit
/optionstrict
Visual Basic Defaults, Projects, Options Dialog Box
Visual Basic Language Reference

Option Strict Statement


Restricts implicit data type conversions to only widening conversions.

Option Strict { On | Off }

Parts
On
Optional. Enables Option Strict checking.
Off
Optional. Disables Option Strict checking. If On or Off is not specified, the default is Off.
Remarks
If used, the Option Strict statement must appear in a file before any other source code statements.
Visual Basic allows conversions of many data types to other data types. Data loss can occur when the value of one data type is
converted to a data type with less precision or smaller capacity. A run-time error occurs if such a narrowing conversion fails.
Option Strict ensures compile-time notification of these narrowing conversions so they can be avoided.
In addition to disallowing implicit narrowing conversions, Option Strict generates an error for late binding. An object is late
bound when it is assigned to a variable that is declared to be of type Object.
Because Option Strict On provides strong typing, prevents unintended type conversions with data loss, disallows late binding,
and improves performance, its use is strongly recommended.
Note
The compiler default is Option Strict Off if you do not specify Option Strict in your code.

You can also set Option Strict in the Visual Studio integrated development environment (IDE) or on a command line.
To set Option Strict in the integrated development environment (IDE)
1. On the Tools menu, choose Options.
2. Open the Projects and Solutions node.
3. Choose VB Defaults.
4. Modify the Option Strict setting.
To set Option Strict on the command line
Include the /optionstrict compiler option in the vbc command.
Example
The following example demonstrates how the Option Strict statement disallows late binding and conversions where data
would be lost.
VB
Option Strict On

VB
Dim thisVar As Integer
Dim thisObj As Object = New widget
thisVar = 1000 ' Declared variable does not generate error.
' Attempting to convert Double to Integer generates a COMPILER ERROR.
thisVar = 1234567890.9876542 ' causes ERROR
' Late-bound call generates a COMPILER ERROR.
Call thisObj.Method1() ' causes ERROR

See Also
Reference
Option Compare Statement
Option Explicit Statement (Visual Basic)
/optioncompare
/optionexplicit
/optionstrict
Visual Basic Defaults, Projects, Options Dialog Box
Concepts
Widening and Narrowing Conversions
Visual Basic Language Reference

Property Statement
Declares the name of a property, and the property procedures used to store and retrieve the value of the property.

[ <attributelist> ] [ Default ] [ accessmodifier ]


[ propertymodifiers ] [ Shared ] [ Shadows ] [ ReadOnly | WriteOnly ]
Property name ( [ parameterlist ] ) [ As returntype ] [ Implements implementslist ]
[ <attributelist> ] [ accessmodifier ] Get
[ statements ]
End Get
[ <attributelist> ] [ accessmodifier ] Set ( ByVal value As returntype [, parameterlist
] )
[ statements ]
End Set
End Property

Parts
attributelist
Optional. List of attributes that apply to this property or Get or Set procedure. See Attribute List.
Default
Optional. Specifies that this property is the default property for the class or structure on which it is defined. Default
properties must accept parameters and can be set and retrieved without specifying the property name. If you declare the
property as Default, you cannot use Private on the property or on either of its property procedures.
accessmodifier
Optional on the Property statement and on at most one of the Get and Set statements. Can be one of the following:
Public
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
propertymodifiers
Optional. Can be one of the following:
Overloads
Overrides
Overridable
NotOverridable
MustOverride
MustOverride Overrides
NotOverridable Overrides
Shared
Optional. See Shared (Visual Basic).
Shadows
Optional. See Shadows.
ReadOnly
Optional. See ReadOnly (Visual Basic).
WriteOnly
Optional. See WriteOnly.
name
Required. Name of the property. See Declared Element Names.
parameterlist
Optional. List of local variable names representing the parameters of this property, and possible additional parameters of the
Set procedure. See Parameter List.
returntype
Required if Option Strict is On. Data type of the value returned by this property.
Implements
Optional. Indicates that this property implements one or more properties, each one defined in an interface implemented by
this property's containing class or structure. See Implements Statement.
implementslist
Required if Implements is supplied. List of properties being implemented.
implementedproperty [ , implementedproperty ... ]

Each implementedproperty has the following syntax and parts:


interface.definedname

Part Description
interface Required. Name of an interface implemented by this property's containing class or structure.

definedname Required. Name by which the property is defined in interface.

Get
Required unless the property is marked WriteOnly. Starts a Get property procedure used to return the value of the
property.
statements
Optional. Block of statements to run within the Get or Set procedure.
End Get
Terminates the Get property procedure.
Set
Required unless the property is marked ReadOnly. Starts a Set property procedure used to store the value of the property.
End Set
Terminates the Set property procedure.
End Property
Terminates the definition of this property.
Remarks
The Property statement introduces the declaration of a property. A property can have a Get procedure (read only), a Set
procedure (write only), or both (read-write).
You can use Property only at module level. This means the declaration context for a property must be a class, structure,
module, or interface, and cannot be a source file, namespace, procedure, or block. For more information, see
Declaration Contexts and Default Access Levels.
Properties default to public access. You can adjust a property's access level with an access modifier on the Property statement,
and you can optionally adjust one of its property procedures to a more restrictive access level.
Visual Basic passes a parameter to the Set procedure during property assignments. If you do not supply a parameter for Set,
the integrated development environment (IDE) uses an implicit parameter named value. This parameter holds the value to be
assigned to the property. You typically store this value in a private local variable and return it whenever the Get procedure is
called.
Rules
Mixed Access Levels. If you are defining a read-write property, you can optionally specify a different access level for
either the Get or the Set procedure, but not both. If you do this, the procedure access level must be more restrictive than
the property's access level. For example, if the property is declared Friend, you can declare the Set procedure Private,
but not Public.
If you are defining a ReadOnly or WriteOnly property, the single property procedure (Get or Set, respectively)
represents the entire property. You cannot declare a different access level for such a procedure, because that would set
two access levels for the property.
Return Type. The Property statement can declare the data type of the value it returns. You can specify any data type or
the name of an enumeration, structure, class, or interface.
If you do not specify returntype, the property returns Object.
Implementation. If this property uses the Implements keyword, the containing class or structure must have an
Implements statement immediately following its Class or Structure statement. The Implements statement must
include each interface specified in implementslist. However, the name by which an interface defines the Property (in
definedname) does not have to be the same as the name of this property (in name).
Behavior
Returning from a Property Procedure. When the Get or Set procedure returns to the calling code, execution
continues with the statement following the statement that invoked it.
The Exit Property and Return statements cause an immediate exit from a property procedure. Any number of Exit
Property and Return statements can appear anywhere in the procedure, and you can mix Exit Property and Return
statements.
Return Value. To return a value from a Get procedure, you can either assign the value to the property name or include it
in a Return statement. The following example assigns the return value to the property name quoteForTheDay and then
uses the Exit Property statement to return.
VB
Private quoteValue As String = "No quote assigned yet."

VB
ReadOnly Property quoteForTheDay() As String
Get
quoteForTheDay = quoteValue
Exit Property
End Get
End Property

If you use Exit Property without assigning a value to name, the Get procedure returns the default value for the
property's data type.
The Return statement simultaneously assigns the Get procedure return value and exits the procedure. The following
example shows this.
VB
Private quoteValue As String = "No quote assigned yet."
VB
ReadOnly Property quoteForTheDay() As String
Get
Return quoteValue
End Get
End Property

Example
The following example declares a property in a class.
VB
Class Class1
' Define a local variable to store the property value.
Private propertyValue As String
' Define the property.
Public Property prop1() As String
Get
' The Get property procedure is called when the value
' of a property is retrieved.
Return propertyValue
End Get
Set(ByVal value As String)
' The Set property procedure is called when the value
' of a property is modified. The value to be assigned
' is passed in the argument to Set.
propertyValue = value
End Set
End Property
End Class

See Also
Tasks
How to: Add Fields and Properties to a Class
Reference
Get Statement
Set Statement (Visual Basic)
Parameter List
Concepts
Default Properties
Visual Basic Language Reference

Q-Z Statements
The following table contains a listing of Visual Basic language statements.

RaiseEvent ReDim REM RemoveHandler

Resume Return Select...Case Set

Stop Structure Sub SyncLock

Throw Try...Catch...Finally Using While...End While

With...End With
See Also
Reference
A-E Statements
F-P Statements
Other Resources
Visual Basic Reference
Visual Basic Language Reference

RaiseEvent Statement
Triggers an event declared at module level within a class, form, or document.

RaiseEvent eventname[( argumentlist )]

Parts
eventname
Required. Name of the event to trigger.
argumentlist
Optional. Comma-delimited list of variables, arrays, or expressions. The argumentlist argument must be enclosed by
parentheses. If there are no arguments, the parentheses must be omitted.
Remarks
The required eventname is the name of an event declared within the module. It follows Visual Basic variable naming
conventions.
If the event has not been declared within the module in which it is raised, an error occurs. The following code fragment
illustrates an event declaration and a procedure in which the event is raised.
VB
' Declare an event at module level.
Event LogonCompleted(ByVal UserName As String)

Sub Logon(ByVal UserName As String)


' Raise the event.
RaiseEvent LogonCompleted(UserName)
End Sub

You cannot use RaiseEvent to raise events that are not explicitly declared in the module. For example, all forms inherit a Click
event from System.Windows.Forms.Form, it cannot be raised using RaiseEvent in a derived form. If you declare a Click event
in the form module, it shadows the form's own Click event. You can still invoke the form's Click event by calling the OnClick
method.
By default, an event defined in Visual Basic raises its event handlers in the order that the connections are established. Because
events can have ByRef parameters, a process that connects late may receive parameters that have been changed by an earlier
event handler. After the event handlers execute, control is returned to the subroutine that raised the event.
Note
Non-shared events should not be raised within the constructor of the class in which they are declared. Although such events
do not cause run-time errors, they may fail to be caught by associated event handlers. Use the Shared modifier to create a s
hared event if you need to raise an event from a constructor.

You can change the default behavior of events by defining a custom event. For custom events, the RaiseEvent statement
invokes the event's RaiseEvent accessor. For more information on custom events, see Event Statement.
Example
The following example uses events to count down seconds from 10 to 0. The code illustrates several of the event-related
methods, properties, and statements, including the RaiseEvent statement.
The class that raises an event is the event source, and the methods that process the event are the event handlers. An event
source can have multiple handlers for the events it generates. When the class raises the event, that event is raised on every
class that has elected to handle events for that instance of the object.
The example also uses a form (Form1) with a button (Button1) and a text box (TextBox1). When you click the button, the first
text box displays a countdown from 10 to 0 seconds. When the full time (10 seconds) has elapsed, the first text box displays
"Done".
The code for Form1 specifies the initial and terminal states of the form. It also contains the code executed when events are
raised.
To use this example, open a new Windows Application project, add a button named Button1 and a text box named TextBox1 to
the main form, named Form1. Then right-click the form and click View Code to open the Code Editor.
Add a WithEvents variable to the declarations section of the Form1 class.
VB
Private WithEvents mText As TimerState

Add the following code to the code for Form1. Replace any duplicate procedures that may exist, such as Form_Load, or
Button_Click.

VB
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Button1.Text = "Start"
mText = New TimerState
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
mText.StartCountdown(10.0, 0.1)
End Sub

Private Sub mText_ChangeText() Handles mText.Finished


TextBox1.Text = "Done"
End Sub

Private Sub mText_UpdateTime(ByVal Countdown As Double) _


Handles mText.UpdateTime
TextBox1.Text = Format(Countdown, "##0.0")
' Use DoEvents to allow the display to refresh.
My.Application.DoEvents()
End Sub
Class TimerState
Public Event UpdateTime(ByVal Countdown As Double)
Public Event Finished()
Public Sub StartCountdown(ByVal Duration As Double, _
ByVal Increment As Double)
Dim Start As Double = DateAndTime.Timer
Dim ElapsedTime As Double = 0
Dim SoFar As Double = 0
Do While ElapsedTime < Duration
If ElapsedTime > SoFar + Increment Then
SoFar += Increment
RaiseEvent UpdateTime(Duration - SoFar)
End If
ElapsedTime = DateAndTime.Timer - Start
Loop
RaiseEvent Finished()
End Sub
End Class

Press F5 to run the preceding example, and click the button labeled Start. The first text box starts to count down the seconds.
When the full time (10 seconds) has elapsed, the first text box displays "Done".
Note
The My.Application.DoEvents method does not process events in exactly the same way as the form does. To allow the for
m to handle the events directly, you can use multithreading. For more information, see Multithreading in Visual Basic.

See Also
Tasks
How to: Add Events to a Class
Reference
Event Statement
AddHandler Statement
RemoveHandler Statement
Handles
Other Resources
Events in Visual Basic
Visual Basic Language Reference

ReDim Statement (Visual Basic)


Reallocates storage space for an array variable.

ReDim [ Preserve ] name(boundlist) [ , name(boundlist) [, ... ] ]

Parts
Preserve
Optional. Modifier used to preserve the data in the existing array when you change the size of only the last dimension.
name
Required. Name of the array variable. See Declared Element Names.
boundlist
Required. List of bounds of each dimension of the redefined array.
Remarks
You can use the ReDim statement to change the size of one or more dimensions of an array that has already been declared. If
you have a large array and you no longer need some of its elements, ReDim can free up memory by reducing the array size.
On the other hand, if your code determines that an array needs more elements, ReDim can add them.
The ReDim statement is intended only for arrays. It is not valid on scalars (variables containing only a single value), collections,
or structures. Note that if you declare a variable to be of type Array, the ReDim statement does not have sufficient type
information to create the new array.
You can use ReDim only at procedure level. This means the declaration context for a variable must be a procedure, and cannot
be a source file, namespace, interface, class, structure, module, or block. For more information, see
Declaration Contexts and Default Access Levels.
Rules
Modifiers. You can specify only the Preserve modifier, and you cannot omit the ReDim keyword if you do so.
Multiple Variables. You can resize several array variables in the same declaration statement, specifying the name and
boundlist parts for each one. Multiple variables are separated by commas.
Array Bounds. Each entry in boundlist can specify the lower and upper bounds of that dimension. The lower bound is
always zero, whether you specify it or not. The upper bound is the highest possible value for that subscript, not the length
of the dimension (which is the upper bound plus one). Each subscript can vary from zero through its upper bound value.
The number of dimensions in boundlist must match the original rank of the array.
Empty Arrays. It is possible to use -1 to declare the upper bound of an array dimension. This signifies that the array is
empty but not Nothing (Visual Basic). For more information, see How to: Create an Array with No Elements. However,
Visual Basic code cannot successfully access such an array. If you attempt to do so, an IndexOutOfRangeException error
occurs during execution.
Data Types. The ReDim statement cannot change the data type of an array variable or of its elements.
Initialization. The ReDim statement cannot provide new initialization values for the array elements.
Rank. The ReDim statement cannot change the rank (the number of dimensions) of the array.
Resizing with Preserve. If you use Preserve, you can resize only the last dimension of the array, and for every other
dimension you must specify the same bound it already has in the existing array.
For example, if your array has only one dimension, you can resize that dimension and still preserve all the contents of the
array, because you are changing the last and only dimension. However, if your array has two or more dimensions, you
can change the size of only the last dimension if you use Preserve.
Properties. You can use ReDim on a property that holds an array of values.
Behavior
Array Replacement. ReDim releases the existing array and creates a new array with the same rank. The new array
replaces the released array in the array variable.
Initialization without Preserve. If you do not specify Preserve, ReDim initializes the elements of the new array to the
default value for their data type.
Initialization with Preserve. If you specify the Preserve modifier, Visual Basic copies the elements from the existing
array to the new array.
Example
The following example increases the size of the last dimension of a dynamic array without losing any existing data in the array,
and then decreases the size with partial data loss. Finally, it decreases the size back to its original value and reinitializes all the
array elements.
VB
Dim intArray(10, 10, 10) As Integer
ReDim Preserve intArray(10, 10, 20)
ReDim Preserve intArray(10, 10, 15)
ReDim intArray(10, 10, 10)

The first ReDim creates a new array which replaces the existing array in variable intArray. ReDim copies all the elements
from the existing array into the new array. It also adds 10 more columns to the end of every row in every layer and initializes
the elements in these new columns to 0 (the default value of Integer, the element type of the array).
The second ReDim creates another new array, copying all the elements that fit. However, five columns are lost from the end of
every row in every layer. This is not a problem if you have finished using these columns. Reducing the size of a large array can
free up memory that you no longer need.
The third ReDim creates still another new array, removing another five columns from the end of every row in every layer. This
time it does not copy any existing elements. This reverts the array to its original size and returns all its elements to their
original default value.
See Also
Tasks
How to: Create an Array with No Elements
Reference
Const Statement (Visual Basic)
Dim Statement (Visual Basic)
Erase Statement (Visual Basic)
Nothing (Visual Basic)
IndexOutOfRangeException
Visual Basic Language Reference

REM Statement (Visual Basic)


Used to include explanatory remarks in the source code of a program.

REM comment
' comment

Parts
comment
Optional. The text of any comment you want to include. A space is required between the REM keyword or single quotation
mark (') and comment.
Remarks
You can put a REM statement alone on a line, or you can put it on a line following another statement. The REM statement must
be the last statement on the line. If it follows another statement, the REM must be separated from that statement by a space.
You can use a single quotation mark (') instead of REM. This is true whether your comment follows another statement on the
same line or sits alone on a line.
Note
You cannot continue a REM statement by using a line-continuation sequence ( _). Once a comment begins, the compiler does
not examine the characters for special meaning. For a multiple-line comment, use another REM statement or a comment sy
mbol (') on each line.

Example
The following example illustrates the REM statement, which is used to include explanatory remarks in a program. It also shows
the alternative of using the single quotation-mark character (') instead of REM.
VB
Dim demoStr1, demoStr2 As String
demoStr1 = "Hello" REM Comment after a statement using REM.
demoStr2 = "Goodbye" ' Comment after a statement using the ' character.
REM This entire line is a comment.
' This entire line is also a comment.

See Also
Tasks
How to: Break and Combine Statements in Code
Concepts
Comments in Code
Visual Basic Language Reference

RemoveHandler Statement
Removes the association between an event and an event handler.

RemoveHandler event, AddressOf eventhandler

Parts
event
The name of the event being handled.
eventhandler
The name of the procedure currently handling the event.
Remarks
The AddHandler and RemoveHandler statements allow you to start and stop event handling for a specific event at any time
during program execution.
For custom events, the RemoveHandler statement invokes the event's RemoveHandler accessor. For more information on
custom events, see Event Statement.
Example
VB
Sub TestEvents()
Dim Obj As New Class1
' Associate an event handler with an event.
AddHandler Obj.Ev_Event, AddressOf EventHandler
' Call the method to raise the event.
Obj.CauseSomeEvent()
' Stop handling events.
RemoveHandler Obj.Ev_Event, AddressOf EventHandler
' This event will not be handled.
Obj.CauseSomeEvent()
End Sub

Sub EventHandler()
' Handle the event.
MsgBox("EventHandler caught event.")
End Sub
Public Class Class1
' Declare an event.
Public Event Ev_Event()
Sub CauseSomeEvent()
' Raise an event.
RaiseEvent Ev_Event()
End Sub
End Class

See Also
Reference
AddHandler Statement
Handles
Event Statement
Concepts
Events and Event Handlers
AddHandler and RemoveHandler
Visual Basic Language Reference

Resume Statement
Resumes execution after an error-handling routine is finished.

Resume [ Next | line ]

Parts
Resume
Required. If the error occurred in the same procedure as the error handler, execution resumes with the statement that caused
the error. If the error occurred in a called procedure, execution resumes at the statement that last called out of the procedure
containing the error-handling routine.
Next
Optional. If the error occurred in the same procedure as the error handler, execution resumes with the statement
immediately following the statement that caused the error. If the error occurred in a called procedure, execution resumes
with the statement immediately following the statement that last called out of the procedure containing the error-handling
routine (or On Error Resume Next statement).
line
Optional. Execution resumes at the line specified in the required line argument. The line argument is a line label or line
number and must be in the same procedure as the error handler.
Remarks
If you use a Resume statement anywhere other than in an error-handling routine, an error occurs.
The Resume statement cannot be used in any procedure that contains a Try...Catch...Finally statement.
Example
This example uses the Resume statement to end error handling in a procedure and then resume execution with the statement
that caused the error. Error number 55 is generated to illustrate use of the Resume statement.
VB
Sub ResumeStatementDemo()
On Error GoTo ErrorHandler ' Enable error-handling routine.
Dim x As Integer = 32
Dim y As Integer = 0
Dim z As Integer
z = x / y ' Creates a divide by zero error
Exit Sub ' Exit Sub to avoid error handler.
ErrorHandler: ' Error-handling routine.
Select Case Err.Number ' Evaluate error number.
Case 6 ' "Divide by zero" error.
y = 1 ' Sets the value of y to 1 and tries the calculation again.
Case Else
' Handle other situations here....
End Select
Resume ' Resume execution at same line
' that caused the error.
End Sub

Requirements
Namespace: Microsoft.VisualBasic
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Reference
Try...Catch...Finally Statement (Visual Basic)
Error Statement
On Error Statement (Visual Basic)
Visual Basic Language Reference

Return Statement (Visual Basic)


Returns control to the code that called a Function, Sub, Get, Set, or Operator procedure.

Return
-or-
Return expression

Part
expression
Required in a Function, Get, or Operator procedure. Expression that represents the value to be returned to the calling code.
Remarks
In a Sub or Set procedure, the Return statement is equivalent to an Exit Sub or Exit Property statement, and expression must
not be supplied.
In a Function, Get, or Operator procedure, the Return statement must include expression, and expression must evaluate to a
data type that is convertible to the return type of the procedure. In a Function or Get procedure, you also have the alternative
of assigning an expression to the procedure name to serve as the return value, and then executing an Exit Function or Exit
Property statement. In an Operator procedure, you must use Return expression.
You can include as many Return statements as appropriate in the same procedure.
Note
The code in a Finally block is run after a Return statement in a Try or Catch block is encountered, but before that Return st
atement is executed. In this situation, a Return statement in the Finally block is executed before the initial Return statement,
allowing for a different return value. To avoid this potentially confusing situation, avoid using Return statements in Finally b
locks.

Example
The following example uses the Return statement several times to return to the calling code when the procedure does not
need to do anything else.
VB
Public Function getAgePhrase(ByVal age As Integer) As String
If age > 60 Then Return "Senior"
If age > 40 Then Return "Middle-aged"
If age > 20 Then Return "Adult"
If age > 12 Then Return "Teen-aged"
If age > 4 Then Return "School-aged"
If age > 1 Then Return "Toddler"
Return "Infant"
End Function

See Also
Reference
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
Get Statement
Set Statement (Visual Basic)
Operator Statement
Property Statement
Exit Statement (Visual Basic)
Try...Catch...Finally Statement (Visual Basic)
Visual Basic Language Reference

Select...Case Statement (Visual Basic)


Runs one of several groups of statements, depending on the value of an expression.

Select [ Case ] testexpression


[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select

Parts
testexpression
Required. Expression. Must evaluate to one of the elementary data types (Boolean, Byte, Char, Date, Double, Decimal,
Integer, Long, Object, SByte, Short, Single, String, UInteger, ULong, and UShort).
expressionlist
Required in a Case statement. List of expression clauses representing match values for testexpression. Multiple expression
clauses are separated by commas. Each clause can take one of the following forms:
expression1 To expression2
[ Is ] comparisonoperator expression
expression
Use the To keyword to specify the boundaries of a range of match values for testexpression. The value of expression1 must
be less than or equal to the value of expression2.
Use the Is keyword with a comparison operator (=, <>, <, <=, >, or >=) to specify a restriction on the match values for
testexpression. If the Is keyword is not supplied, it is automatically inserted before comparisonoperator.
The form specifying only expression is treated as a special case of the Is form where comparisonoperator is the equal sign
(=). This form is evaluated as testexpression = expression.
The expressions in expressionlist can be of any data type, provided they are implicitly convertible to the type of testexpression
and the appropriate comparisonoperator is valid for the two types it is being used with.
statements
Optional. One or more statements following Case that run if testexpression matches any clause in expressionlist.
elsestatements
Optional. One or more statements following Case Else that run if testexpression does not match any clause in the
expressionlist of any of the Case statements.
End Select
Terminates the definition of the Select...Case construction.
Remarks
If testexpression matches any Case expressionlist clause, the statements following that Case statement run up to the next Case,
Case Else, or End Select statement. Control then passes to the statement following End Select. If testexpression matches an
expressionlist clause in more than one Case clause, only the statements following the first match run.
The Case Else statement is used to introduce the elsestatements to run if no match is found between the testexpression and an
expressionlist clause in any of the other Case statements. Although not required, it is a good idea to have a Case Else
statement in your Select Case construction to handle unforeseen testexpression values. If no Case expressionlist clause
matches testexpression and there is no Case Else statement, control passes to the statement following End Select.
You can use multiple expressions or ranges in each Case clause. For example, the following line is valid.
Case 1 To 4, 7 To 9, 11, 13, Is > maxNumber
Note
The Is keyword used in the Case and Case Else statements is not the same as the Is Operator (Visual Basic), which is used for
object reference comparison.

You can specify ranges and multiple expressions for character strings. In the following example, Case matches any string that
is exactly equal to "apples", has a value between "nuts" and "soup" in alphabetical order, or contains the exact same value as
the current value of testItem.
Case "apples", "nuts" To "soup", testItem

The setting of Option Compare can affect string comparisons. Under Option Compare Text, the strings "Apples" and
"apples" compare as equal, but under Option Compare Binary, they do not.
Note
A Case statement with multiple clauses can exhibit behavior known as short-circuiting. Visual Basic evaluates the clauses fro
m left to right, and if one produces a match with testexpression, the remaining clauses are not evaluated. Short-circuiting can
improve performance, but it can produce unexpected results if you are expecting every expression in expressionlist to be eval
uated. For more information on short-circuiting, see Boolean Expressions.

If the code within a Case or Case Else statement block does not need to run any more of the statements in the block, it can exit
the block by using the Exit Select statement. This transfers control immediately to the statement following End Select.
Select Case constructions can be nested. Each nested Select Case construction must have a matching End Select statement
and must be completely contained within a single Case or Case Else statement block of the outer Select Case construction
within which it is nested.
Example
The following example uses a Select Case construction to write a line corresponding to the value of the variable number. The
second Case statement contains the value that matches the current value of number, so the statement that writes "Between 6
and 8, inclusive" runs.
VB
Dim number As Integer = 8
Select Case number
Case 1 To 5
Debug.WriteLine("Between 1 and 5, inclusive")
' The following is the only Case clause that evaluates to True.
Case 6, 7, 8
Debug.WriteLine("Between 6 and 8, inclusive")
Case 9 To 10
Debug.WriteLine("Equal to 9 or 10")
Case Else
Debug.WriteLine("Not between 1 and 10, inclusive")
End Select

See Also
Reference
Choose Function
End Statement
If...Then...Else Statement (Visual Basic)
Option Compare Statement
Exit Statement (Visual Basic)
Visual Basic Language Reference

Set Statement (Visual Basic)


Declares a Set property procedure used to assign a value to a property.

[ <attributelist> ] [ accessmodifier ] Set (ByVal value [ As datatype ])


[ statements ]
End Set

Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional on at most one of the Get and Set statements in this property. Can be one of the following:
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
value
Required. Parameter containing the new value for the property.
datatype
Required if Option Strict is On. Data type of the value parameter. The data type specified must be the same as the data type
of the property where this Set statement is declared.
statements
Optional. One or more statements that run when the Set property procedure is called.
End Set
Required. Terminates the definition of the Set property procedure.
Remarks
Every property must have a Set property procedure unless the property is marked ReadOnly. The Set procedure is used to set
the value of the property.
Visual Basic automatically calls a property's Set procedure when an assignment statement provides a value to be stored in the
property.
Visual Basic passes a parameter to the Set procedure during property assignments. If you do not supply a parameter for Set,
the integrated development environment (IDE) uses an implicit parameter named value. The parameter holds the value to be
assigned to the property. You typically store this value in a private local variable and return it whenever the Get procedure is
called.
The body of the property declaration can contain only the property's Get and Set procedures between the Property Statement
and the End Property statement. It cannot store anything other than those procedures. In particular, it cannot store the
property's current value. You must store this value outside the property, because if you store it inside either of the property
procedures, the other property procedure cannot access it. The usual approach is to store the value in a Private (Visual Basic)
variable declared at the same level as the property. You must define a Set procedure inside the property to which it applies.
The Set procedure defaults to the access level of its containing property unless you use accessmodifier in the Set statement.
Rules
Mixed Access Levels. If you are defining a read-write property, you can optionally specify a different access level for
either the Get or the Set procedure, but not both. If you do this, the procedure access level must be more restrictive than
the property's access level. For example, if the property is declared Friend, you can declare the Set procedure Private,
but not Public.
If you are defining a WriteOnly property, the Set procedure represents the entire property. You cannot declare a
different access level for Set, because that would set two access levels for the property.
Behavior
Returning from a Property Procedure. When the Set procedure returns to the calling code, execution continues
following the statement that provided the value to be stored.
Set property procedures can return using either the Return Statement (Visual Basic) or the Exit Statement (Visual Basic).
The Exit Property and Return statements cause an immediate exit from a property procedure. Any number of Exit
Property and Return statements can appear anywhere in the procedure, and you can mix Exit Property and Return
statements.
Example
The following example uses the Set statement to set the value of a property.
VB
Class propClass
Private propVal As Integer
Property prop1() As Integer
Get
Return propVal
End Get
Set(ByVal value As Integer)
propVal = value
End Set
End Property
End Class

See Also
Tasks
How to: Add Fields and Properties to a Class
Reference
Get Statement
Property Statement
Sub Statement (Visual Basic)
Visual Basic Language Reference

Stop Statement (Visual Basic)


Suspends execution.

Stop

Remarks
You can place Stop statements anywhere in procedures to suspend execution. Using the Stop statement is similar to setting a
breakpoint in the code.
The Stop statement suspends execution, but unlike End, it does not close any files or clear any variables, unless it is
encountered in a compiled executable (.exe) file.
Note
If the Stop statement is encountered in code that is running outside of the integrated development environment (IDE), the de
bugger is invoked. This is true regardless of whether the code was compiled in debug or retail mode.

Example
This example uses the Stop statement to suspend execution for each iteration through the For...Next loop.
VB
Dim i As Integer
For i = 1 To 10
Debug.WriteLine(i)
' Stop during each iteration and wait for user to resume.
Stop
Next i

See Also
Reference
End Statement
Visual Basic Language Reference

Structure Statement
Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that the
structure comprises.

[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ Partial ] _


Structure name [ ( Of typelist ) ]
[ Implements interfacenames ]
datamemberdeclarations
[ methodmemberdeclarations ]
End Structure

Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional. Can be one of the following:
Public
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
Shadows
Optional. See Shadows.
Partial
Optional. Indicates a partial definition of the structure. See Partial (Visual Basic).
name
Required. Name of this structure. See Declared Element Names.
Of
Optional. Specifies that this is a generic structure.
typelist
Required if you use the Of keyword. List of type parameters for this structure. See Type List.
Implements
Optional. Indicates that this structure implements the members of one or more interfaces. See Implements Statement.
interfacenames
Required if you use the Implements statement. The names of the interfaces this structure implements.
datamemberdeclarations
Required. One or more Const, Dim, Enum, or Event statements declaring data members of the structure.
methodmemberdeclarations
Optional. Zero or more declarations of Function, Operator, Property, or Sub procedures, which serve as method members
of the structure.
End Structure
Required. Terminates the Structure definition.
Remarks
The Structure statement defines a composite value type that you can customize. A structure is a generalization of the user-
defined type (UDT) of previous versions of Visual Basic. For more information, see Structures: Your Own Data Types.
Structures support many of the same features as classes. For example, structures can have properties and procedures, they can
implement interfaces, and they can have parameterized constructors. However, there are significant differences between
structures and classes in areas such as inheritance, declarations, and usage. Also, classes are reference types and structures are
value types. For more information, see Structures and Classes.
You can use Structure only at namespace or module level. This means the declaration context for a structure must be a source
file, namespace, class, structure, module, or interface, and cannot be a procedure or block. For more information, see
Declaration Contexts and Default Access Levels.
Structures default to Friend (Visual Basic) access. You can adjust their access levels with the access modifiers. For more
information, see Access Levels in Visual Basic.
Rules
Nesting. You can define one structure within another. The outer structure is called the containing structure, and the
inner structure is called a nested structure. However, you cannot access a nested structure's members through the
containing structure. Instead, you must declare a variable of the nested structure's data type.
Member Declaration. You must declare every member of a structure. A structure member cannot be Protected or
Protected Friend because nothing can inherit from a structure. The structure itself, however, can be Protected or
Protected Friend.
You must declare at least one nonshared variable or nonshared, noncustom event in a structure. You cannot have only
constants, properties, and procedures, even if some of them are nonshared.
Initialization. You cannot initialize the value of any nonshared data member of a structure as part of its declaration. You
must either initialize such a data member by means of a parameterized constructor on the structure, or assign a value to
the member after you have created an instance of the structure.
Inheritance. A structure cannot inherit from any type other than ValueType, from which all structures inherit. In
particular, one structure cannot inherit from another.
You cannot use the Inherits Statement in a structure definition, even to specify ValueType.
Implementation. If the structure uses the Implements Statement, you must implement every member defined by every
interface you specify in interfacenames.
Default Property. A structure can specify at most one property as its default property, using the Default (Visual Basic)
modifier. For more information, see Default Properties.
Behavior
Access Level. Within a structure, you can declare each member with its own access level. All structure members default
to Public (Visual Basic) access. Note that if the structure itself has a more restricted access level, this automatically
restricts access to its members, even if you adjust their access levels with the access modifiers.
Scope. A structure is in scope throughout its containing namespace, class, structure, or module.
The scope of every structure member is the entire structure.
Lifetime. A structure does not itself have a lifetime. Rather, each instance of that structure has a lifetime independent of
all other instances.
The lifetime of an instance begins when it is created by a New (Visual Basic) clause. It ends when the lifetime of the
variable that holds it ends.
You cannot extend the lifetime of a structure instance. An approximation to static structure functionality is provided by a
module. For more information, see Module Statement.
Structure members have lifetimes depending on how and where they are declared. For more information, see "Lifetime"
in Class Statement (Visual Basic).
Qualification. Code outside a structure must qualify a member's name with the name of that structure.
If code inside a nested structure makes an unqualified reference to a programming element, Visual Basic searches for the
element first in the nested structure, then in its containing structure, and so on out to the outermost containing element.
For more information, see Resolving a Reference When Multiple Variables Have the Same Name.
Memory Consumption. As with all composite data types, you cannot safely calculate the total memory consumption of
a structure by adding together the nominal storage allocations of its members. Furthermore, you cannot safely assume
that the order of storage in memory is the same as your order of declaration. If you need to control the storage layout of
a structure, you can apply the StructLayoutAttribute attribute to the Structure statement.
Example
The following example uses the Structure statement to define a set of related data for an employee. It shows the use of
Public, Friend, and Private members to reflect the sensitivity of the data items. It also shows procedure, property, and event
members.
VB
Public Structure employee
' Public members, accessible from throughout declaration region.
Public firstName As String
Public middleName As String
Public lastName As String
' Friend members, accessible from anywhere within the same assembly.
Friend employeeNumber As Integer
Friend workPhone As Long
' Private members, accessible only from within the structure itself.
Private homePhone As Long
Private level As Integer
Private salary As Double
Private bonus As Double
' Procedure member, which can access structure's private members.
Friend Sub calculateBonus(ByVal rate As Single)
bonus = salary * CDbl(rate)
End Sub
' Property member to return employee's eligibility.
Friend ReadOnly Property eligible() As Boolean
Get
Return level >= 25
End Get
End Property
' Event member, raised when business phone number has changed.
Public Event changedWorkPhone(ByVal newPhone As Long)
End Structure

See Also
Reference
Class Statement (Visual Basic)
Interface Statement (Visual Basic)
Module Statement
Dim Statement (Visual Basic)
Const Statement (Visual Basic)
Enum Statement (Visual Basic)
Event Statement
Operator Statement
Property Statement
Concepts
Structures and Classes
Visual Basic Language Reference

Sub Statement (Visual Basic)


Declares the name, parameters, and code that define a Sub procedure.

[ <attributelist> ] [ accessmodifier ] [ proceduremodifiers ] [ Shared ] [ Shadows ]


Sub name [ (Of typeparamlist) ] [ (parameterlist) ] [ Implements implementslist | Handles e
ventlist ]
[ statements ]
[ Exit Sub ]
[ statements ]
End Sub

Parts
attributelist
Optional. See Attribute List.
accessmodifier
Optional. Can be one of the following:
Public
Protected
Friend
Private
Protected Friend
See Access Levels in Visual Basic.
proceduremodifiers
Optional. Can be one of the following:
Overloads
Overrides
Overridable
NotOverridable
MustOverride
MustOverride Overrides
NotOverridable Overrides
Shared
Optional. See Shared.
Shadows
Optional. See Shadows.
name
Required. Name of the procedure. See Declared Element Names.
typeparamlist
Optional. List of type parameters for a generic procedure. See Type List.
parameterlist
Optional. List of local variable names representing the parameters of this procedure. See Parameter List.
Implements
Optional. Indicates that this procedure implements one or more Sub procedures, each one defined in an interface
implemented by this procedure's containing class or structure. See Implements Statement.
implementslist
Required if Implements is supplied. List of Sub procedures being implemented.
implementedprocedure [ , implementedprocedure ... ]

Each implementedprocedure has the following syntax and parts:


interface.definedname

Part Description
interface Required. Name of an interface implemented by this procedure's containing class or structure.

definedname Required. Name by which the procedure is defined in interface.

Handles
Optional. Indicates that this procedure can handle one or more specific events. See Handles.
eventlist
Required if Handles is supplied. List of events this procedure handles.
eventspecifier [ , eventspecifier ... ]

Each eventspecifier has the following syntax and parts:


eventvariable.event

Part Description
eventvariable Required. Object variable declared with the data type of the class or structure that raises the event.

event Required. Name of the event this procedure handles.

statements
Optional. Block of statements to run within this procedure.
End Sub
Terminates the definition of this procedure.
Remarks
All executable code must be inside a procedure. Use a Sub procedure when you do not need to return a value to the calling
code. Use a Function procedure when you need to return a value.
You can use Sub only at module level. This means the declaration context for a sub procedure must be a class, structure,
module, or interface, and cannot be a source file, namespace, procedure, or block. For more information, see
Declaration Contexts and Default Access Levels.
Sub procedures default to public access. You can adjust their access levels with the access modifiers.
Rules
Implementation. If this procedure uses the Implements keyword, the containing class or structure must have an
Implements statement immediately following its Class or Structure statement. The Implements statement must
include each interface specified in implementslist. However, the name by which an interface defines the Sub (in
definedname) does not have to be the same as the name of this procedure (in name).
Behavior
Returning from a Procedure. When the Sub procedure returns to the calling code, execution continues with the
statement following the statement that called it.
The Exit Sub and Return statements cause an immediate exit from a Sub procedure. Any number of Exit Sub and
Return statements can appear anywhere in the procedure, and you can mix Exit Sub and Return statements.
The following example shows a return from a Sub procedure.

Sub mySub(ByVal q As String)


Return
End Sub

Calling a Procedure. A Sub procedure, like a Function procedure, is a separate procedure that can take parameters
and perform a series of statements. However, unlike a Function procedure, which returns a value, a Sub procedure
cannot be used in an expression.
You call a Sub procedure by using the procedure name, followed by the argument list in parentheses, in a statement. You
can omit the parentheses only if you are not supplying any arguments. However, your code is more readable if you
always include the parentheses.
You can optionally use the Call statement to call a Sub procedure. This can improve the readability of your code.
Troubleshooting
Order of Execution. Visual Basic sometimes rearranges arithmetic expressions to increase internal efficiency. For that reason,
if your argument list includes expressions that call other procedures, you cannot rely on them being called in any particular
order.
Example
The following example uses the Sub statement to define the name, parameters, and code that form the body of a Sub
procedure.
VB
Sub computeArea(ByVal length As Double, ByVal width As Double)
' Declare local variable.
Dim area As Double
If length = 0 Or width = 0 Then
' If either argument = 0 then exit Sub immediately.
Exit Sub
End If
' Calculate area of rectangle.
area = length * width
' Print area to Immediate window.
Debug.WriteLine(area)
End Sub

See Also
Tasks
How to: Use a Generic Class
Troubleshooting Procedures
Reference
Implements Statement
Function Statement (Visual Basic)
Parameter List
Dim Statement (Visual Basic)
Call Statement (Visual Basic)
Of
Concepts
Parameter Arrays
Visual Basic Language Reference

SyncLock Statement
Acquires an exclusive lock for a statement block before executing the block.

SyncLock lockobject
[ block ]
End SyncLock

Parts
lockobject
Required. Expression that evaluates to an object reference.
block
Optional. Block of statements that are to execute when the lock is acquired.
End SyncLock
Terminates a SyncLock block.
Remarks
The SyncLock statement ensures that multiple threads do not execute the statement block at the same time. SyncLock
prevents each thread from entering the block until no other thread is executing it.
The most common use of SyncLock is to protect data from being updated by more than one thread simultaneously. If the
statements that manipulate the data must go to completion without interruption, put them inside a SyncLock block.
A statement block protected by an exclusive lock is sometimes called a critical section.
Rules
Branching. You cannot branch into a SyncLock block from outside the block.
Lock Object Value. The value of lockobject cannot be Nothing. You must create the lock object before you use it in a
SyncLock statement.
You cannot change the value of lockobject while executing a SyncLock block. The mechanism requires that the lock
object remain unchanged.
Behavior
Mechanism. When a thread reaches the SyncLock statement, it evaluates the lockobject expression and suspends
execution until it acquires an exclusive lock on the object returned by the expression. When another thread reaches the
SyncLock statement, it does not acquire a lock until the first thread executes the End SyncLock statement.
Protected Data. If lockobject is a Shared variable, the exclusive lock prevents a thread in any instance of the class from
executing the SyncLock block while any other thread is executing it. This protects data that is shared among all the
instances.
If lockobject is an instance variable (not Shared), the lock prevents a thread running in the current instance from
executing the SyncLock block at the same time as another thread in the same instance. This protects data maintained by
the individual instance.
Acquisition and Release. A SyncLock block behaves like a Try...Finally construction in which the Try block acquires an
exclusive lock on lockobject and the Finally block releases it. Because of this, the SyncLock block guarantees release of
the lock, no matter how you exit the block. This is true even in the case of an unhandled exception.
Framework Calls. The SyncLock block acquires and releases the exclusive lock by calling the Enter and Exit methods of
the Monitor class in the System.Threading namespace.
Programming Practices
The lockobject expression should always evaluate to an object that belongs exclusively to your class. You should declare a
Private object variable to protect data belonging to the current instance, or a Private Shared object variable to protect data
common to all instances.
You should not use the Me keyword to provide a lock object for instance data. If code external to your class has a reference to
an instance of your class, it could use that reference as a lock object for a SyncLock block completely different from yours,
protecting different data. In this way, your class and the other class could block each other from executing their unrelated
SyncLock blocks. Similarly locking on a string can be problematic since any other code in the process using the same string
will share the same lock.
You should also not use the Me.GetType method to provide a lock object for shared data. This is because GetType always
returns the same Type object for a given class name. External code could call GetType on your class and obtain the same lock
object you are using. This would result in the two classes blocking each other from their SyncLock blocks.
Example
The following example shows a class that maintains a simple list of messages. It holds the messages in an array and the last
used element of that array in a variable. The addAnotherMessage procedure increments the last element and stores the new
message. Those two operations are protected by the SyncLock and End SyncLock statements, because once the last element
has been incremented, the new message must be stored before any other thread can increment the last element again.
VB
Class simpleMessageList
Public messagesList() As String = New String(50) {}
Public messagesLast As Integer = -1
Private messagesLock As New Object
Public Sub addAnotherMessage(ByVal newMessage As String)
SyncLock messagesLock
messagesLast += 1
messagesList(messagesLast) = newMessage
End SyncLock
End Sub
End Class

If the simpleMessageList class shared one list of messages among all its instances, then the variables messagesList and
messagesLast would be declared as Shared. In this case, the variable messagesLock should also be Shared, so that there would
be a single lock object used by every instance.
See Also
Reference
System.Threading
Monitor
Concepts
Thread Synchronization
Other Resources
Multithreading in Visual Basic
Visual Basic Language Reference

Throw Statement (Visual Basic)


Throws an exception within a procedure.

Throw [ expression ]

Part
expression
Provides information about the exception to be thrown. Optional when residing in a Catch statement, otherwise required.
Remarks
The Throw statement throws an exception that you can handle with structured exception-handling code (Try...Catch...Finally)
or unstructured exception-handling code (On Error GoTo). You can use the Throw statement to trap errors within your code
because Visual Basic moves up the call stack until it finds the appropriate exception-handling code.
A Throw statement with no expression can only be used in a Catch statement, in which case the statement rethrows the
exception currently being handled by the Catch statement.
The Throw statement resets the call stack for the expression exception. If expression is not provided, the call stack is left
unchanged. You can access the call stack for the exception through the StackTrace property.
Example
The following code uses the Throw statement to throw an exception:
VB
' Throws a new exception.
Throw New System.Exception("An exception has occurred.")

Requirements
Namespace: Microsoft.VisualBasic
Module: Interaction
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
See Also
Tasks
How to: Check an Exception's Inner Exception
Reference
Try...Catch...Finally Statement (Visual Basic)
On Error Statement (Visual Basic)
Concepts
Structured Exception Handling Overview for Visual Basic
Unstructured Exception Handling Overview
Visual Basic Language Reference

Try...Catch...Finally Statement (Visual Basic)


Provides a way to handle some or all possible errors that may occur in a given block of code, while still running code.

Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try

Parts
tryStatements
Optional. Statement(s) where an error can occur. Can be a compound statement.
Catch
Optional. Multiple Catch blocks permitted. If an exception occurs while processing the Try block, each Catch statement is
examined in textual order to determine if it handles the exception, with exception representing the exception that has been
thrown.
exception
Optional. Any variable name. The initial value of exception is the value of the thrown error. Used with Catch to specify the
error caught. If omitted, the Catch statement catches any exception.
type
Optional. Specifies the type of class filter. If the value of exception is of the type specified by type or of a derived type, the
identifier becomes bound to the exception object.
When
Optional. A Catch statement with a When clause catches exceptions only when expression evaluates to True. A When clause
is applied only after checking the type of the exception, and expression may refer to the identifier representing the exception.
expression
Optional. Must be implicitly convertible to Boolean. Any expression that describes a generic filter. Typically used to filter by
error number. Used with When keyword to specify circumstances under which the error is caught.
catchStatements
Optional. Statement(s) to handle errors occurring in the associated Try block. Can be a compound statement.
Exit Try
Optional. Keyword that breaks out of the Try...Catch...Finally structure. Execution resumes with the code immediately
following the End Try statement. The Finally statement will still be executed. Not allowed in Finally blocks.
Finally
Optional. A Finally block is always executed when execution leaves any part of the Try statement.
finallyStatements
Optional. Statement(s) that are executed after all other error processing has occurred.
End Try
Terminates the Try...Catch...Finally structure.
Remarks
Local variables from a Try block are not available in a Catch block because they are separate blocks. If you want to use a
variable in more than one block, declare the variable outside the Try...Catch...Finally structure.
The Try block contains code where an error can occur, while the Catch block contains code to handle any error that does
occur. If an error occurs in the Try block, program control is passed to the appropriate Catch statement for disposition. The
exception argument is an instance of the Exception class or a class that derives from the Exception class. The Exception
class instance corresponds to the error that occurred in the Try block. The instance contains information about the error,
including, among other things, its number and message.
If a Catch statement does not specify an exception argument, it catches any kind of system or application exception. You
should always use this variation as the last Catch block in the Try...Catch...Finally structure, after catching all the specific
exceptions you anticipate. Control flow can never reach a Catch block that follows a Catch without an exception argument.
In partial-trust situations, such as an application hosted on a network share, Try...Catch...Finally does not catch security
exceptions that occur before the method containing the call is invoked. The following example, when placed on a server share
and run from there, produces the error "System.Security.SecurityException: Request Failed." For more information on security
exceptions, see the SecurityException class.
VB
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
Try
Process.Start("http://www.microsoft.com")
Catch ex As Exception
MsgBox("Can't load Web page" & vbCrLf & ex.Message)
End Try
End Sub

In such a partial-trust situation, you need to put the Process.Start statement in a separate Sub. The initial call to the Sub will
fail, allowing Try...Catch to catch it before the Sub containing Process.Start is launched and the security exception produced.
Note
If a Try statement does not contain at least one Catch block, it must contain a Finally block.

Example
The following simplified example illustrates the structure of the Try...Catch...Finally statement.
VB
Public Sub TryExample()
Dim x As Integer = 5 ' Declare variables.
Dim y As Integer = 0
Try ' Set up structured error handling.
x = x \ y ' Cause a "Divide by Zero" error.
Catch ex As Exception When y = 0 ' Catch the error.
Beep()
MsgBox("You tried to divide by 0.") ' Show an explanatory message.
Finally
Beep() ' This line is executed no matter what.
End Try
End Sub

See Also
Reference
End Statement
Err Object (Visual Basic)
Exit Statement (Visual Basic)
On Error Statement (Visual Basic)
GoTo Statement
Exception
Visual Basic Language Reference

Using Statement (Visual Basic)


Declares the beginning of a Using block and optionally acquires the system resources that the block controls.

Using { resourcelist | resourceexpression }


[ statements ]
End Using

Parts
resourcelist
Required if you do not supply resourceexpression. List of one or more system resources that this Using block controls.
resourceexpression
Required if you do not supply resourcelist. Reference variable or expression referring to a system resource to be controlled
by this Using block.
statements
Optional. Block of statements that the Using block runs.
End Using
Required. Terminates the definition of the Using block and disposes of all the resources that it controls.
Each resource in the resourcelist part has the following syntax and parts:
resourcename As New resourcetype [ ( [ arglist ] ) ]

-or-
resourcename As resourcetype = resourceexpression

resourcelist Parts
resourcename
Required. Reference variable that refers to a system resource that the Using block controls.
New
Required if the Using statement acquires the resource. If you have already acquired the resource, use the second syntax
alternative.
resourcetype
Required. The class of the resource. The class must implement the IDisposable interface.
arglist
Optional. List of arguments you are passing to the constructor to create an instance of resourcetype. See Parameter List.
resourceexpression
Required. Variable or expression referring to a system resource satisfying the requirements of resourcetype. If you use the
second syntax alternative, you must acquire the resource before passing control to the Using statement.
Remarks
Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using
block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available
for other code to use.
Managed resources are disposed of by the .NET Framework garbage collector (GC) without any extra coding on your part. You
do not need a Using block for managed resources.
A Using block has three parts: acquisition, usage, and disposal.
Acquisition means creating a variable and initializing it to refer to the system resource. The Using statement can acquire
one or more resources, or you can acquire exactly one resource before entering the block and supply it to the Using
statement. If you supply resourceexpression, you must acquire the resource before passing control to the Using
statement.
Usage means accessing the resources and performing actions with them. The statements between Using and End Using
represent the usage of the resources.
Disposal means calling the Dispose method on the object in resourcename. This allows the object to cleanly terminate its
unmanaged resource. The End Using statement disposes of the resources under the Using block's control.
Behavior
A Using block behaves like a Try...Finally construction in which the Try block uses the resources and the Finally block
disposes of them. Because of this, the Using block guarantees disposal of the resources, no matter how you exit the block. This
is true even in the case of an unhandled exception, except for a StackOverflowException.
The scope of every resource variable acquired by the Using statement is limited to the Using block.
If you specify more than one system resource in the Using statement, the effect is the same as if you nested Using blocks one
within another.
Structured Exception Handling Within a Using Block
If you need to handle an exception that might occur within the Using block, you can add a complete Try...Finally construction
to it. If you need to handle the case where the Using statement is not successful in acquiring a resource, you can test to see if
resourcename is Nothing.
Structured Exception Handling Instead of a Using Block
If you need finer control over the acquisition of the resources, or you need additional code in the Finally block, you can rewrite
the Using block as a Try...Finally construction. The following example shows skeleton Try and Using constructions that are
equivalent in the acquisition and disposal of resource.

Using resource As New resourceType


' Insert code to work with resource.
End Using
' THE FOLLOWING TRY CONSTRUCTION IS EQUIVALENT TO THE USING BLOCK
Dim resource As New resourceType
Try
' Insert code to work with resource.
Catch ex As Exception
' Insert code to process exception.
Finally
' Insert code to do additional processing before disposing of resource.
resource.Dispose()
End Try

Note
The code inside the Using block should not assign the object in resourcename to another variable. When you exit the Using
block, the resource is disposed, and the other variable cannot access the resource to which it points.

Example
The following example uses a Using block to acquire a new font. This guarantees that the system calls the Dispose method on
the font when your code exits the block.
VB
Public Sub setbigbold(ByVal c As Control)
Using nf As New System.Drawing.Font("Arial", 12.0F, _
System.Drawing.FontStyle.Bold)
c.Font = nf
c.Text = "This is 12-point Arial bold"
End Using
End Sub
See Also
Tasks
How to: Dispose of a System Resource
Reference
Try...Catch...Finally Statement (Visual Basic)
IDisposable
System.Drawing
Font
Visual Basic Language Reference

While...End While Statement (Visual Basic)


Runs a series of statements as long as a given condition is True.

While condition
[ statements ]
[ Exit While ]
[ statements ]
End While

Parts
condition
Required. Boolean expression. If condition is Nothing, Visual Basic treats it as False.
statements
Optional. One or more statements following While, which run every time condition is True.
Exit While
Optional. Transfers control out of the While block.
End While
Required. Terminates the definition of the While block.
Remarks
Use a While...End While structure when you want to repeat a set of statements an indefinite number of times, as long as a
condition remains True. If you want more flexibility with where you test the condition or what result you test it for, you might
prefer the Do...Loop Statement (Visual Basic). If you want to repeat the statements a set number of times, the
For...Next Statement (Visual Basic) is usually a better choice.
If condition is True, all of the statements run until the End While statement is encountered. Control then returns to the While
statement and condition is again checked. If condition is still True, the process is repeated. If it is False, control passes to the
statement following the End While statement.
Rules
Nature of Condition. The condition usually results from a comparison of two values, but it can be any expression that
evaluates to a Boolean Data Type (Visual Basic) value (True or False). This includes values of other data types, such as
numeric types, that have been converted to Boolean.
Testing the Condition. The While statement always checks the condition before it begins the loop. Looping continues
while the condition remains True.
Number of Iterations. If condition is False when you first enter the loop, it does not run even once.
Nesting Loops. You can nest While loops by placing one loop within another. You can also nest different kinds of
control structures within one another. For more information, see Nested Control Structures.
Transferring Out of the Loop. The Exit Statement (Visual Basic) transfers control immediately to the statement
following the End While statement. You might want to exit a loop if you detect a condition that makes it unnecessary or
impossible to continue iterating, such as an erroneous value or a termination request. You can place any number of Exit
While statements anywhere in the While loop. Exit While is often used after evaluating some condition, for example in
an If...Then...Else structure.
Endless Loops. One use of Exit While is to test for a condition that could cause an endless loop, which is a loop that
could run an extremely large or even infinite number of times. If you detect such a condition, you can use Exit While to
escape the loop. For more information, see Do...Loop Statement (Visual Basic).
Example
This example uses the While...End While structure to increment a counter variable. The statements in the loop run as long as
the condition evaluates to True.
VB
Dim counter As Integer = 0
While counter < 20
counter += 1
' Insert code to use current value of counter.
End While
MsgBox("While loop ran " & CStr(counter) & " times")

See Also
Reference
Do...Loop Statement (Visual Basic)
For...Next Statement (Visual Basic)
Boolean Data Type (Visual Basic)
Exit Statement (Visual Basic)
Concepts
Loop Structures
Nested Control Structures
Visual Basic Language Reference

With...End With Statement (Visual Basic)


Executes a series of statements making repeated reference to a single object or structure.

With object
[ statements ]
End With

Parts
object
Required. Variable or expression. Can evaluate to any data type, including elementary types.
statements
Optional. One or more statements between With and End With that run on object.
End With
Required. Terminates the definition of the With block.
Remarks
With...End With allows you to perform a series of statements on a specified object without requalifying the name of the
object. If the qualification path to the object is long, using With...End With can improve your performance. A With block also
reduces repetitive typing of the qualification path and the risk of mistyping one of its elements.
For example, to change a number of different properties on a single object, place the property assignment statements inside
the With...End With, referring to the object only once instead of for each property assignment.
Rules
Data Types. The data type of object can be any class or structure type, or even a Visual Basic elementary type such as
Integer. The .NET Framework supports all elementary types with classes or structures, which have members you can
access inside a With block.
Declaration. You must declare object before you enter the With block. You cannot declare it in the With statement.
Number of Iterations. A With block is not an iterative construction. Unless there is a loop inside the block, the
statements run only once.
Nesting Structures. You can nest With...End With structures by placing one structure within another. For an example,
see How to: Perform Multiple Actions on an Object.
However, because members of outer statements are masked inside the inner statements, you must provide a fully
qualified object reference in an inner With block to any member of an object in an outer With block.
You can also nest different kinds of control structures within one another. For more information, see
Nested Control Structures.
Transferring Out of the Structure. Visual Basic does not support the Exit Statement (Visual Basic) to transfer control
out of a With block. If you need to exit before all the statements have been executed, put a label on the End With
statement and use the GoTo Statement to branch to it. For more information, see How to: Label Statements.
You cannot transfer control either from outside a With block to inside it, or from inside it to the outside. You can call a
procedure from inside the block, but control returns to the following statement.
Accessing Other Objects. Once you have entered a With block, you cannot reassign object until you have passed the
End With statement. Therefore, you can access the methods and properties of only the specified object without
qualifying them. You can use methods and properties of other objects, but you must qualify them with their object
names.
Example
The following example uses a With block to execute a series of statements on a single object. The example assumes that object
testObject has already been created and exposes the referenced properties.
VB
With testObject
.Height = 100
.Text = "Hello, World"
.ForeColor = System.Drawing.Color.Green
.Font = New System.Drawing.Font(.Font, _
System.Drawing.FontStyle.Bold)
End With

See Also
Tasks
How to: Perform Multiple Actions on an Object
How to: Label Statements
Reference
Exit Statement (Visual Basic)
GoTo Statement
Concepts
Nested Control Structures
Visual Basic Language Reference

Declaration Contexts and Default Access Levels


This topic describes which Visual Basic types can be declared within which other types, and what their access levels default to if
not specified.
Declaration Context Levels
The declaration context of a programming element is the region of code in which it is declared. This is often another
programming element, which is then called the containing element.
The levels for declaration contexts are the following:
Namespace level — within a source file or namespace but not within a class, structure, module, or interface
Module level — within a class, structure, module, or interface but not within a procedure or block
Procedure level — within a procedure or block (such as If or For)
The following table shows the default access levels for various declared programming elements, depending on their
declaration contexts.
Declared element Namespace Module level Procedure l
level evel
Variable (Dim Statement (Visual Basic)) Not allowed Private (Public in Structure, not allowe Public
d in Interface)

Constant (Const Statement (Visual Basic)) Not allowed Private (Public in Structure, not allowe Public
d in Interface)

Enumeration (Enum Statement (Visual Basic)) Friend Public Not allowed

Class (Class Statement (Visual Basic)) Friend Public Not allowed

Structure (Structure Statement) Friend Public Not allowed

Module (Module Statement) Friend Not allowed Not allowed

Interface (Interface Statement (Visual Basic)) Friend Public Not allowed

Procedure (Function Statement (Visual Basic), Not allowed Public Not allowed
Sub Statement (Visual Basic))

External reference (Declare Statement) Not allowed Public (not allowed in Interface) Not allowed

Operator (Operator Statement) Not allowed Public (not allowed in Interface or Mod Not allowed
ule)

Property (Property Statement) Not allowed Public Not allowed

Default property (Default (Visual Basic)) Not allowed Public (not allowed in Module) Not allowed

Event (Event Statement) Not allowed Public Not allowed

Delegate (Delegate Statement) Friend Public Not allowed

For more information, see Access Levels in Visual Basic.


See Also
Reference
Friend (Visual Basic)
Private (Visual Basic)
Public (Visual Basic)
Visual Basic Language Reference

Attribute List
Specifies the attributes to be applied to a declared programming element. Multiple attributes are separated by commas.
Following is the syntax for one attribute.

[ attributemodifier ] attributename [ ( attributearguments | attributeinitializer ) ]

Parts
attributemodifier
Required for attributes applied at the beginning of a source file. Can be Assembly or Module.
attributename
Required. Name of the attribute.
attributearguments
Optional. List of positional arguments for this attribute. Multiple arguments are separated by commas.
attributeinitializer
Optional. List of variable or property initializers for this attribute. Multiple initializers are separated by commas.
Remarks
You can apply one or more attributes to nearly any programming element (types, procedures, properties, and so forth).
Attributes appear in your assembly's metadata, and they can help you annotate your code or specify how to use a particular
programming element. You can apply attributes defined by Visual Basic and the .NET Framework, and you can define your own
attributes.
For more information on when to use attributes, see Attributes in Visual Basic and Common Uses for Attributes. For
information on attribute names, see Declared Element Names.
Rules
Placement. You can apply attributes to most declared programming elements. To apply one or more attributes, you
place an attribute block at the beginning of the element declaration. Each entry in the attribute list specifies an attribute
you wish to apply, and the modifier and arguments you are using for this invocation of the attribute.
Angle Brackets. If you supply an attribute list, you must enclose it in angle brackets ("<" and ">").
Part of the Declaration. The attribute must be part of the element declaration, not a separate statement. You can use
the line-continuation sequence (" _") to extend the declaration statement onto multiple source-code lines.
Modifiers. An attribute modifier (Assembly or Module) is required on every attribute applied to a programming
element at the beginning of a source file. Attribute modifiers are not allowed on attributes applied to elements that are
not at the beginning of a source file.
Arguments. All positional arguments for an attribute must precede any variable or property initializers.
Example
The following example applies the DllImportAttribute attribute to a skeleton definition of a Function procedure.
VB
<DllImportAttribute("kernel32.dll", EntryPoint:="MoveFileW", _
SetLastError:=True, CharSet:=CharSet.Unicode, _
ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function moveFile(ByVal src As String, _
ByVal dst As String) As Boolean
' This function copies a file from the path src to the path dst.
' Leave this function empty. The DLLImport attribute forces calls
' to moveFile to be forwarded to MoveFileW in KERNEL32.DLL.
End Function
DllImportAttribute indicates that the attributed procedure represents an entry point in an unmanaged dynamic-link library
(DLL). The attribute supplies the DLL name as a positional argument and the other information as variable initializers.
See Also
Tasks
How to: Break and Combine Statements in Code
Reference
Assembly
Module (Visual Basic)
Concepts
Common Uses for Attributes
Application of Attributes
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

Parameter List
Specifies the parameters a procedure expects when it is called. Multiple parameters are separated by commas. Following is the
syntax for one parameter.

[ <attributelist> ] [ Optional ] [{ ByVal | ByRef }] [ ParamArray ]


parametername[( )] [ As parametertype ] [ = defaultvalue ]

Parts
attributelist
Optional. List of attributes that apply to this parameter. You must enclose the Attribute List in angle brackets ("<" and ">").
Optional
Optional. Specifies that this parameter is not required when the procedure is called.
ByVal
Optional. Specifies that the procedure cannot replace or reassign the variable element underlying the corresponding
argument in the calling code.
ByRef
Optional. Specifies that the procedure can modify the underlying variable element in the calling code the same way the
calling code itself can.
ParamArray
Optional. Specifies that the last parameter in the parameter list is an optional array of elements of the specified data type.
This allows the calling code to pass an arbitrary number of arguments to the procedure.
parametername
Required. Name of the local variable representing the parameter.
parametertype
Required if Option Strict is On. Data type of the local variable representing the parameter.
defaultvalue
Required for Optional parameters. Any constant or constant expression that evaluates to the data type of the parameter. If
the type is Object, or a class, interface, array, or structure, the default value can only be Nothing.
Remarks
Parameters are surrounded by parentheses and separated by commas. A parameter can be declared with any data type. If you
do not specify parametertype, it defaults to Object.
When the calling code calls the procedure, it passes an argument to each required parameter. For more information, see
Differences Between Parameters and Arguments.
The argument the calling code passes to each parameter is a pointer to an underlying element in the calling code. If this
element is nonvariable (a constant, literal, enumeration, or expression), it is not possible for any code to change it. If it is a
variable element (a declared variable, field, property, array element, or structure element), the calling code can change it. For
more information, see Differences Between Modifiable and Nonmodifiable Arguments.
If a variable element is passed ByRef, the procedure can change it as well. For more information, see
Differences Between Passing an Argument By Value and By Reference.
Rules
Parentheses. If you specify a parameter list, you must enclose it in parentheses. If there are no parameters, you can still
use parentheses enclosing an empty list. This improves the readability of your code by clarifying that the element is a
procedure.
Optional Parameters. If you use the Optional modifier on a parameter, all subsequent parameters in the list must also
be optional and be declared using the Optional modifier.
Every optional parameter declaration must supply the defaultvalue clause.
Parameter Arrays. You must specify ByVal for a ParamArray parameter.
You cannot use both Optional and ParamArray in the same parameter list.
Passing Mechanism. The default mechanism for every argument is ByVal, which means the procedure cannot change
the underlying variable element. However, if the element is a reference type, the procedure can modify the contents or
members of the underlying object, even though it cannot replace or reassign the object itself.
Parameter Names. If the parameter's data type is an array, follow parametername immediately by parentheses. For
more information on parameter names, see Declared Element Names.
Example
The following example shows a Function procedure that defines two parameters.
VB
Public Function howMany(ByVal ch As Char, ByVal st As String) As Integer
End Function
Dim howManyA As Integer = howMany("a"c, "How many a's in this string?")

See Also
Tasks
How to: Break and Combine Statements in Code
Reference
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
Declare Statement
Structure Statement
Option Strict Statement
DllImportAttribute
Concepts
Application of Attributes
Other Resources
Attributes in Visual Basic
Visual Basic Language Reference

Type List
Specifies the type parameters for a generic programming element. Multiple parameters are separated by commas. Following is
the syntax for one type parameter.

typename [ As constraintlist ]

Parts
typename
Required. Name of the type parameter. This is a placeholder, to be replaced by a defined type supplied by the corresponding
type argument.
constraintlist
Optional. List of requirements that constrain the data type that can be supplied for typename. If you have multiple
constraints, enclose them in curly braces ({ }) and separate them with commas. You must introduce the constraint list with
the As keyword. You use As only once, at the beginning of the list.
Remarks
Every generic programming element must take at least one type parameter. A type parameter is a placeholder for a specific
type (a constructed element) that client code specifies when it creates an instance of the generic type. You can define a generic
class, structure, interface, procedure, or delegate.
For more information on when to define a generic type, see Generic Types in Visual Basic. For more information on type
parameter names, see Declared Element Names.
Rules
Parentheses. If you supply a type parameter list, you must enclose it in parentheses, and you must introduce the list
with the Of keyword. You use Of only once, at the beginning of the list.
Constraints. A list of constraints on a type parameter can include the following items in any combination:
Any number of interfaces. The supplied type must implement every interface in this list.
At most one class. The supplied type must inherit from that class.
The New (Visual Basic) keyword. The supplied type must expose a parameterless constructor that your generic
type can access. This is useful if you constrain a type parameter by one or more interfaces. A type that
implements interfaces does not necessarily expose a constructor, and depending on the access level of a
constructor, the code within the generic type might not be able to access it.
Either the Class (Visual Basic) keyword or the Structure (Visual Basic) keyword. If you include Class, the supplied
type must be a reference type. If you include Structure, the supplied type must be a value type. You cannot
include both Class and Structure in the same constraintlist.
The supplied type must satisfy every requirement you include in constraintlist.
Constraints on each type parameter are independent of constraints on other type parameters.
Behavior
Compile-Time Substitution. When you create a constructed type from a generic programming element, you supply a
defined type for each type parameter. The Visual Basic compiler substitutes that supplied type for every occurrence of
typename within the generic element.
Absence of Constraints. If you do not specify any constraints on a type parameter, your code is limited to the
operations and members supported by the Object Data Type for that type parameter.
Example
The following example shows a skeleton definition of a generic dictionary class, including a skeleton function to add a new
entry to the dictionary.
VB
Public Class dictionary(Of entryType, keyType As {IComparable, IFormattable, New})
Public Sub add(ByVal et As entryType, ByVal kt As keyType)
Dim dk As keyType
If kt.CompareTo(dk) = 0 Then
End If
End Sub
End Class

Because dictionary is generic, the code that uses it can create a variety of objects from it, each having the same functionality
but acting on a different data type. The following example shows a line of code that creates a dictionary object with String
entries and Integer keys.
VB
Dim dictInt As New dictionary(Of String, Integer)

The following example shows the equivalent skeleton definition generated by the preceding example.
VB
Public Class dictionary
Public Sub add(ByVal et As String, ByVal kt As Integer)
Dim dk As Integer
If kt.CompareTo(dk) = 0 Then
End If
End Sub
End Class

See Also
Tasks
How to: Use a Generic Class
Reference
Of
New (Visual Basic)
Class (Visual Basic)
Structure (Visual Basic)
Object Data Type
Function Statement (Visual Basic)
Structure Statement
Sub Statement (Visual Basic)
Concepts
Access Levels in Visual Basic
Visual Basic Language Reference

Recommended XML Tags for Documentation Comments (Visual


Basic)
The Visual Basic compiler can process documentation comments in your code to an XML file. You can use additional tools to
process the XML file into documentation.
XML comments are allowed on code constructs such as types and type members. For partial types, only one part of the type
can have XML comments, although there is no restriction on commenting its members.
Note
Documentation comments cannot be applied to namespaces. The reason is that one namespace can span several assemblies,
and not all assemblies have to be loaded at the same time.

The compiler processes any tag that is valid XML. The following tags provide commonly used functionality in user
documentation.

<c> <code> <example>

<exception> 1 <include> 1 <list>

<para> <param> 1 <paramref>

<permission> 1 <remarks> <returns>

<see> 1 <seealso> 1 <summary>

<typeparam> 1 <value>

(1 The compiler verifies syntax.)


Note
If you want angle brackets to appear in the text of a documentation comment, use &lt; and &gt;. For example, the string "&l
t;text in angle brackets&gt;" will appear as <text in angle brackets>.

See Also
Tasks
How to: Create XML Documentation in Visual Basic
Reference
/doc
Concepts
Documenting Your Code with XML (Visual Basic)
Visual Basic Language Reference

<c> (Visual Basic)


Indicates that text within a description is code.

<c>text</c>

Parameters
text
The text you would like to indicate as code.
Remarks
The <c> tag gives you a way to indicate that text within a description should be marked as code. Use <code> (Visual Basic) to
indicate multiple lines as code.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <c> tag in the summary section to indicate that Counter is code.
VB
''' <summary>
''' Resets the value the <c>Counter</c> field.
''' </summary>
Public Sub ResetCounter()
counterValue = 0
End Sub
Private counterValue As Integer = 0
''' <summary>
''' Returns the number of times Counter was called.
''' </summary>
''' <value>Number of times Counter was called.</value>
Public ReadOnly Property Counter() As Integer
Get
counterValue += 1
Return counterValue
End Get
End Property

See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference

<code> (Visual Basic)


Indicates that the text is multiple lines of code.

<code>content</code>

Parameters
content
The text to mark as code.
Remarks
Use the <code> tag to indicate multiple lines as code. Use <c> (Visual Basic) to indicate that text within a description should be
marked as code.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <code> tag to include example code for using the ID field.
VB
Public Class Employee
''' <remarks>
''' <example> This sample shows how to set the <c>ID</c> field.
''' <code>
''' Dim alice As New Employee
''' alice.ID = 1234
''' </code>
''' </example>
''' </remarks>
Public ID As Integer
End Class

See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference

<example> (Visual Basic)


Specifies an example for the member.

<example>description</example>

Parameters
description
A description of the code sample.
Remarks
The <example> tag lets you specify an example of how to use a method or other library member. This commonly involves using
the <code> (Visual Basic) tag.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <example> tag to include an example for using the ID field.
VB
Public Class Employee
''' <remarks>
''' <example> This sample shows how to set the <c>ID</c> field.
''' <code>
''' Dim alice As New Employee
''' alice.ID = 1234
''' </code>
''' </example>
''' </remarks>
Public ID As Integer
End Class

See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference

<exception> (Visual Basic)


Specifies which exceptions can be thrown.

<exception cref="member">description</exception>

Parameters
member
A reference to an exception that is available from the current compilation environment. The compiler checks that the given
exception exists and translates member to the canonical element name in the output XML. member must appear within
double quotation marks (" ").
description
A description.
Remarks
Use the <exception> tag to specify which exceptions can be thrown. This tag is applied to a method definition.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <exception> tag to describe an exception that the IntDivide function can throw.
VB
''' <exception cref="System.OverflowException">
''' Thrown when <paramref name="denominator"/><c> = 0</c>.
''' </exception>
Public Function IntDivide( _
ByVal numerator As Integer, _
ByVal denominator As Integer _
) As Integer
Return numerator \ denominator
End Function

See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference

<include> (Visual Basic)


Refers to another file that describes the types and members in your source code.

<include file="filename" path="tagpath[@name='id']" />

Parameters
filename
Required. The name of the file containing the documentation. The file name can be qualified with a path. Enclose filename in
double quotation marks (" ").
tagpath
Required. The path of the tags in filename that leads to the tag name. Enclose the path in double quotation marks (" ").
name
Required. The name specifier in the tag that precedes the comments. Name will have an id.
id
Required. The ID for the tag that precedes the comments. Enclose the ID in single quotation marks (' ').
Remarks
Use the <include> tag to refer to comments in another file that describe the types and members in your source code. This is an
alternative to placing documentation comments directly in your source code file.
The <include> tag uses the W3C XML Path Language (XPath) Version 1.0 Recommendation. More information for ways to
customize your <include> use is available at http://www.w3.org/TR/xpath.
Example
This example uses the <include> tag to import member documentation comments from a file called commentFile.xml.
VB
''' <include file="commentFile.xml"
''' path="Docs/Members[@name='Open']/*" />
Public Sub Open(ByVal filename As String)
' Code goes here.
End Sub
''' <include file="commentFile.xml"
''' path="Docs/Members[@name='Close']/*" />
Public Sub Close(ByVal filename As String)
' Code goes here.
End Sub

The format of the commentFile.xml is as follows.

<Docs>
<Members name="Open">
<summary>Opens a file.</summary>
<param name="filename">File name to open.</param>
</Members>
<Members name="Close">
<summary>Closes a file.</summary>
<param name="filename">File name to close.</param>
</Members>
</Docs>

See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference

<list> (Visual Basic)


Defines a list or table.

<list type="type">
<listheader>
<term>term</term>
<description>description</description>
</listheader>
<item>
<term>term</term>
<description>description</description>
</item>
</list>

Parameters
type
The type of the list. Must be a "bullet" for a bulleted list, "number" for a numbered list, or "table" for a two-column table.
term
Only used when type is "table". A term to define, which is defined in the description tag.
description
When type is "bullet" or "number", description is an item in the list When type is "table", description is the definition of term.
Remarks
The <listheader> block is used to define the heading of either a table or definition list. When defining a table, you only need to
supply an entry for term in the heading.
Each item in the list is specified with an <item> block. When creating a definition list, you will need to specify both term and
description. However, for a table, bulleted list, or numbered list, you only need to supply an entry for description.
A list or table can have as many <item> blocks as needed.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <list> tag to define a bulleted list in the remarks section.
VB
''' <remarks>Before calling the <c>Reset</c> method, be sure to:
''' <list type="bullet">
''' <item><description>Close all connections.</description></item>
''' <item><description>Save the object state.</description></item>
''' </list>
''' </remarks>
Public Sub Reset()
' Code goes here.
End Sub

See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference

<para> (Visual Basic)


Specifies that the content is formatted as a paragraph.

<para>content</para>

Parameters
content
The text of the paragraph.
Remarks
The <para> tag is for use inside a tag, such as <summary> (Visual Basic), <remarks> (Visual Basic), or <returns> (Visual Basic),
and lets you add structure to the text.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <para> tag to split the remarks section for the UpdateRecord method into two paragraphs.
VB
''' <param name="id">The ID of the record to update.</param>
''' <remarks>Updates the record <paramref name="id"/>.
''' <para>Use <see cref="DoesRecordExist"/> to verify that
''' the record exists before calling this method.</para>
''' </remarks>
Public Sub UpdateRecord(ByVal id As Integer)
' Code goes here.
End Sub
''' <param name="id">The ID of the record to check.</param>
''' <returns><c>True</c> if <paramref name="id"/> exists,
''' <c>False</c> otherwise.</returns>
''' <remarks><seealso cref="UpdateRecord"/></remarks>
Public Function DoesRecordExist(ByVal id As Integer) As Boolean
' Code goes here.
End Function

See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference

<param> (Visual Basic)


Defines a parameter name and description.

<param name="name">description</param>

Parameters
name
The name of a method parameter. Enclose the name in double quotation marks (" ").
description
A description for the parameter.
Remarks
The <param> tag should be used in the comment for a method declaration to describe one of the parameters for the method.
The text for the <param> tag will be displayed in IntelliSense Features and in the Object Browser.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <param> tag to describe the id parameter.
VB
''' <param name="id">The ID of the record to update.</param>
''' <remarks>Updates the record <paramref name="id"/>.
''' <para>Use <see cref="DoesRecordExist"/> to verify that
''' the record exists before calling this method.</para>
''' </remarks>
Public Sub UpdateRecord(ByVal id As Integer)
' Code goes here.
End Sub
''' <param name="id">The ID of the record to check.</param>
''' <returns><c>True</c> if <paramref name="id"/> exists,
''' <c>False</c> otherwise.</returns>
''' <remarks><seealso cref="UpdateRecord"/></remarks>
Public Function DoesRecordExist(ByVal id As Integer) As Boolean
' Code goes here.
End Function

See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference

<paramref> (Visual Basic)


Formats a word as a parameter.

<paramref name="name"/>

Parameters
name
The name of the parameter to refer to. Enclose the name in double quotation marks (" ").
Remarks
The <paramref> tag gives you a way to indicate that a word is a parameter. The XML file can be processed to format this
parameter in some distinct way.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <paramref> tag to refer to the id parameter.
VB
''' <param name="id">The ID of the record to update.</param>
''' <remarks>Updates the record <paramref name="id"/>.
''' <para>Use <see cref="DoesRecordExist"/> to verify that
''' the record exists before calling this method.</para>
''' </remarks>
Public Sub UpdateRecord(ByVal id As Integer)
' Code goes here.
End Sub
''' <param name="id">The ID of the record to check.</param>
''' <returns><c>True</c> if <paramref name="id"/> exists,
''' <c>False</c> otherwise.</returns>
''' <remarks><seealso cref="UpdateRecord"/></remarks>
Public Function DoesRecordExist(ByVal id As Integer) As Boolean
' Code goes here.
End Function

See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference

<permission> (Visual Basic)


Specifies a required permission for the member.

<permission cref="member">description</permission>

Parameters
member
A reference to a member or field that is available to be called from the current compilation environment. The compiler
checks that the given code element exists and translates member to the canonical element name in the output XML. Enclose
member in quotation marks (" ").
description
A description of the access to the member.
Remarks
Use the <permission> tag to document the access of a member. Use the PermissionSet class to specify access to a member.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <permission> tag to describe that the FileIOPermission is required by the ReadFile method.
VB
''' <permission cref="System.Security.Permissions.FileIOPermission">
''' Needs full access to the specified file.
''' </permission>
Public Sub ReadFile(ByVal filename As String)
' Code goes here.
End Sub

See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference

<remarks> (Visual Basic)


Specifies a remarks section for the member.

<remarks>description</remarks>

Parameters
description
A description of the member.
Remarks
Use the <remarks> tag to add information about a type, supplementing the information specified with
<summary> (Visual Basic). This information is displayed in the Object Browser.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <remarks> tag to explain what the UpdateRecord method does.
VB
''' <param name="id">The ID of the record to update.</param>
''' <remarks>Updates the record <paramref name="id"/>.
''' <para>Use <see cref="DoesRecordExist"/> to verify that
''' the record exists before calling this method.</para>
''' </remarks>
Public Sub UpdateRecord(ByVal id As Integer)
' Code goes here.
End Sub
''' <param name="id">The ID of the record to check.</param>
''' <returns><c>True</c> if <paramref name="id"/> exists,
''' <c>False</c> otherwise.</returns>
''' <remarks><seealso cref="UpdateRecord"/></remarks>
Public Function DoesRecordExist(ByVal id As Integer) As Boolean
' Code goes here.
End Function

See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference

<returns> (Visual Basic)


Specifies the return value of the property or function.

<returns>description</returns>

Parameters
description
A description of the return value.
Remarks
Use the <returns> tag in the comment for a method declaration to describe the return value.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <returns> tag to explain what the DoesRecordExist function returns.
VB
''' <param name="id">The ID of the record to update.</param>
''' <remarks>Updates the record <paramref name="id"/>.
''' <para>Use <see cref="DoesRecordExist"/> to verify that
''' the record exists before calling this method.</para>
''' </remarks>
Public Sub UpdateRecord(ByVal id As Integer)
' Code goes here.
End Sub
''' <param name="id">The ID of the record to check.</param>
''' <returns><c>True</c> if <paramref name="id"/> exists,
''' <c>False</c> otherwise.</returns>
''' <remarks><seealso cref="UpdateRecord"/></remarks>
Public Function DoesRecordExist(ByVal id As Integer) As Boolean
' Code goes here.
End Function

See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference

<see> (Visual Basic)


Specifies a link to another member.

<see cref="member"/>

Parameters
member
A reference to a member or field that is available to be called from the current compilation environment. The compiler
checks that the given code element exists and passes member to the element name in the output XML. member must appear
within double quotation marks (" ").
Remarks
Use the <see> tag to specify a link from within text. Use <seealso> (Visual Basic) to indicate text that you might want to appear
in a "See Also" section.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <see> tag in the UpdateRecord remarks section to refer to the DoesRecordExist method.
VB
''' <param name="id">The ID of the record to update.</param>
''' <remarks>Updates the record <paramref name="id"/>.
''' <para>Use <see cref="DoesRecordExist"/> to verify that
''' the record exists before calling this method.</para>
''' </remarks>
Public Sub UpdateRecord(ByVal id As Integer)
' Code goes here.
End Sub
''' <param name="id">The ID of the record to check.</param>
''' <returns><c>True</c> if <paramref name="id"/> exists,
''' <c>False</c> otherwise.</returns>
''' <remarks><seealso cref="UpdateRecord"/></remarks>
Public Function DoesRecordExist(ByVal id As Integer) As Boolean
' Code goes here.
End Function

See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference

<seealso> (Visual Basic)


Specifies a link that appears in the See Also section.

<seealso cref="member"/>

Parameters
member
A reference to a member or field that is available to be called from the current compilation environment. The compiler
checks that the given code element exists and passes member to the element name in the output XML. member must appear
within double quotation marks (" ").
Remarks
Use the <seealso> tag to specify the text that you want to appear in a See Also section. Use <see> (Visual Basic) to specify a
link from within text.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <seealso> tag in the DoesRecordExist remarks section to refer to the UpdateRecord method.
VB
''' <param name="id">The ID of the record to update.</param>
''' <remarks>Updates the record <paramref name="id"/>.
''' <para>Use <see cref="DoesRecordExist"/> to verify that
''' the record exists before calling this method.</para>
''' </remarks>
Public Sub UpdateRecord(ByVal id As Integer)
' Code goes here.
End Sub
''' <param name="id">The ID of the record to check.</param>
''' <returns><c>True</c> if <paramref name="id"/> exists,
''' <c>False</c> otherwise.</returns>
''' <remarks><seealso cref="UpdateRecord"/></remarks>
Public Function DoesRecordExist(ByVal id As Integer) As Boolean
' Code goes here.
End Function

See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference

<summary> (Visual Basic)


Specifies the summary of the member.

<summary>description</summary>

Parameters
description
A summary of the object.
Remarks
Use the <summary> tag to describe a type or a type member. Use <remarks> (Visual Basic) to add supplemental information to
a type description.
The text for the <summary> tag is the only source of information about the type in IntelliSense, and is also displayed in the
Object Browser.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <summary> tag to describe the ResetCounter method and Counter property.
VB
''' <summary>
''' Resets the value the <c>Counter</c> field.
''' </summary>
Public Sub ResetCounter()
counterValue = 0
End Sub
Private counterValue As Integer = 0
''' <summary>
''' Returns the number of times Counter was called.
''' </summary>
''' <value>Number of times Counter was called.</value>
Public ReadOnly Property Counter() As Integer
Get
counterValue += 1
Return counterValue
End Get
End Property

See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference

<typeparam> (Visual Basic)


Defines a type parameter name and description.

<typeparam name="name">description</typeparam>

Parameters
name
The name of the type parameter. Enclose the name in double quotation marks (" ").
description
A description of the type parameter.
Remarks
Use the <typeparam> tag in the comment for a generic type or generic member declaration to describe one of the type
parameters.
Compile with /doc to process documentation comments to a file.
Example
This example uses the <typeparam> tag to describe the id parameter.
VB
''' <typeparam name="T">
''' The base item type. Must implement IComparable.
''' </typeparam>
Public Class itemManager(Of T As IComparable)
' Insert code that defines class members.
End Class

See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference

<value> (Visual Basic)


Specifies the description of a property.

<value>property-description</value>

Parameters
property-description
A description for the property.
Remarks
Use the <value> tag to describe a property. Note that when you add a property using the code wizard in the Visual Studio
development environment, it will add a <summary> (Visual Basic) tag for the new property. You should then manually add a
<value> tag to describe the value that the property represents.

Compile with /doc to process documentation comments to a file.


Example
This example uses the <value> tag to describe what value the Counter property holds.
VB
''' <summary>
''' Resets the value the <c>Counter</c> field.
''' </summary>
Public Sub ResetCounter()
counterValue = 0
End Sub
Private counterValue As Integer = 0
''' <summary>
''' Returns the number of times Counter was called.
''' </summary>
''' <value>Number of times Counter was called.</value>
Public ReadOnly Property Counter() As Integer
Get
counterValue += 1
Return counterValue
End Get
End Property

See Also
Reference
Recommended XML Tags for Documentation Comments (Visual Basic)
Visual Basic Language Reference

Error Messages (Visual Basic)


Error messages can occur while an application is running, either within the Visual Basic environment or as a stand-alone
executable file. Some of these can also occur during design time or compile time. You can test and respond to trappable errors
using the On Error statement and the Err object's Number property. Unused error numbers in the range 1 to 1000 are
reserved for future use by Visual Basic.
Note
The description "Application-defined or object-defined error" occurs when an error is generated using the Err object's Raise
method or the Error statement, but the number does not correspond to an error defined by the Visual Basic language. Such e
rrors may be defined by the host application (for example, Microsoft Excel or Visual Basic), but if you want to generate them f
rom code, you must use the Raise method and fill in all relevant arguments.

While developing in Visual Basic, you can get information from Help on a message by pressing F1. Likewise, you can press F1
on error messages shown in the Task List window.
In This Section
How to: Get Information about Visual Basic Compiler Errors
Explains the concept of compiler errors and how to get help for particular error messages.
How to: Get Information about Visual Basic Run-Time Errors
Explains the concept of run-time errors and how to get help for particular error messages.
Visual Basic Compiler Messages
Contains the Visual Basic error messages that occur at compile time.
Visual Basic Run-Time Messages
Contains the Visual Basic error messages that occur at run time
Related Sections
Exception and Error Handling in Visual Basic
Lists links to topics related to exception handling in Visual Basic.
Walkthrough: Structured Exception Handling
Illustrates how to use the Try...Catch...Finally statement to handle exceptions.
Visual Basic Language Reference

How to: Get Information about Visual Basic Compiler Errors


Visual Basic compiler errors occur when the compiler encounters problems in the code. The code causing the errors is marked
with a wavy line underneath it in the Code Editor, and when your mouse pauses over the marked code, the error message
appears. The messages also appear in the Task List.
Getting Help
The Smart Compile Auto Correction feature suggests corrections for some errors and allows you to apply the fix. When an
error occurs, if there is a hollow rectangular symbol under the right side of the wavy underline, resting your mouse over the
wavy underline or double-clicking the error message in the Task List turns the symbol into a smart tag panel. Clicking or
resting your mouse pointer over the smart tag panel opens the Error Correction Options helper window, which displays a
description of the error, as well as a set of suggestions for fixing the error. For more information, see
How to: Correct Compiler Errors with Auto Correction.
The Visual Basic compiler includes a set of warnings about code that may cause run-time errors. Developers can use that
information to write cleaner, faster code with fewer bugs. For example, the compiler produces a warning when the user
attempts to invoke a member of an unassigned object variable, return from a function without setting the return value, or
execute a Try block with errors in the logic to catch exceptions. To learn more about warnings, including how to turn them on
and off, see Configuring Warnings in Visual Basic.
To get help for a particular error message
1. Highlight the error message in the Task List and press F1.
-or-
2. On the Help menu, click Search.
3. Type the error message in the Search For box in the Search window.
Note
Remember that displayed error messages often incorporate identifiers from the code, such as variable or project name
s, as well as the type names for these elements; these are not part of the underlying error message. Be careful not to inc
lude these words as part of your search.

See Also
Tasks
How to: Get Information about Visual Basic Run-Time Errors
How to: Debug Code in the Editor
How to: Correct Compiler Errors with Auto Correction
Concepts
Configuring Warnings in Visual Basic
Visual Basic Language Reference

How to: Get Information about Visual Basic Run-Time Errors


Visual Basic run-time errors occur when an application attempts to perform an action that the system cannot execute.
The errors that Visual Basic throws are Exception objects. Visual Basic can generate custom errors of any data type, including
Exception objects, by using the Throw statement. A program can display the error number and message of a caught
exception to identify the error. If an error is not caught, the program ends.
Run-time errors can be trapped and examined by the code. By enclosing the code that produces the error in a Try block, any
thrown error can be caught within a matching Catch block.
Getting Help
To get help for a particular error message
1. Click Search on the Help menu.
2. Type the error message in the Search For box in the Search window.
Note
Some error messages include words in single quotation marks that refer to identifiers from the code, such as a project
or variable name, and are not part of the error message. Do not include the quoted words as part of your search.

See Also
Tasks
How to: Get Information about Visual Basic Compiler Errors
How to: Correct Run-Time Errors with the Exception Assistant
Reference
Try...Catch...Finally Statement (Visual Basic)
Concepts
Structured Exception Handling Overview for Visual Basic
Visual Basic Language Concepts

Trappable Errors in Visual Basic


While the structured exception handling model provided in Visual Basic is more useful in developing applications, you might
choose to employ unstructured error handling, particularly when upgrading legacy applications. You can use the
On Error Statement (Visual Basic) to trap and respond to specific errors.
Trappable Errors
Trappable errors can occur while an application is running. Some trappable errors can also occur during development or compile
time. You can test and respond to trappable errors using the On Error statement and the Err Object (Visual Basic).
The following table lists error codes and their associated messages.
C Message
o
d
e
0 No error

3 Return without GoSub (obsolete, no longer used)

5 Procedure call or argument is not valid (Visual Basic)

6 Overflow (Visual Basic Error)


Overflow (Visual Basic Run-Time Error)

7 Out of memory (Visual Basic Compiler Error)


Out of memory (Visual Basic Run-Time Error)

9 Subscript out of range (Visual Basic)

1 This array is fixed or temporarily locked (Visual Basic)


0

1 Division by zero (Visual Basic Run-Time Error)


1

1 Type mismatch (Visual Basic)


3

1 Out of string space (Visual Basic)


4

1 Expression too complex


6

1 Can't perform requested operation (Visual Basic)


7

1 User interrupt occurred


8

2 Resume without error


0
2 Out of stack space (Visual Basic)
8

3 Sub or Function not defined (Visual Basic)


5

4 Too many DLL application clients


7

4 Error in loading DLL (Visual Basic)


8

4 Bad DLL calling convention


9

5 Internal error (Visual Basic)


1

5 Bad file name or number


2

5 File not found (Visual Basic Run-Time Error)


3

5 Bad file mode


4

5 File already open


5

5 Device I/O error


7

5 File already exists


8

5 Bad record length


9

6 Disk full (Visual Basic)


1

6 Input past end of file


2

6 Bad record number


3

6 Too many files


7

6 Device unavailable
8

7 Permission denied (Visual Basic)


0
7 Disk not ready
1

7 Cannot rename with different drive


4

7 Path/File access error


5

7 Path not found


6

9 Object variable or With block variable not set


1

9 For loop not initialized (Visual Basic)


2

9 Invalid pattern string


3

9 Invalid use of Null (obsolete, no longer used)


4

9 Application-defined or object-defined error


5

9 Unable to sink events of object because the object is already firing events to the maximum number of event receivers it supports
6

9 Cannot call friend function on object which is not an instance of defining class
7

9 A property or method call cannot include a reference to a private object, either as an argument or as a return value
8

1 Class '<classname>' does not implement the System.Collections.ICollection interface


0
0

2 System resource or DLL could not be loaded


9
8

3 Cannot use character device names in specified file names


2
0

3 File format not valid


2
1

3 Can't create necessary temporary file


2
2
3 Format not valid in resource file
2
5

3 Data value named not found


2
7

3 Illegal parameter; can't write arrays


2
8

3 Could not access system registry


3
5

3 ActiveX component not correctly registered


3
6

3 ActiveX Component not found


3
7

3 ActiveX Component did not run correctly


3
8

3 Object already loaded


6
0

3 Can't load or unload this object


6
1

3 ActiveX Control specified not found


6
3

3 Object was unloaded


6
4

3 Unable to unload within this context


6
5

3 The specified file is out of date


6
8

3 The specified object can't be used as an owner form for Show


7
1
3 Property value is not valid
8
0

3 Property array index is not valid


8
1

3 Set not supported at run time


8
2

3 Set not supported (read-only property)


8
3

3 Need property array index


8
5

3 Set not permitted


8
7

3 Get not supported at run time


9
3

3 Get not supported (write-only property)


9
4

4 Form already displayed; can't show modally


0
0

4 Code must close topmost modal form first


0
2

4 Property not found


2
2

4 Property or method not found


2
3

4 Object required (Visual Basic)


2
4

4 Cannot create ActiveX Component


2
9
4 Class does not support Automation or does not support expected interface
3
0

4 File name or class name not found during Automation operation (Visual Basic)
3
2

4 Object doesn't support this property or method (Visual Basic)


3
8

4 Automation error
4
0

4 Connection to type library or object library for remote process has been lost
4
2

4 Automation object does not have a default value


4
3

4 Object doesn't support this action (Visual Basic)


4
5

4 Object doesn't support named arguments


4
6

4 Object doesn't support current locale setting (Visual Basic)


4
7

4 Named argument not found (Visual Basic)


4
8

4 Argument not optional (Visual Basic)


4
9

4 Wrong number of arguments or property assignment not valid


5
0

4 Property let procedure not defined and property get procedure did not return an object
5
1

4 Ordinal is not valid


5
2
4 Specified DLL function not found
5
3

4 Code resource not found


5
4

4 Code resource lock error


5
5

4 This key is already associated with an element of this collection


5
7

4 Variable uses an Automation type not supported in Visual Basic


5
8

4 Object or class does not support the set of events


5
9

4 Clipboard format is not valid


6
0

4 Method or data member not found


6
1

4 The remote server machine does not exist or is unavailable (Visual Basic)
6
2

4 Class not registered on local machine


6
3

4 Picture is not valid


8
1

4 Printer error
8
2

7 Cannot save file to TEMP


3
5

7 Search text not found


4
4
7 Replacements too long
4
6

9 Stop statement encountered


9
9

3 Feature not yet implemented


2
7
6
8

The message Application-defined or object-defined error applies to an error code that Visual Basic does not recognize.
See Also
Tasks
Troubleshooting Exception Handling
Reference
On Error Statement (Visual Basic)
Err Object (Visual Basic)
Concepts
Introduction to Exception Handling
Unstructured Exception Handling Overview
Choosing When to Use Structured and Unstructured Exception Handling
Other Resources
Structured Exception Handling in Visual Basic
Visual Basic Reference: Error Messages

No Help available for this Visual Basic error


Most error messages have associated Help pages. However, your project or your code has generated an error for which no
Help page exists.
To correct this error
1. If you do not have Online Help enabled, enable it and check for possible documentation of this error. See
Help Sources: Local Help and Online Help.
2. Search the Microsoft Support Knowledge Base (KB) (http://support.microsoft.com/search/) for possible documentation of
this error.
3. Consult the MSDN Online Library (http://msdn.microsoft.com/library/default.asp) for possible documentation of this
error.
4. If you cannot find any documentation, gather information about the circumstances and contact Microsoft Product
Support Services.
One piece of information that could be useful is the error ID. This consists of the letters BC followed by a 5-digit code, for
example BC30648. You can find the error ID by looking in the Output window. You can display the Output window by
choosing Other Windows from the View menu, and then choosing Output. Alternatively, you can press CTRL+ALT+O.
Keep these points in mind:
You must run the compiler to generate the error in the Output window. To do this, either press F5 or choose Start
Debugging from the Debug menu.
Inside the Output window, for "Show output from:" choose Build.
See Also
Tasks
Locating Readme Files
Reference
Online, Help, Environment, Options Dialog Box
Concepts
Help Sources: Local Help and Online Help
Getting Help from Microsoft Product Support Services (Visual Studio)
Other Resources
Using Help in Visual Studio
Product Support and Accessibility
Visual Basic Language Reference

Visual Basic Compiler Messages


This section contains the Visual Basic error messages that occur at compile time.
See Also
Tasks
How to: Get Information about Visual Basic Compiler Errors
Other Resources
Error Messages (Visual Basic)
Visual Basic Reference: Error Messages

'>' expected
The syntax for the specified code is incorrect. This error often indicates that the closing angle bracket for an attribute is missing.
Error ID: BC30636
To correct this error
Check the syntax for the code being used.
See Also
Concepts
Declaration Statements in Visual Basic
Other Resources
Attributes in Visual Basic
Visual Basic Reference: Error Messages

'=' expected (Let or Set assignment)


A Let or Set assignment statement does not include an equal sign (=).
The Let and Set assignment statements are not supported in Visual Basic 2005. The compiler can determine the type of
assignment from the data type of the programming element that is to receive the value. A value type assignment replaces the
Let statement, and a reference type assignment replaces the former Set statement.
The new Set Statement (Visual Basic) is used in property definitions and has no relation to the Set assignment statement.
Error ID: BC32020
To correct this error
Use a standard assignment statement, including an equal sign (=) and a value to be assigned to the variable or property.
See Also
Concepts
Programming Element Support Changes Summary
Value Types and Reference Types
Assignment Statements
Visual Basic Reference: Error Messages

'=' expected (Declaration)


A Mid statement or a #Const compilation directive does not include an assignment of a value.
Error ID: BC30249
To correct this error
Add an equal sign (=) and a value to be assigned to the string or the compilation constant.
See Also
Reference
Mid Statement
#Const Directive
Concepts
Declaration Statements in Visual Basic
Assignment Statements
Visual Basic Reference: Error Messages

'<variablename>' is not a local variable or parameter, and so


cannot be used as a 'Catch' variable
Variables in Try...Catch...Finally statements must be declared locally, or be parameters for the current procedure.
Error ID: BC31082
To correct this error
Declare local variables or parameters for Try...Catch...Finally statements.
See Also
Reference
Try...Catch...Finally Statement (Visual Basic)
Visual Basic Reference: Error Messages

'<typename1>' cannot be converted to '<typename2>'


A type conversion was attempted between two incompatible types.
Error ID: BC30741
To correct this error
Verify the types that are being cast.
See Also
Reference
CType Function
Visual Basic Reference: Error Messages

'<typename>' values cannot be converted to 'Char'


Error Message
'<typename>' values cannot be converted to Char. Use Microsoft.VisualBasic.ChrW to interpret a numeric value as a Unicode
character or first convert it to 'String' to produce a digit.
An expression attempts to convert a data type other than String or Object to Char.
Error ID: BC32007
To correct this error
Use the ChrW function to convert a numeric value to a Unicode character, or first convert the value to String and then to
Char.
See Also
Reference
Chr, ChrW Functions
Char Data Type (Visual Basic)
Concepts
Implicit and Explicit Conversions
Visual Basic Reference: Error Messages

'<typename>' must be declared 'MustInherit' because it


contains methods declared 'MustOverride'
Types that contain MustOverride members must be declared MustInherit.
Error ID: BC31411
To correct this error
Add the MustInherit modifier to the type.
See Also
Reference
MustInherit
MustOverride
Visual Basic Reference: Error Messages

'<typename>' is an unsupported type


The type specified cannot be represented by Visual Studio.
Error ID: BC30649
To correct this error
Use a supported type.
Develop a new type.
See Also
Reference
Data Type Summary (Visual Basic)
Visual Basic Reference: Error Messages

'<typename>' is an interface type and cannot be used as an


expression
A type name occurs where an expression is required. An expression must consist of a combination of variables, constants,
literals, properties, and Function procedure calls.
Error ID: BC30111
To correct this error
Remove the type name and construct the expression using valid elements.
See Also
Concepts
Operators and Expressions in Visual Basic
Visual Basic Reference: Error Messages

'<typename>' is an Enum type and cannot be used as an


expression
A type name occurs where an expression is required. An expression must consist of a combination of variables, constants,
literals, properties, and Function procedure calls.
Error ID: BC30107
To correct this error
Remove the type name and construct the expression using valid elements.
See Also
Concepts
Operators and Expressions in Visual Basic
Visual Basic Reference: Error Messages

'<typename>' is a type in '<containername>' and cannot be


used as an expression
One of the names being used is already declared as the name of a type, and cannot be used in an expression.
Error ID: BC30691
To correct this error
Uniquely name the member.
Use square brackets around the name of the member.

See Also
Concepts
Keywords as Element Names in Code
Visual Basic Naming Conventions
Visual Basic Reference: Error Messages

'<typename>' is a type and cannot be used as an expression


A type name occurs where an expression is required. An expression must consist of some combination of variables, constants,
literals, properties, and Function procedure calls.
Error ID: BC30108
To correct this error
Remove the type name and construct the expression using valid elements.
See Also
Concepts
Operators and Expressions in Visual Basic
Visual Basic Reference: Error Messages

'<typename>' is a structure type and cannot be used as an


expression
A type name occurs where an expression is required. An expression must consist of some combination of variables, constants,
literals, properties, and Function procedure calls.
Error ID: BC30110
To correct this error
Remove the type name and construct the expression using valid elements.
See Also
Concepts
Operators and Expressions in Visual Basic
Visual Basic Reference: Error Messages

'<typename>' is a namespace and cannot be used as an


expression
A type name occurs where an expression is required. An expression must consist of variables, constants, literals, properties, and
Function procedure calls.
Error ID: BC30112
To correct this error
Remove the type name and construct the expression using valid elements.
See Also
Concepts
Operators and Expressions in Visual Basic
Visual Basic Reference: Error Messages

'<typename>' is a delegate type


Error Message
'<typename>' is a delegate type. Delegate construction permits only a single AddressOf expression as an argument list. Often
an AddressOf expression can be used instead of a delegate construction.
A New clause creating an instance of a delegate class supplies an invalid argument list to the delegate constructor.
You can supply only a single AddressOf expression when creating a new delegate instance.
This error can result if you pass no arguments at all to the delegate constructor, more than one argument, or a single argument
that is not a valid AddressOf expression.
Error ID: BC32008
To correct this error
Use a single AddressOf expression in the argument list for the delegate class in the New clause.
See Also
Tasks
How to: Invoke a Delegate Method
Reference
New (Visual Basic)
AddressOf Operator
Concepts
Delegates and the AddressOf Operator
Visual Basic Reference: Error Messages

'<typename>' is a class type and cannot be used as an


expression
A type name occurs where an expression is required. An expression must consist of a combination of variables, constants,
literals, properties, and Function procedure calls.
Error ID: BC30109
To correct this error
Remove the type name and construct the expression using valid elements.
See Also
Concepts
Operators and Expressions in Visual Basic
Visual Basic Reference: Error Messages

'<typename>' has the same name as another type exposed in a


'My' group
Error Message
'<typename>' has the same name as another type exposed in a 'My' group. Rename the form or its enclosing namespace.
A class or structure is declared with the same name as a class or structure in one of the My objects.
A name collision could not be avoided between two classes that can be accessed through a My object, such as My.Forms.
If there is a potential name collision between classes in a My object, the compiler changes the property name for the type from
ClassName to RootNamespace_Namespace_ClassName. For example, consider two forms named Form1. If one of these forms
is in the root namespace WindowsApplication1 and in the namespace Namespace1, you would access that form through
My.Forms.WindowsApplication1_Namespace1_Form1.

This error can happen if two classes have the same name and are in nested namespaces with underscores in their names.
When the compiler constructs the new property names for the classes, there is still a name collision.
Error ID: BC36015
To correct this error
1. Rename the new form.
2. Rename the namespaces.
Avoid naming any class or structure with the same name as an existing one.
See Also
Reference
My.Forms Object
Form
MyGroupCollectionAttribute
Concepts
Resolving a Reference When Multiple Variables Have the Same Name
Visual Basic Reference: Error Messages

'<typename>' cannot shadow a 'MustOverride' method


implicitly declared for property '<propertyname>' in <type>
'<typename>'
The specified method name conflicts with a MustOverride method implicitly generated by a property in the base class. For
example, if you declare a property named Prop1, the compiler generates the implicit procedures get_Prop1 and set_Prop1.
Error ID: BC31416
To correct this error
1. Give the method a unique name.
2. Remove the MustOverride modifier from the property in the base class.
See Also
Reference
MustOverride
Shadows
Concepts
Property Procedures
Visual Basic Reference: Error Messages

'<typename>' cannot be used as an attribute because it is not a


class
An attempt was made to use a type that is not a class as an attribute.
Error ID: BC31503
To correct this error
Define custom attributes as classes that derive from System.Attribute.
See Also
Other Resources
Attributes in Visual Basic
Visual Basic Reference: Error Messages

'<typename>' cannot be used as an attribute because it is


declared 'MustInherit'
Custom attribute classes cannot be declared as MustInherit.
Error ID: BC31506
To correct this error
Remove the MustInherit modifier from custom attributes.
See Also
Reference
AttributeUsageAttribute Class
Other Resources
Custom Attributes in Visual Basic
Visual Basic Reference: Error Messages

'<typename>' cannot be used as an attribute because it has


'MustOverride' methods that have not been overridden
Classes with MustOverride methods cannot be used as attributes.
MustOverride members of attribute classes can only be used from derived classes that override such members.
Error ID: BC31507
To correct this error
1. Remove the MustOverride modifier from attribute class members.
2. Implement MustOverride members in a derived class, and use that class as an attribute.
See Also
Reference
AttributeUsageAttribute Class
Other Resources
Custom Attributes in Visual Basic
Visual Basic Reference: Error Messages

'<typename>' cannot be used as an attribute because it does


not inherit from 'System.Attribute'
An attempt was made to use a class that is not derived from System.Attribute.
Error ID: BC31504
To correct this error
Define custom attributes as classes that derive from System.Attribute by adding an Imports statement to the first line
of code in the class.
See Also
Reference
AttributeUsageAttribute Class
Other Resources
Custom Attributes in Visual Basic
Visual Basic Reference: Error Messages

'<typename>' cannot be used as an attribute because it does


not have a 'System.AttributeUsageAttribute' attribute
An attempt was made to use an attribute that was declared without the System.AttributeUsageAttribute to define its usage.
Error ID: BC31505
To correct this error
Custom attributes must be classes derived from System.Attribute that have the AttributeUsageAttribute attribute
applied.
See Also
Reference
AttributeUsageAttribute Class
Other Resources
Custom Attributes in Visual Basic
Visual Basic Reference: Error Messages

<typename> '<membername>' must be declared 'Shadows'


because another member with this name is declared 'Shadows'
This property or procedure has the same name as another property or procedure marked with the Shadows modifier.
Error ID: BC30695
To correct this error
Use the Shadows modifier.
See Also
Reference
Shadows
Visual Basic Reference: Error Messages

<type1>'<typename>' must implement '<methodname>' for


interface '<interfacename>'
A class or structure claims to implement an interface but does not implement a procedure defined by the interface. Every
member of the interface must be implemented.
Error ID: BC30149
To correct this error
1. Declare a procedure with the same name and signature as defined in the interface. Be sure to include at least the End
Function or End Sub statement.
2. Add an Implements clause to the end of the Function or Sub statement. For example:

Public Sub DoSomething() Implements IBaseInterface.DoSomething

See Also
Reference
Implements Statement
Concepts
Implements Keyword and Implements Statement
Visual Basic Reference: Error Messages

<type1>'<typename>' must implement '<membername>' for


interface '<interfacename>'
Error Message
'<typename>' must implement '<membername>' for interface '<interfacename>'. Implementing property must have
matching 'ReadOnly'/'WriteOnly' specifiers.
A class or structure claims to implement an interface but does not implement a procedure, property, or event defined by the
interface. Every member of the interface must be implemented.
Error ID: BC30154
To correct this error
1. Declare a member with the same name and signature as defined in the interface. Be sure to include at least the End
Function, End Sub, or End Property statement.
2. Add an Implements clause to the end of the Function, Sub, Property, or Event statement. For example:

Public Event ItHappened() Implements IBaseInterface.ItHappened

3. When implementing a property, make sure that ReadOnly or WriteOnly is used in the same way as in the interface
definition.
4. When implementing a property, declare Get and Set procedures, as appropriate.
See Also
Reference
Implements Statement
Concepts
Implements Keyword and Implements Statement
Visual Basic Reference: Error Messages

'<type1>' cannot override <type2> because it is not declared


'Overridable'
A member in a derived class overrides a base class member that is not marked with the Overridable modifier.
Error ID: BC31086
To correct this error
1. Add the Overridable modifier to the overridden member in the base class.
2. Use the Shadows keyword to shadow the item in the base class.

See Also
Reference
Overridable
Overrides
Shadows
Visual Basic Reference: Error Messages

<type1> '<typename1>' conflicts with a member implicitly


declared for event '<eventname>' in <type2> '<typename2>'
The name of a type member conflicts with the name of a member implicitly created for an event. Events implicitly create
several implicit variables. For example, the declaration Event X implicitly declares the names XEventHandler, XEvent, add_X,
and remove_X.
Error ID: BC31061
To correct this error
Rename the explicitly declared member to remove the naming conflict.
See Also
Concepts
Declaration Statements in Visual Basic
Other Resources
Events in Visual Basic
Visual Basic Reference: Error Messages

<type1> '<typename>' cannot be declared 'Overrides' because


it does not override a <type1> in a base <type2>
A Sub, Function, or Property statement specifies Overrides when no type with the same name exists in a base class.
Error ID: BC30284
To correct this error
1. Check that the type name is spelled correctly.
2. Remove the superfluous Overrides keyword.

See Also
Concepts
Overriding Properties and Methods
Visual Basic Reference: Error Messages

<type1> '<typename>' and <type2> '<typename>', declared


in '<name>', conflict in <namespace> '<namespacename>'
Two declared elements, such as a class and a module, have the same name in the same namespace.
Error ID: BC30175
To correct this error
Move the declaration of one of the elements to a different namespace.
Change the name of one of the elements.

See Also
Concepts
Resolving a Reference When Multiple Variables Have the Same Name
Visual Basic Reference: Error Messages

<type1> '<typename>' and <type2> '<typename>' conflict in


<namespace> '<namespacename>'
Two declared elements, such as a class and a module, have the same name in the same namespace.
Error ID: BC30179
To correct this error
Move the declaration of one of the elements to a different namespace.
Change the name of one of the elements.

See Also
Concepts
Resolving a Reference When Multiple Variables Have the Same Name
Visual Basic Reference: Error Messages

<type1> '<propertyname>' conflicts with a member implicitly


declared for event '<eventname>' in the base <type2>
'<classname>'
A property is declared with the same name as an implicit member formed from an event in the base class. For example, if the
base class defines an event named Event1, the compiler generates the implicit procedures add_Event1 and remove_Event1.
If the property in this class has one of these names, it should shadow the base class member.
This message is a warning. Shadows is assumed by default. For more information on hiding warnings or treating warnings as
errors, see Configuring Warnings in Visual Basic.
Error ID: BC40014
To correct this error
1. To hide the base class member, add the Shadows keyword to the property declaration.
2. If you do not intend to hide the base class member, change the property name.
See Also
Reference
Property Statement
Event Statement
Shadows
Concepts
Shadowing in Visual Basic
Visual Basic Reference: Error Messages

<type1> '<membername>' shadows an overloadable member


declared in the base <type2> '<classname>'
Error Message
<type1> '<membername>' shadows an overloadable member declared in the base <type2> '<classname>. If you want to
overload the base method, this method must be declared 'Overloads'.
A derived class defines a Function or Sub procedure or a Property with the same name as a procedure or property defined in
the base class. Because procedures and properties are overloadable members, the derived class can either overload or shadow
the base class member. However, the derived class code does not specify either Overloads or Shadows in the declaration. In
the absence of either keyword, the compiler assumes Shadows.
It is good programming practice to specify either Overloads or Shadows. This makes your code easier to read and
understand.
By default, this message is a warning. For more information about hiding warnings or treating warnings as errors, see
Configuring Warnings in Visual Basic.
Error ID: BC40003
To correct this error
If you want to overload the base class method or property, include the Overloads keyword in the declaration.
If you want to shadow the base class method or property, include the Shadows keyword instead of Overloads.
If you do not want to either overload or shadow the base class member, change the name of the derived class member.
See Also
Reference
Overloads
Shadows
Function Statement (Visual Basic)
Sub Statement (Visual Basic)
Property Statement
Concepts
Procedure Overloading
Shadowing in Visual Basic
Visual Basic Reference: Error Messages

<type1> '<membername>' conflicts with <type2>


'<membername>' on the base class <type3> '<classname>'
and should be declared 'Shadows'
A programming element is declared with the same name as an element defined in the base class. In this situation, the element
in this class should shadow the base class element.
This message is a warning. Shadows is assumed by default. For more information about hiding warnings or treating warnings
as errors, please see Configuring Warnings in Visual Basic.
Error ID: BC40004
To correct this error
Add the Shadows keyword to the declaration, or change the name of the element being declared.
See Also
Reference
Shadows
Concepts
Shadowing in Visual Basic
Visual Basic Reference: Error Messages

<type> parameters cannot be declared 'ParamArray'


A definition of a delegate, event, or operator declares a ParamArray parameter.
ParamArray parameters are allowed only on Declare, Function, Property, and Sub parameters.
Error ID: BC33009
To correct this error
Remove the ParamArray keyword from the parameter list.
If you are defining an operator, you might be able to achieve the ParamArray functionality with a series of overloads.
If you are defining a delegate or event, you must rework the overall logic of this part of your application. You cannot use
Optional (Visual Basic) or ParamArray parameters, or overloaded versions, on delegate or event parameters.
See Also
Reference
Overloads
Operator Statement
Concepts
Operator Procedures
Visual Basic Reference: Error Messages

<type> parameters cannot be declared 'Optional'


A definition of a delegate, event, or operator declares an Optional (Visual Basic) parameter.
Optional parameters are allowed only on Declare, Function, Property, and Sub parameters.
Error ID: BC33010
To correct this error
Remove the Optional keyword from the parameter list.
If you are defining an operator, you might be able to achieve the Optional functionality with a series of overloads.
If you are defining a delegate or event, you must rework the overall logic of this part of your application. You cannot use
Optional or ParamArray parameters, or overloaded versions, on delegate or event parameters.
See Also
Reference
Overloads
Operator Statement
Concepts
Operator Procedures
Visual Basic Reference: Error Messages

'<type>' cannot be inherited more than once


You have duplicated an Inherits statement.
Error ID: BC30584
To correct this error
Remove the redundant Inherits statement.
See Also
Reference
Inherits Statement
Visual Basic Reference: Error Messages

<type> '<typename>' shadows an overridable method in the


base class
Error Message
<type> '<typename>' shadows an overridable method in the base class. If you want to override the base method, this method
must be declared 'Overrides'.
A programming element is declared with the same name as an overridable procedure or property defined in the base class. In
this situation, the element in this class should shadow the base class element.
By default, this message is a warning. For more information about hiding warnings or treating warnings as errors, see
Configuring Warnings in Visual Basic.
Error ID: BC40005
To correct this error
If you intend to override the base procedure, add the Overrides keyword to the declaration.
If you intend to shadow the base procedure, add the Shadows keyword to the declaration.
If you do not intend either overriding or shadowing, change the name of the element being declared.
See Also
Reference
Overrides
Shadows
Concepts
Overriding Properties and Methods
Shadowing in Visual Basic
Visual Basic Reference: Error Messages

<type> '<methodname>' conflicts with other members of the


same name across the inheritance hierarchy and so should be
declared 'Shadows'
An interface inheriting from two or more interfaces defines a procedure with the same name as a procedure already defined in
more than one of the base interfaces. The procedure in this interface should shadow one of the base interface procedures.
This message is a warning. Shadows is assumed by default. For more information on hiding warnings or treating warnings as
errors, see Configuring Warnings in Visual Basic.
Error ID: BC42000
To correct this error
If you intend to hide one of the base interface procedures, add the Shadows keyword to the new procedure declaration.
If you do not intend to hide any of the base interface procedures, change the name of the new procedure.
See Also
Reference
Shadows
Concepts
Shadowing in Visua

Potrebbero piacerti anche