Pages

Sunday, 14 June 2015

Parameters

About Parameters

So far, you’ve seen that methods are named units of code that can be called from many places in a program and can return a single value to the calling code. Returning a single value is certainly valuable, but what if you need to return multiple values? Also, it would be useful to be able to pass data into a method when it starts execution. Parameters are a special kind of variable that can allow you to do both these things.

Formal Parameters

Formal parameters are local variables that are declared in the method declaration’s parameter list, rather than in the body of the method. The formal parameters are used throughout the method body, for the most part, it's just like local variables.
The following method header shows the syntax of parameter declarations. It declares two formal parameters—one of type int and the other of type float.
public void PrintSum( int x, int y )  //x and y is Formal Parameters
{
 int sum = x + y;
 Console.WriteLine(x + " + " + y + " is " + sum);
}
 
Here are something about formal parameters you should know:
  • Formal parameters are variables, they have a data type and a name, and they can be written to and read from.
  • Unlike a method’s local variables, the parameters are defined outside the method body and are initialized before the method starts (except for one type, called output parameters).
  • The parameter list can have any number of formal parameter declarations, and the declarations must be separated by commas.

Actual Parameters

When your code calls a method, the values of the formal parameters must be initialized before the code in the method begins execution.
  • The expressions or variables used to initialize the formal parameters are called the actual parameters. They are also sometimes called arguments.
  • The actual parameters are placed in the parameter list of the method invocation.
  • Each actual parameter must match the type of the corresponding formal parameter, or the compiler must be able to implicitly convert the actual parameter to that type.
Read below code for better understanding
class intCalculator
{
 public int power(int x)         //declare method, x is formal parameter
 {
  return x * x;
 }
 public int sum(int x, int y)    //declare method, x and y are formal parameter
 {
  return x + y;
 }
 public int avg(int x, int y)    //declare method, x and y are formal parameter
 {
  return sum(x, y) / 2;       //invoke sum, x and y are actual parameter
 }
}

class Program
{
 static void Main(string[] args)
 {
  intCalculator myCalculator = new intCalculator();
  int x = 5;
  int y = 33;
  Console.WriteLine("x = " + x);
  Console.WriteLine("y = " + y);
  Console.WriteLine("sum = " + myCalculator.sum(x, y));        //invoke sum, x and y are actual parameter
  Console.WriteLine("avg = " + myCalculator.avg(x, y));        //invoke avg, x and y are actual parameter
  Console.WriteLine("pow(x) = " + myCalculator.power(x));      //invoke pow, x is actual parameter   
  Console.WriteLine("pow(y) = " + myCalculator.power(y));      //invoke pow, y is actual parameter
  Console.Read();
 }
}
This code will output:
x = 5
y = 33
sum = 38
avg = 19
pow(x) = 25
pow(y) = 1089

Kind of Parameters

There are several kinds of parameters, each of which passes data to and from the method in slightly different ways.

Value Parameter

Value parameters is parameter which passed data to the method by copying the value of the actual parameter to the formal parameter. When a method is called, the system does the following:
  • It allocates space on the stack for the formal parameters.
  • It copies the values of the actual parameters to the formal parameters.
An actual parameter for a value parameter doesn’t have to be a variable. It can be any expression evaluating to the matching data type.
The thing you should remember about value parameter is before you can use a variable as an actual parameter, that variable must be assigned a value. For example:
public int power(int x)         //declare method, x is formal parameter
{
 return x * x;
}
....
static void Main(string[] args)
{
 intCalculator myCalculator = new intCalculator();
 int x = 5;
 int y = 33;
 ....
 Console.WriteLine("pow(5) = " + myCalculator.power(5));        //invoke pow, with literal as actual parameter
 Console.WriteLine("pow(x) = " + myCalculator.power(x));        //invoke pow, with variable as actual parameter 
 Console.WriteLine("pow(x+y) = " + myCalculator.power(x + y));       // invoke pow, expression as actual parameter
 ....
 int z;
 Console.WriteLine("pow(z) = " + myCalculator.power(z));        //compile error, use of unassigned local variable 'z'
}

Reference Parameters

Reference parameters have the following characteristics:
  • They do not allocate memory on the stack for the formal parameters.
  • Instead, a formal parameter name acts as an alias for the actual parameter variable, referring to the same memory location.
  • The actual parameter must be a variable, and it must be assigned to before being used as the actual parameter
When using a reference parameter, you must use the ref modifier in both the declaration and the invocation of the method. See following example:
public void inc(ref int x)
{
 ++x;
}
....
static void Main(string[] args)
{
 intCalculator myCalcultor = new intCalculator();
 int x = 5;
 int y = 33;
 int z;
 
 myCalculator.inc(ref y);     //invoke inc
 Console.WriteLine("inc(y) = " + y);   //y will be 34
 myCalculator.inc(5);      //compile error, can not pass literal to reference parameter
 myCalculator.inc(x + y)      //compile error, can not pass expression to reference parameter
 myCalculator.inc(z);      //compile error, use of unassigned local variable 'z'
 ....
}

Output Parameter

Output parameters are used to pass data from inside the method back out to the calling code. Their behavior is very similar to reference parameters. But unlike reference parameters, output parameters require the following:
  • Inside the method, an output parameter must be assigned to before it can be read from. This means that the initial values of the parameters are irrelevant and that you don’t have to assign values to the actual parameters before the method call.
  • Inside the method, every possible path through the code must assign a value to every output parameter before the method can exit.
Output parameters have the following requirements:
  • You must use a modifier in both the method declaration and the invocation. With output parameters, the modifier is out, rather than ref.
  • Like reference parameters, the actual parameter must be a variable,it cannot be another type of expression.
