Article

Build Your Own ASP.NET Website Using C# And VB.NET, Chapter 3 - VB.NET and C# Programming Basics

Page: 1 2 3 Next

Functions

Functions are exactly the same as subroutines, but for one key difference: they return a value. In VB.NET, we declare a function using the Function keyword in place of Sub, while, in C#, we simply have to specify the return type in place of using void. The following code shows a simple example:

Example 3.14. Functions.aspx

<html>  
<head>  
<script runat="server" language="VB">  
 
' Here's our function  
Function getName() as String  
 Return "Zak Ruvalcaba"  
End Function  
 
' And now we'll use it in the Page_Load handler  
Sub Page_Load(s As Object, e As EventArgs)  
 lblMessage.Text = getName()  
End Sub  
</script>  
</head>  
 
<body>  
<form runat="server">  
<asp:Label id="lblMessage" runat="server" />  
</form>  
</body>  
</html>

Example 3.15. Functions.aspx

<html>  
<head>  
<script runat="server" language="C#">  
 
// Here's our function  
string getName() {  
 return "Zak Ruvalcaba";  
}  
 
// And now we'll use it in the Page_Load handler  
void Page_Load() {  
 lblMessage.Text = getName();  
}  
</script>  
</head>  
 
<body>  
<form runat="server">  
<asp:Label id="lblMessage" runat="server" />  
</form>  
</body>  
</html>

Figure 3.2 shows the result in the browser.

1328_image2

Figure 3.2. The Page_Load event is raised, the function is called, and the code within the function is executed.

Here's what's happening: the line in our Page_Load subroutine calls our function, which returns a simple string that we can then assign to our label. I hope this illustrates what functions are about and how you can use them. In this simple example, we're merely returning a fixed string (my name), but the function could just as well retrieve the name from a database—or somewhere else. The point is that, regardless of how the function gets its data, we use it (that is, call it) in just the same way.

When we're declaring our function, we must remember to specify the correct return type. Take a look at the following code:

' Here's our function  
Function addUp(x As Integer, y As Integer) As Integer  
 Return x + y  
End Function  
 
' And now we use it in Page_Load  
Sub Page_Load(s As Object, e As EventArgs)  
 lblMessage.Text = addUp(5, 5).ToString()  
End Sub  
// Here's our function  
int addUp(int x, int y) {  
 return x + y;  
}  
 
// And now we use it in Page_Load  
void Page_Load() {  
 lblMessage.Text = Convert.ToString(addUp(5, 5));  
}

You can easily adapt the previous example to use this new code and see the results in your browser.

Have a look at this code, and see if you can spot what's different and why. The first thing you might notice is that our function now accepts parameters. Any function or subroutine can take any number of parameters, each of any type (there's no need for parameter types to match the return type—that's just coincidental in this example).

