ASP.NET Basics (Part 6): Fully Function-al - Passing the Buck
(Page 5 of 8 )
Now, if you've been paying attention, you've seen how functions can help you segregate blocks of code, and use the same piece of code over and over again, thereby eliminating unnecessary duplication. But, this is just the tip of the iceberg.
The functions you've seen thus far are largely static, in that the variables they use are already defined. It's also possible to pass variables to a function from the main program; these variables are called "arguments", and they add a whole new level of power and flexibility to your code.
To illustrate this, let's go back a couple of pages and revisit the tempConv() function.
double tempConv
() { double celsius = 35; double fahrenheit; fahrenheit = (celsius * 1.8) + 32; return fahrenheit; }
As is, this function will always calculate the Fahrenheit equivalent of 35 degrees Celsius, no matter how many times you run it or how many roses you buy it. However, it would be so much more useful if it could be modified to accept *any* value, and return the Fahrenheit equivalent of that value to the calling program.
This is where arguments come in - they allow you to define placeholders, if you will, for certain variables; these variables are provided at run-time by the main program.
Let's now modify the tempConv() example to accept an argument.
<SCRIPT language=c# runat="server">
// define a function
double tempConv(double temperature)
{
double fahrenheit;
fahrenheit = (temperature * 1.8) + 32;
return fahrenheit;
}
void Page_Load()
{
string result;
double alpha = 45;
result = tempConv(alpha).ToString();
output.Text = alpha.ToString() + " Celsius is " + result + " Fahrenheit.";
}
</SCRIPT>
<asp:label id=output runat="server"></asp:label>
And now, when the tempConv() function is called with an argument, the argument is assigned to the placeholder variable "temperature" within the function, and then acted upon by the code within the function definition.
Note that it's mandatory to specify the data type of the arguments being passed to the function.
It's also possible to pass more than one argument to a function - as the following example demonstrates.
<SCRIPT language=c# runat="server">
// define a function
string addIt(string item1, string item2, string item3)
{
return item1 + item2 + item3;
}
void Page_Load()
{
output.Text = addIt("hello", "-", "john");
}
</SCRIPT>
<asp:label id=output runat="server"></asp:label>
And its output.

Next: Going Nowhere >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire