8.22.2012

Difference Between ref and out parameters

Difference between Ref and Out parameters
S.No
Ref
Out
1
Ref parameters are both input and output - a value is passed into a method and a new value is passed out
Out parameters are only for output - a value is passed out of a method


2
An argument passed to ref parameter must be initialized
out argument does not have to be explicitly initialized.
3
Ref parameter may be written to before returning from method
Out parameter must be written to before returning from method
4
Ref parameter may be referenced inside method before being written to
Out 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.

No comments:

Post a Comment