Handwritten Text Recognition for manuscripts and early printed texts
Difference between ref and out parameters
1. Difference between Ref and Out parameters
S.No Ref Out
1 Ref parameters are both input and Out parameters are only for output - a
output - a value is passed into a value is passed out of a method
method and a new value is passed
out
2 An argument passed to ref out argument does not have to be
parameter must be initialized explicitly initialized.
3 Ref parameter may be written to Out parameter must be written to
before returning from method before returning from method
4 Ref parameter may be referenced Out parameter may not be referenced
inside method before being inside method before being written to
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)
{
2. 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.
And, further updates on difference between questions and answers, please visit my blog @
http://onlydifferencefaqs.blogspot.in/