Chapter 2: Language Surprises in VB .NET


This chapter demonstrates that the relatively familiar face of VB .NET conceals a quite different beast underneath than the one to which you are accustomed. The examples in this chapter show unintuitive and sometimes surprising behavior ensuing from some of the new and changed features in VB .NET. The result of executing each of the code samples in this chapter often violates the important principle of "least surprise." Because surprises are one of the major causes of bugs, it is worthwhile to take the time to analyze and understand these examples. Many of the examples mentioned in this chapter are surprises associated with implementation inheritance. This is no accident . Inheritance is a complicated subject fraught with difficulties, and without a good understanding of the issues it is very easy to create both design and implementation bugs when coding base or derived classes.

The True Value of True in VB .NET

I start with something simple. VB.Classic was always prone to taking a contrary view of the world, usually in order to make life simpler for its users. For instance, while most languages considered true to equate to 1, VB.Classic stated that true was really “1. When moving VB forward to .NET, the language team faced a dilemma. Should they redefine true to be the value used by the common language runtime (CLR) and the other .NET languages, or should they keep the same value to remain compatible with gigabytes of VB.Classic code that already exist? Listing 2-1 shows that they decided to have their cake and eat it too.

Listing 2-1. What Is True Really?
start example
 Option Strict On Module Test     Sub Main()         Console.WriteLine("CInt(True) = " + CInt(True).ToString)         Console.WriteLine("Convert(True) = " + Convert.ToInt16(True).ToString)         Console.ReadLine()     End Sub End Module 
end example
 

This code returns the following result:

start sidebar
 CInt(True) = -1 Convert(True) = 1 
end sidebar
 

So the value of true in VB .NET is not fixed ”it depends on which view you take. If you use VB.Classic functions such as CInt , then true will be “1. On the other hand, VB .NET functions such as Convert will return true as 1. As long as you have Option Strict On so that no implicit conversions are performed, and as long as you always compare to true or false rather than to “1 or 1, you will be okay.




Comprehensive VB .NET Debugging
Comprehensive VB .NET Debugging
ISBN: 1590590503
EAN: 2147483647
Year: 2003
Pages: 160
Authors: Mark Pearce

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net