Download - VB18
-
8/8/2019 VB18
1/58
Differences between VB6 and VB.NET
Compatibility
VB6 and VB.NET can run on the same computer.Inheritance
You can derive a class from a parent class.
Structured Error HandlingThere will be some kind of more structured error handling, though I don't knowthe details yet.
CoexistanceYou should be able to run VB6 and VB.NET on the same computer.
UpgradingWhen you open a VB6 program in VB.NET, a Migration Wizard appears to helpyou convert it into VB.NET. There are a lot of changes, however, so you willprobably still need to do a fair amount of work.
Control AnchorsYou can anchor a control, to the lower left corner of the form for example, so youdon't need to reposition it in Form_Resize.
Easy DelpoymentYou can install executables and components buy copying them into the rightdirectory. No more messing with Regsvr32.
New FormsVisual Basic forms become Windows forms.
No PrintForm
Windows forms do not have PrintForm. I don't know what we're supposed to useinstead.
Unified IDEAll Microsoft languages use the same IDE. You can debug an OCX written inC++ while running it in a VB.NET program.
Extensibility ModelThe new extensibility model applies to the IDE universally. That means you canwrite Add-Ins in VB.NET and use them in C#.
GDI+The GDI (Graphics Device Interface) has new functions including Alphablending, anti-aliasing, and support for more file formats.
ADO.NETImproved performance.
No DAO/RDO BindingVB.NET does not support DAO or RDO data binding, Data controls, or the RDOUser Connection.
Object type
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
2/58
-
8/8/2019 VB18
3/58
No VarPtr, ObjPtr, StrPtr, etc.These statements no longer exist.
No LSetThis statement no longer exists.
No As Any
You cannot use As Any in API declarations. You must make separate declarationsfor each data type you will pass to the API function.
No OLE ContainerThe Windows form does not support this control.
No Shape or Line ControlsThese no longer exist.
New Graphics MethodsNew methods replace Circle, CLS, PSet, Line, and Point.
Timer IntervalSetting a Timer's Interval to 0 does not disable it.
Context MenusWindows forms have a main menu and a separate context menu used for popups.
No DDEWindows forms do not support DDE.
New Drag and DropDrag and Drop still exists but is different.
New ClipboardImproved clipboard functions.
Name PropertyThe Name property is no longer available at run time.
SurveyHere are the results of a survey I took on 4/21/01. Comments people made aboutquestions 3 and 4 are at the end.
1. Are you using the VB.NET beta?
Yes2
No 15
2. Do you plan to use Beta 2?
Yes3
Probably 1
Maybe 4
No9
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
4/58
-
8/8/2019 VB18
5/58
No. I'm still trying to learn VB6. From what I've read, VB.NET is a different language.
Yes, slowly. I'm just trying to understand what it is. Also, can you answer what will benecessary to learn along with it. I gather XML will be one. Will JavaScript work with it.That's what I mean by number 4
Yes, to find out more about it.
No. I see no reason to get all hyped up about software that isn't even on the open marketyet. As far as I am concerned, VB 6 is the latest version of VB and that is what theexamples, tips, tricks and hints should be based on.
Later on, after VB.NET has been released (and the third service pack released within 6months after that), then our organization >>> MIGHT
-
8/8/2019 VB18
6/58
Overview of Changes from VB6 to VB.NET
This article discusses the important language changes from VB6/VBScript to
VB.NET. When creating ASP.NET pages, you are required to use a .NET-compatible programming language, such as C#, VB.NET, or JScript.NET.However, there are some significant changes from VB6/VBScript toVB.NET, which this article addresses. To learn more about ASP.NET ingeneral, be sure to check out the ASP.NET Article Index!
Also, for more information be sure to check out Microsoft's article:Preparing Your Visual Basic 6.0 Applications for the Upgrade to VisualBasic.NET.
IntroductionWith release of Microsoft .NET platform, Visual Basic has emerged into a fully objectedoriented language (dubbed VB.NET). With these radical changes, though, the learningcurve between VB6 and VB.NET might be reasonably high even for experiencedprogrammers. In this article I will try to list language changes to Visual Basic along withsample examples wherever appropriate. The list presented here may not be complete butit does cover majority of features. If you are a VB programmer wanting to shift toVB.NET this is a must read for you.
Note that currently (as of May 30th, 2001), ASP.NET is in Beta 1, which is freelydownloadable from www.ASP.NET. However, some of the changes discussed in thisarticle are changes that are proposed for the Beta 2 version, which is scheduled to bereleased to the public on June 17th. These areas that are new to Beta 2 (and therefore will
not work with the Beta 1 version of ASP.NET) are marked.
Data Type ChangesThe .NET platform provides Common Type System to all the supported languages. Thismeans that all the languages must support the same data types as enforced by commonlanguage runtime. This eliminates data type incompatibilities between various languages.For example on the 32-bit Windows platform, the integer data type takes 4 bytes inlanguages like C++ whereas in VB it takes 2 bytes. Following are the main changesrelated to data types in VB.NET:
Under .NET the Integer data type in VB.NET is also 4 bytes in size. VB.NET has no currency data type. Instead it provides decimal as a replacement. VB.NET introduces a new data type called Char. The char data type takes 2 bytes
and can store Unicode characters.
VB.NET do not have Variant data type. To achieve a result similar to variant typeyou can use Object data type. (Since every thing in .NET - including primitivedata types - is an object, a variable of object type can point to any data type).
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
7/58
In VB.NET there is no concept of fixed length strings. In VB6 we used the Type keyword to declare our user defined structures. VB.NET
introduces the structure keyword for the same purpose. The rest of the syntax issame. That is:
Structure MyStruct1...End Structure
Declaring VariablesConsider this simple example in VB6:
Dim x,y as integer
In this example VB6 will consider x as variant and y as integer, which is somewhat oddbehavior. VB.NET corrects this problem, creating both x and y as integers. Furthermore,VB.NET allows you to assign initial values to the variables in the declaration statementitself:
Dim str1 as string="hello"
VB.NET also introduces Read-Only variables. Unlike constants Read-Only variables canbe declared without initialization but once you assign a value to it, it can not be changed.
'no initialization hereDim readonly x as integer
'in later codex=100
'now x can't be changedx=200 '***** error *********
Arrays
With VB6, you could programmatically define the lower and upper bounds of an array. InVB.NET, however, an array's lower bound is always zero. Also, when defining an arraylike so:
Dim aStates(50) as String
in actuality, 51 elements are being created, with 0 as the lower bound and 50 as theupper bound! (Note that in Beta 1 of the VB.NET compiler, the above statement wouldcreate 50 elements, from bounds 0 through 49.)
In Part 1 we examined VB.NET's changes to data types, variable declaration, and arrays.In this part we'll continue our examination of VB.NET's syntax changes.
Variable ScopingConsider following VB6 code:
If x=y thenDim z as integer' other code
End If
z=100 'Outside of If ... Then block
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
8/58
The above code runs perfectly with VB6 because there is no block-level variable scoping.(Block-level scoping occurs in other modern programming languages (such as C++).Variables defined within statement blocks, such as the variable defined in the If ... Thenblock, fall out of scope when the statement block ends. Therefore, accessing z outside ofthe If ... Then block where it's defined, would cause an error in modern programming
languages.) VB.NET, contrary to VB6, employs block-level variable scoping.
The Set and Let StatementsIn VB6 you must use the Set statement to assign an object instance to a variable. This wasnecessary in VB6 because of default properties. To tell VB that we want to assign avariable to the object itself (as opposed to the value of the object's default property) youhad to use the Set keyword. For example, in VB6:
Dim x as VariantDim strName as string
'Assign the value of Text1.Text to StrName'(Text is the default property of the textbox control in VB6)
StrName=Text1
'Here we assign the actual Textbox object to the variable x'Note that we use the Set keyword so VB knows we want to assign'to x the object itself instead of the default propertySet x=Text1
In VB.NET, however, there are no default properties allowed (except for parameterizedproperties) and hence there is no need for the Set keyword. (Likewise, the Let keywordhas been removed from the VB.NET syntax.)
Error HandlingVisual Basic has finally incorporated structured error handling. The keywords Try, Catch
and Finally make error handling easy and make VB.NET at par with languages like C++or C#. This Try ... Catch model allows developers to place code that may cause anexception within a Try block. If that code throws an exception (synonymous to raising anerror), the code in the Catch block is executed; the code in this block should be designedto gracefully handle the exception.
Note that VB6's older error handling techniques (On Error Resume Next and the like) are stillsupported for backward compatibility, although when writing new applications withVB.NET you should valiantly strive not to use these old techniques. The following codesnippet illustrates various error handling techniques with VB.NET:
Try
...Catch
...End Try
The above code simply "catches" any exceptions caused by offending code inside theassociated Try block. VB.NET allows you to handle specific exceptions by using multipleCatch blocks:
Try
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
9/58
...Catch e1 as NullPointerException...
Catch e2 as Exception...
End Try
In addition to catching predefined exceptions you can also create your own customexception classes that inherit from the System.Exception base class. You can also 'Throw'your own exceptions (similar to using the Raise method of the Err object in VB6:
If myvar < 1000 thenThrow new Exception("Business Logic Error")
End If
In Part 2 we continued our examination of VB.NET's new features, looking at varaiblescoping, default object properties, the Set and Let keywords, and error handling. In thisthird and final part, we'll complete our study of VB.NET's new features.
Static Methods
VB.NET now allows you to create static methods in your classes. Static methods aremethods that can be called withoutrequiring the developer to create an instance of theclass. For example, if you had a class named Foo with the non-static method NonStatic()and the static method Static(), you could call the Static() method like so:
Foo.Static()
However, non-static methods require than an instance of the class be created, like so:
'Create an instance of the Foo classDim objFoo as New Foo()
'Execute the NonStatic() methodobjFoo.NonStatic()
To create a static method in a VB.NET class, simply prefix the method definition withthe keyword Shared.
Procedures and FunctionsIn VB6 all the procedure parameters are passed by reference (ByRef) by default. InVB.NET they are passed by value (ByVal) by default. Parentheses are required forcalling procedures and functions whether they accept any parameters or not. In VB6functions returned values using syntax like: FunctionName = return_value. In VB.NET youcan use the Return keyword (Return return_value) to return values or you can continue to usethe older syntax, which is still valid.
Property SyntaxIn VB6 we used Property Get and property Set/Let for creating properties in classes. The twoappeared as separate routines:
Public Property Get PropertyName() asDataType...
End Property
Public Property Let PropertyName(value asDataType)...
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
10/58
End Property
In VB.NET the syntax changes quite a bit. Rather than having two separate Property Getand Property Let/Set statements, these are combined into one Property statement. Also,within the Set portion of the Property statement the variable Value indicates the valueentered by the user when assigning a value to the indicated property.
Public [ReadOnly|WriteOnly] Property PropertyName asDataTypeGetReturn m_var
End Get
SetM_var = Value
End SetEnd Property
ConclusionThere are some changes to VB.NET's semantics and syntax, but these are the mostimportant changes that you, as an ASP.NET developer, will come across. The most
important things to keep in mind when working with VB.NET to create ASP.NET Webpages are:
1. Variables can be typed and are no longer all Variants. That is, if you need anInteger variable, use Dim i as Integer instead of just Dim i. (Typing your variablesleads to tremendous performance increases over untyped variables.)
2. Remember that VB.NET requires that subroutine calls have parenthesis aroundthe calling parameters! That means Response.Write "Hello, World!" will generate anerror. Rather, you need to place parenthesis around the parameter you are passinginto the function: Response.Write("Hello, World!")
3. VB.NET no longer supports default properties - you must explicitly specify theproperty you wish to access from an object.
4. Be careful when declaring arrays. As aforementioned, all arrays in VB.NET havea lower bound of zero, and an upper bound of the number you specify (resultingin one more element than you may have thought you had when creating thearray).
Happy Programming!
Visual Fred
Following are the bullets you will not see on the side of the box or the marketeer's glossy.
This list has been characterized as "sensationalistic" and, frankly, it is. The changesproposed for this language are indeed sensational! I'd personally be ecstatic if thereweren't so many fundamental hazards facing today's functional code. New developmentmay be very well-served, but migration is a shaky proposition, at best.
This is a short list of some of the incompatabilities -- considered "gratuitous" to "essential"depending who you talk to -- Microsoft plans to introduce with the roll-out ofVisual Fred.Yes, there are ways to workaround many of these issues, but the fact that workarounds are
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
11/58
-
8/8/2019 VB18
12/58
19. Dim may not always create procedure-level variables.20. Redim will not create arrays not already declared.21. Local variables are not necessarily visible (in scope) throughout a procedure.22. VarType is not supported.23. Empty is not supported.24. Null is not supported.25. IsEmpty is not supported.26. IsMissing is not supported.27. IsNull is not supported.28. IsObjectis not supported.29. Letis not supported.30. Core language constants do not have a "vb" prefix (vbRedbecomesRed).31. Terminate will not fire when an object's last reference is released.32. Object finalization code will not execute in a predictable order.33. Implicit object creation is not delayed until first reference.34. Public object variables are not safe from alteration when passed as parameters.35. Can not expose Property procedures with mixed visibility (Friend Set/Public Get).36. Procedure parameters are not by default passedByRefanymore.37. ParamArray arguments are not passedByRefanymore.38. Property parameters may not be passedByRefanymore.39. Implements is not implemented the same, so must be rewritten.40. Static is not supported as a procedure level modifier.41. Use ofAs New does not force auto-reinstantiation when an object is released.42. Parenthesis are not optional when calling procedures.43. Setis not supported for object assignment.44. Parameterless default properties are not supported.45. Default values for Optional parameters are not optional.46. Code is not compiled to native, thus making decompilation much easier.47. Resource files have changed format and old ones are not supported.48. LSetis not supported.49. RSetis not supported.
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
13/58
50. UDTs are notTypes, but are called Structures instead.51. UDTs are not by default contiguous blocks of memory, but are objects.52. Enums will not be recognized unless fully-qualified.53. While/Wendloops are not supported.54. GoSub/Return is not supported.55. On/GoTo is not supported.56. On/GoSub is not supported.57. Line numbers are not supported. Labels may be numeric.58. Erl is not supported.59. TheMsgBox function is not supported.60. TheDoEvents function is not supported.61. TheDate statement is not supported.62. The Time statement is not supported.63. And, Or,XOr, andNotare not bitwise operators. (Addressed in Beta2)64. Comparison operators are not evaluated before logical operators. (Addressed in Beta2)65. Sqris not supported.66. Sgn is not supported.67. Atn is not supported.68. Control arrays are not supported.69. UnloadMode detection is not offered, as QueryUnload is history.70. ListBox controls do not offer anItemData property.71. ListBox controls do not offer anNewIndex property.72. Windowless controls are not supported.73. Image controls are not supported.74. Shape controls are not supported.75. Line controls are not supported.76. OLE Container controls are not supported.77. Label controls will not have a Caption property.78. The Tag property is not supported. (Addressed in Beta2)79. The ToolTipTextproperty is not supported.80. The TextHeightproperty is not supported.
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
14/58
-
8/8/2019 VB18
15/58
112.Data binding with DAO is not supported.113.Data binding with RDO is not supported.114.115.116.
Microsoft Responds!
Yes, it's true. The black helicopters, er, uh, Microsoft does payattention to what's going on out here. They've prepared thisresponse especially for you to download from this site. If you see itoffered elsewhere, there's no vouching for its authenticity. I don'twant to be accused of altering anything they've said, so I'm posting
Microsoft's response in it's original Word 97/2000 format (135K,last updated 9-Mar-01), and assume you have some way to readthat. For now, I will withhold my own comments, but I am veryinterested in hearing what you think about this latest response!Keep those cards and letters coming, folks! People are payingattention. :-)
Further Reading
More than likely, you'll want to read more about these issues, andwhat you can do to minimize their impact. Randy Birch hascollected a number of interesting articles, many from Visual Studio
developers and product managers, as well as some of the morepoignent newsgroup commentary. He's also conducting a pollregarding your plans for migration.
Fans of Bruce McKinney (author ofHardcore Visual Basic) willlikely appreciate his insights (incites?) into the upcoming sea-changes. Jump to his website and click on the VB.NET link formore of his wit and wisdom.
More Details and Workarounds
Bob Butler has amassed a very good compendium of the upcomingchanges, and what they really mean to you, as well as suggestionson how you might consider modifying your code so it may work inthe future. Bob's site is under constant construction, as he adds newinformation for your benefit. Many of the not's above came directlyfrom his pages, and there you'll find far more details supporting theclaims made above.
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
16/58
Defensive Practices
Another interesting read would be that offered by Microsoft's ownmigration white paper. This is the paper that convinced me of theneed to provide this very page for you, because reading it
demonstrated to me just how profound the changes were to be.
Open Sores?
The first open source decompiler and source code generator hasnow been released for .NET executables. Looks like the onlyprotection for your source code is to house it solely on your ownservers. If it's distributed, it's wide-open. Forget the /OWNERcompiler switch, as that's only protection against willing codebreakers like ILDASM.
Parting Thoughts
"Anyway, if you really want to listen and consider other POV's,here's mine. I personally don't use and don't like GoSub. I dohowever realise that it is part of the language and other people douse it. Forcing an incompatibility with other peoples code because Idon't use a feature is not what I would consider rational. In fact,because it is harder for them to smoothly move into VB.NETimmediately, it has a net negative impact on the uptake and successof the language. That will have a negative impact on me, and mystocks. I honestly think the reality of this situation is if it's a feature
you don't use then don't worry about it, and don't ask for it to beremoved. Look at the bigger picture, and try to make decisions thatbenefit all, because as a programmer community, like it or not, oursuccesses are in part tied to the success of the community as awhole."
Bill McCarthy, Microsoft Visual Basic MVP, on DevXhttp://www.totalenviro.com/vb7
The Transition from Visual Basic 6.0 to
Visual Basic.NETIntroductionMicrosoft Visual Basic.NET is the next version of Microsoft Visual Basic, built fromthe ground up on the .NET Framework to enable you to easily create next-generationapplications for the Microsoft Windows operating system and the Web. With VisualBasic.NET, it's a snap to visually develop Web applications, Web Services, Windows
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
17/58
applications, and server-side components. In addition, Visual Basic.NET deliversXCOPY deployment of Windows applications, so you no longer need to worry aboutDLL versioning issues. With Visual Basic.NET, DLL Hell is a thing of the past.When designing Visual Basic.NET, we looked at the top requests of Visual Basicdevelopers worldwide. The Visual Basic language is now truly object-oriented and
supports implementation inheritance. The form designer supports visual inheritance andcontains new features, such as automatic form resizing, resource localization, andaccessibility support. The data tools now inherently support XML data, and the design-time data binding works with disconnected data. In addition, Visual Basic.NET is builtdirectly on the .NET Framework, so you have full access to all of the platform features,as well as interoperability with other .NET languages.In delivering these features, we have made changes to several aspects of the product. Thisdocument describes some of the changes from Visual Basic 6.0 to Visual Basic.NET, andexplains the motivation behind them. It also describes capabilities of the VisualBasic.NET Upgrade Wizard, a tool provided as part of the product that will help youupgrade your existing applications to Visual Basic.NET.
Additional information regarding the upgrade from Visual Basic 6.0 to Visual Basic.NETcan be found in the white paper Preparing Your Visual Basic 6.0 Applications for theUpgrade to Visual Basic.NET. This paper describes the upgrade process and providesarchitectural recommendations for making the upgrade as smooth as possible.
Language
Variant
Visual
Basic 6.0
Variant is a special universal data type that can contain any kind of data exceptfixed-length strings. An Object variable is used as a pointer to an object. Variant isthe default data type.
VisualBasic.NET
The common language runtime (CLR) uses Object for the universal data type. VisualBasic.NET could have continued to use Variant for the universal data type, but choseto adopt the naming convention of the CLR to avoid confusion for cross-languagedevelopment. The type system is simplified by having only a single universal datatype. The default data type is Object.
UpgradeWizard
Variant data types are changed to Object, so the following code:Dim x As Variant
is upgraded to:Dim x As Object
Integer and LongVisual
Basic 6.0
Long variables are stored as signed 32-bit numbers, and Integer variables are storedas 16-bit numbers.
VisualBasic.NET
Long variables are stored as signed 64-bit numbers, Integer variables are stored as 32-bit numbers,and Short variables are stored as 16-bit numbers. On 32-bit systems, 32-bit integer operations arefaster than either 16-bit or 64-bit integer operations. This means that Integer will be the most efficientand fundamental numeric type.
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
18/58
As some of the .NET Framework technologies are based around modern 32-bit and 64-bittechnologies, it makes sense to update the data sizes to the new technology.
UpgradeWizard
The variable types are changed, so the following code:Dim x As IntegerDim y As Long
is upgraded to:Dim x As ShortDim y As Integer
Currency
Visual
Basic 6.0
Visual Basic 6.0 supports a Currency data type. You cannot declare a variable to beof type Decimal (although variants can have a subtype ofDecimal).Currency variables are stored as 64-bit numbers in an integer format, scaled by10,000 to give a fixed-point number with 15 digits to the left of the decimal point and4 digits to the right. This representation provides a range of -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Decimal variables are stored as 96-bit signed integers scaled by a variable power of10. The power-of-10 scaling factor specifies the number of digits to the right of thedecimal point, and ranges from 0 to 28. With a scale of 0 (no decimal places), thelargest possible value is +/-79,228,162,514,264,337,593,543,950,335. With 28decimal places, the largest value is +/-7.9228162514264337593543950335 and thesmallest non-zero value is +/-0.0000000000000000000000000001.
VisualBasic.NET
The Currency data type does not provide sufficient accuracy to avoid roundingerrors, so Decimal was created as its own data type.
UpgradeWizard
Currency data types are changed to Decimal, so the following code:Dim x As Currency
is upgraded to:Dim x As Decimal
Date
Visual
Basic 6.0
A Date variable is stored internally in a Double format and can be manipulated asDouble.Date variables are stored as IEEE 64-bit floating-point numbers that represent datesranging from 1 January 100 to 31 December 9999 and times from 0:00:00 to23:59:59. Any recognizable literal date values can be assigned to Date variables.When other numeric types are converted to Date, values to the left of the decimalrepresent date information while values to the right of the decimal represent time.
Midnight is 0 and midday is 0.5. Negative whole numbers represent dates before 30December 1899.VisualBasic.NET
Date variables are stored internally as 64-bit integers, so they cannot be manipulateddirectly as Double. The .NET Framework provides the ToOADate andFromOADate functions to convert between Double and Date. Representing dates asintegers simplifies and speeds up the manipulation of dates.
UpgradeWizard
Although not all cases can be detected for example, where a variant is used to store aDate as a Double), the upgrade tool typically inserts the appropriate ToOADate or
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
19/58
FromOADate method where a Double is assigned to a Date. For example, thefollowing code:Dim dbl As Double
Dim dat As Date
Dbl = dat
is upgraded to:Dim dbl As Double
Dim dat As Date
Dbl = dat.ToOADate
Fixed-length strings
Visual
Basic 6.0
Variables can be declared with a fixed-length string, except for Public variables in aclass module.
VisualBasic.NET
Fixed-length strings are not supported in the first version of the CLR. This supportwill be added in a later version.
UpgradeWizard
In most cases, this is not an issue. A compatibility class provides fixed-length stringbehavior, so the following code:Dim MyFixedLengthString As String * 100
is upgraded to:Dim MyFixedLengthString As New VB6.FixedLengthString(100)
See the white paper Preparing Your Visual Basic 6.0 Applications for the Upgrade toVisual Basic.NET for a full discussion of this topic.
Type
Visual
Basic 6.0
The Type statement is used to define a user-defined data type.
VisualBasic.NET
The names Type and User-Defined Type are confusing, because classes, enums, andinterfaces are also types that can be defined by users. Type and User-Defined Typeare vestiges of QuickBasic, in which structures and records were the only types that auser could define. The CLR uses the name Type in a broad sense to include all datatypes.For this reason, the statement Type is changed to Structure in Visual Basic.NET
UpgradeWizard
Type statements are changed to Structure, so the following code:Type MyType
MyVariable As Integer
End Type
is upgraded to:Structure MyType
Dim MyVariable As Short
End Structure
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
20/58
User-defined type storage
Visual
Basic 6.0
User-defined data types can contain one or more elements of a data type, an array, ora previously defined user-defined type. In Visual Basic 6.0, they are stored incontiguous blocks of memory.
VisualBasic.NET
In the CLR, user-defined types are stored in whatever format is most efficient. Thismay or may not be a contiguous block of memory. Structures can be marked withmarshalling attributes to ensure they are passed to COM components as a contiguousblock of memory.
UpgradeWizard
APIs are marked with a TODO comment wherever you many need to addmarshalling attributes (attributes are not added automatically; they are not neededunless you pass the structures to APIs).
True
Visual
Basic 6.0
True has a value of 1.
VisualBasic.NET
True has a value of 1.For language interoperability, a consistent representation is needed across alllanguages.
UpgradeWizard
When a Boolean is coerced to a non-Boolean type, code is marked with an upgradewarning. For example, the following code:Dim MyBoolean As Boolean
Dim MyInteger As Integer
MyInteger = MyBoolean
is upgraded to:Dim MyBoolean As Boolean
Dim MyInteger As Short
' UPGRADE_WARNING: Boolean MyBoolean is being converted into a numeric
MyInteger = MyBoolean
Empty
Visual
Basic 6.0
Variants are initialized to Empty, which automatically converts to zero when used ina numeric expression, or to an empty string when used in a string expression.
Visual
Basic.NET
Object variables are initialized to Nothing, which automatically converts to zero
when used in a numeric expression, or to an empty string when used in a stringexpression. Using Nothing instead of a special Empty value reduces complexity inthe language and allows for better language interoperability.
UpgradeWizard
Empty is converted to Nothing.
Null and Null propagation
VisualNull values are Variant subtypes indicating that a variable contains no valid data.
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
21/58
Basic 6.0 Null values "propagate" through expressions and functions. If any part of anexpression evaluates to null, the entire expression evaluates to Null. Passing Null asan argument to most functions causes those functions to return Null.
VisualBasic.NET
Null propagation is not supported. The model for programming data with ADO.NETis to test fields explicitly for Null before retrieving their values. Variants containing
null are marshalled into the CLR as objects of type DBNull.Visual Basic.NET makes the rule for Null more intuitivestring functions, such asLeft(), always return a string as you would expect.
UpgradeWizard
Null values and IsNull functions are commented with an upgrade warning. Forexample, the following code:If x Is Null Then MsgBox "Null"
is upgraded to:' UPGRADE_WARNING: Use of IsNull() detected
If IsDBNull(x) Then MsgBox "Null"
Def
Visual
Basic 6.0
DefBool, DefByte, DefInt, DefLng, DefCur, DefSng, DefDbl, DefDec, DefDate,DefStr, DefObj, and DefVar statements are used at the module level to set thedefault data type for variables, parameters, and procedure return types whose namesstart with the specified characters.
VisualBasic.NET
Readability and robustness of code is improved by avoiding the use of implicit typedeclarations.
UpgradeWizard
Explicit declarations of the variable types are inserted into the code. For example, thefollowing code:DefStr a-z
Sub MySub
s = Hello
End Sub
is upgraded to:Sub MySub
Dim s As String
s = Hello
End Sub
Local variables inside blocks
VisualBasic 6.0
Local variables are visible from the line containing the declaration to the end of theprocedure.
VisualBasic.NET
Visual Basic.NET supports block scoping of variables. This means that a localvariable is visible from the line containing the declaration to the end of the block inwhich the declaration appears. For example:Sub Test(x As Integer)
If x < 0 ThenDim y As Integer = - x
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
22/58
'...Else
'...End If
End Sub
The variable "y" in the example above is available only within the block in which it isdeclared; specifically, it is available only from its declaration down to the Elsestatement. If the variable needs to be available to the entire procedure, then it must bedeclared outside of the If/Else/EndIfcontrol structure.Block scoping of variables is a feature common to many structured languages. Just asprocedure locals support structured programming by allowing definition of variablesthat are private to a procedure, block-level variables support structureddecomposition by allowing definition of variables that are private to a block of code.
UpgradeWizard
If variables are declared inside a block, they are automatically moved to module-levelscope. For example, the following code:If x =1 Then
Dim y As IntegerEnd If
is upgraded to:Dim y As Integer
If x =1 Then
End If
New auto-reinstantiation
Visual
Basic 6.0
A class variable declaration of the form "Dim x As New " causes thecompiler to generate code on every reference to "x". That code checks to see whether"x" is Nothing; if it is Nothing, a new instance of the class is created. For example,the code:Dim x As New MyClass'...Call x.MyMethod()
is equivalent to:Dim x As MyClass'...If x Is Nothing Then
Set x = New MyClassEnd IfCall x.MyMethod()
Even after the variable is set to Nothing, it will be reinstantiated on the next call to it.VisualBasic.NET
A variable declaration of the form "Dim x As New " is equivalent to"Dim x As = New ". No special code is generated forreferences to variables that are declared with this syntax.Visual Basic.NET declarations for "As New" are far more efficient than the samedeclaration in Visual Basic 6.0. For most references to such variables, the extraoverhead is unnecessary. Also, the "auto-instantiation" behavior of Visual Basic 6.0
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
23/58
is a surprise to many programmers when it is discovered.UpgradeWizard
It is rare that this will be an issue. However, if code tries to use a class after it hasbeen set to Nothing, it will cause an easily detectable run-time exception. The codecan then be easily modified to instantiate a new version of the class, as in thefollowing example:Dim x As New MyClass
x = Nothing
x = New MyClass
Object finalization
Visual
Basic 6.0
The COM reference-counting mechanism is used to garbage collect object instances.When objects are not in cycles, reference counting will immediately detect when anobject is no longer being used, and will run its termination code.
VisualBasic.NET
A tracing garbage collector walks the objects starting with the reachable referencesstored in stack variables, module variables, and shared variables. This tracing process
runs as a background task, and, as a result, an indeterminate period of time can lapsebetween when the last reference to an object goes away and when a new reference isadded.In some cases, clients do need the ability to force an object to release its resources.The CLR uses the convention that such an object should implement the IDisposableinterface, which provides a Dispose method. When a client has finished using anobject with a Dispose method, it can explicitly call the Dispose method so that itsresources will be released. For example, an object that wraps a database connectionshould expose a Dispose method.The tracing garbage collector can release objects in reference cycles correctly. Also,the performance of the tracing garbage collector is much faster than the performance
of reference counting.UpgradeWizard
In most cases, this change will not cause a problem. If you have code that holds aresource handle open (For example., Microsoft SQL Server connections or filehandles), you should explicitly close the handle. The problem is easily detected andcauses a run-time error.
Arrays
Visual
Basic 6.0
Arrays can be defined with lower and upper bounds of any whole number. TheOption Base statement is used to determine the default lower bound if a range is notspecified in the declaration.
Visual
Basic.NET
To enable interoperability with other languages, all arrays must have a lower bound
of zero. This makes the Option Base statement no longer necessary.UpgradeWizard
During upgrade, you have the option to treat your arrays as zero lower bound, or tochange them to an array compatibility class, as in the following example:
Dim a(1 To 10) As String
is upgraded to:Dim a As System.Array = VB6.NewArray(GetType(String), 1, 10)
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
24/58
ReDim
Visual
Basic 6.0
Visual Basic 6.0 has a distinction between fixed-size and variable-size arrays. Fixed-size arrays are declared with the Dim statement, which includes the bounds of thearray within this declaration. Dynamic arrays are declared in Dim statements by notspecifying bounds information. The dynamic array then needs to be re-dimensionedwith the ReDim statement before it can be used. In Visual Basic 6.0, the ReDimstatement provides a shorthand way to declare and allocate space for a dynamic arraywithin a single statement. The ReDim statement is the only statement in Visual Basic6.0 that can be used both to declare and to initialize a variable.
VisualBasic.NET
The ReDim statement is used only for allocating or reallocating the space for an arrayrather than reallocating the array. This is because all arrays in Visual Basic.NET aredynamic, and a Dim statement can be used in Visual Basic.NET both to declare andto initialize a dynamic array.Because all variable declarations can both declare and specify an initial value forvariables, the use ofReDim to both declare and initialize variables becomesredundant and unnecessary. Requiring that only the Dim statement can be used todeclare variables keeps the language simpler and more consistent.
UpgradeWizard
IfReDim() is used to declare an array, the appropriate declaration is inserted into thecode for you. However, the best practice is to insert the Dim statement into the arrayfirst yourself, since using ReDim to declare an array relies on the upgrade tool toinfer the correct declaration. Using ReDim also makes for awkward code, since thearray is being declared identically in two places.
Assignment
Visual
Basic 6.0
There are two forms of assignment: Let assignment (the default) and Set assignment.Set assignment can be used only to assign object references. The semantics ofLet
assignment are complex, but can be summarized as follows: If the expression on the right-hand side of the Let statement evaluates to an
object, the default property of the instance is automatically retrieved and theresult of that call is the value that was assigned.
If the expression on the left-hand side of the Let statement evaluates to anobject, the default Let property of that object is called with the result ofevaluating the right-hand side. An exception to this rule applies if the left-hand side is a variant containing an object, in which case the contents of thevariant are overwritten.
VisualBasic.NET
There is only one form of assignment. "x = y" means to assign the value of variableor property "y" to the variable or property "x". The value of an object type variable is
the reference to the object instances, so if "x" and "y" are reference type variables,then a reference assignment is performed. This single form of assignment reducescomplexity in the language and makes for much more readable code.
UpgradeWizard
Set and Let statements are removed. The default properties for strongly typed objectsare resolved and explicitly added to the code.See the white paper Preparing Your Visual Basic 6.0 Applications for the Upgrade toVisual Basic.NET for a full discussion of this topic.
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
25/58
And, Or, Xor, and Not
Visual
Basic 6.0
And, Or, Xor, and Not operators perform both logical operations and bitwiseoperations, depending on the expressions.
VisualBasic.NET
And, Or, and Xor apply only to type Boolean. The And operator and Or operatorwill short-circuit evaluation if the value of their first operand is sufficient todetermine the result of the operator. The new operators BitOr, BitAnd, and BitXorare used for bitwise logical operations. The Bitxxx operators do not short-circuit.This change is necessary to standardize the value ofTrue across all languages, and toreduce programming errors where it is unclear whether a bitwise or logical operationis to be applied. Short-circuiting improves performance, since only the necessaryoperations of an expression are evaluated.
UpgradeWizard
If the And/Or statement is non-Boolean or contains functions, methods, orproperties, it is upgraded to use a compatibility function with the same behavior asVisual Basic 6.0. If the And/Or statement is Boolean, and is without side effects, it isupgraded to use the native Visual Basic.Net statement.See the white paper Preparing Your Visual Basic 6.0 Applications for the Upgrade toVisual Basic.NET for a full discussion of this topic.
Operator precedence
Visual
Basic 6.0
The precedence of the logical and bitwise And, Or, Xor, and Not operators is higherthan the precedence of the comparison operators.
VisualBasic.NET
The precedence of the And, Or, Xor, and Not operators is lower than the precedenceof the comparison operators, so "a > b And a < c" will be evaluated as "(a > b) And (a< c)". The precedence of the new BitAnd, BitOr, and BitXor operators is higher than
the precedence of the comparison operators, so "a BitAnd &HFFFF 0" will beevaluated as "((a BitAnd &HFFFF) 0)".Since BitAnd, BitOr, and BitNot are operations that return numeric results, theirprecedence is higher than that of the relational operators such that the defaultprecedence allows the result from one of these operators to be compared with anothervalue.This results in a more intuitive precedence system than Visual Basic 6.0.
UpgradeWizard
This is handled by the Upgrade Wizard. See the white paper Preparing Your VisualBasic 6.0 Applications for the Upgrade to Visual Basic.NET for a full discussion ofthis topic.
Calling procedures
Visual
Basic 6.0
Two forms of procedure calls are supported: one using the Call statement, whichrequires parentheses around the list of arguments, and one without the Call statement,which requires that parentheses around the argument list not be used.It is common in Visual Basic 6.0 for a developer to call a procedure without the callkeyword but to attempt to include parentheses around the argument list. Fortunately,when there is more than one parameter, the compiler will detect this as a syntax error.However, when only a single parameter is given, the parentheses around the single
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
26/58
argument will have the affect of passing an argument variable as ByVal rather thanByRef. This can result in subtle bugs that are difficult to track down.
VisualBasic.NET
Parentheses are now required around argument lists in all cases.
Upgrade
Wizard
Parentheses are inserted for procedure calls that do no have them.
Static procedures
Visual
Basic 6.0
Procedures can be declared with the Static keyword, which indicates that theprocedure's local variables are preserved between calls.
VisualBasic.NET
The Static keyword is not supported on the procedure, and all static local variablesneed to be explicitly declared with the Static statement.There is very little need to have all the variables within a procedure be static.Removing this feature simplifies the language and improves its readability, becauselocal variables are always stack allocated unless explicitly declared as static.
UpgradeWizard
If a procedure is marked as Static, all local variable declarations are changed toStatic.Static Sub MySub()
Dim x As Integer
Dim y As Integer
End Sub
Is upgraded to:Sub MySub()
Static x As Integer
Static y As Integer
End Sub
Parameter ByVal/ByRef default
Visual
Basic 6.0
Parameters that do not specify either ByVal or ByRefdefault to ByRef.
VisualBasic.NET
Parameters that do not specify either ByVal or ByRefdefault to ByVal.Defaulting to ByVal rather than ByRefeliminates the problem of having a proceduremistakenly modify a variable passed in by the caller. This also makes the defaultcalling convention consistent with assignment, such that parameters are effectively
bound to the expressions passed in by an assignment of the expression to the formalparameter.Note that to avoid confusion for users moving from Visual Basic 6.0 to VisualBasic.NET, the IDE will automatically add the ByVal keyword on any parameterdeclarations that the user enters without explicitly specifying ByVal or ByRef.
UpgradeWizard
ByRefis added to parameters that don't have either a ByVal or ByRefmodifier.
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
27/58
-
8/8/2019 VB18
28/58
ByVal lpReturnedString As String, _ByVal nSize As Integer, _ByVal lpFileName As String) As Integer
could be replaced with two Declare versions, one that accepts a Integer and one thataccepts a string:Overloads 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
Overloads 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 Integer, _ByVal lpFileName As String) As Integer
This improves type safety and reduces the chance of a bug causing your program tofail. This can happen because the compiler will not allow the API to be called withdata types other than those that it is explicitly defined to accept.
UpgradeWizard
Declare statements using As Any parameters are commented with an upgradewarning.
Implements
Visual
Basic 6.0
The Implements statement specifies an interface or class that will be implemented inthe class module in which it appears.The Visual Basic 6.0 model stems from the fact that COM does not actually allowclasses to have methods; instead, classes are simply a collection of interfaceimplementations. Visual Basic 6.0 simulates classes with methods by introducing theconcept of a default interface. When an Implements statement specifies a class, thatclass implements the default interface of the class. Unfortunately the default interfaceconcept is not supported in other languages, and any cross-language programmingmust deal directly with the default interface.
VisualBasic.NET
Implements in Visual Basic.NET is different than in Visual Basic 6.0 in twoessential ways:
1. Classes can not be specified in Implements statements.2. Every method that implements an interface method requires an Implements
clause at the end of the method declaration statement. This will specify whatinterface method it implements.
Visual Basic.NET maintains a strict distinction between interfaces and classes.Readability is improved by requiring an Implements clause on each method thatimplements a method in an interface; it is obvious when reading code that the methodis being used to implement an interface method.
UpgradeWizard
If class "a" implements class "b", the interface is declared for class "b", and class "a"is changed to implement the interface of class "b":
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
29/58
Interface _b
Function MyFunction() As String
End Interface
Class a
Implements _bFunction b_MyFunction() As String Implements _b.MyFunction
End Function
End Class
Property
Visual
Basic 6.0
In Visual Basic 6.0, the Get, Let, and Set property functions for a specific propertycan be declared with different levels of accessibility. For example, the PropertyGetfunction can be Public while the PropertyLet is Friend.
Visual
Basic.NET
The Get and Set functions for a property must both have the same level of
accessibility. This allows Visual Basic.NET to interoperate with other .NETlanguages.
UpgradeWizard
If there is a different level of accessibility, the new property is public
Default properties
Visual
Basic 6.0
Any member can be marked as the default for a class.
VisualBasic.NET
Only properties that take parameters can be marked as default. It is common for thoseproperties with parameters to be indexers into a collection.
This makes code more readable, since a reference to an object variable without amember always refers to the object itself, rather than referring to the object in somecontexts and to the default property value in other contexts. For example, a statement"Call Display(TextBox1)" might be passing the text box instance to the Displayfunction or it might be passing the contents of the text box.Also, removing this ambiguity eliminates the need for a separate statement to performreference assignment. An assignment "x = y" always means to assign the contents ofvariable "y" to variable "x", rather than to assign the default property of the objectthat "y" references to the default property of the object that "x" references.
UpgradeWizard
Default properties are resolved where possible. Error comments are added where theycannot be resolved (on-late bound objects).
Enumerations
Visual
Basic 6.0
Enumeration constants can be referenced without qualification.
VisualBasic.NET
Enumerations constants can be referenced without qualification if an Import for theenumeration is added at file or project level.This keeps consistency with classes, structures, and interfaces in which members can
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
30/58
be given generic names without a risk of conflict with other members. For example,the Color enumeration and the Fruit enumeration can both contain a constant namedOrange. In Visual Basic 6.0, the convention is to prefix enumeration constants tomake them unique, which leads to awkward names such as MsColorOrange andMsFruitOrange.
UpgradeWizard References to enumerations are changed to be fully qualified.
While
Visual
Basic 6.0
While statements are ended with a WEnd statement.
VisualBasic.NET
To be consistent with other block structures, the terminating statement for While isnow End While. This improves language consistency and readability.
UpgradeWizard
WEnd statements are changed to End While.
OnGoTo and OnGoSub
Visual
Basic 6.0
The OnexpressionGotodestinationlistand OnexpressionGoSubdestinationliststatements branch to one of several specified lines in the destination list, dependingon the value of an expression.
VisualBasic.NET
OnGoTo and OnGoSub are nonstructured programming constructs. Their usemakes programs harder to read and understand. Select Case can provide a morestructured and flexible way to perform multiple branching.Note:On Error GoTo is still supported.
UpgradeWizard
The following example:On MyVariable GoTo 100,200,300
is commented with an upgrade error:' UPGRADE_ISSUE On MyVariable GoTo was not upgraded
On MyVariable GoTo 100,200,300
You should rewrite your code to avoid such statements. For example:On x Goto 100,200,300
Can be rewritten as:Select Case x
Case 1: 'Insert the code for line 100
Case 2: 'Insert the code for line 200
Case 3: 'Insert the code for line 300End Select
GoSubReturn
VisualThe GoSubline Return statement branches to and returns from a subroutinewithin a procedure.
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
31/58
Basic 6.0
VisualBasic.NET
GoSubReturn is a nonstructured programming construct. Its use makes programsharder to read and understand. Creating separate procedures that you can call mayprovide a more structured alternative.
Upgrade
Wizard
As with On...GoTo, these statements are commented with an upgrade error.
LSet
Visual
Basic 6.0
LSet pads a string with spaces to make it a specified length, or copies a variable ofone user-defined type to a variable of a different user-defined type.
VisualBasic.NET
The LSet statement is not supported. LSet is not type safe, so it can result in errors atrun time. Also, because it is not type safe it requires full trust in order to be executed.Removing the LSet statement discourages the copying of one structure over another;however, you can achieve the same effect by modifying your Visual Basic.NET codeto use RtlCopyMemory.
UpgradeWizard
This statement:LSet a1 = a2
It is commented with an upgrade error' UPGRADE_ISSUE: LSet cannot assign a UDT from one type to another
LSet a1 = a2
VarPtr, StrPtr, and ObjPtr
Visual
Basic 6.0
VarPtr, StrPtr, and ObjPtr return the addresses of variables as integers, which canthen be passed to API functions that take addresses, such as RtlCopyMemory.VarPtr returns the address of a variable, StrPtr returns the address of a string, and
ObjPtr returns the address of an object. These functions are undocumented.VisualBasic.NET
The addresses of data items can be retrieved, but retrieval must be done via calls intothe CLR. This is because the CLR is normally free to move items within memory, soit needs to know when not to move the item while the address is being used. Thefollowing example retrieves the address of an object:Dim MyGCHandle As GCHandle = GCHandle.Alloc(o, GCHandleType.Pinned)Dim Address As Integer = CInt(MyGCHandle.AddrOfPinnedObject())'...MyGCHandle.Free() 'allows the object instance to be moved again
Allowing data items to be moved by the runtime improves the performance of theruntime.
UpgradeWizard
There is no automatic upgrade for these statements, so they are commented with a"(statement) is not supported" upgrade error. For example, the following code:a = VarPtr(b)
is upgraded to:' UPGRADE_ISSUE: Function VarPtr() is not supported
a = VarPtr(b)
This also causes a compile error.
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
32/58
File I/O
Visual
Basic 6.0
File I/O statements are included in the language.
VisualBasic.NET
File I/O operations are available only through class libraries. Removing the file I/Ostatements from the language allows different I/O libraries to be easily used fromVisual Basic.NET. This would be more awkward if the file I/O statements were in thelanguage, because identifiers such as Open, Close, Print, and Write would bereserved words.
UpgradeWizard
The file I/O statements are upgraded to the corresponding functions. For example, thefollowing code:Open "MyFile.txt" For Input As #1
is upgraded to:FileOpen( 1, "MyFile.txt", OpenMode.Input )
Debug.PrintVisual
Basic 6.0
Debug.Print outputs a line of text to the Immediate window.
VisualBasic.NET
In Visual Studio.NET, the Immediate window is replaced with the Immediate and Output windows.The Immediate window is used to enter and display results when an application is in break mode. TheOutput window shows build information and program output.
Debug.WriteLine outputs a line of text to the Output window. There is also aDebug.Write method that outputs text to the Output window without a linefeed.
UpgradeWizard
Debug.Print is upgraded to Debug.WriteLine.
Resource files
Visual
Basic 6.0
Visual Basic 6.0 supports one .res file per project.
VisualBasic.NET
Visual Basic.NET has rich support for resources. Forms can be bound to retrieveresources automatically from the new .resX-formatted resource files. Any CLR classcan be stored in a .resX file.
UpgradeWizard
Files are upgraded from .res to .resX, and code is changed to load from the .resXfiles.
Windows ApplicationsVisual Basic forms
Visual
Basic 6.0
Visual Basic 6.0 has its own forms package for creating graphical Windowsapplications.
Visual Windows Forms is a new forms package for Visual Basic.NET. Because Windows
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
33/58
Basic.NETForms is built from the ground up to target the common language runtime (CLR), itcan take advantage of all of its features. In particular, because the Windows Formspackage takes advantage of the deployment, application isolation, versioning, andcode-access security features, you can now build Windows Client applications thatare significantly easier to deploy and update. You can even build Windows Forms
applications that have the same browser deployment characteristics as HTML. Thesecharacteristics, like the granular control of code access security, also make usingWindows Forms controls in the browser very compelling.The Windows Forms set also offers Visual Basic developers many new features, suchas visual inheritance, improved localization and accessibility support, automatic formresizing, and an in-place menu editor.
UpgradeWizard
Visual Basic forms are upgraded to Windows Forms.
PrintForm method
Visual
Basic 6.0
The PrintForm method sends a bit-by-bit image of a Form object to the printer.
However, this printing feature doesn't work correctly on some forms.
VisualBasic.NET
In Windows Forms, Visual Basic.NET has a printing framework that allows you tobuild complex print documents quickly. It also includes a built-in Print Previewdialog box.
UpgradeWizard
PrintForm method calls are commented with an upgrade error. You can use the newprinting framework to build a print document, or you can even grab a screenshot ofthe application window and print it.
Circle, Cls, PSet, Line, and Point methods
Visual
Basic 6.0
The Circle, Cls, PSet, Line, and Point methods allow you to draw graphics on a
form as well as to clear them.
VisualBasic.NET
Windows Forms has a new set of graphics commands that replace the Form methodsCircle, Cls, PSet, Line, and Point. The Windows Forms package is built on top ofGDI+, a feature-rich 2-D text and imaging graphics library that is now directlyaccessible from Visual Basic.NET. Visual Basic programmers have not been able toaccess these types of features in previous versions without having to drop down toDeclare statements and GDI APIs. While the learning curve is a little steeper, theflexibility and power of GDI+ will allow programmers to quickly developapplications that that would have taken significantly more work in previous versionsof Visual Basic.
UpgradeWizard
Calls to these methods are commented with an upgrade error. You can write yourgraphics calls using the GDI+ classes in System.Drawing.
Name property
Visual
Basic 6.0
The Name property returns the name used in code to identify a form, control, or dataaccess object. It is read-only at run time.
Visual Windows Forms does not support the Name property for forms and controls at run
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
34/58
Basic.NETtime. If you need to iterate the Controls collection to find a control with a certainname, you can use the .NET FrameworkSystem.Reflection classes to find it.
UpgradeWizard
Use of the Name property on controls is commented with an upgrade error.
Caption property
Visual
Basic 6.0
Some controls, such as Label, have a Caption property that determines the textdisplayed in or next to the control. Other controls, such as TextBox, have a Textproperty that determines the text contained in the control.
VisualBasic.NET
In Windows Forms, the property that displays text in a control is consistently calledText on all controls. This simplifies the use of controls.
UpgradeWizard
Caption properties for the controls are changed to Text.
Tag property
Visual
Basic 6.0
The Tag property returns or sets an expression that stores any extra data needed for
your program.In Visual Basic 6.0, you need the Tag property because you cannot extend the built-in controls.
VisualBasic.NET
In Windows Forms, you can use inheritance to extend the built-in controls and addyour own properties. Having inheritance available as a tool makes the built-incontrols significantly more flexible. Not only can you add as many properties as youlike, you can also make those properties strongly typed.
UpgradeWizard
A Windows Forms extender Tag control in the compatibility library is used toprovide the same functionality.
ScaleMode property
Visual
Basic 6.0
The ScaleMode property returns or sets a value that indicates the unit ofmeasurement for coordinates of an object when using graphics methods or whenpositioning controls.
VisualBasic.NET
Windows Forms simplifies form layout by always making measurements in pixels.In addition, Windows Forms has a better way to handle resizing. TheAutoScaleBaseSize property automatically adjusts the scale according to theresolution (dpi) of the screen and font size you use.
UpgradeWizard
Code that used 'twips' (the default Visual Basic 6.0 ScaleMode setting) upgradesperfectly. IfScaleMode is non-twips, you'll have sizing issues.See the white paper Preparing Your Visual Basic 6.0 Applications for the Upgrade to
Visual Basic.NET for a full discussion of this topic.
Fonts
Visual
Basic 6.0
Forms and controls can use any Windows font.
VisualBasic.NET
Forms and controls can only use TrueType or OpenType fonts. These types of fontssolve many inconsistencies across different operating-system versions and their
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
35/58
localized versions. These fonts also provide features, such as device resolutionindependence and anti-aliasing.
UpgradeWizard
If you have non-TrueType fonts in your application, these are changed to the defaultWindows Form font; however, formatting (size, bold, italic, underline) will be lost.
Screen.MousePointer property
Visual
Basic 6.0
The MousePointer property on the Screen object returns or sets a value indicatingthe type of mouse pointer displayed when the mouse is outside your application'sforms at run time.
VisualBasic.NET
The mouse pointer can be manipulated for forms inside of the application, but itcannot when it's outside of the application. We will be addressing this feature in afuture release.
UpgradeWizard
Use ofSceen.MousePointer is commented with an upgrade error.
Timer.Interval property
Visual
Basic 6.0
The Interval property on a Timer control returns or sets the number of millisecondsbetween calls to the Timer event. If it's set to 0, it disables the Timer control. TheEnabled property also determines whether the timer is running. This is confusing,because even when the Enabled propertyis true, the timer won't be enabled if theinterval is 0.
VisualBasic.NET
The Interval property indicates the time, in milliseconds, between timer ticks. Thisproperty cannot be set to 0. The Enabled property indicates whether the timer isrunning. This provides a more intuitive behavior to simplify coding with Timerobjects.
UpgradeWizard
Where the Upgrade Wizard can detect that Timer.Interval is set to 0, it will becommented with an upgrade error.
You are advised to use Timer.Enabled in your Visual Basic 6.0 applications, as thisupgrades perfectly.
Control arrays
Visual
Basic 6.0
A control array is a group of controls that share the same name and type. They alsoshare the same event procedures. A control array has at least one element and cangrow to as many elements as your system resources and memory permit. Elements ofthe same control array have their own property settings.
VisualBasic.NET
The Windows Form architecture natively handles many of the scenarios for whichcontrol arrays were used. For instance, in Windows Forms you can handle more thanone event on more than one control with a single event handler.
UpgradeWizard
A Control Array Windows Forms extender control in the compatibility libraryprovides this feature.
Menu controls
Visual
Basic 6.0
A Menu control represents each item in a menu tree. The same Menu controlinstance can be used simultaneously as a main menu or a context menu.
Visual A MenuItem control represents each item in a menu tree. The MenuItem control can
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
36/58
Basic.NETbe added to either a MainMenu item or a ContextMenu item, but not to both atonce. You can use the CloneMenu method on the MenuItem to create a copy ifyou'd like to share a menu between a MainMenu object and a ContextMenu object.
UpgradeWizard
Use of context menus is commented with an upgrade error. You can useMenuItem.CloneMenu to make a copy of the MainMenu item for use as a
ContextMenu item.
OLE container control
Visual
Basic 6.0
The OLE container control enables you to add OLE objects to your forms.
VisualBasic.NET
There is no OLE container control in Visual Basic.NET. If you need the equivalent ofthe OLE container control, you can add the WebBrowser control to a form and use itas an OLE container control.
UpgradeWizard
An error is added in the upgrade report, and an unsupported-control placeholder is puton the form.
Image control
Visual
Basic 6.0
The Image and PictureBox controls both display a graphic from a bitmap, icon,metafile, enhanced metafile, JPEG, or GIF file.
VisualBasic.NET
The Visual Basic.NET PictureBox control replaces the Visual Basic 6.0 PictureBoxand Image controls. The Windows Forms PictureBox control also supports animatedGIFs. However, if you require a very lightweight solution for painting an image ontoa form, you can also override the OnPaint event for the form and use theDrawImage method.
Upgrade
Wizard
Image controls are changed to PictureBox controls.
Line and Shape controls
Visual
Basic 6.0
The Line control displays as a horizontal, vertical, or diagonal line. The Shape controldisplays a rectangle, square, oval, circle, rounded rectangle, or rounded square.
VisualBasic.NET
The GDI+ classes in System.Drawing replace the Line and Shape controls. If youwant to draw shapes on the form, override the OnPaint event and paint circles,squares, and so forth by using the GDI+ Draw methods.
UpgradeWizard
Horizontal and vertical Line controls are changed to Label controls (no text, withheight or width set to 1). Diagonal lines raise an error in the report, and an
unsupported-control placeholder is put on the form.Rectangle and square Shape controls are changed to Label controls. Other Shapecontrols raise an error in the report, and an unsupported-control placeholder is put onthe form.
Windowless controls
VisualLightweight controls, sometimes referred to as windowless controls, differ fromregular controls in one significant way: They don't have a window handle (hWnd
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
37/58
Basic 6.0 property). Because of this, they use fewer system resources. You create a lightweightuser control by setting the Windowless property to true at design time. Lightweightuser controls can contain only other lightweight controls. Not all containers supportlightweight controls.
Visual
Basic.NET
Most windowless controls will default to being windowed when used in Windows
Forms. The main benefit of using windowless controls is to reduce resourceconsumption (window handles) when you have a very large number of controls on aform. This applies to Windows 9x only. Windows NT and Windows 2000 do nothave these resource constraints.While there are disadvantages to using windowless controls (layout issues such aslayering problems), Microsoft recognizes the value of them and will be releasingsamples that show how to achieve similar effects in Windows Forms.
UpgradeWizard
No special action is required.
Clipboard
VisualBasic 6.0
The Clipboard object provides access to the system clipboard.
VisualBasic.NET
The Clipboard class provides methods to place data on and retrieve data from thesystem clipboard. The new Clipboard class offers more functionality and supportsmore clipboard formats than the Visual Basic 6.0 Clipboard object. The objectmodel has been restructured to support these.
UpgradeWizard
The existing clipboard code cannot automatically be upgraded because of thedifferences between object models. Clipboard statements will be commented with anupgrade error.
Dynamic data exchangeVisual
Basic 6.0
Certain controls have properties and methods that support Dynamic Data Exchange(DDE) conversations.
VisualBasic.NET
Windows Forms has no built-in DDE support.
UpgradeWizard
DDE properties and methods are commented with an upgrade warning.
Web Applications
WebClasses
Visual
Basic 6.0
A WebClass is a Visual Basic component that resides on a Web server and respondsto input from the browser. A WebClass typically contains WebItems that it uses toprovide content to the browser and expose events.
VisualBasic.NET
Web Forms is a .NET Framework feature that you can use to create a browser-baseduser interface for your Web applications. Visual Basic.NET has a WYSIWYGdesigner for graphical Web Form creation using controls from the Toolbox. This
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
38/58
gives Web user-interface development the same feel as Windows development. Also,when the project is built, the Internet Information Services (IIS) server does not haveto be stopped and restarted to deploy the new bits, as it does with WebClasses.
UpgradeWizard
WebClasses are upgraded to Web Forms. Any state storage calls will be commentedwith an upgrade warning. These can be rewritten to take advantage of the ASP.NET
state management features.You may also choose to leave WebClass applications in Visual Basic 6.0, andnavigate from a Visual Basic.NET Web Form to a WebClass, to a WebForm, and soon..
ActiveX documents and DHTML applications
Visual
Basic 6.0
ActiveX documents can appear within Internet browser windows, and offer built-inviewport scrolling, hyperlinks, and menu negotiation. DHTML applications containDHTML pages and client-side ActiveX DLLs.
VisualBasic.NET
Web Forms support broad-reach applications through standard HTML. Richapplications can be supported in a much more secure way by using Windows Forms
controls hosted in a browser, or with a downloaded "safe Windows Form" EXE. Thiscode runs inside of a secure sandbox, so that it cannot do harm to a user's computer.
UpgradeWizard
While ActiveX documents and DHTML applications cannot be directly upgraded,you can still navigate between ActiveX documents, DHTML applications, and WebForms.
Data
ADO, RDO, and DAO code
Visual
Basic 6.0
ADO, RDO, and DAO objects are used for connected and disconnected data access.
VisualBasic.NET
ADO.NET provides additional classes for disconnected data access. These classesprovide performance and scalability improvements over previous versions ofActiveX Data Objects (ADO) when used in distributed applications. They alsoallow simpler integration of XML data with your database data.
Upgrade ADO, RDO, and DAO can still be used in Visual Basic.NET code.
ADO, RDO, and DAO Data Binding
Visual
Basic 6.0
Controls on Visual Basic forms can be bound to ADO, RDO, and DAO data sources.
VisualBasic.NET
ADO.NET offers read/write data binding to controls for Windows Forms and read-only data binding for Web Forms.
UpgradeWizard
ADO data binding is upgraded to the new ADO.NET data binding. However, RDOand DAO data binding cannot be upgraded and will add errors to the upgrade report.
Integrated Development Environment
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
39/58
Immediate window
Visual
Basic 6.0
From the Immediate window in Design mode, you can run parts of your code withoutlaunching the entire application through its Startup object. For example, you canshow forms, call module procedures, and interact with global variables. This ispossible because Visual Basic 6.0 is running the application from an in-memoryimage of the code, and is not debugging the built output that's used at run time.
VisualBasic.NET
From the Command window in Design mode, you can execute IDE commands, butyou cannot run individual parts of your application. This is because VisualBasic.NET runs and debugs the actual built output that is used at run time. This formof debugging provides the most accurate replication of the run-time behavior.
IDE and project extensibility
Visual
Basic 6.0
The Visual Basic 6.0 integrated development environment (IDE) extensibility modelis supported by Visual Basic 6.0 only.
VisualBasic.NETThe new IDE extensibility model is generic for all project types inside of VisualStudio.NET. This makes it much simpler to create add-ins that work with manydifferent types of projects. The Visual Basic project system extensibility model isalso shared with C#--so project specific functions, such as adding a reference orchanging a project property, are done the same way in both languages.A Visual Studio.NET code model also gives extensibility writers a common objectmodel to walk the code in projects of different languages. Visual Basic supportsreading code through the code model. To write code, you can grab an insert pointfrom the model and then spit out Visual Basic syntax.
10 Syntax Changes in VB.NET Beta 2The long-awaited VB.NET Beta 2 has been released at last, so this week's column is devoted to a few ofthe many changes in syntax that this new version enforces. This isn't a complete list, of course, and I ampretty sure I am leaving out something important, but at least you can use this information to get familiarwith the new beta in less time.
1) BitAnd, BitOr, BitXor, and BitNot are goneBeta 1 used these operators to implement bit-wise operations, whereas the old And, Or, Xor, and Not, hadbecome pure Boolean operators. After many complains from the VB community, they decided to restorethings as they work in VB6: And, Or, Xor, and Not are again bit-wise operators, and the Bitxxx operatorsare gone.
2) The AndAlso and OrElse operatorsThese operators implement short-circuit evaluation in If and Do expressions (and in general, in all Booleanexpressions that consist of multiple Boolean items). Consider this expression:
If x > 0 AndAlso y ^ x < 1 Then 26
In this case VB doesn't evaluate the term (y ^ x) if (x > 0) happens to be False, because that wouldn'tchange the value of the expression. Similarly, in the following case
Do While x = 0 OrElse y ^ 3 < x
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
40/58
VB stops evaluating the expression if (x = 0) is True, because the entire expression is surely True. While Idon't like the new AndAlso and OrElse, I think that these new names prevent VB developers fromcarelessly applying short-circuiting when they don't really mean to do so. Maybe the language is lesselegant, but certainly there will be fewer mistakes when converting legacy VB6 code.
3) Value in DIM and REDIM is the UBound of the arrayIn Beta 1, the value passed to Dim and ReDim was the number of elements (as in C++ and C#), a detail thatpuzzled many die-hard VBers. In Beta 2 this value has the same meaning as under VB6. Because allVB.NET arrays are zero-based, it means that the array always has one more element than the numberspecified in the statement:
Dim arr(10) As Integer ' this array has 11 elements
4) Equality must be performed with the Is operatorIn Beta 1 you can check whether two object variables point to the same object instance using the =operator; in Beta 2 and the final version you must use the Is operator (as you do in VB6).
5) The Microsoft.VisualBasic.Compatibility.VB6 namespace has movedThis namespace contained all the functions that have a VB6 name, and was meant to assist VB developersin migrating their apps. In Beta 2 all these functions are in the less verbose Microsoft.VisualBasicnamespace. If you have written VB.NET code that uses these functions, you should only modify the
Imports statement.
6) Attributes now precede the item they refer toIn Beta 1, position of < > attributes preceded the _name_ of the item they refer to, which led to a ratherweird syntax, as in:
Class MyClass
Fortunately, in Beta 2 and the final release, attributes will precede the item they refer to, making for a morereadable syntax that is similar to C#'s:
Class MyClass
You can move the attribute to a line of its own for a syntax that resembles C# even more closely:
_ Class MyClass
7) The Currency data type is goneThis data type isn't supported any longer and you should use Decimal instead. The Decimal type has ahigher precision and larger valid range.
8) The ToString method is now locale-awareAll classes inherit the ToString method from System.Object (the mother of all objects in .NET), and usuallyoverride it so that it returns a textual representation of the object's value. For all the objects in the .NETframework, ToString returns a local-aware value now. For example, if the object has a numeric value,ToString will return the string representation of such a value, but will use different symbols for the decimalseparator: a period in the US, a comma in most European countries.
9) Names of collection objects have changedThis change affects the name of many objects in the framework. In Beta 1 the convention for namingcollection-like objects was to use the plural of the name (e.g. "Parameters", "Properties", etc.). In Beta 2 theconvention has changed, and now these objects have a trailing "Collection" word (e.g."ParameterCollection", "PropertyCollection"). You should use a similar naming convention in your ownobject hierarchies.
10) ADO.NET namespaces have changedIn Beta 1, ADO.NET had two important namespaces: System.Data.ADO for objects of the generic dataprovider, and System.Data.Sql for the more specific SQL Server provider. These namespaces have changedinto System.Data.OleDb and System.Data.SqlClient, respectively.
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
41/58
Preparing Your Visual Basic 6.0 Applications for the Upgrade to VisualBasic.NET
Microsoft Corporation
October 2000
Summary: This document provides recommendations for Microsoft Visual Basicdevelopers planning to upgrade their applications toVisual Basic.NET. It includes information on the Visual Basic.NET Upgrade Tool and discusses architectural guidelines for enablinga smooth upgrade from Visual Basic 6 to Visual Basic.NET. (26 printed pages)
Contents
OverviewWhat Is Visual Basic.NET?Why Is Visual Basic.NET Not 100% Compatible?Upgrading to Visual Basic.NETWorking with Both Visual Basic 6.0 and Visual Basic.NETArchitecture Recommendations
Browser-based Applications Client/Server Projects Single-tier Applications DataUpgrading
Variant to Object Integer to Short Property Syntax Visual Basic Forms to Windows Forms InterfacesUpgrade Report and CommentsProgramming Recommendations
Use Early-Binding Use Date for Storing Dates Resolve Parameterless Default Properties Avoid Null Propagation Use Zero Bound Arrays Use Constants Instead of Underlying Values Arrays and Fixed-Length Strings in User-Defined Types Avoid Legacy Features Windows APIs Considerations for Forms and Controls
Overview
This document provides recommendations for developers using Microsoft Visual Basic who are planning to upgrade theirapplications to Microsoft Visual Basic.NET.
Visual Basic.NET will open and upgrade Visual Basic 6.0 projects to Visual Basic.NET technologies, but in most cases you will needto make some modifications to your projects after bringing them into Visual Basic.NET. The purpose of this document is torecommend how to design and implement your current Visual Basic projects to minimize the number of changes you will need tomake when they are upgraded to Visual Basic.NET. Where appropriate, we use new language constructs; however, this document isnot intended to be a Visual Basic.NET language reference.
Note Visual Basic.NET is still in development; some compatibility details may change before the product isreleased. Following the guidelines in this document does not guarantee your code will not require changes;instead the guidelines aim to reduce the amount of work needed for conversion.
The upgrade wizard and command-line upgrade tools in Visual Basic.NET are still in an early stage ofdevelopment and, as such, their functionality is limited. The purpose of including them in the Beta release is togive you a feel for how the upgrade process will work and to see how VB 6.0 code is modified to work inVB.NET; in Beta1, most real-world projects probably cannot be migrated successfully.
What Is Visual Basic.NET?
icense: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
-
8/8/2019 VB18
42/58
Visual Basic.NET is the next version of Visual Basic. Rather than simply adding some new features to Visual Basic 6.0, Microsoft hasreengineered the product to make it easier than ever before to write distributed applications such as Web and enterprise n-tier systems.Visual Basic.NET has two new forms packages (Windows Forms and Web Forms); a new version of ADO for accessing disconnecteddata sources; and streamlined language, removing legacy keywords, improving type safety, and exposing low-level constructs thatadvanced developers require.
These new features open new doors for the Visual Basic developer: With Web Forms and ADO.NET, you can now rapidly developscalable Web sites; with inheritance, the language now truly supports object-oriented programming; Windows Forms natively supports
accessibility and visual inheritance; and deploying your applications is now as simple as copying your executables and componentsfrom directory to directory.
Visual Basic.NET is now fully integrated with the other Microsoft Visual Studio.NET languages. Not only can you developapplication components in different programming languages, your classes can now inherit from classes written in other languagesusing cross-language inheritance. With the unified debugger, you can now debug multiple language applications, irrespective ofwhether they are running locally or on remote computers. Finally, whatever language you use, the Microsoft .NET Frameworkprovides a rich set of APIs for Microsoft Windows and the Internet.
Why Is Visual Basic.NET Not 100% Compatible?
There were two options to consider when designing Visual Basic.NETretrofit the existing code base to run on top of the .NETFramework, or build from the ground up, taking full advantage of the platform. To deliver the feat