Monday, June 4, 2012

Difference between ref and out in C#


using System;

namespace Difference_ref_out
{
    class Program
    {
        static void Main(string[] args)
        {

            int input1 = 10;// variable must be initialized

            Console.WriteLine("Initial value\t:\t{0}",input1);

            TestCase _testCase = new TestCase();
            _testCase.TestMethod1(ref input1);// the arg must be passed as ref

            Console.WriteLine("Processed value\t:\t{0}", input1);

            Console.WriteLine("***\t***\t***\t***");

            int input2;// variable need not be initialized

            _testCase.TestMethod2(out input2);// the arg must be passed as out

            Console.WriteLine("Processed value\t:\t{0}", input2);

            Console.Read();
        }
    }


    class TestCase
    {
        public void TestMethod1(ref int input1)
        {
            input1 = input1 + 10;
        }

        public void TestMethod2(out int input2)
        {
            input2 =10;//The out parameter 'input2' must be assigned to before control leaves the current method

        }
    }
}


Reference :  MSDN
Post a Comment