|
Introduction
The .NET Framework classes (or the System classes) provide a huge amount of core functionality that Microsoft has made available and that you can take advantage of when building .NET applications from any .NET language. In part one (http://www.15seconds.com/Issue/010322.htm) of this two-part series of articles, I introduced the Microsoft .NET Framework and described several of the base System classes: System.Math and System.Random. In this article, I discuss additional classes that you may find useful in your ASP.NET applications: the System.String, System.Array, and System.DateTime classes.
Download supporting code and files
Figuring Out What's Out There
Before I begin to delve into more system classes, I thought I'd first mention how you figure out what classes are available. The definitive source of information on the system classes can be found under the .NET Framework Reference node of the .NET Framework SDK Documentation Help file that is installed onto your computer when you install the .NET Framework SDK or Visual Studio.NET (see http://msdn.microsoft.com/downloads/default.asp?URL=/code/sample.asp?url=/msdn-files/027/000/976/msdncompositedoc.xml). For example, Figure 1 shows a summary of the members of the System.Array class from the .NET Framework SDK Documentation Help file.

Figure 1. The members of the Array class as documented in the .NET Framework SDK Documentation help file.
Of course, since the .NET Framework is currently in beta, the "definitive" source is still a work in progress. Regardless, you'll find a lot of useful information--but not many examples--on using the System classes in the .NET Framework SDK Documentation help file.
As mentioned in Part 1 of this series, if you use VB.NET as your development language, you will often have a choice of whether to use functionality built into the Visual Basic language or the equivalent System class functionality. This is the certainly the case when manipulating arrays and working with dates, times, and strings. If you're an experienced VB 6.0 programmer, your first inclination will be to stick with the tried and true ways of doing things. I would encourage you, however, to break with the old and use the .NET System classes wherever possible. Why? Because using the System classes makes your code more portable to other languages and better suited for future versions of VB.NET.
Manipulating Strings Using the System.String Class
The System.String class provides rich functionality for manipulating strings. Using System.String, you can determine a string's length, search for substrings, change the case of a string, compare two strings, and split strings, among other things.
You use the Length property to determine a string's length. For example, in the following code, intLength would equal 4:
Dim strColor As String = "blue"
Dim intLength As Integer
intLength = strColor.length
You use the IndexOf method to extract the first instance of a substring from a string. IndexOf returns the starting position of the substring if it's found (with the first character located at position 0) or -1 if the substring is not found. All searches are case sensitive.
IndexOf is overloaded, allowing you to pass it a parameter of type Char, String, or an array of type Char. The following page (IndexOf.aspx) illustrates the use of IndexOf with each of these different parameter types:
<%@ Page Language="vb" Explicit="True"%>
<head>
<title>15Seconds System.String Example</title>
<script language="vb" runat="server">
Sub Page_Load(Src as Object, E as EventArgs)
Dim chrG As Char = "G"
Dim strWord As String = "for"
Dim chrVowels As Char() = {"a","e","i","o","u"}
Dim strPhrase As String = _
"One small step for man, one giant leap for mankind."
Dim i As Integer
lblOutput.Text &= "<br />strPhrase = " & strPhrase
lblOutput.Text &= "<br />Position of chrG = " _
& strPhrase.IndexOf(chrG)
lblOutput.Text &= "<br />Position of strWord = " _
& strPhrase.IndexOf(strWord)
lblOutput.Text &= "<br />Position of chrVowels = " _
& strPhrase.IndexOf(chrVowels)
End Sub
</script>
</head>
<body>
<asp:label id="lblOutput" runat="server" />
</body>
</html>
The output generated by this page is shown in Figure 2.

Figure 2. This page (IndexOf.aspx) illustrates the use of the String.IndexOf method. Notice that chrG (which contains "G") was not found because searches are case-sensitive.
IndexOf takes two optional parameters that let you limit the search by specifying the starting and ending position within the string to search. For example, the following code would limit the search for chrVowels to between position 10 and 20:
strPhrase.IndexOf(chrVowels, 10, 20)
The LastIndexOf method is identical to IndexOf except that it searches for the last instance of a substring. For example, if you modified IndexOf.aspx to use the LastIndexOf method instead of the IndexOf method, the position of strWord would be 39 instead of 15.
You use the ToUpper and ToLower methods of the System.String class to change the case of a string into all uppercase or all lowercase, respectively. For example:
strUpper = "This is a mixed case sentence".ToUpper()
strLower = "This is a mixed case sentence".ToLower()
This example illustrates that you can use the System.String class properties and methods with string literals, in addition to string variables.
You can use the Compare method to compare two strings for equality. Compare returns 0 if the strings are equal, a negative number if the first string is less than the second, or a positive number if the first string is greater than the second string. Compare is a static method (see the first part of this series for a discussion of the difference between static and instance members). By default its comparisons are case-sensitive and made without regard to locale information. For example, the following comparison between str1 and str2 returns a value of -1, indicating that str1 is less than str2:
Dim str1 As String = "15Seconds.com"
Dim str2 As String = "15Seconds.Com"
answer = String.Compare(str1, str2)
You can pass the Compare method, an optional third parameter with a value of True, to ignore case. Thus, in the following code, the answer would equal 0, indicating that the strings are identical:
answer = String.Compare(str1, str2, True)
Like the IndexOf method, Compare is overloaded. You can pass it a fourth parameter to indicate you wish to make a locale-specific comparison. Or you can call it with starting and ending character positions to limit the comparison to a subset of the strings. See the .NET Framework SDK Documentation for more details.
Use the Split method to take a string and convert it into an array of substrings. You need to pass Split a separator character of type Char that it uses to split the strings. The following code from Split.aspx illustrates the use of the Split method:
<%@ Page Language="vb" Explicit="True"%>
<head>
<title>15Seconds String.Split Example</title>
<script language="vb" runat="server">
Sub Page_Load(Src as Object, E as EventArgs)
Dim strASP As String = _
"ASP.NET is the next generation of Active Server Pages."
Dim strWords() As String
Dim i As Integer
strWords = strASP.Split(" ")
For i = strWords.GetLowerBound(0) to strWords.GetUpperBound(0)
lblOutput.Text &= i & ": " & strWords(i) & "<br />"
Next
End Sub
</script>
</head>
<body>
<asp:label id="lblOutput" runat="server" />
</body>
</html>
The output from Split.aspx is shown in Figure 3.

Figure 3. The array of words produced using the String.Split method.
I've shown here just a sample of the properties and methods of the String class. This class contains additional members for creating a string from an array, replacing one character with another, trimming leading and trailing whitespace from a string, and more.
Using System.Array to Work with Arrays
You can use the System.Array class to manipulate arrays in a variety of ways. Again, much of the functionality of System.Array duplicates legacy VB functionality. However, the Array class adds a few things that legacy VB functions can't accomplish, like the ability to search and sort arrays.
The GetLowerBound and GetUpperBound methods of the Array class are used to determine the lower and upper bounds of a given dimension of an array. The following statement from Split.aspx (introduced in the previous section of code) uses these methods to determine the boundaries of the strWords array:
For i = strWords.GetLowerBound(0) to strWords.GetUpperBound(0)
Use the static Sort method of the System.Array class to sort the contents of a one-dimensional array. The Sort method sorts the elements using a case-sensitive algorithm and won't work with arrays of more than one dimension. You call the Sort method like this:
Array.Sort(array_name)
You can also use the Reverse method to reverse the elements in a one-dimensional array. Its syntax is similar to Sort:
Array.Reverse(array_name)
This code (from the ArraySort.aspx sample Web page) demonstrates the use of Sort and Reverse:
Dim strTerms() As String = {"JScript", "VB", "ASP", "ASP.NET", ".NET"}
Dim i As Integer
lblOutput.Text &= "Original Array<br />"
For i = strTerms.GetLowerBound(0) to strTerms.GetUpperBound(0)
lblOutput.Text &= i & ": " & strTerms(i) & "<br />"
Next
Array.Sort(strTerms)
lblOutput.Text &= "<br />After Sorting<br />"
For i = strTerms.GetLowerBound(0) to strTerms.GetUpperBound(0)
lblOutput.Text &= i & ": " & strTerms(i) & "<br />"
Next
Array.Reverse(strTerms)
lblOutput.Text &= "<br />After Reversing<br />"
For i = strTerms.GetLowerBound(0) to strTerms.GetUpperBound(0)
lblOutput.Text &= i & ": " & strTerms(i) & "<br />"
Next
The output produced by the ArraySort.aspx page is shown in Figure 4.

Figure 4. The System.Array class includes two static methods, Sort and Reverse, for sorting and reversing arrays, respectively.
The System.Array class also supports searching for items in one-dimensional arrays using the IndexOf and LastIndexOf methods, which are analogous to the System.String class' methods of the same name. To search for an item in an array using IndexOf or LastIndexOf, use the following syntax:
answer = Array.IndexOf(array_name, search_string)
answer = Array.LastIndexOf(array_name, search_string)
The methods return the position of the either the first or last item that matches the search string, or -1 if no match is found. The searches are case-sensitive. For example, in the following code, the answer would equal 2, indicating that the string "ASP" was found in the third element of the strTerms array:
Dim strTerms() As String = {"JScript", "VB", "ASP", "ASP.NET", ".NET"}
answer = Array.IndexOf(strTerms, "ASP")
Arranging Dates Using the System.DateTime Class
The System.DateTime class provides a number of methods for working with DateTime values. To create a DateTime value, simply declare a variable of type DateTime and assign it to a DateTime constant using "#" as the delimiter. For example:
Dim SeattleQuake As DateTime = #02/28/01 10:54#
One of the great things about the System.DateTime class is how easy it is to parse DateTime values using its properties. The properties are pretty self-explanatory: Year, Month, Day, DayOfWeek, DayOfYear, Hour, Minute, Second, Millisecond, Ticks, etc. A tick represents 100 nanoseconds. In the following line of code the answer would equal 10:
answer = SeattleQuake.Hour
You can also use the Date and TimeOfDay properties to grab only the date or only the time portions of a DateTime value. DateTime returns another DateTime value, but TimeOfDay returns a TimeSpan value, which represents an elapsed time in ticks. As you might have guessed, you can also use properties of a TimeSpan value to parse out the parts of a TimeSpan time. See the .NET Framework SDK Documentation for more details.
The System.DateTime class also provides several methods for adding (or subtracting) portions of time to DateTime values: AddYears, AddMonths, AddDays, AddHours, AddMinutes, AddSeconds, AddMilliseconds, and AddTicks.
For example, the following code takes a date (BDay) and adds and subtracts one year from it:
Dim BDay As DateTime = #6/25/2001 12:00#
Dim NextBDay As DateTime
Dim LastBDay As DateTime
NextBDay = TheDate.AddYears(1)
LastBDay = TheDate.AddYears(-1)
Summary
The .NET Framework provides a wealth of functionality that is built into a number of System classes. This two-part series explored the properties and methods of the System.Math, System.Random, System.String, System.Array, and System.DateTime classes. But I've only scratched the surface of the System classes. The .NET Framework contains literally hundreds of classes containing thousands of properties and methods. As mentioned in the beginning of this article, your best resource for investigating the .NET Framework in general and the System classes in particular is the .NET Framework SDK Documentation Help file that is part of the .NET Framework SDK. One caveat: this article was based on my experimentation with Beta1 of the .NET Framework. Some of the classes I discussed may change between now and when the final version of .NET ships.
About the Author
Paul Litwin is the president of Litwin Consulting, providing development, training, and mentoring services in ASP, ASP.NET, Visual Basic, SQL Server, XML, Microsoft Access, and related technologies. He is the Conference Chair for the ASP Connections conference (www.asp-connections.com) and the author of several books including the forthcoming ASP.NET for Developers (SAMS) and Access 2002 Developer's Handbook (Sybex). He can be reached at paul@litwinconsulting.com or www.litwinconsulting.com.
|