Home > Articles

This chapter is from the book

Branching Logic

Branching logic causes code execution to branch in different directions. Typically, this type of logic is used when some code needs to be used over and over again from different locations.

In the factory example, every time a clock is assembled, it needs to be put in a box. The boxing machine is in the basement. When you're through with a clock, you send it to the basement for a box, and then it comes right back up for you to apply the proper postage. The boxing machine is essentially branching logic—it can be used from any location in the factory, not just your assembly line. Putting a single boxing machine in the basement is much more efficient than putting one next to each assembly line.

There are two types of branching logic controls in VB.NET: functions and subroutines. The only difference between the two is that functions send information back to whatever called them, and subroutines don't. In other words, functions compute values, and subroutines perform actions. In C#, there is only a function, and it may or may not return values. These two controls are essential to ASP.NET development—without them, nothing would get done. Let's examine subroutines first.

Subroutines

Subroutines (sometimes called procedures) in VB.NET follow this format:

Sub name (parameters)
  code
End Sub

In C#:

void name (parameters) {
  code
}

In VB.NET you use the keyword sub, but there is no corresponding keyword in C#. The word that precedes the name of the function in C# describes the data type that is returned by the function. void means no value is returned (we'll see more on this in a moment).

You've been looking at this type of syntax already in all of your ASP.NET pages. Recall this line:

sub Page_Load(Sender as object, e as EventArgs)
  code
end sub

Listing 3.10 contains some code in VB.NET that multiplies numbers; Listing 3.11 shows the same code in C#.

Listing 3.10 Multiplying Numbers in a Subroutine

1:  <%@ Page Language="VB" %>
2:
3:  <script runat="server">
4:    sub Page_Load(obj as object, e as eventargs)
5:     MultiplyNumbers(8,9)
6:
7:     MultiplyNumbers(4,12)
8:
9:     MultiplyNumbers(348,23)
10:    end sub
11:
12:    sub MultiplyNumbers(intA as integer, intB as integer)
13:     Response.Write(intA * intB & "<br>")
14:    end sub
15:  </script>
16:
17:  <html><body>
18:
19:  </body></html>

Listing 3.11 Multiplying Numbers in a Subroutine in C#

1:  <%@ Page Language="C#" %>
2:  
3:  <script runat="server">
4:    void Page_Load(Object Sender, EventArgs e) {
5:     MultiplyNumbers(8,9);
6:  
7:     MultiplyNumbers(4,12);
8:  
9:     MultiplyNumbers(348,23);
10:    }
11:  
12:    void MultiplyNumbers(int intA, int intB) {
13:     Response.Write(intA * intB + "<br>");
14:    }
15:  </script>
16:  
17:  <html><body>
18:  
19:  </body></html>***

In the code declaration block on line 12, you create a subroutine named MultiplyNumbers. The variables in the parentheses are called parameters or arguments. These are values that are passed into the subroutine from the code that's using it. The subroutine can use these values to perform any actions it needs to. A group of parameters is called a parameter list. Specifying these parameters is very similar to declaring variables (note the differences between C# and VB.NET). The parameters you declare here must be passed in by the calling code that uses this subroutine, or else you'll receive errors.

On line 13, you write the product of these parameters to the browser using Response.Write, and you close the subroutine on line 14. Now that you've created the subroutine, you can use it from anywhere else on the page. This subroutine will never execute unless you tell it to explicitly—it won't execute just because you put it there.

On line 5 you call the subroutine. This tells the program to execute the code inside the subroutine and come back to line 5 when it's done (you can see the branching logic at work here). When you call MultiplyNumbers, you specify the two parameters that the subroutine defined—two Integers. MultiplyNumbers takes these integers and performs its actions.

Lines 7 and 9 do identical things but pass different parameters to the subroutine. This is part of the beauty of branching logic controls—you can call them from anywhere and give them different parameters to play with each time. This code will produce what's shown in Figure 3.7.

Figure 3.7 Using subroutines to perform encapsulated logic.

CAUTION

If you're familiar with VBScript and traditional ASP, you may remember calling subroutines and functions with the following syntax:

MultiplyNumbers 8, 9

That is, without parentheses. With C#, VB.NET, and ASP.NET, you must always include the parentheses when calling a function or there will be an error.

Functions

Functions are very similar to subroutines—their syntax is nearly identical, and they can both perform the same actions. Functions, however, return a value to the code that called it. Let's modify Listing 3.10 to use a function instead of a subroutine.

