#269 – Use ref Modifier on Parameters that Are Input/Output

You can use the ref modifier on a parameter to signal that it should be passed by reference.  Instead of passing in a copy of the current value, a reference to the variable is passed into the method.  The method can read or change the current value.  Changes to ref parameters are seen by the calling code when the method returns.

The ref modifier should be used for input/output parameters, when you want to pass data into the method and also receive updated data when the method returns.

        public static bool DoubleBigNumber(ref int aNumber)
        {
            bool didIt = false;

            if (aNumber > 1000)
            {
                aNumber *= 2;
                didIt = true;
            }

            return didIt;
        }

When calling the method, you use the ref modifier for any ref parameters.

            int myNumber = 1200;
            bool didit = NumberHelper.DoubleBigNumber(ref myNumber);

            Console.WriteLine(myNumber);        // Value now 2400
Advertisements