Facts of ref and out type Parameters in C#
Introduction
Parameters are initialized with
a copy of argument when we pass an argument to a method, even this is true
regardless of whether parameter is a value type like int, int? (nullable) or
reference type. Look at the example given below, it is impossible to change the
parameter to affect the value of the argument passed.
static void Main(string[]
args)
{
int
num = 33;
myfunction(num);
Console.WriteLine(num);
Console.ReadKey();
}
private
static void
myfunction(int rcnum)
{
rcnum++;
}
In above example, the value to
the console is 33 not 34. The myfunction method increments a copy of the
argument named rcnum and not the original argument. C# Language provides the
ref and out keywords to do this.
Ref Type Parameters
When we pass a parameter as ref
type to a method, the method refers to the same variable and changes made will
affect the actual variable. We need to add prefix ref and it becomes an alias
for the actual argument rather than a copy to the argument. When we use ref
parameter, anything we do to the parameter also do the same with original
argument because the parameter and the argument both reference the same object.
Look at the example given below:
static void Main(string[]
args)
{
int
num = 33;
myfunction(ref
num);
Console.WriteLine(num);
Console.ReadKey();
}
private
static void
myfunction(ref int
rcnum)
{
rcnum++;
}
In above example, we have
passed myfunction method a reference to the original argument rather than a
copy of the original argument and because of this any changes the method makes
change also the original argument and result 34 displays on the screen.
Out Type Parameters
Variable passed as out parameter
is similar to ref, but there are few implementation differences when you use it
in C#. Argument passed as ref must be initialized before it is passed to the
method, whereas in case of out it is not necessary, but after a call to the
method as an out parameter the variable must be initialized. Look at the
example below which will clarify all your doubts:
static void Main(string[]
args)
{
int
num;
myfunction(out
num);
Console.WriteLine(num);
Console.ReadKey();
}
private
static void
myfunction(out int
rcnum)
{
rcnum = 33;
}
In above example, we have not
passed any value from the main method; this is the importance of out type
parameter.
Thanks for joining here.
Comments
Post a Comment