C# method parameters
In this chapter you will learn:
- What is method parameter
- Pass-by-value versus pass-by-reference
- Note for Pass-by-value
- Example for Pass-by-value versus pass-by-reference
- Note for parameter
Description
A method has a sequence of parameters. Parameters define the set of arguments that must be provided for that method.
The following code defines a method called
add
, which adds two int
type variables together.
add
method has two parameters, a
and b
.
When calling the add
method we must provide data for a
and b
.
using System;//w ww .j a v a2s . co m
class Program
{
static int add(int a, int b)
{
int result = a + b;
Console.WriteLine(result);
return result;
}
static void Main(string[] args)
{
add(1, 2);
}
}
In general, parameters can be passed into methods by reference or by value.
The code above generates the following result.
Pass-by-value versus pass-by-reference
When a variable is passed by reference, the called method gets the actual variable. Any changes made to the variable inside the method persist when the method exits.
When a variable is passed by value, the called method gets a copy of the variable. Any changes made are lost when the method exits.
Note
In C#, all parameters are passed by value unless you specifically say otherwise. We have to understand the implications for reference types.
Reference type variables hold only a reference to an object, it is this reference that will be copied, not the object itself. Hence, changes made to the underlying object will persist.
Value type variables, in contrast, hold the actual data, so a copy of the data itself will be passed into the method.
Example
An int is passed by value to a method, and any changes that the method makes do not change the value of the original int object.
If an array or any other reference type, such as a class, is passed into a method, and the method uses the reference to change a value in that array, the new value is reflected in the original array object.
using System; // w ww . ja v a 2 s . co m
class MainClass
{
static void SomeFunction(int[] ints, int i)
{
ints[0] = 100;
i = 100;
}
public static int Main()
{
int i = 0;
int[] ints = { 0, 1, 2, 4, 8 };
SomeFunction(ints, i);
Console.WriteLine("i = " + i);
Console.WriteLine("ints[0] = " + ints[0]);
return 0;
}
}
Notice how the value of i remains unchanged, but the value changed in ints is also changed in the original array.
The code above generates the following result.
Note 2
You can control how parameters are passed with the ref and out modifiers:
Parameter modifier | Passed by | Variable must be definitely assigned |
---|---|---|
None | Value | Going in |
ref | Reference | Going in |
out | Reference | Going out |
Next chapter...
What you will learn in the next chapter:
- What is ref parameter
- How to create ref parameter
- Example for ref parameter
- Example to swap two values with ref parameter
- Note for ref parameter
- Swap two references by Using ref with reference types