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.
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.
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
This code returns the following result:
CInt(True) = -1 Convert(True) = 1
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.