Monday, July 28, 2014

Understanding Out Parameter Modifier in C#

Understanding Out Parameter Modifier in C#
  • Out keyword is used to return more than one value from a function by using it in the param passing.
  •  Out can also be used in formal arguments without initializing in the actual arguments. Provided initialization has to be done in the function and cannot be left uninitialized.



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

namespace Apps
{
    class Test
    {
        public static void Manipulations(int a, int b, out int add, out int sub, out int kvalue)
        {
            //kvalue is assigned here in the method after passing using Out parameter unlike the ref(which should initialize before passing to the method) parameter
            kvalue = 10;

            //Here the add and sub values are returned to Main with the help of out parameter because it is creates a reference to the values in the memory
            add = a + b;
            sub = a - b;
        }
    }
        
    class UnderstandingOutParameterModifier
    {
        public static void Main(string[] args)
        {
            int add, sub, kvalue;
            Test.Manipulations(102, 11, out add, out sub, out kvalue);
            Console.WriteLine(add);
            Console.WriteLine(sub);
            Console.WriteLine(kvalue);
        }
    }
}

No comments:

Post a Comment