![]() | ![]() |
When data is passed to the function by value, the copies of the data passed are created inside the function and the original values are not changed. All the primitive data types are passed by values in C#. Let’s see an example of how data can be passed by value in C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyProgram
{
class Program
{
static void Main(string[] args)
{
int num1 = 10;
int num2 = 20;
Console.WriteLine("Numbers before function call {0} and {1}", num1, num2);
PrintSquares(num1, num2);
Console.WriteLine("Numbers after function call {0} and {1}", num1, num2);
Console.ReadKey();
}
public static void PrintSquares (int a, int b)
{
a = a * a;
b = b * b;
Console.WriteLine("Squares are: {0} and {1}", a, b);
}
}
}
In the script above we declared two integer variables num1 and num2, we then pass these two variables as a parameter to the PrintSquares() function which takes squares of both the numbers and print them on the screen. In the code above we print the value of num1 and num2 variables before and after passing them to the PrintSquares() function. You will see that the values are not updated. This is because an integer is a primitive type and is passed as values. Inside the PrintSquares() function, a copy of these variables is created and the originally passed values are not updated. The output looks like this: