Information Technology Reference
In-Depth Information
Return Values
A method can return a value to the calling code. The returned value is inserted into the calling
code at the position in the expression where the invocation occurred.
To return a value, the method must declare a
return type
before the method name.
If a method does not return a value, it must declare a return type of
void
.
The following code shows two method declarations. The first returns a value of type
int
.
The second does not return a value.
Return type
↓
int GetHour() { ... }
void DisplayHour() { ... }
↑
No value is returned.
A method that declares a return type must return a value from the method by using the fol-
lowing form of the return statement, which includes an expression after the keyword
return
.
Every path through the method must end with a
return
statement of this form.
return
Expression
; // Return a value.
↑
Evaluates to a value of the return type
For example, the following code shows a method called
GetHour
, which returns a value of
type
int
.
Return type
↓
int GetHour( )
{
DateTime dt = DateTime.Now; // Get the current date and time.
int hour = dt.Hour; // Get the hour.
return hour;
// Return an int.
}
↑
Return statement