Passing Arguments

By default, parameters are passed by value. In this method a duplicate copy is made and sent to the called function. There are two copies of the variables. So if you change the value in the called method it won’t be changed in the calling method.

We use this process when we want to use but don’t want to change the values of the parameters passed.

By default, C# uses call by value to pass arguments.

The following example demonstrates by value:

The Code:

New Project130.png

The Output of Your Program:

New Project131.png

In this case, x is the parameter of the Sqr method and a is the actual argument passed into the method.

As you can see, the Sqr method does not change the original value of the variable, as it is passed by value, meaning that it operates on the value, not the actual variable.

Passing by Reference

Passing by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist in the calling environment. To pass a parameter by reference, use the ref or out keyword.

The Code:

New Project132

The Output of Your Program:

New Project133
The ref keyword passes the memory address to the method parameter, which allows the method to operate on the actual variable.

The ref keyword is used both when defining the method and when calling it.

Passing by Output

Output parameters are similar to reference parameters, except that they transfer data out of the method rather than accept data in. They are defined using the out keyword.
The variable supplied for the output parameter need not be initialized since that value will not be used. Output parameters are particularly useful when you need to return multiple values from a method.

The Code:

New Project134.png

The Output of Your Program:

New Project135.png

Unlike the previous reference type example, where the value 3 was referred to the method, which changed its value to 9, output parameters get their value from the method (5 and 42 in the above example).

Similar to the ref keyword, the out keyword is used both when defining the method and when calling it.

Prev Lesson:

Optional & Named Arguments

Next Lesson:

Methods Overloading