In the previous article in this series, you discovered how to use variables to store information, do math and other operations, and how to display the results. In this article, you’ll explore the use of functions and arguments.
Commands in VB.NET come in two flavors: statements and functions. A statement is a command that stands on its own and simply does something. Dim, which declares variables, is a statement:
Dim Artist, CD As String
A function, on the other hand, returns a value for you to use in your code. In this article, I describe how functions work and introduce you to some functions that are handy when dealing with dates.
Getting a Date
The following code shows how you can use the Today function:
Imports System Imports Microsoft.VisualBasic Module DateToday Public Sub Main() Dim CurrentDate As String CurrentDate = Today Console.WriteLine("The current date is " & CurrentDate) End Sub End Module
The first thing you’ll notice is that I added another Imports line at the top. The Microsoft.VisualBasic library is one that contains all the core functions for the Visual Basic language. You’ll want to include this library in almost every Visual Basic .NET application that you write.
The variable CurrentDate is created and then assigned the value that is returned from the Today function. Then, the value of CurrentDate is used within a sentence to inform the user of the current date.
You might think that Today looks like a variable that simply isn’t declared—And you’re right. It does look like that. However, you know it isn’t a variable because it isn’t declared and because you happen to know that Today is a built-in function with a special meaning in VB.NET. (Okay, you may not have known that before, but you do now!) You’ll discover more built-in functions as you explore VB.NET.
What Is Meant By “Returns a Value?”
If you haven’t used a computer language with functions before, the concept of a function returning a value can be confusing. When I say a value is returned, what do I mean?
You call the built-in VB.NET function Today when you use its name in the code. When it’s called, the function goes out to the system clock and finds out the current date. Then, the function sends that current date back to your code and places the value in the code right where the Today function appears. The date returned by the function is then assigned to the CurrentDate variable:
CurrentDate = Today
So, this line does two things:
- It calls the Today function.
- It assigns the date returned from the Today function to the CurrentDate variable.
A function also can have arguments (sometimes referred to as parameters). An argument is a value that you can send to the function when you call it. By passing an argument to a function, you give the function information to work on. For example, take a look at the Weekday function:
Imports System Imports Microsoft.VisualBasic Module WeekdayToday Public Sub Main() Dim ThisDay, ThisDate As String ThisDate = Today ThisDay = Weekday(ThisDate) Console.WriteLine("It is day number " & ThisDay) End Sub End Module
First, ThisDay and ThisDate are declared as string variables.
The next line calls the Today function. The Today function gets the system date and returns it. The value returned is assigned to ThisDate.
The next line calls the Weekday function and passes the value of ThisDate as an argument. Weekday uses this date to determine the weekday on which the date falls. Notice that you pass arguments by placing them after the function name and putting them in parentheses. If this function had taken two arguments, you would put them both inside parentheses and separate them with a comma.
For the Weekday function, the value returned is a number from 1 to 7, indicating Sunday through Saturday. If you want to make this code more concise, you could do it this way:
Imports System Imports Microsoft.VisualBasic Module WeekdayToday Public Sub Main() Dim ThisDay As String ThisDay = Weekday(Today) Console.WriteLine("It is day number " & ThisDay) End Sub End Module
The Today function is called first and then the value it returns is immediately sent to the Weekday function as an argument.
Using Functions in Formulas with Rnd and Int
One of the handier things about functions and the way they return their values is that you can use them right in the middle of larger formulas. To illustrate how this works, I’m going to introduce you to two new functions: Rnd and Int.
Run the following program and look at the results:
Imports System Imports Microsoft.VisualBasic Module RandomNumber Public Sub Main() Dim RandNum As Single Randomize RandNum = Rnd Console.WriteLine(RandNum) End Sub End Module
Now, run the program again. And again. If everything went well, you see a new number appear each time you run the program. Because the number is random, I don’t know exactly what number you’ll see, and you get a different number every time. But the number probably looks something like this:
The Randomize statement and the Rnd function work together to generate random numbers. Randomize needs to appear in any program where you plan to use the Rnd function—before you use it. Randomize gets the ball rolling.
Then, Rnd returns decimal numbers that are greater than 0 but less than 1. You get a different number each time you run the program. Random numbers come in very handy when you’re creating games and some types of cool graphics.
Note: The computer actually goes through a complex formula to generate a “random” number. But, the computer needs a number to stick into the formula to kick it off—what programmers call a seed value. If you don’t use the Randomize statement, the computer always starts with the same seed. And, therefore, the computer ends up with the same series of “random” numbers every single time. Not very random, right? So, Randomize goes to the system clock and gets the numbers that it uses as the seed for the complex formula. That way, the seed and the random numbers are different every time you run your program.
But, these random numbers between 0 and 1 aren’t very useful, are they? For example, if you wanted to create a program that simulates drawing cards or rolling dice, you would want numbers between 1 and 13 or between 1 and 6. Unfortunately, VB.NET doesn’t provide any other random-number functions. So, you have to use this one and tweak it a little. Take a look at this code:
RandNum = (Rnd * 6) + 1
This line calls the Rnd function, which returns a decimal value between 0 and 1. Then, that value is multiplied by 6. Now, you have a decimal value between 0 and 5. So you add 1 to get a decimal value between 1 and 6. That number is then assigned to the RandNum variable.
The parentheses help VB.NET decide which calculations it does first. In this case, it multiplies 6 times the number returned from Rnd first because that’s in parentheses. (Actually, in this case, even if the parentheses weren’t there, VB.NET would always do the multiplication before the addition, but the parentheses make it clearer.)
Try plugging the preceding line of code into your program in place of the RandNum = Rnd line. Save it, compile, and run. See what you get. You’ll should see a number that looks something like this:
Run it again. You should continue to see numbers like that between 1 and 6. Great! That’s what you wanted, right? Well, yes, except for that annoying decimal part of the number. If only you could just chop off that decimal part.
And, of course, you can. Just use a function called Int, which stands for integer. Just as the Integer data type enables you to create variables that hold whole numbers, so the Int function takes a number with a decimal part (like the ones you’re getting here) and returns an integer. The Int function expects one argument: a number with a decimal part. Int returns the exact same number with the decimal part chopped off.
Notice I didn’t say that Int rounds the number off—it doesn’t. Int simply, unceremoniously, chops off any decimal part and returns the whole number.
Replace the RandNum = (Rnd * 6) + 1 line in your program with this new one:
RandNum = Int(Rnd * 6) + 1
Save, compile, and run your program again. Again, I can’t predict exactly what number you’ll see, but it should look something like this:
Run it again. Each time, you should see whole numbers between 1 and 6. Perfect! Now you can create random numbers between 1 and any number you like.
Want to simulate pulling cards off a deck? Use this line:
RandNum = Int(Rnd * 13) + 1
The 1 is an Ace, 11 through 13 are Jacks through Kings, and the rest are number cards. Easy enough.
Want to simulate flipping a coin? Use this line:
RandNum = Int(Rnd * 2) + 1
This code generates either a 1 or a 2. Call 1 heads and 2 tails and you’re ready to go!
Finally, if you want to generate random percentages, use this line:
RandNum = Int(Rnd * 100) + 1
More Common Functions
This section introduces you to some of the more commonly used functions in VB.NET. You’ve seen a few of these functions already, but most of them, you haven’t.
This summary should give you a good idea of many things VB.NET can help you do. But, keep in mind that this isn’t an exhaustive list of functions—not by a long shot. And even with the functions I do list here, I won’t bore you with every last detail. If you need more information, you can check out the VB.NET documentation, which comes with the .NET Framework.
Playing with Strings
Strings are letters, words, and numbers that can be stored in a variable. For example, names, addresses, and book titles are stored in the computer as strings. Because strings are so important, many commands and functions exist to deal with them. I describe some of the more important ones here.
Len is short for length. When you send a string to this function as an argument, it returns the number of characters in the string.
Here’s an example:
Imports System Imports Microsoft.VisualBasic Module StringLength Public Sub Main() Dim MyString As String Dim MyLength As Integer MyString = "Butter side down" MyLength = Len(MyString) Console.WriteLine("This string: " & MyString) Console.WriteLine("Is " & MyLength & " letters long.") End Sub End Module
MyLength is 16—that’s how many letters are in the string.
LCase and UCase both take one string as an argument. They both return that same string converted to lower- or uppercase, respectively:
LCase("This Is A Scary Story")
This function would return “this is a scary story”.
UCase("This Is A Scary Story")
This function returns “THIS IS A SCARY STORY”.
LTrim, RTrim, Trim
The trim functions—LTrim, RTrim, and Trim—each receive a string as an argument and return a string. The string returned is the same as the string sent except that:
- LTrim chops off any spaces that appear on the left side of the string (at the beginning). These are often referred to as leading spaces.
- RTrim chops off any spaces that appear on the right side of the string (at the end). These are often referred to as trailing spaces.
- Trim chops off both leading and trailing spaces.
LTrim(" Hello! ")
This function returns "Hello! ".
RTrim(" Hello! ")
This function returns " Hello!".
Trim(" Hello! ")
This function returns "Hello!".
With the Space function, you can easily create a string with lots of spaces in it. Just send a number indicating how many spaces you want, and Space returns a string of that length, filled with spaces:
This function returns " " (15 spaces).
Left, Mid, Right
Left, Mid, and Right are very useful. They enable you to tear apart a string into smaller strings.
Left takes two arguments: a string and a number. It returns a string that consists of the left-most characters of the string sent:
This function returns “Dog”.
This function returns “Rubb”.
Right works exactly the same way, but it takes the characters from the right side of the string:
This function returns “bones”.
Mid takes characters from anywhere within a string. The first argument is the string you want to work with. The second argument determines where in the string to begin, and the third argument determines how many characters to use. Mid returns the string that results:
Mid("Quick brown fox",7, 5)
This function returns “brown”.
It starts with the seventh character (“b”) and takes five characters total (including the seventh).
InStr is a really handy function. It searches for a shorter string within a long string. If it finds the shorter string, InStr returns the position within the larger string where the shorter string can be found.
In other words, InStr returns the character position at which it finds the second argument within the first argument.
Here’s an example:
Imports System Imports Microsoft.VisualBasic Module EggsHam Public Sub Main() Dim BigString, FindString As String Dim Position As Integer BigString = "I do not like green eggs and ham." FindString = "eggs" Position = InStr(BigString, FindString) Console.WriteLine("This string: " & FindString) Console.WriteLine("Appears inside: " & BigString) Console.WriteLine("At position " & Position) End Sub End Module
Position holds the value 21, because “eggs” starts at the 21st position in BigString.
Replace goes a step further than InStr. It looks for a small string inside a larger one, and when the small string is found, it is replaced with another specified string.
Here’s an example:
Imports System Imports Microsoft.VisualBasic Module MaryLamb Public Sub Main() Dim BigString as string BigString = "Mary had a little lamb" Console.WriteLine(Replace(BigString, "little", "big")) End Sub End Module
This program displays the following line:
Mary had a big lamb
Format enables you to take a date, time, or number and format it the way you want it to look. You send two arguments. The first can be a date, a time, or a number. Or, you can use a variable holding a date, time, or number. The second argument can hold many different values depending on what you’re trying to format and how you want it to look.
Here’s an example:
Imports System Imports Microsoft.VisualBasic Module VariousFormats Public Sub Main() Console.WriteLine(Format(0.675,"p")) Console.WriteLine(Format(55102,"n")) Console.WriteLine(Format(1552,"c")) Console.WriteLine("") Console.WriteLine(Format(Now,"g")) Console.WriteLine(Format(Now,"d")) Console.WriteLine(Format(Now,"t")) Console.WriteLine("") Console.WriteLine(Format(Now,"MMM dd, yyyy")) End Sub End Module
Here’s the result this program produces:
67.50 % 55,102.00 $1,552.00 12/21/2004 6:20 PM 12/21/2004 6:20 PM Dec 21, 2004
As this example shows, you can use many letters for the second argument, and each letter has a predefined meaning. Table 1 lists common examples of the letters you can use for this argument.
Table 1. Common Format arguments.
|Letter||What It Means|
You also can enter your own format using certain letters in combination, as the last Format line in the example shows. For more details and options, see the .NET Framework documentation.
Date and Time Functions
These VB.NET functions provide key date and time access and manipulation functions.
Today, TimeOfDay, Now
Today, TimeOfDay, and Now are functions that take no arguments and each returns a single value, swiped from the system clock:
- Today returns today’s date.
- TimeOfDay returns the current time.
- Now returns the date and time together.
Weekday accepts a date as an argument. It returns a number between 1 and 7, indicating the number of the day on which that date falls.
WeekdayName conveniently accepts a number argument between 1 and 7 and returns the name of the associated weekday:
This line would display the current day of the week.
Other date and time functions
VB.NET provides a broad variety of date and time commands and functions. Here are some date and time functions you may find interesting:
- DateDiff: Returns how many days, weeks, months, or years exist between two dates.
- DateAdd: Adds a certain number of days, weeks, months, or years to a date and returns the new date.
- Day, Month, Year: Each of these functions takes a date and returns a number, which indicates the part of the date associated with the function’s name. For example, if MyDate holds 10/5/67, then Month(MyDate) returns 10, Day(MyDate) returns 5, and Year(MyDate) returns 67.
- MonthName: Takes a month number (1 to 12) and returns the name of the month (“January” through “December”).
In this installment, you discovered statements and functions and how they work in a Visual Basic program. You also explored a host of handy built-in functions that can make your programs more powerful, user-friendly and useful. In the next article, I’ll show you how to make your programs smarter by letting them make their own decisions.
About the Author
Bill Hatfield (MCSD, MCAD, MCP) is an internationally best-selling author of books on Internet, intranet and client/server technologies. Among his most recent books is ASP.NET For Dummies.
# # #