The
keyword out is used to get the value from the function.
1. You don't need to initialize the value in the calling function.
2. Need to initialize the value in the called function, otherwise the compiler will report an error.
void funcA(out int a)
{
a = 0;
...
}
void funcB()
{
...
int a;
funcA(out a);
...
}
The
keyword ref is to pass and get modified value from a function.
1. You need to initialize the variable before you call the function.
2. Function may or may not change the value of the ref parameter
(if it doesn't change any thing then whats the purpose?)
void funcA(ref int a)
{
...
a = a + 1;
...
}
void funcB()
{
...
int a = 1;
funcA(ref a);
...
}
Overriding of methods with only difference keyword, as shown below, will lead to compile time error "cannot define overloaded methods that differ only on ref and out"
static public void funcA(out int a)
{
a = 1;
}
static public void funcA(ref int a)
{
a = a + 1;
}
We can assign a value to the out parameter function in the caller function. However, this will lead to compile time exception "Use of unassigned out parameter a"
namespace ConsoleApplication1
{
class Program
{
static public void funcA(out int a)
{
if (a == 1)
a = 2;
else a = 1;
}
static void Main(string[] args)
{
int a = 1;
funcA(out a);
}
}
}
HTH