Friday, February 15, 2013

Difference between ref and out keyword



Example: ref keyword
 
    Initialization not must to inside in method.
    Before calling a method must be Initialized the values of variables.

namespace ConsoleApplication1
{
    public class swapClass 
    {
        // Swap using third variable, ref keywords
        public  void swapMethod(ref int a, ref int b)
        {
            // Initialization not must to inside in method.
            // before calling a method must be Initialized the values of variables.
         
            int Temp;
            Temp = a;
            a = b;
            b = Temp;
        }
    }
    public class Program
    {
        static void Main(string[] args)
        {
            swapClass obj = new swapClass();
            // using ref Keywords
            int a=10;
            int b=20;         
            obj.swapMethod(ref a, ref b);
            Console.WriteLine("After Swap A= " + a + " B =" + b);

            Console.ReadLine();
        }
    }
}





Example: Out keyword

     Initialization must to inside in method
     Before calling a method maybe initialized or not the values of variables.

namespace ConsoleApplication1
{
    public class swapClass 
    {
        // Swap without using third variable, out keywords
        public void swapWTMethod(out int c, out int d)
        {
          // Initialization must to inside in method
          // before calling a method maybe Initialized or not the values of variables.
            c = 10;
            d = 20;
            c = c + d;
            d = c - d;
            c = c - d;         
        }
    }
    public class Program
    {
        static void Main(string[] args)
        {
            // using out keywords
            int c;
            int d;
            obj.swapWTMethod(out c, out d);
            Console.WriteLine("Before SwapWT C= " + c + " D =" + d);           

            Console.ReadLine();
        }
    }
}


No comments: