Saturday, March 17, 2012

What is difference between ref and out parameter in c# .net

 We know that in c# language the out and the ref parameters are used to return values in the same variables, that you pass an an argument of a method. These both parameters are very useful when your method needs to return more than one values.

Key difference:

"ref keyword required that variable must be initialized before passed to function while Out keyword variable initialization is not required. But before returning to called function from calling is require to assign the value before returning else give compile time error

                                                                                                                                                                          "

The ref and out keyword treat different in run time but same at compile time so we can’t overload method if one method have out argument and one have ref argument


The out Parameter

The out parameter can be used to return the values in the same variable passed as a parameter of the method. Any changes made to the parameter will be reflected in the variable.
Only Method can do Read and Write operation on the passed variable while the caller can only read it.
    public class mathClass
    {
        public static int TestOut(out int iVal1, out int iVal2)
        {
            iVal1 = 10;
            iVal2 = 20;
            return 0;
        }
        public static void Main()
        {
            int i, j; // variable need not be initialized
            Console.WriteLine(TestOut(out i, out j));
            Console.WriteLine(i);
            Console.WriteLine(j);
        }
    }



The ref parameter

The ref keyword on a method parameter causes a method to refer to the same variable that was passed as an input parameter for the same method. If you do any changes to the variable, they will be reflected in the variable.

You can even use ref for more than one method parameters. 
Caller and the method can do Read & Write operation on the passed variable.
namespace TestRefP
    {
        using System;
        public class myClass
        {
            public static void RefTest(ref int iVal1)
            {
                iVal1 += 2;
            }
            public static void Main()
            {
                int i; // variable need to be initialized
                i = 3;
                RefTest(ref i);
                Console.WriteLine(i);
            }
        }
    }

0 comments:

 
Powered by Code Imagine