Functions and Subs and void, OH MY

   

Functions and Subs and void, OH MY!

So far in this chapter and in this book you've been dealing with code blocks that are self-contained, or in other words, that do all the work within themselves. What if I told you there was another way in certain instances to write less code, reuse code, save loads of time when you're debugging, and separate out your code into compartmentalized blocks that are easier to use and to read? Would that be exciting? Okay, you're not gonna jump out of your chair and do cartwheels, but it is a little exciting, isn't it?

Functions and subs, enter stage right. Functions provide a great way to achieve all the above-mentioned benefits and probably many more I can't think of. They give us a way to use blocks of code over and over from anywhere in pages or even whole applications.

I think before we even get into it, I should address what functions and subs are and how both languages handle them. Now how to unscramble this mess? Ok, gotta start somewhere.

In Visual Basic .NET there are both functions and subs. C# has only functions, but C#'s functions can accomplish what both the Visual Basic .NET function and sub can do.

Whew! I can't believe I explained that in one sentence.

Think of it this way: Imagine you're at a Little League baseball game and your son comes running up to you asking for money for ice cream. You have four choices:

  • Tell him to forget it, because he didn't clean his room and is not getting any ice cream.

  • Give him a few dollars and let him get ice cream.

  • Say, "Hey, you've already got money. Buy it yourself. And in fact, while you're at it, bring me back a toasted almond bar."

  • Give him a few dollars to get ice cream and tell him to bring back a toasted almond bar for you.

That pretty much sums it up.

Now I will interpret for Visual Basic .NET. The first two options represent subs. Subs do stuff and don't return any data to you directly. They can effect change on something with your application, but they don't directly return anything to you. In both instances, you spoke to your child and the child performed an action, in the latter instance with some input from you. They can accept input from you to perform their actions or, in other words, you can require parameters to be passed to them.

The second two options represent functions. They return something to you, namely a delicious toasted almond bar. In one instance you gave a directive without input from your wallet, and in the second instance you passed your kid a few bucks.

Functions operate in exactly the same way as subs do, but they return values to you, like your toasted almond bar. They too can accept input from you to in the form of parameters.

As I've said before, C# uses its form of a function for what both subs and functions perform in Visual Basic .NET. Take a look at how these are structured to understand this better:

Visual Basic .NET
'This is a Sub that doesn't take parameters  Sub SubName()      Code to be performed  End Sub  'This is a Sub that takes parameters  Sub SubName(ParameterName as ParameterType)      Code to be performed  End Sub  'This is a Function doesn't that take parameters  Function FunctionName()      Code to be performed      return WhatYouWantReturned  End Function  'This is a Function that takes parameters  Function FunctionName(ParameterName as ParameterType)      Code to be performed      return WhatYouWantReturned  End Function 
C#
//This is a C# Function that doesn't return anything that doesn't take parameters  void FunctionName(){      Code to be performed;  }  //This is a C# Function that doesn't return anything that takes parameters  void FunctionName(ParameterType ParameterName){      Code to be performed;  }  //This is a Function that returns data but doesn't that take parameters  ReturnDataType FunctionName(){      Code to be performed;      return WhatYouWantReturned  }  //This is a Function that takes parameters  ReturnDataType FunctionName(ParameterType ParameterName) {      Code to be performed;      return WhatYouWantReturned  } 

As you can see, Visual Basic .NET uses the words Sub and Function to differentiate between whether or not you need something returned. C# differentiates these by using the word void in place of declaring a return data type. Now let's look at a Sub/void function to understand it in practical application.

Sub/void

In one of the previous loops, you added a <br> directly in the string as you went through the loop. This created line breaks in the browser so the loop code doesn't just show up on one line. This example uses a Sub/void function to add <br> tags as it runs through the loop, instead of adding them to the string inside the loop. To make the generated code more readable, you are also going to insert a carriage return in code so you can view the rendered code. In the previous examples, if you viewed the source of the generated HTML it would have been a giant string like: <span >This is line number 1 in ourloop.<br>This is line number 2 in our loop.<br>This is line number 3 in our loop.<br>This is line number 4 in our loop.<br>This is line number 5 in our loop.<br></span>.

Note

For all the examples that follow, you need a new template for testing code. Use the following templates for all these examples.

 functiontemplate_vb.aspx    <%@ page language="vb" runat="server"%>    <script  runat=server>        'Replace this with your code    </script>    <html>    <title>VB.NET Template</title>    <body>    <asp:label  runat="server"/>    </body>    </html>  functiontemplate_cs.aspx    <%@ page language="c#" runat="server"%>    <script  runat=server>        //Replace with your code    </script>    <html>    <title>C# Template</title>    <body>    <asp:label  runat="server"/>    </body>    </html> 


