Methods' Arguments |
|
Introduction |
A method performs an assignment that completes the operations of a class. The methods we used in the previous sections relied on local variables to exchange information with other sections of the program. Sometimes, a method would need one or more values in order to carry its assignment. The particularity of such a value or such values is that another method that calls this one must supply the needed value(s). When a method needs a value to complete its assignment, such a value is called an argument. Like a variable, an argument is represented by its type of value. For example, one method may need a character while another would need a string. Yet another method may require a decimal number. This means that the method or class that calls a method is responsible for supplying the right value, even though a method may have an internal mechanism of checking the validity of such a value. |
The value supplied to a method is typed in the parentheses of the method and it's called an argument. In order to declare a method that takes an argument, you must specify its name and the argument between its parentheses. Because a method must specify the type of value it would need, the argument is represented by its data type and a name. Suppose you want to define a method that displays the side length of a square. Since you would have to supply the length, you can define such a method as follows: using System; public class NewProject { static void DisplaySide(double Length) { } static int Main() { return 0; } } In the body of the method, you may or may not use the value of the argument. Otherwise, you can manipulate the supplied value as you see fit. In this example, you can display the value of the argument as follows: using System; public class NewProject { static void DisplaySide(double Length) { Console.Write("Length: "); Console.WriteLine(Length); } static int Main() { return 0; } } When calling a method that takes an argument, you must supply a value for the argument; otherwise you would receive an error. Also, you should/must supply the right value; otherwise, the method may not work as expected and it may produce an unreliable result. Here is an example: using System; public class NewProject { static void DisplaySide(double Length) { Console.Write("Length: "); Console.WriteLine(Length); } static void Main() { DisplaySide(35.55); return 0; } } As mentioned already, a method that takes an argument can also declare its own local variable(s). A method can take more than one argument. When defining such a method, provide each argument with its data type and a name. The arguments are separated by a comma.
|
|
||
Previous | Copyright © 2006-2007 FunctionX, Inc. | Next |
|