DIFFERENCE BETWEEN REF AND OUT KEYWORDS

Anupam Mishra

Total Post:135

Points:949
Posted by  Anupam Mishra
C#  .NET 
C#
 478  View(s)
Ratings:
Rate this:
Hi Everyone,
 I want to know what is difference between ref and out keywords.Please can anyone give me a exact situation.
thank you.
  1. Anupam Mishra

    Post:135

    Points:949
    Re: difference between ref and out keywords


    If we want to pass a variable as ref parameter we need to initialize it before we pass it as ref parameter to method. Ref keyword will pass parameter as a reference this means when the value of 
    parameter is changed in called method it get reflected in calling method also.

    i = 10;
    public static void RefTest(ref int val1)
    {
    val1 += 10;
    }
    Output : 20
    If we want to pass a variable as out parameter we don’t need to initialize it before we pass it as out parameter to method. Out keyword also will pass parameter as a reference but here out parameter must be initialized in called method before it return value to calling method.

    int i,j; // No need to initialize variable
    OutTest(out i, out j);
    public static int OutTest(out int val1, out int val2)
    {
    val1 = 5;
    val2 = 10;
    return 0;
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!