When a parameter is passed into a method, it can be passed in one of three ways:
- By value (this is the default): Think of these as being in-only
- By reference as a
ref
parameter: Think of these as being in-and-out - As an
out
parameter: Think of these as being out-only
In the Person
class, add the following method:
public void PassingParameters(int x, ref int y, out int z) { // out parameters cannot have a default // AND must be initialized inside the method z = 99; // increment each parameter x++; y++; z++; }
In the Main
method, add the following statements to declare some int
variables and pass them into the method:
int a = 10; int b = 20; int c = 30; WriteLine($"Before: a = {a}, b = {b}, c = {c}"); p1.PassingParameters(a, ref b, out c); WriteLine($"After: a = {a}, b = {b}, c = {c}");
Run the application and see the output:
Before: a = 10, b = 20, c = 30
After: a = 10, b = 21, c = 100