#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

  1. Pingback: #674 – Can Overload If Parameters Differ Only by ref Modifier « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: