HI WELCOME TO SIRIS

Part 17 - C# Tutorial - Call By Reference

Leave a Comment
C# provides a ref keyword to pass argument as reference-type. It passes reference of arguments to the function rather than copy of original value. The changes in passed values are permanent and modify the original variable value.

C# Call By Reference Example

  1. using System;  
  2. namespace CallByReference  
  3. {  
  4.     class Program  
  5.     {  
  6.         // User defined function  
  7.         public void Show(ref int val)  
  8.         {  
  9.              val *= val; // Manipulating value  
  10.             Console.WriteLine("Value inside the show function "+val);  
  11.             // No return statement  
  12.         }  
  13.         // Main function, execution entry point of the program  
  14.         static void Main(string[] args)  
  15.         {  
  16.             int val = 50;  
  17.             Program program = new Program(); // Creating Object  
  18.             Console.WriteLine("Value before calling the function "+val);  
  19.             program.Show(ref val); // Calling Function by passing reference            
  20.             Console.WriteLine("Value after calling the function " + val);  
  21.         }  
  22.     }  
  23. }  
Output:
Value before calling the function 50
Value inside the show function 2500
Value after calling the function 2500

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.