Visual Basic has been a powerful and easy-to-use language for many years , in part because many common operations are intrinsic to the language. With VB.NET, these operations have become members of the Microsoft.VisualBasic namespace. This namespace provides many of the functions that were previously built in to the language. By making the functions part of the .NET Framework Class Library, they become available to other .NET languages, not just VB.NET. In addition, the .NET System namespace provides many other functions that VB programmers will find useful. This chapter outlines several types of utility functions available to VB.NET programmers, ranging from common mathematical operations to financial functions to character and string manipulation operations. For a detailed discussion of these functions and many example programs, please consult Chapter 8 of our book Introduction to Visual Basic Using .NET . Overview In this section we give an overview of the variety of useful functions that are available. On the book's software distribution we provide a set of example programs, which should help you get up and running. You can find detailed descriptions of the functions in the .NET Framework SDK documentation. Table 4-3 provides a summary of the various groups of utility functions that are available. We show the namespace for the classes that implement the functions Table 4-3. VB.NET Utility Functions Function Group | Namespace(s) | Math | System.Math | Financial | Microsoft.VisualBasic.Financial | Informational | Microsoft.VisualBasic.Information | Conversion | Built-in (CInt, CStr, CType, etc.) System (Convert class) Microsoft.VisualBasic.Conversion | Control Characters | Microsoft.VisualBasic.ControlChars Microsoft.VisualBasic.Constants | Character Manipulation | System (Char structure) | String Manipulation | System (String, StringBuilder classes) Microsoft.VisualBasic.Strings | Date and Time | System (DateTime and TimeSpan structures) Microsoft.VisualBasic.DateTime | Format | System (String.Format method) Microsoft.VisualBasic.Strings | Environment | System.Environment | Math Functions There are many mathematical functions available in the .NET Framework. These functions include algebraic functions such as Log and Sqrt , as well as trigonometric functions such as Sin and Cos . There are also constants E and PI . In VB.NET most mathematical functions are provided by the System.Math class in .NET Framework class library. Many of these functions replace functions that were a part of the VB6 language. | The MathFunctions program illustrates the use of some of the mathematic functions available to Visual Basic .NET programmers as well as the use of the System.Math constants. You will notice that because the exponentiation (^) and remainder ( Mod ) operators are part of the Visual Basic language, the .NET functions Exp , Pow , and IEEERemainder provide alternate ways of performing operations that are already part of the programming language. | Financial Functions | There are many financial functions available for use by VB.NET programmers. The Microsoft.VisualBasic.Financial namespace is home to many functions that were found in previous versions of Visual Basic. Table 4-4 lists some of the more useful functions. Examples of the use of many of these functions can be found in the program FinancialFunctions . | Table 4-4. Financial Functions available in VB.NET Microsoft.VisualBasic.Financials functions | Description | DDB | Uses the double-declining balance method to find the depreciation of an asset. | FV | Calculates the future value of an annuity. | IPmt | Finds the interest payment for a given period of an annuity based on periodic fixed payments and a fixed interest rate. | MIRR | Finds the modified internal rate of return for a series of periodic cash flows (payments and receipts). | NPer | Finds the number of periods for an annuity based on periodic fixed payments and a fixed interest rate. | NPV | Finds the net present value of an investment based on a series of periodic cash flows (payments and receipts) and a discount rate. | Pmt | Calculates the payment for annuity. | PPmt | Finds the principal payment for a given period of an annuity based on periodic fixed payments and a fixed interest rate. | PV | Calculates the present value of an annuity. | SLN | Uses the straight-line method to find the depreciation of an asset. | SYD | Uses the sum-of-years digits method to find the depreciation of an asset. | Informational Functions There are functions in the Micrsoft.VisualBasic.Information namespace that can be used to make decisions about the type of contents of a variable. In general these functions would be used to preserve compatibility with existing VB code. For newer code, you should be able to accomplish the same task using native .NET functions. Conversion Functions The most basic type of conversion involves use of built-in functions such as CInt . The spirit of the use of these functions is the same as in earlier versions of VB, but details are different, because VB.NET has a different set of data types, and some data types have changed size (for example, Integer is 32 bits in VB.NET and was only 16 bits in earlier versions of VB). For more elaborate conversions in new code, you should use the Convert class of the System namespace. The Microsoft.VisualBasic.Conversion namespace is available to preserve compatibility with conversions in legacy VB code. Control Characters The Microsoft.VisualBasic.ControlChars namespace contains a collection of character constants that represent control characters. Here are some examples: -
Back -
Cr -
Lf -
CrLf -
and so forth As we saw earlier in the chapter in Table 4-1, you can also use the classic VB constants of vbBack , vbCr , vbLf , vbCrLf , and so forth. Character Manipulation Functions The Microsoft.VisualBasic.Strings namespace contains several functions, such as Asc , AscW , Chr , and so on, that can be useful when working with characters. For new code, you should use methods of the Char structure. String Manipulation Functions For new code, you should use the .NET String and StringBuilder classes, which we discussed earlier in the chapter. For compatibility with older VB code, you can make use of functions in the Microsoft.VisualBasic.Strings namespace. Date and Time For compatibility with previous VB code, you can use functions in the Microsoft.VisualBasic.DateTime namespace. For new code, use the DateTime structure in the System namespace, which is identical to the built-in VB.NET Date type. Because of its importance in many applications, you should take time to familiarize yourself with the new .NET DateTime structure and its many useful properties and methods. Basically, DateTime represents dates and times ranging from 12 midnight, January 1 of the year 1 A.D . to 11:59:59 of December 31 of the year 9999 A.D . Time values are measured in units of 100 nanoseconds, called ticks . A TimeSpan structure can be used to represent an interval of time. Table 4-5 shows some of the common properties and methods of DateTime . Table 4-5. Selected Methods and Properties of DateTime Member | Property or Method | Description | Now | Shared Method | Current local date and time | ToString | Method (several overloads) | String representation, available in a variety of formats | DayOfYear | Property | Day of the year of this instance | DayOfWeek | Property | Day of the week of this instance | Hour | Property | Hour component of this instance | Minute | Property | Minute component of this instance | Ticks | Property | Number of 100 nanosecond ticks | Add | Method | Add a TimeSpan to a DateTime | The program DateTimeDemo illustrates these operations. The current date and time is found and displayed in various ways. The following are a few of the many formats available for displaying a DateTime using the ToString method: -
d or short date -
D or long date -
t or short time -
T or long time A TimeSpan object is created using one of several overloaded constructors. The constructor in this program takes as parameters a day, hour, minute, and second. We want to find a time 30 days and 1 hour in the future. The date and time at this future moment are displayed. Here is the code: Module DateTimeDemo Sub Main() Dim dt As DateTime = DateTime.Now Console.WriteLine("Current date and time") Console.WriteLine("DateTime = {0}", dt) Console.WriteLine("Date (short) = {0}", _ dt.ToString("d")) Console.WriteLine("Date (long) = {0}", _ dt.ToString("D")) Console.WriteLine("Time (short) = {0}", _ dt.ToString("t")) Console.WriteLine("Time (long) = {0}", _ dt.ToString("T")) 'Some other date and time metrics Console.WriteLine("DayOfYear = {0}", _ dt.DayOfYear) Console.WriteLine("DayOfWeek = {0}", _ dt.DayOfWeek) Console.WriteLine("Hour = {0}", _ dt.Hour) Console.WriteLine("Minute = {0}", _ dt.Minute) Console.WriteLine("Ticks = {0}", _ dt.Ticks) 'TimeSpan of 30 days and 1 hour Dim ts As New TimeSpan(30, 1, 0, 0) Console.WriteLine("30 days and 1 hour later") dt = dt.Add(ts) Console.WriteLine("DateTime = {0}", dt) End Sub End Module Here is the output: Current date and time DateTime = 2/11/2002 5:06:11 PM Date (short) = 2/11/2002 Date (long) = Monday, February 11, 2002 Time (short) = 5:06 PM Time (long) = 5:06:11 PM DayOfYear = 42 DayOfWeek = Monday Hour = 17 Minute = 6 Ticks = 631490439719857312 30 days and 1 hour later DateTime = 3/13/2002 6:06:11 PM Format Functions The String data type has several methods to help you format information, including the methods Format , PadLeft , and PadRight . There are additional formatting functions in the Microsoft.VisualBasic.Strings namespace. The following code examples are taken from the program FormatFunctions . The Format method is useful for formatting numbers . It uses the same syntax that is used in the WriteLine method. It returns a value representing the formatted string. For example: Dim s As String Dim n As Decimal = 123.45 s = String.Format("Amount = {0,10:C}", n) Console.WriteLine(s) The output of this example is: Amount = 3.45 If you only want to control the formatting of string values, that is, make them align the way you want, then use the PadLeft and PadRight methods. The methods require that you specify the total width of the string that you want returned, including the text before padding, and they create a return value padded to the desired width. In the following code, a string is built by padding two column headings. The pad character is a space. Dim heading1 As String = "Number" Dim heading2 As String = "Power" Dim heading As String = heading1.PadRight(12) & _ heading2.PadLeft(13) Console.WriteLine(heading) Dim i As Integer Dim value As Long For i = 0 To 31 value = 2 ^ i Console.WriteLine("2^{0,-10}{1,13:N0}", i, value) Next The format for the variable i specifies a field width of 10, left justified. The format for the variable value indicates a field width of 13, right justified, numeric (N) with 0 digits after the decimal. The column heading for i was padded to a width of 12 to correspond to the output of the value i (width 10) combined with the two characters in the literal "2^". Output of this example is: Number Power 2^0 1 2^1 2 2^2 4 2^3 8 2^4 16 2^5 32 . . . 2^28 268,435,456 2^29 536,870,912 2^30 1,073,741,824 2^31 2,147,483,648 The PadLeft and PadRight methods can also be used specify a padding character. In the following example, a decimal account is preceded by asterisks : Dim s As String Dim n As Decimal = 123.45 s = n.ToString() s = s.PadLeft(9, "*"c) Console.WriteLine(s) The output is: ***123.45 Environment Functions The System.Environment namespace contains a collection of properties and methods that can be used to gather information about the environment that an application is running in. Table 4-6 lists some of the more useful functions: Table 4-6. Environment Functions in VB.NET Function | Description | CurrentDirectory | Returns a string containing the name of the current working directory. | Exit | Terminates the process. | GetCommandLineArgs | Returns an array of strings representing the command line arguments that were used to launch the program. | GetEnvironmentVariables | Returns all environment variables and their values. | MachineName | Returns a string containing the NetBIOS name of the computer. | OSVersion | Returns an OperatingSystem object that can be queried to determine information about the current operating system. | TickCount | Returns the number of milliseconds that have elapsed since the system started. Useful for benchmarking the execution speed of code. | UserName | Returns a string containing the user name of the person who started the thread. | The program EnvironmentFunctions shown below illustrates the use of some of these methods. It uses TickCount to benchmark the performance of the application. You will notice from the output that it executes much more slowly from within the Visual Studio IDE. The program displays the name of the user and the name of the machine that the program runs on. ' Demonstrates the use of the Environment functions Imports System Imports Microsoft.VisualBasic.ControlChars Module EnvironmentFunctions Sub Main() ' Get the tick when the application begins Dim startTick As Long startTick = Environment.TickCount ' Find the user and machine name Dim userName As String = Environment.UserName Dim machineName As String = Environment.MachineName Console.WriteLine(_ "Current user on machine {0} is {1}", _ machineName, userName) ' Get the tick at the end of the application Dim endTick As Long endTick = Environment.TickCount ' Write benchmarking times to the console Console.WriteLine(_ "The code took {0} milliseconds to execute", _ endTick - startTick) End Sub End Module |