Search This Blog

Saturday 22 August 2015

What is the difference between out and ref parameter? or Out vs Ref parameter

Step 1 :- Explanation

ref parameter must first be initialized before being passed from the calling function to the called function. but an out parameter need not be initialized. 

The called function must set the value of 
out variable before control returns to calling function.

Step 2:- Complete Code

using System;

namespace Ref_vs_Out
{
    public class Program
    {
        public void RefMethod(ref int value)
        {
            value++;
        }

        public void OutMethod(out int value)
        {
            value = 50;
        }

        static void Main(string[] args)
        {
            Program p = new Program();

            int refValue = 50;
            p.RefMethod(ref refValue);
            Console.WriteLine("Ref value - " + refValue);

            int outvalue;
            p.OutMethod(out outvalue);
            Console.WriteLine("Out value - " + outvalue);


            Console.ReadLine();
        }
    }
}

Step 3:- Output




Note :- 

You cannot differentiate the method overloading only with ref and out keyword.


        public void Method(ref int value)
        {
            value++;
        }

        public void Method(out int value)
        {
            value = 50;
        }

Following error occurred.

Cannot define overloaded method 'Method' because it differs from another method only on ref and out.


No comments:

Post a Comment