Monday, 8 October 2018

Ref and out key word.


Ref and out key word :-

Ref and out key word use to passing the value as reference to the function,If you want to pass a variable as ref parameter you must need to initialize it, before you pass it as ref parameter to any 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.


class Refkeyword
{
static void Main()
{
int i; // variable need to be initialized
i = 3;
Refsamplemethod(ref i);
Console.WriteLine(i);
}
public static void Refsamplemethod (ref int val1)
{
  val1 += 10;
}
}


Properties of ref keyword :-
  • ·         Must be initialized.
  • ·         Always return the single value.
  • ·         Ref keyword used to pass an argument in a method.


Out Key word :-
If you want to pass a variable as out parameter you don’t need to initialize it before you 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 .





class OutKeyword
{
static void Main()
{
int i,j; // No need to initialize variable
Outsample(out i, out j);
Console.WriteLine(i);
Console.WriteLine(j);
}
public static int Outsample(out int val1, out int val2)
{
val1 = 5;
val2 = 10;
return 0;
}
}







Properties of ref keyword :-
  • ·         No need to initialize.
  • ·         Return the multiple value.
  • ·         Out  keyword used to pass an argument in a method.


Note : Out and Ref work differently at run time but both are same at compile time. So, if you want to create two functions with the same names and same parameters but the only difference is Out and Ref keyword, then it will give a compile time error. We can say overloading is not possible in case of  the same functions and they have only one difference, i.e. Ref and Out keyword.


No comments:

Post a Comment