Now for the example:

Visual Basic .NET sub_simple_vb.aspx
Sub InsertLineFeed()      OurLabel.Text += "<br>" + ControlChars.CrLf  End Sub  Sub Page_Load()      dim i as Integer      for i=1 to 5          OurLabel.Text += "This is line number " + i.ToString()          InsertLineFeed()      next  End Sub 
C# function_void_cs.aspx
void InsertLineFeed(){      OurLabel.Text += "<br> \n";  }  void page_load(){     int i;      for(i = 1;i <= 5;++i){         OurLabel.Text += "This is line number " + i.ToString();          InsertLineFeed();      }  } 

And now the generated HTML, which is identical for both languages:

 <html>  <title>Function - Void</title>  <body>  <span >  This is line number 1<br>  This is line number 2<br>  This is line number 3<br>  This is line number 4<br>  This is line number 5<br>  </span>  </body>  </html> 

As you can see, the sub or function (depending on your language) has performed its duty as it was called each time through the loop. It didn't return any data to use, but it did the work it was asked to by adding the <br> and a carriage return to OurLabel.Text each time through the loop.

Note

The way to insert a carriage return in Visual Basic .NET and C# is quite different. Visual Basic .NET has an object called ControlChars that contains a property called CrLf. In C# you simply insert \n as a string and the interpreter recognizes this as a desired carriage return.


Now look at a similar example where you pass in a parameter to the Sub/void and use this parameter to determine what action you want taken.

Visual Basic .NET sub_param_vb.aspx
Sub AppendText(OurString as String)      OurLabel.Text += OurString + ControlChars.CrLf  End Sub  Sub Page_Load()      dim i as Integer      OurLabel.Text = ControlChars.CrLf      AppendText("This is a line we insert before the loop<br>")      for i=1 to 5          OurLabel.Text += "This is line number " + i.ToString()          AppendText("<br>")      next      AppendText("This is a line we insert after the loop")  End Sub 
C# function_void_param_cs.aspx
void AppendText(String OurString){      OurLabel.Text += OurString + "\n";  }  void page_load(){ int i;  OurLabel.Text = "\n";  AppendText("This is a line we insert before the loop<br>");  for(i = 1;i <= 5;++i){         OurLabel.Text += "This is line number " + i.ToString();          AppendText("<br>");  }  AppendText("This is a line we insert after the loop");  } 

You can see the results of the Sub/function in Figure 3.19.

Figure 3.19. Passing parameters to subs or functions allows you to better control what they actually do and multiply their power.
graphics/03fig19.gif

As you can see, a parameter called OurString has been set up in the function and you can define what you want added to the string by passing in the text you want appended when you call the Sub/void function. This really just scratches the surface of what you can do, but it demonstrates the basic concept of passing parameters to functions.

Let's move on to functions that can return data that can be used in function calls. We aren't going to demonstrate functions that don't receive any parameters. Reason? You will VERY RARELY run into a situation where you won't be passing a parameter to a function. Besides it isn't too difficult to project how a function of this type will work after you understand a function with parameters. It works exactly the same way, but without parameters. Got it?

Visual Basic .NET function_single_param_vb.aspx
Function AddToTen(OurNum as Integer)      dim FuncNum as Integer = 10      return FuncNum + OurNum  End Function  Sub Page_Load()      OurLabel.Text = AddToTen(89).ToString()      OurLabel.Text += " Bottles of Beer on the Wall<br>"      OurLabel.Text += AddToTen(88).ToString()      OurLabel.Text += " Bottles of Beer on the Wall<br>"      OurLabel.Text += AddToTen(87).ToString()      OurLabel.Text += " Bottles of Beer on the Wall<br>"  End Sub 
C# function_single_param_cs.aspx
int AddToTen(int OurNum){      int FuncNum = 10;      return FuncNum + OurNum;  }  void page_load(){     OurLabel.Text = AddToTen(89).ToString();      OurLabel.Text += " Bottles of Beer on the Wall<br>";      OurLabel.Text += AddToTen(88).ToString();      OurLabel.Text += " Bottles of Beer on the Wall<br>";      OurLabel.Text += AddToTen(87).ToString();      OurLabel.Text += " Bottles of Beer on the Wall<br>";  } 

And you can see the results in Figure 3.20

Figure 3.20. Functions can return data that can be used in function calls.
graphics/03fig20.gif

Note

Notice that to call to the function, the ToString() method needed to be appended to the calls. After the Text property of OurLabel is appended to, it becomes impossible to append an integer to a string. You cannot add 98 to " Bottles of Beer on the Wall." It is mathematically impossible. So you must tell ASP.NET that you want to concatenate and not add these values by turning the Int into a String.


