Out Parameter Modifier in C# with Example

Out Parameter Modifier in C# with Example
Out Parameter Modifier in C# with Example

An another parameter modifier is out, which we use when we are expecting more than 1 output from a method.  Normally, a method return only 1 type of value depending upon the return data type like string, int, array etc.  In this case, you can create multiple variables of different data types to store the output values and you can create the method of return type void, which will not return any value.  You must use out keyword in front of data type in the method declaration.  Also, before calling that method, you must use out keyword in front of method arguments which you are going to pass.  Just for info, the variables in the method declaration are known as method parameters and the variables passed to that method are known as method arguments.  A simple example is given below, where we want to obtain addition and multiplication of 2 numbers.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hello
{     

    class Program
    {
        static void Main(string[] args)
        {
            //variables
            int num1 = 10;
            int num2 = 20;
            int add = 0;
            int multiply = 0;

            //calling method
            calculation(num1, num2, out add, out multiply);

            Console.WriteLine("Addition: {0}   Multiplication: {1}", add, multiply);
        }

        //Calculation method
        public static void calculation(int num1, int num2, out int addition, out int multiplication)
        {
            addition = num1 + num2;
            multiplication = num1 * num2;
        }
    }
}

Output:

Addition: 30   Multiplication: 200
Press any key to continue . . .