C# - Passing Parameters by Value



This is the default mechanism for passing parameters to a method. In this mechanism, when a method is called, a new storage location is created for each value parameter.

What Are Value Parameters?

The C# value parameter refers to passing variables to a method. When variables are passed to a method, their values are copied and used inside the method. Hence, the changes made to the parameter inside the method have no effect on the argument. The original variable remains unchanged. The following example demonstrates the concept

Example of Passing Parameters by Value

The following example provides you with an understanding of value parameters in C#:

using System;

class Program {
    static void Square(int num) {
        num = num * num;
        Console.WriteLine("Inside method: " + num);
    }

    static void Main() {
        int number = 5;
        Square(number);
        Console.WriteLine("Outside method: " + number);
    }
}

When the above code is compiled and executed, it produces the following result −

Inside method: 25  
Outside method: 5  

More Examples

Practice the following examples to understand the concept of value parameters.

Example 1: No Effect of Value Parameter Passing

The following example demonstrates how to swap the values of two variables using a method in C# and showcases the behavior of passing parameters by value −

using System;
namespace CalculatorApplication {
   class NumberManipulator {
      public void swap(int x, int y) {
         int temp;
         
         temp = x; /* save the value of x */
         x = y;    /* put y into x */
         y = temp; /* put temp into y */
      }
      static void Main(string[] args) {
         NumberManipulator n = new NumberManipulator();
         
         /* local variable definition */
         int a = 100;
         int b = 200;
         
         Console.WriteLine("Before swap, value of a : {0}", a);
         Console.WriteLine("Before swap, value of b : {0}", b);
         
         /* calling a function to swap the values */
         n.swap(a, b);
         
         Console.WriteLine("After swap, value of a : {0}", a);
         Console.WriteLine("After swap, value of b : {0}", b);
         
         Console.ReadLine();
      }
   }
}

When the above code is compiled and executed, it produces the following result −

Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200

It shows that there is no change in the values though they had changed inside the function.

Example 2: Value Parameters and Their Scope

This example shows that modifying parameters inside a method does not change the original values.

using System;
namespace ValueParameterExample {
   class ValueExample {
      public void ModifyValues(int x, int y) {
         x = x * 2;
         y = y * 2;
         Console.WriteLine("Inside ModifyValues method, x: {0}, y: {1}", x, y);
      }

      static void Main(string[] args) {
         ValueExample example = new ValueExample();

         int a = 10;
         int b = 20;

         Console.WriteLine("Before calling ModifyValues, a: {0}, b: {1}", a, b);

         // Calling the ModifyValues method
         example.ModifyValues(a, b);

         Console.WriteLine("After calling ModifyValues, a: {0}, b: {1}", a, b);

         Console.ReadLine();
      }
   }
}

The value will remain unchanged outside the method because the method parameters are passed by value, meaning the original values are not modified −

Before calling ModifyValues, a: 10, b: 20
Inside ModifyValues method, x: 20, y: 40
After calling ModifyValues, a: 10, b: 20

When to Use Value Parameters?

1. Modify a copy without changing the original

Value parameters create a copy of the variables, so any changes inside the method do not change the original value. This is useful when the original data should remain unchanged.

Consider the following example where a store calculates a discount price but keeps the original price unchanged:

using System;
namespace ValueParameterExample {
   class Store {
      public void ApplyDiscount(double price) {
         price = price - (price * 0.10); // Applying 10% discount
         Console.WriteLine("Discounted Price: $" + price);
      }

      static void Main(string[] args) {
         Store store = new Store();

         double originalPrice = 100.00;
         Console.WriteLine("Original Price: $" + originalPrice);

         // Calling the ApplyDiscount method
         store.ApplyDiscount(originalPrice);

         Console.WriteLine("After calling ApplyDiscount, Original Price: $" + originalPrice);

         Console.ReadLine();
      }
   }
}

The original price remains unchanged outside the method as it is passed by value −

Original Price: $100.00
Discounted Price: $90.00
After calling ApplyDiscount, Original Price: $100.00

2. Best for small data types

You can use value parameters for the small data types because they are lightweight (occupy less memory) to copy and do not impact performance.

Consider the following example:

using System;
namespace SmallDataTypesExample {
   class SmallTypeExample {
      public void DisplaySquare(int n) {
         Console.WriteLine("Square: " + (n * n));
      }

      static void Main(string[] args) {
         SmallTypeExample example = new SmallTypeExample();

         int number = 5;
         Console.WriteLine("Original Number: " + number);

         // Calling the DisplaySquare method
         example.DisplaySquare(number);

         Console.ReadLine();
      }
   }
}

The original number remains unchanged outside the method as it is passed by value −

Original Number: 5
Square: 25

3. Protects original values

Value parameters prevent modifications to the original variable. You can use value parameters when you want to keep the original values unchanged.

using System;
namespace EncapsulationExample {
   class EncapsulationTest {
      public void PrintMessage(string msg) {
         msg = "Modified: " + msg; // This does not affect the original string
         Console.WriteLine(msg);
      }

      static void Main(string[] args) {
         EncapsulationTest example = new EncapsulationTest();

         string message = "Hello, World!";
         Console.WriteLine("Original Message: " + message);

         // Calling the PrintMessage method
         example.PrintMessage(message);

         Console.WriteLine("After calling PrintMessage: " + message);

         Console.ReadLine();
      }
   }
}

Since strings are immutable in C#, modifying the copied value inside the method does not change the original string −

Original Message: Hello, World!
Modified: Hello, World!
After calling PrintMessage: Hello, World!
Advertisements