Diff b/w Ref & Out parameters in C#.Net

Out Parameter:
Variable gets value initialized after going into the method, Later the same value is returned to the main method
EX:
namespace outPar{
    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;

        }

    }
}
 
OutPut:
10
 
Ref Parameter: 
 Variable should be initialized before going to the method,Later the same value or modified value 
 will be return to the main method
Ex:
namespace refPar
 {
    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:
10 
 

No comments:

Post a Comment