Parameters allow information to be passed in and out of a method. To pass a parameter, you can include them inside the braces that follow the method name.
The syntax to declare a parameter is similar to the syntax used to declare variable. When more than one parameter is passes, they are separated using commas. When a method is called, you must pass the parameter to the method.
You can pass a parameter as a reference to the memory location. In this case, a function parameter in C# references the memory location of the parameter. A new memory location is not created in this case.
Step 1: Syntax
The declaration of a reference parameter is by using the ref keyword before the data type of the parameter. If there are multiple parameters, the ‘ref’ keyword should be attached to each of the parameter before the data type.
Thus the following is a simple example of passing two parameters, a ‘pass by reference’ and a ‘pass by value’. The ‘ref’ keyword marks the parameter that is passed by reference.
public void example(ref int number1, int number2)
If you need to pass all the parameters by reference, all the parameters should possess the ‘ref’ keyword. Look into the following code snippet:
Public void example(ref int number1,ref int number2,ref float number3)
number1, number2 and number3 are passed by reference to the method and the method call should be as follows:
Object.example(ref n1, ref n2, ref n3);
If the ‘ref’ keyword is missing, an error message will be generated, “Argument must be passed with the ‘ref’ keyword”.
To return a value from the method, you can use the return statement. The limitation is that only one value can be returned for a method. To overcome this limitation, another function parameter you can use is the output parameter.
The output parameter is similar to the reference parameter except that it gets data outside the method. This is useful when there is more than one value to be returned by the method. These parameters need not possess any initial value. ‘out’ keyword is used to denote the output parameter.
Step 2: Implementation
Similar to ‘ref’ keyword, the ‘out’ keyword should be placed before each output parameter passed in a method. The following code shows the use of both function parameters in C#, the reference parameter and the output parameter:
Step 3: Output
When the method Math() is called in the Main method, four parameters are passed. Addition and subtraction are out parameters while n1 and n2 are ref parameters. Note that the variables addition and subtraction are not initialized. The values are got after the method execution.
Step 4: Avoiding Error
The output parameters are unassigned local variables. Therefore, it is compulsory to assign a value to them inside the method. Otherwise, the compiler will throw an error. Thus in the example, the statement that assigns value to the variable sub is commented. When the program is compiled, an error is shown saying that the variable must be assigned a value.