CSharp - Use ref Parameter

Description

Use ref Parameter

Demo

using System;
class Program//from w  ww .j av a  2s  . co m
{

    static void Change(ref int x)
    {
        x = x * 2;
        Console.WriteLine("Inside Change(), myVariable is {0}", x);//50
    }
    static void Main(string[] args)
    {
        int myVariable = 25;
        Change(ref myVariable);
        Console.WriteLine("Inside Main(), myVariable={0}", myVariable);//25
    }
}

Result

Here we made a change inside the Change() method.

And this changed value is reflected outside the Change() method.

Here the ref keyword has done the trick.

With ref int x, we did not mean an integer parameter, rather we meant a reference to an int.

Related Topic