Showing posts with label C# out. Show all posts
Showing posts with label C# out. Show all posts

Friday, January 30, 2015

Out keyword in C#

As you know, a return statement enables a method to return a value to its caller. However, a method can return only one value each time it is called. What if you need to return two or more piece of information?

For example: What if you want to create a method that decomposes a floating-point number into its integer and fractional parts? To do this requires that two pieces of information be returned: the integer portion and the fractional component, this method cannot be written using only a single return value. The Out modifier solves this problem.

Use out

An out parameter is similar to a ref parameter with this one exception. It can only be used to pass a value out of a method.
It is not necessary to give the variable used as an out parameter an initial value prior to calling the method. The method will give the variable a value. Furthermore, inside the method, an out parameter is considered unassigned; that is, it is assumed to have no initial value. This implies that the method must assign the parameter a value prior to the method termination. Thus, after the call to the method, an out parameter will contain a value.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace use_out
{
    class decomp
    {
        public int Twoval(double n, out double frac)
        {
            int whole;
            whole = (int)n;
            frac = n - whole;
            return whole;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            decomp obj = new decomp();
            int a;
            double f;
            a =obj.Twoval (20.125,out f);
            Console.WriteLine("integer part is" + a);
            Console.WriteLine("fractional part is" + f);
            Console.Read();
        }
    }
}

Output



Note: Twoval() method return two piece of information. First is integer portion of n is returned as Twoval()’s return value. Second, the fractional portion of n is passed back to the caller through the out parameter frac. So the above mention example it is possible for one method to return two values.  

                                                        Author-Sayta Prakash