Both ref and out parameters are used to pass arguments within a method.
These ref and out parameters are useful whenever your method wants to return more than one value.
Regarding ref parameter you need to initialize it before passing to the method and out parameter you don’t need to initialize before passing to function.
Ref Parameter
If you want to pass a
variable as ref parameter you need to initialize it before you 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.
Declaration of Ref Parameter
int i=3; // variable need to be
initialized
Refsample(ref
i);If you observe above code first we declared variable and initialized with value 3 before it pass a ref parameter to Refsample method
Example
class Program
{
static void Main()
{
int i; // variable need to be
initialized
i = 3;
Refsample(ref
i);
Console.WriteLine(i);
}
public static void Refsample(ref int val1)
{
val1 += 10;
}
}
When
we run above code we will get like as shown below
*********Output************
13
As
we discussed if ref parameter value changed in called method that parameter
value reflected in calling method also
Out Parameter
Declaration of Out Parameter
int i,j; // No need to initialize
variable
Outsample(out
i, out j);If you observe above code first we declared variable and we it pass a out parameter to Outsample method without initialize the values to variables
Example
class Program
{
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;
}
}
If
we observe code we implemented as per our discussion like out parameter values
must be initialized in called method before it return values to calling method
Output
5
10using System;
class Program
{
static void Main()
{
int val = 0;
Example1(val);
Console.WriteLine(val); // Still 0!
Example2(ref val);
Console.WriteLine(val); // Now 2!
Example3(out val);
Console.WriteLine(val); // Now 3!
}
static void Example1(int value)
{
value = 1;
}
static void Example2(ref int value)
{
value = 2;
}
static void Example3(out int value)
{
value = 3;
}
}
Output
0
2
3
No comments:
Post a Comment