Friday, March 8, 2013

Out Keyword in C#.Net

Out is a keyword which is used in c#. Generally a method returns only one value to where the call to the method is made. Suppose we want to return more than one value from a method , it is not possible.If we want to return more than one value from a method we use out key word . Just place the out keyword before the declaration of parameters in the method.
 Example: public int add(out int a, out int b)
{
--------
--------
}
In the above example I declared a method add(). It has two parameters a , b of integer types. Now, when the call to this method is made , then this method returns two values of integer type.
Example:
using System;

namespace Out_Keyword
{
    class Program
    {
        static void Main()
        {
            int a, b;
            float f;
            double d;
            char c;
            string s;
            Display(out a, out b,out f,out d, out c, out s);
            Console.WriteLine(a+"\n"+b+"\n"+f+"\n"+d+"\n"+c+"\n"+s);
            Console.ReadKey();
        }
        public static void Display(out int a1,out int b1,out float f1,out double d1, out char c1,out string s1)
        {
            a1 = 5;
            b1 = 6;
            f1= 64.654783f;
            d1 = 875.339854721;
            c1 = 's';
            s1 = "sagar rayala";
     
        }
    }
}

In the above example I declared  method Display() with 6 parameters of int , float , double , char and string types.And I initialized the parameters with some values.
In the main() I declared  variables of same types declared in the Display().And I called the Display() with variables declared in the main (). The Display() returns values to the variables.


No comments: