Difference
between Ref and Out parameters
-
S.No RefOut1Ref parameters are both input and output - a value is passed into a method and a new value is passed outOut parameters are only for output - a value is passed out of a method2 An argument passed to ref parameter must be initializedout argument does not have to be explicitly initialized.3 Ref parameter may be written to before returning from methodOut parameter must be written to before returning from method4 Ref parameter may be referenced inside method before being written toOut parameter may not be referenced inside method before being written to
Example
for ref parameter :
class
Program
{
static void M1(ref
int i)
{
i = 1;
i += 1;
}
static void
Main(string[] args)
{
int j=0; //Assigned
M1(ref j);
Console.Write(j);
Console.Read();
}
}
The
output is same: 2, but we have to assign the variable before used
otherwise we will get an error.
Example
for out parameter :
class
Program
{
static void M1(out
int i)
{
i = 1;
i += 1;
}
static
void Main(string[] args)
{
int j; //Not
assigned
M1(out j);
Console.Write(j);
Console.Read();
}
}
}
The
output is : 2
Summary:
1. Both are
treated differently @ runtime but same in the compile time, so can’t
be overloaded.
2.
Both are passed by references except ‘ref’ requires that the
variable to be initialized before passed.
thanks for your informative article .its veryuseful.best dot net training in chennai | dot net training institutes in chennai | dot net training institutes in velachery
ReplyDeletethanks for giving this blog with usefull information .i got a idea of ref and out.thanks for your info article and i am waiting for your next post keep on updating these kinds of knowledgeable things. dot net training in chennai velachery |
ReplyDeletedot net training and placement in chennai