Information Technology Reference
In-Depth Information
The following code shows an example of a void method with a return statement. The
method writes out a message only if the time is after noon. The process, illustrated in Figure 5-5,
is as follows:
￿
First the method gets the current date and time. (Don't worry about understanding the
details of this right now.)
￿
If the hour is less than 12 (that is, before noon), the return statement is executed, and
control immediately returns to the calling method.
If the hour is 12 or greater, the return statement is skipped, and the WriteLine statement
is executed.
￿
class MyClass {
Void return type
void TimeUpdate() {
DateTime dt = DateTime.Now; // Get the current date and time.
if (dt.Hour < 12) // If the hour is less than 12,
return; // then return.
Return to calling method.
Console.WriteLine("It's afternoon!"); // Otherwise, print message.
}
static void Main() {
MyClass mc = new MyClass(); // Create an instance of the class.
mc.TimeUpdate(); // Invoke the method.
}
}
Figure 5-5. Using a return statement with a void return type
Search WWH ::




Custom Search