Translate

Saturday, July 6, 2013

Difference between ref and out c#

ref means value must be assigned before going in the method. out means value must be assigned before going out of the method.

For example, the code below will fail if we pass x into the method as out instead of ref.


using System;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            int p=0;
            Test(ref p);

        }

        static void Test(ref int x)
        {
        //if x is passed in as out, compilation will fail with an error
        //"The out parameter 'x' must be assigned to before control leaves the current   method"    

        }

    }
}




This code below will fail if we pass x in as ref instead of out. 

using System;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            int p;// NOTE: We have not initialized p here (No value before going in.)
            Test(out p);

        }

        static void Test(out int x)
        {
            //if x is passed in as ref, compilation will fail with an error
            //"Use of unassigned local variable 'p' "

            x = 5;
        }

    }
}

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator