Translate

Thursday 25 July 2013

Difference between ref and out parameters in .NET


Before calling the method:

[ref]: The caller must set the value of the parameter before passing it to the called method.
[out]: The caller method is not required to set the value of the argument before calling the method. Most likely, you shouldn't. In fact, any current value is discarded.

During the call:

[ref]: The called method can read the argument at any time.
[out]: The called method must initialize the parameter before reading it.

Example for OUT : Variable gets value initialized after going into the method. Later the same value is returned to the main method.


namespace outreftry
{
    class outref
    {
        static void Main(string[] args)
        {
            yyy a = new yyy(); ;

            // u can try giving int i=100 but is useless as that value is not passed into
            // the method. Only variable goes into the method and gets changed its
            // value and comes out. 
            int i; 

            a.abc(out i);

            System.Console.WriteLine(i);
        }
    }
    class yyy
    {

        public void abc(out int i)
        {

            i = 10;

        }

    }
}



Example for Ref : Variable should be initialized before going into the method. Later same value or modified value will be returned to the main method.
namespace outreftry
{
    class outref
    {
        static void Main(string[] args)
        {
            yyy a = new yyy(); ;

            int i = 0;

            a.abc(ref i);

            System.Console.WriteLine(i);
        }
    }
    class yyy
    {

        public void abc(ref int i)
        {
            System.Console.WriteLine(i);
            i = 10;

        }

    }
}
Output:
    0
    10

No comments:

Post a Comment