Introduction
This post explains pass by value and pass by references in C#
Pass by Value
In C#, Pass a copy of the original value to the function rather than reference. It does not modify the original value. The changes made to the parameter inside of the called method will not have an effect on the original value. The Variable value is directly stored in the memory.
The following is an example of passing a value type parameter to a method by value:
Create a console application with the following steps
File -->new -->Project
Select the Console Application with proper solution name and project name (like PassbyValue)
Add the Code For Pass by Value
Create the parameterized method in the Program class and increment the Input parameter value by Five (increment with any number), and print in the console window.
In the Main Method first Declare a variable with some value (like int A=10).
Print the Variable value before and after calling the function for different values.
The output looks like:
Pass by Reference
In C#, it passes a reference of arguments to the function. The changes in passed values are permanent and modify the original variable values. The Reference types won't store variable values directly in the memory. Rather, it will store the memory address of the variable value to indicate where the value is being stored.
Following is an example of passing a reference type parameter to a method by reference:
Create Another Console Application in the Existing Solution
Right Click on the solution -->Add--> New Project
Select the Console application with some meaningful name (like PassbyRef)
Add the Method in the Program Class with a ref parameterized method.
Output looks like:
Summary
The above article showed how to use the pass by value and pass by references in C# .