Passing by value and passing by reference
When passing values into a method or constructor, there are two ways to do this. They are passing by value and passing by reference:
- Passing by value: By default, all value types are passed by value into constructors and methods using copy semantics. This means that a copy is made of the value being passed in. The original value remains unchanged, and it is the copy that is used with the constructor or method.
- Passing by reference: When a reference type is passed into a constructor or method, a variable is made on the stack that points to the same object on the heap. So, both the variable that is passed in and the copied variable used inside the constructor or method operate on the same object in memory.
Now that we know what passing by value and passing by reference are, let's write a simple program that demonstrates what we have learned.