These are ways of passing data in a subroutines/functions/procedures/methods
Fundamentally it boils down to
- whether the method receives a copy of the argument’s value or
- direct access to the argument’s storage location
Pass By Value
When an argument is passed to a subroutine by value, each parameter specified for the subroutine will hold a copy of the data from the original argument.
- This data is held in a separate memory location and is only available to the subroutine (meaning the parameter has local scope).
- Even if the value of the parameter is changed within the subroutine, the value of the original argument is unchanged.
- You can modify the object’s properties (e.g.,
user.Name = "Alice"), and the caller will see it, because both pointers point to the same object. - You cannot reassign the object itself (e.g.,
user = new User()). This only updates the local copy of the pointer, leaving the caller’s variable unchanged.
- You can modify the object’s properties (e.g.,
Pass By Reference
When an argument is passed to a subroutine by reference,
- this creates a pointer that contains the memory address of the original variable.
- Therefore, any change to the parameter within the subroutine also affects the value of the original variable.
- You can completely reassign the object (
user = new User()), and the original variable outside the method will now point to this brand-new object.
- You can completely reassign the object (
Java is strictly Pass by Value for both primitives and objects.
By default, C# passes all arguments by value unless you explicitly use modifiers like ref or out. ^2
References
- https://www.javadude.com/post/20010516-pass-by-value/
- https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/method-parameters
- https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value/430958
- https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value
- https://adacomputerscience.org/concepts/sub_value_reference