ASP.NET Basics (Part 6): Fully Function-al - Sweet Tooth
(Page 4 of 8 )
Of course, it's also possible to specify an explicit return value with the "return" statement, as in the next example
<SCRIPT language=c# runat="server">
// define and initialize variable
int time = 9;
// define a function
string whatYouDoing()
{
// check the condition
if (time == 9)
{
return "On my way to work";
}
else if (time == 6)
{
return "Done with work, on my way to dinner with friends";
}
else
{
return "I'm sleeping";
}
}
void Page_Load()
{
answer.Text = "Right now? " + whatYouDoing();
}
</SCRIPT>
Hi, what are you doing right now?
<asp:label id=answer runat="server"></asp:label>
Notice how the function is able to read the values of variables defined outside the function. This is related to variable scope in C#, and I plan to discuss it in detail a little further down.
Return values need not be numbers or strings alone - a function can just as easily return an array, as demonstrated in the following example:
<SCRIPT language=c# runat="server">
// define a function
// to return the dessert
// menu as an array
string [] DessertMenu()
{
string [] desserts = {"chocolate mousse", "tiramisu", "apple pie", "chocolate chip cookies", "caramel custard", "butter scotch icecream",
"blackforest cake"};
return desserts;
}
void Page_Load()
{
// get the system time
DateTime date = System.DateTime.Now;
// cast the day of the week
// as an integer
int day = (int) date.DayOfWeek;
// define an array to
// to store our dessert array
string [] menu;
// call the function
menu = DessertMenu();
// write the day of the week…
today.Text = date.DayOfWeek.ToString();
// ... and the dessert for the day
special.Text = menu[day];
}
</SCRIPT>
It's <asp:label id=today runat="server"></asp:label>today, and our chef's whipped up some great <asp:label id=special runat="server"></asp:label>for today's special. Would you like some?
This is what you should see in the browser.
Next: Passing the Buck >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire