Value Type Parameter vs Reference Type Parameter in C#
Posted by Superadmin on August 15 2022 07:55:30

Value Type Parameter vs Reference Type Parameter in C#

 

This C# Program Demonstrates the Difference between Value Type Parameter and Reference Type Parameter.The increment of an variable id done by both value type parameter and reference type parameter.

 

Here is source code of the C# Program to Demonstrate the Difference between Value Type Parameter and Reference Type Parameter. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

  1. /*
  2.  * C# Program to Demonstrate the Difference between 
  3.  * Value Type Parameter and Reference Type Parameter
  4.  */
  5. using System;
  6. namespace Example1
  7. {
  8.     class Program
  9.     {
  10.         public static void value(int num)
  11.         {
  12.             num++;
  13.         }
  14.         public static void reference(ref int num)
  15.         {
  16.             num++;
  17.         }
  18.  
  19.         static void Main(string[] args)
  20.         {
  21.             int num;
  22.             Console.Write("Enter a Number:\t");
  23.             num = Convert.ToInt32(Console.ReadLine());
  24.             Console.WriteLine("\n\tValue Type:");
  25.             Console.Write("\nPrevious Value:\t{0}", num);
  26.             Program.value(num);
  27.             Console.Write("\nCurrent Value:\t{0}", num);
  28.             Console.WriteLine("\n\tReference Type");
  29.             Console.Write("\nPrevious Value:\t{0}", num);
  30.             Program.reference(ref num);
  31.             Console.Write("\nCurrent Value:\t{0}", num);
  32.             Console.ReadLine();
  33.         }
  34.     }
  35. }

Here is the output of the C# Program:

Enter a Number : 10
           Value Type :
Previous Value : 10
Current Value :10
 
           Reference Type :
Previous Value : 10
Current Value :11