Author Topic: C# - Difference between pass by value and pass by reference  (Read 1357 times)

kathir

  • Administrator
  • Sr. Member
  • *****
  • Posts: 283
C# - Difference between pass by value and pass by reference
« on: December 12, 2011, 02:11:27 pm »
If you pass parameter by value, then a copy of the value is being passed. So if you change the value inside the function, it will not affect the caller. Pass by reference means if you change the value inside the function, then it would affect the caller. Refer to the following example with its output.

Code:
//Source Code Listing

using System;
using System.Collections.Generic;
using System.Text;

namespace CSTest
{  
   class Program
   {
      static void FnPassByRef(ref int value)
      {
         value = 200;
         Console.WriteLine("Value Inside function Pass By Reference: {0}", value);
      }

      static void FnPassByValue(int value)
      {
         value = 300;
         Console.WriteLine("Value Inside function Pass By Value: {0}", value);
      }

      static void Main(string[] args)
      {
         int data = 100;
         Console.WriteLine("Inital Value: {0}", data);
         FnPassByValue(data);
         Console.WriteLine("Value After Calling function Pass By Value: {0}", data);
         FnPassByRef(ref data);
         Console.WriteLine("Value After Calling function Pass By Reference: {0}", data);
      }
   }

/*** 
// Output
Inital Value: 100
Value Inside function Pass By Value: 300
Value After Calling function Pass By Value: 100
Value Inside function Pass By Reference: 200
Value After Calling function Pass By Reference: 200
Press any key to continue . . .

***/
}

 


Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.
Content copyright 2010-2014. Kathiresan. All rights reserved.
This page is using SMF version 2.0.1