value type and ref type

In C#, classes and arrays are always passed with reference, i.e., their address is passed instead of value (String class is an exception).

The variables of primitive data types, such as int, float, double, etc are passed with values.

The following example demonstrates the difference between value type and reference type:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication6
{
    
    class PhoneCustomer
    {
        public const string DayofSendingEmail = "Monday";
        public int CustomerID;
        public string FirstName;
        public string LastName;

        public static void Show(int[] intArray, int i)
        {
            intArray[1] = 300;
            intArray[2] = 500;
            i = 1000;
        }
    }

    class Program
    {
   
        static void Main(string[] args)
        {
            int[] myArray = { 10, 20, 30 };
            int i = 10;

            Console.WriteLine("Values before passing to function");
            for (int j = 0; j < myArray.Length; j++)
            {
                Console.WriteLine(myArray[j]);
            }

            Console.WriteLine("i = {0}", i);

            PhoneCustomer.Show(myArray, i);

            Console.WriteLine("\nValues after passing to function");
            for (int j=0; j<myArray.Length; j++)
            {
                Console.WriteLine(myArray[j]);
            }

            Console.WriteLine("i = {0}", i);
           
        }
    }
}

 

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *