Return a Value
Although methods with a return type of void are not rare, most methods will return a value.
In fact, the ability to return a value is one of the most useful features of a method. You have
already seen an example of a return value: when we used Math.Sqrt( ) to obtain a square root
in chapters 2 and 3.
Return values are used for a variety of purposes in programming. In some cases, such
as with Math.Sqrt( ), the return value contains the outcome of some calculation. In other
cases, the return value may simply indicate success or failure. In still others, it may contain
a status code. Whatever the purpose, using method return values is an integral part of C#
programming.
Methods return a value to the calling routine using this form of return:
return value;
Here, value is the value returned.
You can use a return value to improve the implementation of Range( ). Instead of
displaying the range, a better approach is to have Range( ) compute the range and return
this value. Among the advantages to this approach is that you can use the value for other
calculations. The following example modifies Range( ) to return the range rather than
displaying it:
// Use a return value.
using System;
// A class that encapsulates information about vehicles.
class Vehicle {
public int Passengers; // number of passengers
public int FuelCap; // fuel capacity in gallons
public int Mpg; // fuel consumption in miles per gallon
---------- Post added at 11:17 AM ---------- Previous post was at 11:17 AM ----------
// Return the range.
public int Range() {
return Mpg * FuelCap;
}
}
class RetMeth {
static void Main() {
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();
int range1, range2;
// Assign values to fields in minivan.
minivan.Passengers = 7;
minivan.FuelCap = 16;
minivan.Mpg = 21;
// Assign values to fields in sportscar.
sportscar.Passengers = 2;
sportscar.FuelCap = 14;
sportscar.Mpg = 12;
// Get the ranges.
range1 = minivan.Range();
range2 = sportscar.Range();
---------- Post added at 11:20 AM ---------- Previous post was at 11:17 AM ----------
Console.WriteLine("Minivan can carry " + minivan.Passengers +
" with range of " + range1 + " miles.");
Console.WriteLine("Sportscar can carry " + sportscar.Passengers +
" with range of " + range2 + " miles.");
}
}
The output is shown here:
Minivan can carry 7 with range of 336 miles.
Sportscar can carry 2 with range of 168 miles.
In the program, notice that when Range( ) is called, it is put on the right side of an
assignment statement. On the left is a variable that will receive the value returned by Range( ).
Thus, after this line executes,
range1 = minivan.Range();
the range of the minivan object is stored in range1.
Notice that Range( ) now has a return type of int. This means that it will return an integer
value to the caller. The return type of a method is important because the type of data returned
---------- Post added at 11:20 AM ---------- Previous post was at 11:20 AM ----------
by a method must be compatible with the return type specified by the method. Thus, if you
want a method to return data of type double, its return type must be type double.
Although the preceding program is correct, it is not written as efficiently as it could be.
Specifically, there is no need for the range1 or range2 variables. A call to Range( ) can be
used in the WriteLine( ) statement directly, as shown here:
Console.WriteLine("Minivan can carry " + minivan.Passengers +
" with range of " + minivan.Range() + " Miles");
In this case, when WriteLine( ) is executed, minivan.Range( ) is called automatically and its
value will be passed to WriteLine( ). Furthermore, you can use a call to Range( ) whenever
the range of a Vehicle object is needed. For example, this statement compares the ranges of
two vehicles:
if(v1.Range() > v2.Range()) Console.WriteLine("v1 has greater range");
---------- Post added at 11:37 AM ---------- Previous post was at 11:20 AM ----------
Q: I have heard that C# detects “unreachable code.” What does this mean?
A: You heard correctly. The C# compiler will issue a warning message if you create a method
that contains code that no path of execution will ever reach. Consider this example:
public void m() {
char a, b;
// ...
if(a==b) {
Console.WriteLine("equal");
return;
} else {
Console.WriteLine("not equal");
return;
}
Console.WriteLine("this is unreachable");
}
Here, the method m( ) will always return before the final WriteLine( ) statement is executed.
If you try to compile this method, you will receive a warning. In general, unreachable code
constitutes a mistake on your part, so it is a good idea to take unreachable code warnings
seriously!
---------- Post added at 11:38 AM ---------- Previous post was at 11:37 AM ----------
Use Parameters
It is possible to pass one or more values to a method when the method is called. As explained,
a value passed to a method is called an argument. Inside the method, the variable that receives
the argument is called a formal parameter, or just parameter, for short. Parameters are declared
inside the parentheses that follow the method’s name. The parameter declaration syntax is the
same as that used for variables. The scope of a parameter is the body of its method. Aside from
its special task of receiving an argument, it acts like any other local variable.
Here is a simple example that uses a parameter. Inside the ChkNum class, the method
IsEven( ) returns true if the value that it is passed is even. It returns false otherwise.
Therefore, IsEven( ) has a return type of bool.
// A simple example that uses a parameter.
using System;
// This class contains the method isEven that takes a parameter.
class ChkNum {
// Return true if x is even.
public bool IsEven(int x) {
if((x%2) == 0) return true;
else return false;
}
}
---------- Post added at 11:44 AM ---------- Previous post was at 11:38 AM ----------
class ParmDemo {
static void Main() {
ChkNum e = new ChkNum();
if(e.IsEven(10)) Console.WriteLine("10 is even.");
if(e.IsEven(9)) Console.WriteLine("9 is even.");
if(e.IsEven(8)) Console.WriteLine("8 is even.");
}
}
Here is the output produced by the program:
10 is even.
8 is even.
In the program, IsEven( ) is called three times, and each time, a different value is passed. Let’s
look at this process closely. First, notice how IsEven( ) is called. The argument is specified
between the parentheses. When IsEven( ) is called the first time, it is passed the value 10. Thus,
when IsEven( ) begins executing, the parameter x receives the value 10. In the second call, 9 is
the argument and x then has the value 9. In the third call, the argument is 8, which is the value
---------- Post added at 11:47 AM ---------- Previous post was at 11:44 AM ----------
that x receives. The point is that the value passed as an argument when IsEven( ) is called is
the value received by its parameter, x.
A method can have more than one parameter. Simply declare each parameter, separating
one from the next with a comma. For example, the Factor class defines a method called
IsFactor(( ) that determines if the first parameter is a factor of the second.
using System;
class Factor {
// Determine if x is a factor of y.
public bool IsFactor(int x, int y) {
if( (y % x) == 0) return true;
else return false;
}
}
class IsFact {
static void Main() {
Factor x = new Factor();
if(x.IsFactor(2, 20)) Console.WriteLine("2 is factor");
if(x.IsFactor(3, 20)) Console.WriteLine("this won't be displayed");
}
}
Notice that when IsFactor( ) is called, the arguments are also separated by commas.
When using multiple parameters, each parameter specifies its own type, which can differ
from the others. For example, this is perfectly valid:
int MyMeth(int a, double b, float c) {
// ...
---------- Post added at 11:49 AM ---------- Previous post was at 11:47 AM ----------
Add a Parameterized Method to Vehicle
You can use a parameterized method to add a new feature to the Vehicle class: the ability
to compute the amount of fuel needed for a given distance. This new method is called
FuelNeeded( ). This method takes the number of miles that you want to drive and returns the
number of gallons of gas required. The FuelNeeded( ) method is defined like this:
public double FuelNeeded(int miles) {
return (double) miles / Mpg;
}
Notice that this method returns a value of type double. This is useful, since the amount of fuel
needed for a given distance might not be an even number.
---------- Post added at 11:50 AM ---------- Previous post was at 11:49 AM ----------
The entire Vehicle class that includes FuelNeeded( ) is shown here:
/*
Add a parameterized method that computes the
fuel required for a given distance.
*/
using System;
class Vehicle {
public int Passengers; // number of passengers
public int FuelCap; // fuel capacity in gallons
public int Mpg; // fuel consumption in miles per gallon
// Return the range.
public int Range() {
return Mpg * FuelCap;
}
// Compute fuel needed for a given distance.
public double FuelNeeded(int miles) {
return (double) miles / Mpg;
}
}
class CompFuel {
static void Main() {
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle();
double gallons;
int dist = 252;
// Assign values to fields in minivan.
minivan.Passengers = 7;
minivan.FuelCap = 16;
minivan.Mpg = 21;
// Assign values to fields in sportscar.
sportscar.Passengers = 2;
sportscar.FuelCap = 14;
sportscar.Mpg = 12;
gallons = minivan.FuelNeeded(dist);
Console.WriteLine("To go " + dist + " miles minivan needs " +
gallons + " gallons of fuel.");
gallons = sportscar.FuelNeeded(dist);