Listing 3.12 Multiplying Numbers in a Function

1:  <%@ Page Language="VB" %>
2:
3:  <script runat="server">
4:    sub Page_Load(obj as object, e as eventargs)
5:     Response.Write(MultiplyNumbers(8,9) & "<br>")
6:
7:     Response.Write(MultiplyNumbers(4,12) & "<br>")
8:
9:     Response.Write(MultiplyNumbers(348,23) & "<br>")
10:    end sub
11:
12:    function MultiplyNumbers(intA as integer, intB as integer) _
13:     as Integer
14:     Return intA * intB
15:    end function
16:  </script>
17:
18:  <html><body>
19:
20:  </body></html>

The MultiplyNumbers function would look like the following code snippet in C#:

12:    int MultiplyNumbers(int intA, int intB) {
13:     return(intA * intB);
14:    }

This code is slightly different from Listing 3.10. The first difference is that the function on line 12 doesn't write the product of the two parameters to the browser. Rather, it uses the return keyword to send the product back to the code that called it. Note that the function also specifies As Integer after the parameter list (or int in front of the function name in C#). This is used to tell the calling code what type of data to expect in return. This listing produces the same output as the previous listing. On line 5, you call MultiplyNumbers inside a Response.Write. This seems kind of odd at first glance, but let's examine it further. First, line 5 calls MultiplyNumbers with the parameters 8 and 9. Then this function takes over, multiplies the two parameters on line 14, and returns them to line 5. Response.Write on line 5 now only sees the product, 72. It's equivalent to writing Response.Write(72).

This allows you to use function calls in many different places. For example, you could write any of the following:

MultiplyNumbers(8,9)
intCount = MultiplyNumbers(8,9) * 72
if MultiplyNumbers(8,9) < 80 then
  ...

These all work because the function executes first and the code will end up seeing only the returned value. There are two ways to return values in VB.NET. The first way you've already seen—using the keyword return. The second way is to assign the return value to the function itself. For example, the following works the same way as the function in Listing 3.12:

12:  function MultiplyNumbers(intA as integer, intB as integer) _
13:    as integer
14:    MultiplyNumbers = intA * intB
15:  end function

A function doesn't have to return a value, but it may if necessary. You could have included the Response.Write statement in the function, as you did for the subroutine in Listing 3.10, but this method works for the sake of demonstration,. Optionally, you can also specify the data type of the return value:

function MultiplyNumbers(intA as integer, intB as integer)_
  as integer

This tells the calling code that you're returning an integer.

TIP

Always make sure to specify a return type when declaring a function. This includes readability of the code and also increases type safety.

There is an important thing to note with the return keyword. Once you call return, all execution in that particular method stops, and execution returns to the calling method. In other words, if you wrote Response.Write("HI") after line 14 in Listing 3.12, it would never be executed because return passed the control back to the Page_Load method.

Optional Parameters

What happens if you think you may use a parameter for your function or subroutine, but you don't need the code to tell you what it is? You want the parameter to be optional. Luckily, VB.NET allows you to do this with the Optional keyword. Let's look at an example:

function MultiplyNumbers(intA as integer, optional intB as__
  integer = 3) as Integer
  return intA * intB
end function

On the first line, you use the optional keyword to tell VB.NET that any code that calls this function isn't required to specify a value for intB, but that it may. You could then call this function with either of the following:

MultiplyNumbers(8)
MultiplyNumbers(8,9)

What happens if the code doesn't specify a value? On the third line, you multiply the two values together. If intB wasn't specified, this would produce an error.

When you specify that a parameter is optional, you must also specify a default value. On the first line, you have optional intB as integer = 3. This tells VB.NET what this value should be in case it isn't specified.

There is one caveat to using optional: Once you specify that one parameter is optional, all subsequent parameters must also be optional. The following code would produce an error:

function MultiplyNumber(intA as integer, optional intB as _
  integer = 3, intC as integer) as Integer

Instead, use this:

function MultiplyNumber(intA as integer, optional intB as _
  integer = 3, optional intC as integer = 4) as Integer

In C#, there is no equivalent optional keyword. The only way to provide optional parameters is to use method overloading—a concept of object-oriented programming that is out of the scope of this lesson. See the .NET Framework documentation for more details.

Event Handlers

