Sunday, November 23, 2008

ref - out : at a glance

The ref


The ref keyword causes argument passed by reference. The effect is that any chnages is made to the parameter in the method will be reflected in that variable when control passes back to the calling method. To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword.

An argument passed to to a ref parameter must first be initialized. his differs it from out whose argument need not be explicitly initialize before being passed.

Both ref and out are treated differently at runtime, but treated the same at compilation. Therefore, methods can't be overloaded if one method takes a ref keyword and the other takes an out argument.

Exaple:

class refpara
{
static void refMath(ref String STR)
{
STR = "Hi!";
}
static void Main()
{
String str = "Hello!";
refMath(ref str);
}
}


The out



The out keyword also causes argument to be passed by reference. There no need to initialize the out variable as it requires in case of ref variable.

Exaple:

class refpara
{
static void refMath(out String STR)
{
STR = "Hi!";
}
static void Main()
{
String str = "Hello!";
refMath(out str);
}
}

No comments:

Post a Comment