See following code for better understanding
public void assign_inc(out int x)
{
 x = 3;
 ++x;
}
....
static void Main(string[] args)
{
 intCalculator myCalcultor = new intCalculator();
 int x = 5;
 int y = 33;
 int z;
 
 myCalcultor.assign_inc(out y);    //invoke assign_inc
 Console.WriteLine("inc(y) = " + y);   //y will be 4
 myCalcultor.assign_inc(out z);    
 Console.WriteLine("inc(z) = " + z);   //z will be 4
 myCalcultor.assign_inc(5);     //compile error,compile error, can not pass literal to output parameter
 myCalcultor.assign_inc(x + y);    //compile error, can not pass expression to reference parameter
 ....
}

Parameter Arrays

Parameter arrays are different in the way they allow zero or more actual parameters of a particular type for a particular formal parameter. Important points about parameter arrays are the following:
  • There can be only one parameter array in a parameter list.
  • If there is one, it must be the last parameter in the list.
  • All the parameters represented by the parameter array must be of the same type.
To declare a parameter array, you must do the following:
  • Use the params modifier before the data type.
  • Place a set of empty square brackets after the data type.
public int sum(params int[] numbers)    //declare method, with array parameters
{
 int sum = 0;
 for (int i = 0; i < numbers.Length; ++i)
 {
  sum += numbers[i];              //sum all numbers member
 }
 return sum;
}
....
static void Main(string[] args)
{
 intCalculator myCalcultor = new intCalculator();
 int x = 5;
 int y = 33;
 int[] arr = { 5, 2, 15 };
 int z;

 Console.WriteLine("sum(x)", myCalcultor.sum(x));     //invoke sum with 1 variable
 Console.WriteLine("sum(x, y)", myCalcultor.sum(x, y));    //invoke sum with 2 variables
 Console.WriteLine("sum(x, y, z)", myCalcultor.sum(x, y, z));  //compile error, use of unassigned local variable 'z'
 Console.WriteLine("sum(arr)", myCalcultor.sum(arr));    //invoke sum with array of int
 Console.WriteLine("sum(2)", myCalcultor.sum(2));     //invoke sum with 1 literal
 Console.WriteLine("sum(2, 6, 20)", myCalcultor.sum(2, 6, 20));  //invoke sum with 3 literals
 .... 
}

Summary of Parameter Types

Since there are four parameter types, it’s sometimes difficult to remember their various characteristics.
Parameter Type Modifier Used at Declaration? Used at Invocation? Implementation
Value None The system copies the value of the actual parameter to the formal parameter.
Reference ref Yes Yes The formal parameter is an alias for the actual parameter.
Output out Yes Yes Parameter contains only a returned value. The formal parameter is an alias for the actual parameter.
Array params Yes No Parameter allows passing a variable number of actual parameters to a method.

Named Parameters

So far in our discussion of parameters we’ve used positional parameters, which, as you’ll remember, means that the position of each actual parameter matches the position of the corresponding formal parameter.

Alternatively, C# allows you to use named parameters. Named parameters allow you to list the actual parameters in your method invocation in any order, as long as you explicitly specify the names of the parameters. The details are the following:
  • Nothing changes in the declaration of the method.
  • In the method invocation, however, you use the formal parameter name, followed by a colon, in front of the actual parameter value or expression.
See following example
 static void printID(uint ID, string firstName, string lastName, char bloodType, float height)
{
 Console.WriteLine("ID number: " + ID);
 Console.WriteLine("Name: " + firstName +" "+lastName);
 Console.WriteLine("Blood Type: " + bloodType);
 Console.WriteLine("Height: " + height);
}

static void Main(string[] args)
{
 uint myID = 578;
 string myFirstName = "Yang", myLastName = "Sopiana";
 char myBloodType = 'B';
 float myHeight = 167.3F;

 printID(myID, myFirstName, myLastName, myBloodType, myHeight);      //invoke printID, using positional parameters

 printID(firstName:myFirstName,height:myHeight,ID:myID,lastName:myLastName,bloodType:myBloodType)    //invoke printID, using named parameters
}

Named Parameters

When we see printID method, the problem will occur when a person doesn't have last name.

C# also allows optional parameters. An optional parameter is a parameter that you can either include or omit when invoking the method.

To specify that a parameter is optional, you need to include a default value for that parameter in the method declaration. The syntax for specifying the default value is the same as that of initializing a local variable.
Lets modify our printID method:
static void printID(uint ID, string firstName, char bloodType, float height, string lastName="") //lastName is optional parameter, it should be put on last of parameter list
{
 Console.WriteLine("ID number: " + ID);
 Console.WriteLine("Name: " + firstName +" "+lastName);
 Console.WriteLine("Blood Type: " + bloodType);
 Console.WriteLine("Height: " + height);
}

static void Main(string[] args)
{
 uint myID = 578;
 string myFirstName = "Yang", myLastName = "Sopiana";
 char myBloodType = 'B';
 float myHeight = 167.3F;

 uint ID1 = 578;
 string firstName1 = "Hamzah";
 char bloodType1 = 'B';
 float height1 = 167.3F;

 printID(myID, myFirstName, myBloodType, myHeight,myLastName);                       //invoke printID, with complete parameters

 printID(ID1, firstName1, bloodType1, height1);                           //invoke printID, using positional parameters

 printID(firstName: firstName1, height: height1, ID: ID1, bloodType: bloodType1);   //invoke printID, using named parameters
}

0 comments:

Post a Comment