Events, as discussed on Days 1, "Getting Started with ASP.NET," and 2, "Building ASP.NET Pages," are actions that may occur in your application—a mouse click or a button press, for instance. Usually, whenever an event occurs, you need to do some processing. For example, when a Submit button is clicked, you should enter form information into a database. Or if the user clicks a link, you want to send him to the appropriate page. This functionality doesn't happen by itself—you must tell the program what to do.

You do this by creating an event handler. The syntax is identical to that for a subroutine, so you should be familiar with it already. The difference lies in the parameter list. When an event is raised—meaning the event has occurred—it produces variables that describe the event. Your event handler can use these variables to figure out what to do.

Nearly all of the events in ASP.NET produce the same parameter list. Listing 3.13 shows an example.

Listing 3.13 Handling Events in ASP.NET

1:  <%@ Page Language="VB" %>
2:
3:  <script runat="server">
4:    Sub Button_Click(Sender As Object, e As EventArgs)
5:     Response.Write("You clicked the button!")
6:    End Sub
7:  </script>
8:
9:  <html><body>
10:    <form runat="server">
11:     <asp:button id="btSubmit" Text="Submit" 
12:       runat=server
13:       OnClick="Button_Click"/><p>
14:    </form>
15:  </body></html>

Line 4 contains what appears to be a normal subroutine. However, the parameter list distinguishes it as an event handler. The first parameter is an Object data type that represents the object that raised the event. The second parameter is a new type you haven't seen yet, EventArgs. This parameter contains any information specific to the event that occurred. Typically, this variable will be empty. This is the standard event handler parameter list, although in a few days you'll see some exceptions to the rule. In C#, this standard list looks like the following code snippet:

void event_handler_name(Object Sender, EventArgs e)

NOTE

Remember that you can call your parameters whatever you like. You're using Sender and e here for simplicity and standardization.

On line 11, you create an ASP.NET button control. You may recall this control from Days 1 and 2, and it's explored further on Day 5, "Beginning Web Forms." For now, you just need to know that you set its ID—its unique name—to btSubmit, set the text it will display to Submit, and specify that it runs at the server. Whenever this button is clicked, it raises an event called Click. On line 13, you tell the button the following: "When the Click event occurs, execute the subroutine Button_Click." You just defined its event handler.

Now, whenever the button is clicked, it executes the subroutine on lines 4–6 and writes "You clicked the button!" to the browser. Save this code in a file called listing0310. aspx and view it from your browser. When you click the button, you'll see Figure 3.8.

Figure 3.8 Handling events in ASP.NET.

This is the basis for handling all actions in ASP.NET pages. Once you learn how to handle events, ASP.NET becomes much more powerful. Let's modify Listing 3.13 a bit to use the parameters supplied to the event handler as shown in Listing 3.14.

Listing 3.14 Using Event Parameters in ASP.NET

1:  <%@ Page Language="VB" %>
2:
3:  <script runat="server">
4:    Sub Button_Click(Sender As Object, e As EventArgs)
5:     Response.Write(Sender.Text)
6:    End Sub
7:  </script>
8:
9:  <html><body>
10:    <form runat="server">
11:     <asp:button id="btSubmit" Text="Submit" 
12:       runat=server
13:       OnClick="Button_Click"/><p>
14:    </form>
15:  </body></html>

When you view this page and click the button, you'll see the word "Submit" in place of "You clicked the button!" Let's examine line 5. Recall that the first parameter represents the object that raised the event. In this case, it happens to be the Submit button. Thus, obj is one name you can use to reference this button. The other name is the id value, btSubmit. Line 5 writes the Text property of the button to the browser. On line 11, the Text property is set to "Submit". You could change line 5 to read as follows and it would produce the same output:

Response.Write(btSubmit.Text)

But we're getting ahead of ourselves. You'll examine this more thoroughly on Day 5.

CAUTION

Generally, events in ASP.NET can be handled only if the code that generates them lies within <form>...</form> tags. This is because the events must be posted to the server, which will be discussed in more detail on Day 5.

There's another event that you've been using quite a bit in today's examples: the Page_Load event. Recall Listing 3.12, for example. On line 4 is a method called Page_Load, with the standard event parameter list: Sender as object, e as EventArgs. When an ASP.NET page loads, the Page_Load event is raised and you can use it to do some processing. Typically, you'll use this event handler to display something to the user as soon as the page loads. Day 4, "Using ASP.NET Objects with C# and VB.NET," will take a closer look at this event.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020