Calling
Methods exist to be called! You call a method by
Specifying the Method Call Syntax
The syntax of a C# method call is as
methodName ( argumentList )
The methodName must exactly match the name of the method you're calling. Remember, C# is a case-sensitive language.
The
argumentList
IMPORTANT
You must include the parentheses in every method call, even when calling a method that has no arguments.
Here is the addValues method again:
int addValues(int leftHandSide, int rightHandSide) { // ... }
The addValues method has two int parameters, so you must call it with two comma-separated int arguments:
addValues(39, 3); // okay
You can also replace the literal values 39 and 3 with the
int arg1 = 99;
int arg2 = 1;
addValues(arg1, arg2);
If you try to call addValues in some other way, you will probably not succeed, for the reasons described in the following examples:
addValues; // compile time error, no parentheses addValues(); // compile time error, not enough arguments addValues(39); // compile time error, not enough arguments addValues("39", "3"); // compile time error, wrong types
The addValues method returns an int value. This int value can be used wherever an int value can be used. Consider these examples:
result = addValues(39, 3); // on right hand side of an assignment showResult(addValues(39, 3)); // as argument to another method call
The following exercise continues using the MathsOperators application. This time you will examine some method calls.
Examine method calls
Return to the Methods project. (This project is already open in Visual Studio 2005 if you're continuing from the previous exercise. If you are not,
Display the code for Form1.cs in the Code and Text Editor window.
Locate the
calculate_Click
method, and look at the first two statements of this method after the
try
statement and opening curly
The statements are as follows:
int leftHandSide = System.Int32.Parse(leftHandSideOperand.Text); int rightHandSide = System.Int32.Parse(rightHandSideOperand.Text);
These two statements declare two
int
variables called
leftHandSide
and
rightHandSide
. However, the interesting
Look at the fourth statement in the calculate_Click method (after the if statement and another opening curly brace):
calculatedValue = addValues(leftHandSide, rightHandSide));
This statement calls the addValues method, passing the values of the leftHandSide and rightHandSide variables as its arguments. The value returned by the addValues method is stored in the calculatedValue variable.
Look at the
showResult(calculatedValue);
This statement calls the showResult method, passing the value in the calculatedValue variable as its argument. The showResult method does not return a value.
In the Code and Text Editor window, find the
showResult
method you
The only statement of this method is this:
result.Text = answer.ToString();
Notice that the ToString method call uses parentheses even though there are no arguments.
TIP
You can call methods