Curriculum
In C#, parameters in a function can be passed by value or by reference. When a parameter is passed by value, the function receives a copy of the value of the parameter, and any changes made to the parameter inside the function do not affect the original variable outside of the function. This is known as call by value.
Here is an example of a function that takes two integers as parameters and adds them together using call by value:
public void Add(int a, int b) { int sum = a + b; Console.WriteLine("The sum of {0} and {1} is {2}", a, b, sum); }
When this function is called with the parameters a = 2
and b = 3
like this:
int x = 2; int y = 3; Add(x, y);
the output will be:
The sum of 2 and 3 is 5
Even though sum
was calculated inside the Add
function, it is not returned to the calling code, and the original variables x
and y
remain unchanged.
In call by value, the function cannot modify the original values of the variables passed as parameters. If you want a function to be able to modify the original values of the variables, you can pass the parameters by reference using the ref
keyword.