You can also pass multiple parameters to a function. In the next example you are going to pass two parameters to the function, do some math, and return the results.

Visual Basic .NET function_mutli_param_vb.aspx
Function Add(Num1 as Integer, Num2 as Integer)      return Num1 + Num2  End Function  Sub Page_Load()      OurLabel.Text = "10 + 5 = " + Add(10,5).ToString() + "<br>"      OurLabel.Text += "32 + 11 = " + Add(32,11).ToString()+ "<br>"      OurLabel.Text += "77 + 44 = " + Add(77,44).ToString()+ "<br>"      OurLabel.Text += "212 + 458 = " + Add(212,458).ToString()+ "<br>"      OurLabel.Text += "1493 + 716 = " + Add(1493,716).ToString()+ "<br>"  End Sub 
C# function_mutli_param_cs.aspx
int Add(int Num1,int Num2){      return Num1 + Num2;  }  void page_load(){     OurLabel.Text = "10 + 5 = " + Add(10,5).ToString() + "<br>";      OurLabel.Text += "32 + 11 = " + Add(32,11).ToString()+ "<br>";      OurLabel.Text += "77 + 44 = " + Add(77,44).ToString()+ "<br>";      OurLabel.Text += "212 + 458 = " + Add(212,458).ToString()+ "<br>";      OurLabel.Text += "1493 + 716 = " + Add(1493,716).ToString()+ "<br>";  } 

You can see in Figure 3.21 that more parameters can provide you with a door for more functions.

Figure 3.21. Passing multiple parameters to functions opens up a whole world of possibilities for reusing code to create and manipulate data.
graphics/03fig21.gif

Now just to demonstrate something simple you can do inside a function, I threw together a quick and dirty calculator for simple addition, subtraction, multiplication, and division. I've only included this to illustrate that there are virtually no limits to what can be performed in a function, and that you can now reuse this code numerous times on a page without having to write specific blocks of code all over to calculate your numbers. Notice how there is a Select/switch statement inside the function to evaluate the third parameter passed in, named Type, to control what type of mathematical operation is performed. Pretty cool!

Visual Basic .NET function_calc_vb.aspx
Function OurCalc(Num1 as Integer, Num2 as Integer,CalcType as String)      dim MathType as String      MathType = CalcType      Select Case MathType          Case "+"              Return Num1 + Num2          Case "-"              Return Num1 - Num2          Case "*"              return Num1 * Num2          Case "/"              return Num1 / Num2      End Select  End Function  Sub Page_Load()      OurLabel.Text = "10 + 5 = " + OurCalc(10,5,"+").ToString() + "<br>"      OurLabel.Text += "32 - 11 = " + OurCalc(32,11,"-").ToString()+ "<br>"      OurLabel.Text += "77 * 44 = " + OurCalc(77,44,"*").ToString()+ "<br>"      OurLabel.Text += "736 / 16 = " + OurCalc(736,16,"/").ToString()+ "<br>"  End Sub 
C# function_calc_cs.aspx
int OurCalc(int Num1,int Num2,String CalcType){      String MathType;      int MyReturn;      MathType = CalcType;      MyReturn = 0;      switch(MathType){          case "+":              MyReturn = Num1 + Num2;              break;          case "-":              MyReturn = Num1 - Num2;              break;          case "*":              MyReturn = Num1 * Num2;              break;          case "/":              MyReturn = Num1 / Num2;              break;      }      return MyReturn;  }  void Page_Load(){     OurLabel.Text = "10 + 5 = " + OurCalc(10,5,"+").ToString() + "<br>";      OurLabel.Text += "32 - 11 = " + OurCalc(32,11,"-").ToString()+ "<br>";      OurLabel.Text += "77 * 44 = " + OurCalc(77,44,"*").ToString()+ "<br>";      OurLabel.Text += "736 / 16 = " + OurCalc(736,16,"/").ToString()+ "<br>";  } 

Take a look at Figure 3.22 to see the results.

Figure 3.22. Functions can be used for a multitude of things such as performing different types of mathematical calculations.
graphics/03fig22.gif

We had to jump through a few hoops to get the C# example to work, whereas Visual Basic .NET is much more liberal. Visual Basic .NET enables you to return straight out of the Select statement, whereas C# forces you to populate a variable and return it at the end of the function.


   
Top


ASP. NET for Web Designers
ASP.NET for Web Designers
ISBN: 073571262X
EAN: 2147483647
Year: 2005
Pages: 94
Authors: Peter Ladka

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net