Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference Between Out and ref Keywords in C#

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 280
    Comment on it
    Ref  Out
    1. Ref keyword is required to initialize a passing parameter first then passed it to ref.

     1. Out keyword doesn't required to initialize a passing parameter before it is passed it to out.

    2. A called method doesn't need to initialize a value of a parameter before return to the calling method.

     2. A called method doesn't need to initialize a value of a parameter before return to the calling method.
    3. In ref we can pass the data in bi-facial.

     3. In out we can can pass the data only in uni-facial.

    4. Example:-

    public static int GetByRef(ref int i)
    {
        int returnString = i.ToString();
        i += 1;
        return returnString;
    }
    static void Main(string[] args)
    {
        int i = 1;
        Console.WriteLine("Previous value of i=" + i.ToString());
        int str = GetByRef(ref i);
        Console.WriteLine("Current value of i=" + i.ToString());
    }

     

    Output:-
    Previous value of i=1
    Current value of i=2

    4. Example:-

    public static int GetByOut(out int i)
      {
           i = 1;
           int returnText = i;
           return returnText;
       }
    static void Main(string[] args)
    {
        int i = 10;
        Console.WriteLine("Previous value of i=" + i.ToString());
        int str = GetByOut(out i);
        Console.WriteLine("Current value of i=" + i.ToString());
    }

     

    Output:-
    Previous value of i=10
    Current value of i=1

    5. Ref keyword is basically used when we need to reflect the changes made in the passing parameter of a function 5. Out keyword is basically used when need to return a multiple values from a function.

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: