Out Parameters

C# Out parameters are parameters that can accept uninitialized variables or arguments. The out keyword is used when passing an uninitialized variable to a method. Uninitialized variables are variables that contain no value or it has not been assigned a value yet. The method should give that uninitialized variable a value. Passing uninitialized variables to a method is useful when you just want to be supplied with data from a method. Using the out keyword for an argument also passes it by reference and not by value. Let’s take a look at the following example program.

using System;

namespace OutParametersDemo
{
    public class Program
    {
        static void GiveValue(out int number)
        {
            number = 10;
        }

        public static void Main()
        {
            //Uninitialized variable
            int myNumber;

            GiveValue(out myNumber);

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

Example 1 – out Parameters Example

myNumber = 10

We used the out keyword for the parameter of the method so that it can hold an uninitialized variable. In the Main method,  line 17 calls the method and we precede the argument with the out keyword. The uninitialized variable is passed to the method and there, we assign it a value of 10  (line 9). We displayed the value of myNumber(line  19) and to show that it now contains the value that we assigned inside the method.

Using out parameters doesn’t mean that you always need to pass an uninitialized argument. In fact, you can still pass an argument that already contains a value. Doing that is equivalent to using the ref keyword.

Written by compitionpoint

Leave a Comment

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