We can then readily use the parameters inside the function or subroutine just by using the names we gave them in the function declaration (here, we've chosen x and y, but we could have chosen different names).

The other difference between this and the function declaration we had before is that we now declare our function with a return type of Integer or int, rather than String, because we want it to return a whole number.

When we now call the new function, we simply have to specify the required number of parameters, and remember that the function will return a value with the type we specified. In this case, that means we have to convert the integer value it returns to a string, so we can assign it to the label.

In VB.NET, we tack .ToString() onto the end of the function call, while in C# we use the Convert.ToString(…). Note the differences in how these two methods are used—converting numbers to strings is a very common task in ASP.NET, so it's good to get a handle on it early. Don't be too concerned if you're a little confused by how these conversions work, though—the syntax will become clear once we discuss the object oriented concepts involved later in this chapter.

Again, a complete discussion of functions could take up an entire chapter, but I hope the brief examples here are enough to prepare you for what we're going to cover in future chapters. Don't worry too much if you're still a bit unsure what functions and subroutines are all about right now—they'll become second nature very quickly.

Operators

Throwing around values with variables and functions isn't much use unless you can use them in some meaningful way, and to do this we use operators. An operator is a symbol that has a certain meaning when applied to values. Don't worry—they're nowhere near as scary as they sound! In fact, in the last example, when our function added two numbers, we were using an operator—the addition operator, +. Most of the other available operators are just as well known, although there are one or two that will probably be new to you. Table 3.2 outlines the operators that you'll use most often.

1328_table2

Table 3.2. ASP.NET Operators

The following code uses some of these operators:

If (user = "Zak" And itemsBought <> 0) Then  
 lblMessage.Text = "Hello Zak! Do you want to proceed to " & _  
   "checkout?"  
End If  
if (user == "Zak" && itemsBought != 0) {  
 lblMessage.Text = "Hello Zak! Do you want to proceed to " +  
   "checkout?";  
}

Here, we use the equality, inequality (not equals to) and logical 'and' operators in an If statement to print a message only for a given user, and only when he or she has bought something. Of particular note is C#'s equality operator, ==, which is used when comparing two values to see if they are equal. Don't use a single equals sign in C# unless you are assigning a value to a variable, or your code will have a very different meaning than you expect!

Breaking Long Lines of Code

Since the message string in the above example was too long to fit on one line in this book, I also used the string concatenation operator to combine two shorter strings on separate lines to form the complete message. In VB.NET, I also had to break one line of code into two using the line continuation symbol (_, an underscore at the end of the line to be continued). Since C# marks the end of each command with a semicolon (;), I can split a single command over two lines without having to do anything special.

I'll use these techniques throughout this book to show long lines of code within a limited page width. Feel free to recombine the lines in your own code if you like—there is no actual length limit on lines of code in VB.NET and C#.

Conditional Logic

As you develop ASP.NET applications, there will be many instances in which you'll need to perform an action only if a certain condition is met, for instance, if the user has checked a certain checkbox, selected a certain item from a DropDownList control, or typed a certain string into a TextBox control.

We check for such things using conditionals, the simplest of which is probably the If statement. This statement is often used in conjunction with an Else statement, which specifies what should happen if the condition is not met. So, for instance, we may wish to check if the name entered in a text box is "Zak," redirecting to one page if it is, or else redirecting to an error page:

If (txtUsername.Text = "Zak") Then  
 Response.Redirect("ZaksPage.aspx")  
Else  
 Response.Redirect("errorPage.aspx")  
End If  
if (txtUsername.Text == "Zak") {  
 Response.Redirect("ZaksPage.aspx");  
} else {  
 Response.Redirect("errorPage.aspx");  
}

Often, we want to check for one of many possibilities, and perform a particular action in each case. In that event, we can use the Switch Case (VB.NET) or switch (C#) construct:

Dim strName As String = txtUsername.Text  
Select Case strName  
 Case "Zak"  
   Response.Redirect("ZaksPage.aspx")  
 Case "Mark"  
   Response.Redirect("MarksPage.aspx")  
 Case "Fred"  
   Response.Redirect("FredsPage.aspx")  
 Case Else  
   Response.Redirect("errorPage.aspx")  
End Select  
string strName = txtUsername.Text;  
switch (strName) {  
 case "Zak":  
   Response.Redirect("ZaksPage.aspx");  
   break;  
 case "Mark":  
   Response.Redirect("MarksPage.aspx");  
   break;  
 case "Fred":  
   Response.Redirect("FredsPage.aspx");  
   break;  
 default:  
   Response.Redirect("errorPage.aspx");  
   break;  
}

Loops

As you've just seen, an If statement causes a code block to execute once if the value of its test expression is true. Loops, on the other hand, cause a code block to execute repeatedly for as long as the test expression remains true. There are two basic kinds of loop:

  • While loops, also called Do loops, which sounds like something Betty Boop might say!
  • For loops, including For Next and For Each

A While loop is the simplest form of loop; it makes a block of code repeat for as long as a particular condition is true. Here's an example:

Dim Counter As Integer = 0  
 
Do While Counter <= 10  
 
 ' Convert out Integer to a String  
 lblMessage.Text = Counter.ToString()  
 
 ' Below we use the += operator to increase our variable by 1  
 Counter += 1  
Loop  
int counter = 0;  
 
while (counter <= 10) {  
 
 // Below we use a sneaky way to convert our int to a string  
 lblMessage.Text = counter + "";  
 
 // C# has the operator ++ to increase a variable by 1  
 counter++;  
}

You can try out this code—enter it inside a Page_Load subroutine of one of the pages you've already created. The page illustrating Page_Load at the start of this chapter would be ideal. Make sure you remove any other code in the subroutine, and that there is an ASP.NET Label control in the HTML of the page with the ID lblMessage. When you open the page, the label will be set to show the number 0, then 1, then 2, all the way to 10. Of course, since all this happens in Page_Load (i.e. before any output is sent to the browser), you'll only see the last value assigned, 10.

This demonstrates that the loop repeats until the condition is no longer met. Try changing the code so that the counter variable is initialized to 20 instead of 10. When you open the page now, you won't see anything on screen, because the loop condition was never met.

There is another form of the While loop, called a Do While loop, which checks if the condition has been met at the end of the code block, rather than at the beginning:

Dim Counter As Integer = 0  
 
Do  
 
 ' Convert our Integer to a String  
 lblMessage.Text = Counter.toString()  
 
 ' Below we use the += operator to increase our variable by 1  
 Counter += 1  
Loop While Counter <= 10  
int counter = 0;  
 
do {  
 
 // Below we use a sneaky way to convert our int to a string  
 lblMessage.Text = counter + "";  
 
 // C# has the operator ++ to increase a variable by 1  
 counter++;  
} while (counter <= 10);

If you run this code, you'll see it provides the exact same output we saw when we tested the condition before the code block. However, we can see the crucial difference if we again change it so the counter variable is initialized to 20. In this case, we will, in fact, see 20 on screen, because the loop code is executed once before the condition is even checked! There are some instances when this is just what we want, so being able to place the condition at the end of the loop can be very handy.

A For loop is similar to a While loop, but is typically used when the number of times we need it to execute is known beforehand. The following example displays the count of items within a DropDownList control called ddlProducts:

Dim i As Integer  
For i = 1 To ddlProducts.Items.Count  
 lblMessage.Text = i.toString()  
Next  
int i;  
for (i = 1; i <= ddlProducts.Items.Count; i++) {  
 lblMessage.Text = Convert.ToString(i);  
}

In VB.NET, the loop syntax specifies the starting and ending values for our counter variable in the For statement itself. In C#, we assign a starting value (i = 1), a condition to be tested each time through the loop, just like a While loop (i <= ddlProducts.Items.Count), and how the counter variable should be incremented after each loop (i++). While this allows for some powerful variations on the theme in C#, it can be confusing at first. In VB.NET, the syntax is considerably simpler, but can be a bit limiting in exceptional cases.

The other type of For loop is For Each, which loops through every item within a collection. The following example loops through an array called arrayName:

For Each item In arrayName  
 lblMessage.Text = item  
Next  
foreach (string item in arrayName) {  
 lblMessage.Text = item;  
}

You may also come across instances in which you need to exit a loop prematurely. In this case, you would use Exit (VB.NET) or break (C#) to terminate the loop:

Dim i As Integer  
For i = 0 To 10  
 If (i = 5) Then  
   Response.Write("Oh no! Not the number 5!!")  
   Exit For  
 End If  
Next  
int i;  
for (i = 0; i <= 10; i++) {  
 if (i == 5) {  
   Response.Write("Oh no! Not the number 5!!");  
   break;  
 }  
}

In this case, as soon as our For loop hits 5, it displays a warning message, using the Response.Write() method that will be familiar to those with past ASP experience, and exits the loop so that no further passes through the loop will be made.

Although we have only scratched the surface, VB.NET and C# provide a great deal of power and flexibility to the Web developer, and time spent learning the basics now will more than pay off in the future.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links