Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Passing by Value and by Reference

using System.IO;
using System;

class Program
{
    int a = 10;
    int b = 20;
    string str1 = "before";
    string str2 = "after";
    
    private void DisplayNumbers(string txt, int int1, int int2)
    {
        Console.WriteLine("Numbers {0} swap : a = {1}, b = {2} ", txt, int1, int2);
    }
    
    private void SwapByValue(int int1, int int2)
    {
        Console.WriteLine("SwapbyValue is called.");
        int temp = int1;
        int1 = int2;
        int2 = temp;
    }
    
    private void SwapByRef(ref int int1, ref int int2)
    {
        Console.WriteLine("SwapbyRef is called.");
        int temp = int1;
        int1 = int2;
        int2 = temp;
    }
    
    static void Main()
    {
        Program p = new Program();
        
        p.DisplayNumbers(p.str1, p.a, p.b);
        p.SwapByValue(p.a,p.b);
        p.DisplayNumbers(p.str2, p.a, p.b);
        Console.WriteLine();
        
        p.DisplayNumbers(p.str1, p.a, p.b);
        p.SwapByRef(ref p.a,ref p.b);
        p.DisplayNumbers(p.str2, p.a, p.b);
    }
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.