home *** CD-ROM | disk | FTP | other *** search
/ Programming Microsoft Visual Basic .NET / Programming Microsoft Visual Basic .NET (Microsoft Press)(X08-78517)(2002).bin / setup / vbnet / 08 net data types / nettypesdemo / module1.vb < prev    next >
Encoding:
Text File  |  2002-03-16  |  38.5 KB  |  997 lines

  1. Imports System.Globalization
  2. Imports System.IO
  3. Imports Microsoft.Win32
  4.  
  5. Module MainModule
  6.  
  7.     Sub Main()
  8.         ' Run one of the Textxxxx procedures below by uncommenting only one statement
  9.  
  10.         'TestStringsAreObjects()
  11.         'TestBoxing()
  12.         'TestBoxing2()
  13.         'TestStringFunctions()
  14.         'TestForEachOnStrings()
  15.         'TestStringOptimizations()
  16.         'TestCompareOrdinal()
  17.         'TestCultureInfo()
  18.         'TestFormatNumbers()
  19.         'TestFormatDates()
  20.         'TestFormatToString()
  21.         'TestIFormattable()
  22.         'TestIFormatProvider()
  23.         'TestIFormatProvider2()
  24.         'TestChar()
  25.         'TestStringBuilder()
  26.         'TestStringBuilderVsStrings()
  27.         'TestNumberClasses()
  28.         'TestNumberFormatting()
  29.         'TestNumberParsing()
  30.         'TestConvertClass()
  31.         'TestBase64Conversions()
  32.         'TestRandom()
  33.         'TestDateTime()
  34.         'TestDateFormats()
  35.         'TestDateParsing()
  36.         'TestTimeZone()
  37.         'TestGuid()
  38.         'TestEnum()
  39.         'TestEnumFlags()
  40.  
  41.         ' These statements are usuful when running inside Visual Studio.NET
  42.         Console.WriteLine("")
  43.         Console.WriteLine(">>> write Enter to terminate the program <<<")
  44.         Console.ReadLine()
  45.     End Sub
  46.  
  47.     ' This procedure test the reference type nature of the String class.
  48.  
  49.     Sub TestStringsAreObjects()
  50.         Dim s1 As String = "ABCD"
  51.         Dim s2 As String = s1
  52.         ' Prove that both variables point to the same object, therefore strings are reference types.
  53.         Console.WriteLine(s1 Is s2)     ' => True
  54.     End Sub
  55.  
  56.     ' This procedure benchmarks calls to empty routines, one requiring boxing and the other one
  57.     ' not requiring it
  58.  
  59.     Sub TestBoxing()
  60.         Dim i As Integer
  61.         Dim start As Date
  62.         Dim res As Integer
  63.  
  64.         ' benchmark the version that does NOT use boxing
  65.         start = Now
  66.         For i = 1 To 10000000
  67.             res = GetInteger(i)
  68.         Next
  69.         Console.WriteLine("Without boxing: " & Now.Subtract(start).ToString)
  70.  
  71.         ' benchmark the version that uses boxing and unboxing
  72.         start = Now
  73.         For i = 1 To 10000000
  74.             res = CInt(GetObject(i))
  75.         Next
  76.         Console.WriteLine("With boxing: " & Now.Subtract(start).ToString)
  77.     End Sub
  78.  
  79.     ' support procedures for TestBoxing
  80.  
  81.     Function GetInteger(ByVal n As Integer) As Integer
  82.         Return n
  83.     End Function
  84.  
  85.     Function GetObject(ByVal o As Object) As Object
  86.         Return o
  87.     End Function
  88.  
  89.     ' test code optimized for boxing
  90.  
  91.     Sub TestBoxing2()
  92.         Dim i, j As Integer
  93.         Dim start As Date
  94.  
  95.         ' The version that does NOT cache the value type in a reference variable.
  96.         start = Now
  97.         For i = 1 To 1000
  98.             For j = 1 To 100000
  99.                 GetObject2(i, j)
  100.             Next
  101.         Next
  102.         Console.WriteLine("Non-optimized: " & Now.Subtract(start).ToString)
  103.  
  104.         ' The version that caches the value type in a reference variable.
  105.         start = Now
  106.         For i = 1 To 1000
  107.             ' Cache the value type in an Object variable.
  108.             Dim o As Object = i
  109.             For j = 1 To 100000
  110.                 GetObject2(o, j)
  111.             Next
  112.         Next
  113.         Console.WriteLine("Optimized: " & Now.Subtract(start).ToString)
  114.     End Sub
  115.  
  116.     Function GetObject2(ByVal o As Object, ByVal o2 As Object) As Object
  117.         Return o
  118.     End Function
  119.  
  120.     ' this procedure tests several string functions
  121.  
  122.     Sub TestStringFunctions()
  123.         ' A sequence of <N> characters û similar to VB6 String() function.
  124.         '    (Note the c suffix to "A" as a Char rather than a string.) 
  125.         Dim s As New String("A"c, 10)
  126.         Console.WriteLine(s)                           ' => AAAAAAAAAA
  127.  
  128.         'Another way to get the same result.x
  129.         s = New String(CChar("A"), 10)
  130.         Console.WriteLine(s)                           ' => AAAAAAAAAA
  131.  
  132.         s = "ABCDEFGHIJ"
  133.         Console.WriteLine(s.Length)                    ' => 10
  134.         ' Note that index is always zero-based.
  135.         Console.WriteLine(s.Chars(3))                  ' => D
  136.  
  137.         s = "ABCDEFGHIJ"
  138.         ' The VB6 way of inserting a substring after 3rd character.
  139.         s = Left(s, 3) & "1234" & Mid(s, 4)
  140.         ' The VB.NET object-oriented way to perform the same operation.
  141.         s = s.Insert(3, "1234")
  142.         Console.WriteLine(s)                           ' => ABC1234DEFGHIJ
  143.  
  144.         ' trim leading/trailing spaces and tab chars from a string.
  145.         s = "  A sentence to be trimmed  "
  146.         Dim cArr() As Char = {" "c, Chr(9)}
  147.         s = s.TrimStart(cArr)
  148.         Console.WriteLine("'" & s & "'")                           ' => 'a sentence to be trimmed'
  149.  
  150.         ' check whether a string begins with a given character sequence
  151.         If s.StartsWith("abc") Then
  152.             Console.WriteLine("The string begins with 'abc'")
  153.         Else
  154.             Console.WriteLine("The string doesn't begin with 'abc'")
  155.         End If
  156.  
  157.         ' pad to the right with zeroes
  158.         s = "12345"
  159.         s = s.PadRight(10, "0"c)
  160.         Console.WriteLine(s)                           ' => 1234500000
  161.  
  162.         ' >>>>>> This code proves that the CompareTo method works in strange ways
  163.         s = "aaa"
  164.         Console.WriteLine(s.CompareTo("AAA"))          ' => -1 
  165.         Console.WriteLine(s.CompareTo("ZZZ"))          ' => -1
  166.         Console.WriteLine(s.CompareTo("aaz"))          ' => -1  ??????
  167.         Console.WriteLine(s.CompareTo("000"))          ' =>  1  ??????
  168.  
  169.         ' use the string enumerator
  170.         s = "ABCDE"
  171.         Dim c As Char
  172.         For Each c In s
  173.             Console.Write(c & ".")       ' => A.B.C.D.E.
  174.         Next
  175.  
  176.         ' the Concat shared method
  177.         Console.Write(String.Concat("ABC ", "DEF ", "GHI"))  ' => ABC DEF GHI
  178.  
  179.         ' Compare two strings in case insensitive mode.
  180.         Dim s1 As String = "A"
  181.         Dim s2 As String = "z"
  182.         Select Case String.Compare(s1, s2, True)
  183.             Case 0 : Console.WriteLine("s1 = s2")
  184.             Case 1 : Console.WriteLine("s1 > s2")
  185.             Case -1 : Console.WriteLine("s1 < s2")
  186.         End Select
  187.     End Sub
  188.  
  189.     ' this procedure tests For Each on a string
  190.  
  191.     Sub TestForEachOnStrings()
  192.         Dim start As Date
  193.         Dim i As Integer
  194.         Dim s As New String("*"c, 1000000)
  195.         Dim c, ch As Char
  196.  
  197.         start = Now
  198.         For Each c In s
  199.             ch = c
  200.         Next
  201.         Console.WriteLine("For Each: {0} secs.", Now.Subtract(start))
  202.  
  203.         start = Now
  204.         For i = 0 To s.Length - 1
  205.             ch = s.Chars(i)
  206.         Next
  207.         Console.WriteLine("For + Chars method: {0} secs.", Now.Subtract(start))
  208.  
  209.     End Sub
  210.  
  211.     ' this procedure tests various string optimization techniques
  212.  
  213.     Sub TestStringOptimizations()
  214.         Dim s1 As String
  215.         Dim s2 As String
  216.  
  217.         ' prove that the compiler can optimize string allocation
  218.         s1 = "1234" & "5678"
  219.         s2 = "12345678"
  220.         Console.WriteLine(s1 Is s2)                     ' => True
  221.  
  222.         ' Attempt to modify the S1 string
  223.         Mid(s1, 2, 1) = "x"
  224.         ' prove that a new string was created behind the scenes
  225.         Console.WriteLine(s1 Is s2)                     ' => False
  226.  
  227.         ' Prove that the compiler isn't always able to detect same strings.
  228.         s1 = "1234"
  229.         s1 &= "5678"
  230.         s2 = "12345678"
  231.         Console.WriteLine(s1 Is s2)                     ' => False
  232.  
  233.         ' similar code, but this time
  234.         ' explicitly ask the runtime to look for a string match in the intern pool.
  235.         s1 = "ABCD"
  236.         s1 = String.Intern(s1 & "EFGH")
  237.         s2 = String.Intern("ABCDEFGH")
  238.         Console.WriteLine(s1 Is s2)                     ' => True
  239.     End Sub
  240.  
  241.     ' this procedure tests the CompareOrdinal method
  242.  
  243.     Sub TestCompareOrdinal()
  244.         Dim start As Date
  245.         Dim i As Integer
  246.         Dim res As Integer
  247.  
  248.         start = Now
  249.         For i = 1 To 10000000
  250.             res = String.CompareOrdinal("one", "ONE")
  251.         Next
  252.         Console.WriteLine("CompareOrdinal: {0} secs.", Now.Subtract(start))
  253.  
  254.         start = Now
  255.         For i = 1 To 10000000
  256.             res = String.Compare("one", "ONE")
  257.         Next
  258.         Console.WriteLine("Compare: {0} secs.", Now.Subtract(start))
  259.  
  260.         start = Now
  261.         TestOptionCompareBinary(1000000)
  262.         Console.WriteLine("Option Compare Binary: {0} secs.", Now.Subtract(start))
  263.  
  264.         start = Now
  265.         TestOptionCompareText(1000000)
  266.         Console.WriteLine("Option Compare Text: {0} secs.", Now.Subtract(start))
  267.     End Sub
  268.  
  269.     ' support routine for testing binary comparisons
  270.  
  271.     Sub TestOptionCompareBinary(ByVal times As Integer)
  272.         Dim i As Integer
  273.         Dim res As Boolean
  274.         For i = 1 To times
  275.             res = ("1111" >= CStr(i))
  276.         Next
  277.     End Sub
  278.  
  279.     ' this procedure test the CultureInfo object
  280.  
  281.     Sub TestCultureInfo()
  282.         ' Get information about the current locale.
  283.         Dim ci As CultureInfo = CultureInfo.CurrentCulture
  284.  
  285.         ' Assuming that the current language is Italian, we get:
  286.         Console.WriteLine(ci.Name)                          ' => it
  287.         Console.WriteLine(ci.EnglishName)                   ' => Italian
  288.         Console.WriteLine(ci.NativeName)                    ' => italiano
  289.         Console.WriteLine(ci.LCID)                          ' => 16
  290.         Console.WriteLine(ci.TwoLetterISOLanguageName)      ' => it
  291.         Console.WriteLine(ci.ThreeLetterISOLanguageName)    ' => ita
  292.         Console.WriteLine(ci.ThreeLetterWindowsLanguageName)  ' => ITA
  293.  
  294.         ' get additional info through the TextInfo object
  295.         Dim ti As TextInfo = ci.TextInfo
  296.         Console.WriteLine(ti.ANSICodePage)                    ' => 1252
  297.         Console.WriteLine(ti.EBCDICCodePage)                  ' => 20280
  298.         Console.WriteLine(ti.OEMCodePage)                     ' => 850
  299.         Console.WriteLine(ti.ListSeparator)                   ' => ;
  300.  
  301.         ' How do you spell "Sunday" in German?
  302.         ' First, create a CultureInfo for German.
  303.         Dim ciDe As New CultureInfo("de-DE")
  304.         ' Next, get the corresponding DateTimeFormatInfo object.
  305.         Dim dtfi As DateTimeFormatInfo = ciDe.DateTimeFormat
  306.         '' Here's the answer.
  307.         Console.WriteLine(dtfi.GetDayName(DayOfWeek.Sunday))   ' => Sonntag
  308.  
  309.         ' Get info on all the installed cultures.
  310.         Dim ciArr() As CultureInfo = CultureInfo.GetCultures(CultureTypes.AllCultures)
  311.  
  312.         ' Print abbreviation and English name of each culture.
  313.         Dim c As CultureInfo
  314.         For Each c In ciArr
  315.             Console.WriteLine(c.Name & " (" & c.EnglishName & ")")
  316.         Next
  317.  
  318.         ' Compare these two strings in case insensitive mode
  319.         ' according to rules of Italian language.
  320.         Dim s1 As String = "cioΦ"
  321.         Dim s2 As String = "CIO╚"
  322.         ' You can create a CultureInfo on the fly.
  323.         If String.Compare(s1, s2, True, New CultureInfo("it")) = 0 Then
  324.             Console.WriteLine("s1 = s2")
  325.         End If
  326.  
  327.     End Sub
  328.  
  329.     ' this procedure tests formatting number options
  330.  
  331.     Sub TestFormatNumbers()
  332.         Dim msg As String
  333.  
  334.         ' Print the value of a string variable.
  335.         Dim xyz As String = "foobar"
  336.         msg = String.Format("The value of {0} variable is {1}", "XYZ", xyz)
  337.         Console.WriteLine(msg)      ' => The value of XYZ variable is foobar
  338.  
  339.         ' Format a Currency according to current locale.
  340.         msg = String.Format("Total is {0:C}, balance is {1:C}", 123.45, -67)
  341.         Console.WriteLine(msg)      ' => Total is $123.45, balance is ($67.00)
  342.  
  343.         ' The Number format uses the thousand separator character
  344.         msg = String.Format("Total is {0:N}", 123456.78)
  345.         Console.WriteLine(msg)      ' => Total is 123,456.78
  346.  
  347.         ' You can append an integer after the "N" character to round 
  348.         ' or extend the number of digits after the decimal point:
  349.         msg = String.Format("Total is {0:N4}", 123456.785555)
  350.         Console.WriteLine(msg)      ' => Total is 123,456.7856
  351.  
  352.         ' the Decimal format works with integers only
  353.         msg = String.Format("Total is {0:D8}", 123456)
  354.         Console.WriteLine(msg)      ' => Total is 00123456
  355.  
  356.         'The fixed-point format is useful with decimal values, 
  357.         ' and you can specify how many decimal digits should be displayed (2 if no length is provided):
  358.         msg = String.Format("Total is {0:F3}", 123.45678)
  359.         Console.WriteLine(msg)      ' => Total is 123.457
  360.  
  361.         'The scientific (or exponential) format displays numbers as n.nnnnE+eeee 
  362.         ' and you can control how many digital digits are used in the mantissa portion:
  363.         msg = String.Format("Total is {0:E}", 123456.789)
  364.         Console.WriteLine(msg)      ' => Total is 1.234568E+005
  365.  
  366.         msg = String.Format("Total is {0:E3}", 123456.789)
  367.         Console.WriteLine(msg)      ' => Total is 1.235E+005
  368.  
  369.         'The General format converts to either fixed-point or exponential format, 
  370.         ' depending on which format delivers the most compact result:
  371.         msg = String.Format("Total is {0:G}", 123456)
  372.         Console.WriteLine(msg)      ' => Total is 123456
  373.  
  374.         msg = String.Format("Total is {0:G4}", 123456)
  375.         Console.WriteLine(msg)      ' => Total is 1235E+05
  376.  
  377.         ' the X format converts numbers to hexadecimal strings; 
  378.         ' if you specify a length, the number is padded with leading zeroes if necessary:
  379.         msg = String.Format("Total is {0:X8}", 65535)
  380.         Console.WriteLine(msg)      ' => Total is 0000FFFF
  381.  
  382.         ' The Percent format
  383.         msg = String.Format("Percentage is {0:P}", 0.123)
  384.         Console.WriteLine(msg)      ' => Percentage is 12.30 %
  385.  
  386.         ' The RoundTrip format converts numbers to a string without omitting any prevcision loss
  387.         msg = String.Format("Value of PI is {0:R}", Math.PI)
  388.         Console.WriteLine(msg)      ' => Value of PI is 3.1415926535897931
  389.  
  390.         ' examples of custom formats for numbers
  391.  
  392.         msg = String.Format("Total is {0:##,###.00}", 1234.567)
  393.         Console.WriteLine(msg)      ' => Total is 1,234.57
  394.  
  395.         msg = String.Format("Percentage is {0:##.000%}", 0.3456)
  396.         Console.WriteLine(msg)      ' => Percentage is 34.560%
  397.  
  398.         ' An example of prescaler
  399.         msg = String.Format("Length in {0:###,.00 }", 12344)
  400.         Console.WriteLine(msg)      ' => Total is 12.34
  401.  
  402.         ' Two examples of exponential format
  403.         msg = String.Format("Total is {0:#.#####E+00}", 1234567)
  404.         Console.WriteLine(msg)      ' => Total is 1.23457E+06
  405.  
  406.         msg = String.Format("Total is {0:#.#####E0}", 1234567)
  407.         Console.WriteLine(msg)      ' => Total is 1.23457E6
  408.  
  409.         ' Two examples with separate sections
  410.         msg = String.Format("Total is {0:##;<##>}", -123)
  411.         Console.WriteLine(msg)      ' => Total is <123>
  412.  
  413.         msg = String.Format("Total is {0:#;(#);zero}", -1234567)
  414.         Console.WriteLine(msg)      ' => Total is (1234567)
  415.  
  416.         Dim N1 As Integer = 1234
  417.         Dim N2 As Integer = 4566
  418.         msg = String.Format("N1 is {0:greater than;less than;equal to} N2", N1 - N2)
  419.         Console.WriteLine(msg)      ' => N1 is less than N1
  420.     End Sub
  421.  
  422.     ' this procedure test date formatting
  423.  
  424.     Sub TestFormatDates()
  425.         Dim msg As String
  426.  
  427.         msg = String.Format("Current Date Time is {0:f}", Now())
  428.         Console.WriteLine(msg)      ' => Current Date Time is Sunday, March 04, 2001 3:54 PM
  429.  
  430.         msg = String.Format("Current year is {0:yyyy}", Now())
  431.         Console.WriteLine(msg)      ' => Current year is 2001
  432.  
  433.         ' Format a date in the format mm/dd/yyyy, regardless of current locale.
  434.         msg = String.Format("{0:MM\/dd\/yyyy}", Now())
  435.         Console.WriteLine(msg)      ' => 03/04/2001
  436.     End Sub
  437.  
  438.     ' This procedure demonstrates that an object can change the way it reacts when
  439.     ' passed to a Console.Write method, by overriding the ToString method
  440.  
  441.     Sub TestFormatToString()
  442.         Dim msg As String
  443.         Dim p As New PointXY(12.4, 5.6)
  444.  
  445.         msg = String.Format("First point is {0}", p)
  446.         Console.WriteLine(msg)        ' => First point is (12.4,5.6)
  447.     End Sub
  448.  
  449.     ' this procedure tests the IFormattable interface
  450.  
  451.     Sub TestIFormattable()
  452.         Dim msg As String
  453.         msg = String.Format("First point is {0:[X-Y]}", New PointXY2(1, 5))
  454.         Console.WriteLine(msg)
  455.     End Sub
  456.  
  457.     ' this procedure tests the IFormatProvider and ICustomFormatter interfaces
  458.  
  459.     Sub TestIFormatProvider()
  460.         ' Prepare an array of arguments (25 inches and 5.2 feet).
  461.         Dim args() As Object = {25, 5.1}
  462.         ' Note that we create an instance of MetricConverter on the fly.
  463.         Console.WriteLine(String.Format(New MetricConverter(), _
  464.             "Width is {0:in}, Height is {1:fe} meters", args))
  465.         ' => Width is 0.635, Height is 1.683 meters
  466.     End Sub
  467.  
  468.     ' this procedure tests how to use IFormatter and a CultureInfo object
  469.  
  470.     Sub TestIFormatProvider2()
  471.         ' Create a CultureInfo object for French-Canadian
  472.         Dim ci As New System.Globalization.CultureInfo("fr-CA")
  473.         ' This is the amount to be format as Canadian money (dollars).
  474.         Dim amount As Double = 12345.6
  475.         Dim msg As String = String.Format(ci, "{0:C}", amount)
  476.         Console.WriteLine(msg)          ' => 12 345.60 $
  477.     End Sub
  478.  
  479.     ' this procedure tests a few shared methods of the Char data type
  480.  
  481.     Sub TestChar()
  482.         ' Check an individual Char value.
  483.         Console.WriteLine(Char.IsDigit("1"c))          ' => True
  484.         ' Check the N-th character in a string.
  485.         Console.WriteLine(Char.IsDigit("A123", 0))     ' => False
  486.     End Sub
  487.  
  488.     ' this procedure tests the StringBuilder object
  489.  
  490.     Sub TestStringBuilder()
  491.         ' Create a StringBuilder object with capacity of 1000 characters.
  492.         Dim sb As New System.Text.StringBuilder(1000)
  493.  
  494.         ' Create a comma-delimited list of the first 100 integers.
  495.         Dim n As Integer
  496.         For n = 1 To 100
  497.             ' Note that two Append methods are faster than a single Append
  498.             ' whose argument is the concatenation of N and ",".
  499.             sb.Append(n)
  500.             sb.Append(",")
  501.         Next
  502.  
  503.         ' insert a string at the beginning of the buffer
  504.         sb.Insert(0, "List of numbers: ")
  505.  
  506.         Console.WriteLine(sb)   ' => List of numbers: 1,2,3,4,5,6,...
  507.  
  508.         ' display length of the current string 
  509.         Console.WriteLine("Length is " & sb.Length.ToString)   ' => 309
  510.  
  511.         ' Show how to use a StringBuilder to receive a value from an API call.
  512.         ' Get the path of the windows directory
  513.         Dim tmpPath As New System.Text.StringBuilder(256)
  514.         Dim length As Integer = GetTempPath(tmpPath.Capacity, tmpPath)
  515.         tmpPath.Length = length
  516.         Console.WriteLine("Windows Temp Directory: {0}", tmpPath.ToString)
  517.     End Sub
  518.  
  519.     Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" (ByVal nBufferLength As Integer, ByVal lpBuffer As System.Text.StringBuilder) As Integer
  520.  
  521.     ' this procedure compares performance of String ans StringBuilder classes
  522.  
  523.     Sub TestStringBuilderVsStrings()
  524.         Dim i As Integer
  525.         Dim s As String
  526.         Dim dt As DateTime
  527.  
  528.         Const TIMES As Integer = 10000
  529.  
  530.         Console.WriteLine(TIMES.ToString & " iterations.")
  531.  
  532.         Console.Write("Appending to a regular string: ")
  533.         dt = Date.Now
  534.         For i = 1 To TIMES
  535.             s &= CStr(i) & ","
  536.         Next
  537.         Console.WriteLine(Now.Subtract(dt).ToString & " secs.")
  538.  
  539.         Console.Write("Appending to a StringBuilder: ")
  540.         dt = Date.Now
  541.         Dim sb As New System.Text.StringBuilder(TIMES * 4)
  542.  
  543.         For i = 1 To TIMES
  544.             sb.Append(CStr(i))
  545.             sb.Append(",")
  546.         Next
  547.         Console.WriteLine(Now.Subtract(dt).ToString & " secs.")
  548.     End Sub
  549.  
  550.     ' this procedure demonstrates how to use the ToString method and
  551.     ' other members of numeric classes
  552.  
  553.     Sub TestNumberClasses()
  554.         ' Convert an integer to hexadecimal.
  555.         Console.WriteLine(1234.ToString("X"))           ' => 4D2
  556.  
  557.         ' Display PI with 6 digits (in all).
  558.         Dim d As Double = Math.PI
  559.         Console.WriteLine(d.ToString("G6"))         ' => 3.14159
  560.  
  561.         Dim sngValue As Single = 1.23
  562.         ' Compare the Single variable sngValue with 1.
  563.         ' Note that you must force the argument to Single.
  564.         Select Case sngValue.CompareTo(CSng(1))
  565.             Case 1
  566.                 Console.WriteLine("sngValue is > 1")
  567.             Case 0
  568.                 Console.WriteLine("sngValue is = 1")
  569.             Case -1
  570.                 Console.WriteLine("sngValue is < 1")
  571.         End Select
  572.  
  573.         ' Display the highest value you can store in a Double variable.
  574.         Console.WriteLine(Double.MaxValue)      ' => 1.7976931348623157E308
  575.  
  576.         ' the smallest positive numbers that can be stored in a Single or Double variable
  577.         Console.WriteLine(Single.Epsilon)       ' => 1.401298E-45
  578.         Console.WriteLine(Double.Epsilon)       ' => 4.94065645841247E-324
  579.  
  580.         ' Any number divided by infinity gives zero.
  581.         Console.WriteLine(1 / Double.PositiveInfinity)       ' => 0
  582.     End Sub
  583.  
  584.     ' this procedure tests the formatting of numbers
  585.  
  586.     Sub TestNumberFormatting()
  587.         Dim intValue As Integer = 12345
  588.         Console.WriteLine(intValue.ToString("##,##0.00", Nothing))  ' => 12,345.00
  589.  
  590.         ' this code requires the following Imports
  591.         '    Imports System.Globalization
  592.  
  593.         ' create a readable NumberFormatInfo object which is initialized
  594.         ' with attributes from the current locale
  595.         Dim nfi As NumberFormatInfo = CType(NumberFormatInfo.CurrentInfo.Clone, NumberFormatInfo)
  596.         ' NFI is a read-write object, so we can change its properties.
  597.         nfi.NumberDecimalSeparator = ","
  598.         nfi.NumberGroupSeparator = " "
  599.         ' We can now format a value with our custom NumberFormatInfo object.
  600.         Dim sngValue As Single = 12345.5
  601.         Console.WriteLine(sngValue.ToString("##,##0.00", nfi))  ' => 12 345,50
  602.     End Sub
  603.  
  604.     ' this procedure tests the parsing of numerical values
  605.  
  606.     Sub TestNumberParsing()
  607.         ' Next line assigns 1234 to the variable.
  608.         Dim shoValue As Short = Short.Parse("1234")
  609.         Console.WriteLine(shoValue)                  ' => 1234
  610.  
  611.         Dim dblValue As Double = Double.Parse(" 1,234.56E6  ", NumberStyles.Any)
  612.         Console.WriteLine(dblValue)                  ' => 1234560000
  613.  
  614.         Dim style As NumberStyles = NumberStyles.AllowDecimalPoint Or NumberStyles.AllowLeadingSign
  615.         ' This works and assigns û123.45 to dblValue.
  616.         Dim sngValue As Single = Single.Parse("-123.45", style)
  617.         Console.WriteLine(sngValue)                  ' => -123.45
  618.  
  619.         ' This throws a FormatException, because of the thousand separator.
  620.         Try
  621.             sngValue = Single.Parse("12,345.67", style)
  622.         Catch ex As Exception
  623.             Console.WriteLine("An exception has occurred")
  624.         End Try
  625.  
  626.         ' Allow a thousand separator, but you decide what a thousand separator can be.
  627.         Dim nfi As NumberFormatInfo = _
  628.             CType(NumberFormatInfo.CurrentInfo.Clone, NumberFormatInfo)
  629.         ' Use a period to group digits, and a comma as a decimal separator
  630.         nfi.NumberGroupSeparator = "."
  631.         nfi.NumberDecimalSeparator = ","
  632.         ' Parse a string using the specified separators.
  633.         dblValue = Double.Parse("12345,56", NumberStyles.Any, nfi)
  634.         Console.WriteLine(dblValue)
  635.     End Sub
  636.  
  637.     ' this procedure tests the Convert class
  638.  
  639.     Sub TestConvertClass()
  640.         ' Use a NumberFormatInfo object to convert a string into a Double.
  641.  
  642.         Dim nfi As NumberFormatInfo = _
  643.             CType(NumberFormatInfo.CurrentInfo.Clone, NumberFormatInfo)
  644.         ' Use a period to group digits, and a comma as a decimal separator
  645.         nfi.NumberGroupSeparator = "."
  646.         nfi.NumberDecimalSeparator = ","
  647.  
  648.         ' Parse a string using the specified separators.
  649.         Dim dblValue As Double = Convert.ToDouble("12.345,56", nfi)
  650.         Console.WriteLine(dblValue)     ' => 12345.56
  651.     End Sub
  652.  
  653.     ' this procedure tests Base64 conversions
  654.  
  655.     Sub TestBase64Conversions()
  656.         ' an array of 16 bytes (two identical sequances of 8 bytes)
  657.         Dim b() As Byte = {12, 45, 213, 88, 11, 220, 34, 0, 12, 45, 213, 88, 11, 220, 34, 0}
  658.         ' convert it to a base64 string (for UU-encoding)
  659.         Dim s64 As String = Convert.ToBase64String(b)
  660.         Console.WriteLine(s64)
  661.  
  662.         ' convert it back to an array of bytes
  663.         Dim b2() As Byte = Convert.FromBase64String(s64)
  664.  
  665.         ' check that the two arrays are equal
  666.         Dim i As Integer
  667.         Dim different As Boolean
  668.         For i = 0 To b.GetUpperBound(0)
  669.             Console.Write(b2(i).ToString & " ")
  670.             If b(i) <> b2(i) Then different = True
  671.         Next
  672.  
  673.         Console.WriteLine("")
  674.         If different Then
  675.             Console.WriteLine("The base-64 string wasn't converted back correctly")
  676.         Else
  677.             Console.WriteLine("The base-64 string was converted back correctly")
  678.         End If
  679.     End Sub
  680.  
  681.     ' this procedure tests random number generation
  682.  
  683.     Sub TestRandom()
  684.         ' You need these conversions because the Ticks property
  685.         ' returns a 64-bit value that must be truncated to a 32-bit integer.
  686.         Dim rand As New Random(CInt(Date.Now.Ticks And Integer.MaxValue))
  687.  
  688.         ' display 10 random integer values.
  689.         Dim i As Integer
  690.         For i = 1 To 10
  691.             Console.WriteLine(rand.Next)
  692.         Next
  693.  
  694.         ' Get a value in the range 0 to 1000.
  695.         Dim intValue As Integer = rand.Next(1000)
  696.         Console.WriteLine(intValue)
  697.         ' Get a value in the range 100 to 1000.
  698.         intValue = rand.Next(100, 1000)
  699.  
  700.         ' get a floating point value in the range 0-1
  701.         Dim dblValue As Double = rand.NextDouble
  702.         Console.WriteLine(dblValue)
  703.  
  704.         ' Get an array of 100 random byte values.
  705.         Dim buffer(100) As Byte
  706.         rand.NextBytes(buffer)
  707.  
  708.         Dim b As Byte
  709.         For Each b In buffer
  710.             Console.Write(b.ToString & " ")
  711.         Next
  712.     End Sub
  713.  
  714.     ' this procedure tests date and time methods
  715.  
  716.     Sub TestDateTime()
  717.         ' Create a Date value by providing year, month, and day values.
  718.         Dim dt1 As Date = New Date(2001, 3, 6)              ' March 6, 2001
  719.         Console.WriteLine(dt1)
  720.  
  721.         ' Provides also hour, minute, and second values.
  722.         Dim dt2 As Date = New Date(2001, 3, 6, 18, 30, 20)  ' March 6, 2001 6:30:20 PM
  723.         Console.WriteLine(dt2)
  724.  
  725.         ' Add millisecond value (half a second in this example).
  726.         Dim dt3 As Date = New Date(2001, 3, 6, 18, 30, 20, 500)
  727.         Console.WriteLine(dt3)
  728.  
  729.         ' Create a time value from ticks (10 million ticks = 1 second)
  730.         Dim ticks As Long = 20000000                        ' 2 seconds
  731.         ' This is considered the time elapsed from Jan 1, 0001.
  732.         Dim dt4 As Date = New Date(ticks)                   ' 1/1/0001 12:00:02 AM
  733.         Console.WriteLine(dt4)
  734.  
  735.         ' The Now property returns the system date and time.
  736.         Dim dt5 As Date = Date.Now          ' e.g. October 21, 2001 3:22:30 PM
  737.         Console.WriteLine(dt5)
  738.         ' The Today property returns the system date only.
  739.         Dim dt6 As Date = Date.Today        ' e.g. October 21, 2001 0:00:00 AM
  740.         Console.WriteLine(dt6)
  741.  
  742.         ' Is today the first day of the current month?
  743.         If Date.Today.Day = 1 Then Console.WriteLine("First day of month")
  744.         ' How many days have passed since January 1?
  745.         Console.WriteLine(Date.Today.DayOfYear)
  746.         ' Get current time û note that ticks are included.
  747.         Console.WriteLine(Date.Now.TimeOfDay)     ' => 10:39:28.3063680
  748.  
  749.         ' Tomorrow's date
  750.         Console.WriteLine(Date.Today.AddDays(1))
  751.         ' Yesterday's date
  752.         Console.WriteLine(Date.Today.AddDays(-1))
  753.         ' What time will it be 2 hours and 30 minutes from now?
  754.         Console.WriteLine(Date.Now.AddHours(2.5))
  755.  
  756.         ' A CPU-intensive way to pause for 2 seconds.
  757.         Dim endTime As Date = Date.Now.AddSeconds(2)
  758.         Do : Loop Until Date.Now > endTime
  759.  
  760.         ' TimeSpan constructors
  761.  
  762.         ' One Long value is interpreted as a Ticks value.
  763.         Dim ts1 As TimeSpan = New TimeSpan(13500000)         ' 1.35 seconds
  764.         Console.WriteLine(ts1)
  765.         ' Three Integer values are interpreted as hours, minutes, seconds.
  766.         Dim ts2 As TimeSpan = New TimeSpan(0, 32, 20)        ' 32 minutes, 20 seconds
  767.         Console.WriteLine(ts2)
  768.         ' Four Integer values are interpreted as days, hours, minutes, seconds.
  769.         Dim ts3 As TimeSpan = New TimeSpan(1, 12, 0, 0)      ' 1 day and a half
  770.         Console.WriteLine(ts3)
  771.         ' (Note that arguments aren't checked for out-of-range errors, therefore
  772.         '  the next statement delivers the same result as the previous one.)
  773.         Dim ts4 As TimeSpan = New TimeSpan(0, 36, 0, 0)      ' 1 day and a half
  774.         Console.WriteLine(ts4)
  775.         ' A fifth argument is interpreted as a millisecond value.
  776.         Dim ts5 As TimeSpan = New TimeSpan(0, 0, 1, 30, 500) ' 90 seconds and a half
  777.         Console.WriteLine(ts5)
  778.  
  779.         ' What will be the time 2 days, 10 hours, and 30 minutes from now?
  780.         Console.WriteLine(Date.Now.Add(New TimeSpan(2, 10, 30, 0)))
  781.  
  782.         ' What was the time 1 day, 12 hours, and 20 minutes ago?
  783.         Console.WriteLine(Date.Now.Subtract(New TimeSpan(1, 12, 20, 0)))
  784.  
  785.         ' How many days, hours, minutes, and seconds have elapsed 
  786.         ' since the beginning of the third millennium ?
  787.         Dim startDate As New Date(2001, 1, 1)
  788.         Dim ts As TimeSpan = Date.Now.Subtract(startDate)
  789.         Console.WriteLine(ts)                ' => 206.11:11:35.4627792 (may vary, of course)
  790.  
  791.         ' Is current date later than October 30, 2001 ?
  792.         Select Case Date.Today.CompareTo(New Date(2001, 10, 30))
  793.             Case 1   ' later than Oct 30, 2001
  794.                 Console.WriteLine("Later than Oct 30, 2001")
  795.             Case -1  ' earlier than Oct 30, 2001
  796.                 Console.WriteLine("Earlier than Oct 30, 2001")
  797.             Case 0   ' Today is Oct 30, 2001
  798.                 Console.WriteLine("Today is Oct 30, 2001")
  799.         End Select
  800.  
  801.         ' Test for a leap year.
  802.         Console.WriteLine(Date.IsLeapYear(2000))          ' => True
  803.         ' Retrieve number of days in a given month.
  804.         Console.WriteLine(Date.DaysInMonth(2000, 2))      ' => 29
  805.     End Sub
  806.  
  807.     ' this procedure tests date formats
  808.  
  809.     Sub TestDateFormats()
  810.         ' This is March 6, 2001 6:18:20.500 PM û US East Coast time.
  811.         Dim dt As Date = New Date(2001, 3, 6, 18, 30, 20, 500)
  812.  
  813.         Console.WriteLine(dt.ToShortDateString)   ' => 03/06/2001
  814.         Console.WriteLine(dt.ToLongDateString)    ' => Tuesday, March 06, 2001
  815.         Console.WriteLine(dt.ToShortTimeString)   ' => 6:30 PM
  816.         Console.WriteLine(dt.ToLongTimeString)    ' => 6:30:20 PM
  817.         Console.WriteLine(dt.ToFileTime)          ' => 126283734205000000
  818.         Console.WriteLine(dt.ToOADate)            ' => 36956.7710706019
  819.         Console.WriteLine(dt.ToUniversalTime)     ' => 3/6/2001 11:30:20 PM
  820.         Console.WriteLine(dt.ToLocalTime)         ' => 3/6/2001 1:30:20 PM
  821.  
  822.     End Sub
  823.  
  824.     ' this procedure tests date parsing
  825.  
  826.     Sub TestDateParsing()
  827.         Dim dt As Date = Date.Parse("2001/3/6 12:20:30")
  828.         Console.WriteLine(dt)                               ' => 3/6/2001 12:20:30 PM
  829.  
  830.         ' Get a writeable copy of the current locale's DateTimeFormatInfo object.
  831.         Dim dtfi As DateTimeFormatInfo
  832.         dtfi = CType(DateTimeFormatInfo.CurrentInfo.Clone, DateTimeFormatInfo)
  833.         ' Change date and time separators.
  834.         dtfi.DateSeparator = "-"
  835.         dtfi.TimeSeparator = "."
  836.         ' Now we're ready to parse a date formatted in a non-standard way.
  837.         Dim dt2 As Date = Date.Parse("2001-3-6 12.20.30", dtfi)
  838.         Console.WriteLine(dt2)                              ' => 3/6/2001 12:20:30 PM
  839.  
  840.         ' Prepare to parse (dd/mm/yy) dates, in short or long format.
  841.         dtfi.ShortDatePattern = "d/M/yyyy"
  842.         dtfi.LongDatePattern = "dddd, dd MMMM, yyyy"
  843.  
  844.         ' Both dt3 and dt4 are assigned the date "March 6, 2001".
  845.         Dim dt3 As Date = Date.Parse("6-3-2001", dtfi)
  846.         Console.WriteLine(dt3)                                  ' => 3/6/2001 12:00:00 AM
  847.         Dim dt4 As Date = Date.Parse("Tuesday, 6 March, 2001", dtfi)
  848.         Console.WriteLine(dt4)                                  ' => 3/6/2001 12:00:00 AM
  849.  
  850.         ' Print the abbreviated names of months.
  851.         Dim s As String
  852.         For Each s In DateTimeFormatInfo.CurrentInfo.AbbreviatedMonthNames
  853.             Console.WriteLine(s)
  854.         Next
  855.  
  856.         ' dt5 is assigned the date "March 6, 2001".
  857.         Dim dt5 As Date = Date.ParseExact("6-3-2001", "d-M-yyyy", Nothing)
  858.         Console.WriteLine(dt5)                                  ' => 3/6/2001 12:00:00 AM
  859.     End Sub
  860.  
  861.     ' this procedure tests the TimeZone object
  862.  
  863.     Sub TestTimeZone()
  864.         ' Get the TimeZone object for current time zone.
  865.         Dim tz As TimeZone = TimeZone.CurrentTimeZone
  866.         ' Display name of time zone, without and with daylight time.
  867.         ' (I got this results by running this code in Italy.)
  868.         Console.WriteLine(tz.StandardName)  ' => W. Europe Standard Time
  869.         Console.WriteLine(tz.DaylightName)  ' => W. Europe Daylight Time
  870.  
  871.         ' Time offset of W.Europe time zone in March, when no daylight time is active.
  872.         Console.WriteLine(tz.GetUtcOffset(New Date(2001, 3, 1)))         ' => 01:00:00
  873.         ' Time offset of W.Europe time zone in July, when daylight time is active.
  874.         Console.WriteLine(tz.GetUtcOffset(New Date(2001, 7, 1)))         ' => 02:00:00
  875.  
  876.         ' Daylight time in July.
  877.         Console.WriteLine(tz.IsDaylightSavingTime(New Date(2001, 7, 1)))   ' => True
  878.  
  879.         ' Retrieve the DaylightTime object for year 2001 for Italy.
  880.         Dim dlc As System.Globalization.DaylightTime = tz.GetDaylightChanges(2001)
  881.         Console.WriteLine("Starts at " & dlc.Start)    ' => Starts at 3/25/2001 2:00:00 AM
  882.         Console.WriteLine("Ends at " & dlc.End)        ' => Ends at 10/28/2001 3:00:00 AM
  883.         ' Delta returns a TimeSpan object
  884.         Console.WriteLine("Delta is " & dlc.Delta.TotalMinutes.ToString & " minutes.")
  885.         ' => Delta is 60 minutes.
  886.     End Sub
  887.  
  888.     ' this procedure tests the GUID type
  889.  
  890.     Sub TestGuid()
  891.         ' create a new GUID
  892.         Dim guid1 As Guid = Guid.NewGuid
  893.  
  894.         ' By definition, you'll surely get a different output here.
  895.         Console.WriteLine("New GUID: " & guid1.ToString)
  896.         '=> New GUID: 3f5f1d42-2d92-474d-a2a4-1e707c7e2a37
  897.  
  898.         ' initialize from a string.
  899.         Dim guid2 As New Guid("45FA3B49-3D66-AB33-BB21-1E3B447A6621")
  900.  
  901.         ' Convert to an array of bytes.
  902.         Dim bytes() As Byte = guid1.ToByteArray
  903.         Dim b As Byte
  904.         For Each b In bytes
  905.             Console.Write(b.ToString & " ")
  906.         Next
  907.         Console.WriteLine("")
  908.  
  909.         ' Compare two GUIDs.
  910.         If guid1.Equals(guid2) Then
  911.             Console.WriteLine("GUIDs are equal.")
  912.         Else
  913.             Console.WriteLine("GUIDs are different.")
  914.         End If
  915.     End Sub
  916.  
  917.     ' this procedure tests various Enum behaviors
  918.  
  919.     Sub TestEnum()
  920.         Dim de As DataEntry = DataEntry.DateTime
  921.  
  922.         ' Display the numeric value.
  923.         Console.WriteLine(de)                 ' => 3
  924.         ' Display the symbolic value.
  925.         Console.WriteLine(de.ToString)        ' => DateTime
  926.  
  927.         ' Show the value in hexadecimal format with four digits.
  928.         Console.WriteLine(de.ToString("X"))   ' => 0003
  929.  
  930.         ' You can use the GetType method (inherited from System.Object)
  931.         ' to get the Type object required by the Parse method.
  932.         de = CType([Enum].Parse(de.GetType, "CharString"), DataEntry)
  933.         ' Print the enum value corresponding to CharString
  934.         Console.WriteLine(de)                   ' => 2
  935.  
  936.         ' *** This statement throws an exception. 
  937.         Try
  938.             de = CType([Enum].Parse(de.GetType, "charstring"), DataEntry)
  939.         Catch ex As Exception
  940.             Console.WriteLine(ex.Message)
  941.         End Try
  942.  
  943.         ' This works well, because case-insensitive comparison is used.
  944.         de = CType([Enum].Parse(de.GetType, "charstring", True), DataEntry)
  945.         Console.WriteLine(de)
  946.  
  947.         ' The GetUnderlying method
  948.         Console.WriteLine([Enum].GetUnderlyingType(de.GetType))    ' => System.Int16
  949.  
  950.         ' NOTE: it is important that the second argoment of IsDefined
  951.         '       be the same type as the underlying type of the Enum (Short in this case)
  952.         If [Enum].IsDefined(GetType(DataEntry), 3S) Then
  953.             ' 3 is a valid value for the DataEntry class.
  954.             de = CType(3, DataEntry)
  955.             Console.WriteLine(de.ToString)                          ' DateTime
  956.         End If
  957.  
  958.         ' This code produces an invalid result, yet it doesn't throw an exception.
  959.         de = CType(123, DataEntry)
  960.  
  961.         ' Another way to check whether an enum value is valid
  962.         ' (doesn't require strict type matching ,as IsDefined does)
  963.         If [Enum].GetName(GetType(DataEntry), 3) <> "" Then
  964.             de = CType(3, DataEntry)
  965.         End If
  966.         Console.WriteLine("")
  967.  
  968.         ' List all the values in DataEntry.
  969.         Dim names() As String = [Enum].GetNames(GetType(DataEntry))
  970.         Dim values As Array = [Enum].GetValues(GetType(DataEntry))
  971.         Dim i As Integer
  972.  
  973.         For i = 0 To names.Length - 1
  974.             Console.WriteLine("{0} = {1}", names(i), CInt(values.GetValue(i)))
  975.         Next
  976.     End Sub
  977.  
  978.     ' this procedure tests bitcoded Enums
  979.  
  980.     Sub TestEnumFlags()
  981.         Dim vde As ValidDataEntry
  982.         vde = ValidDataEntry.IntegerNumber Or ValidDataEntry.DateTime
  983.         Console.WriteLine(vde.ToString)       ' => IntegerNumber, DateTime
  984.  
  985.         Dim vde2 As ValidDataEntry
  986.         Console.WriteLine(vde2.ToString)      ' => None
  987.  
  988.         vde = CType(123, ValidDataEntry)
  989.         Console.WriteLine(vde.ToString)       ' => 123
  990.  
  991.         vde = CType([Enum].Parse( _
  992.             vde.GetType, "IntegerNumber, FloatingNumber"), ValidDataEntry)
  993.         Console.Write(CInt(vde))              ' => 3
  994.     End Sub
  995.  
  996. End Module
  997.