Pages

Jun 17, 2008

Use of Out and Ref parameter in C#

OUT:

The out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword. For example:


Class Sample
{
static void Method(out int i)
{
i = 2;
}
static void Main()
{
int value;
Method(out value);
// value is now 2// We can use this value for further process
}
}

The ref and out keywords are treated differently at run-time, but they are treated the same at compile time. Therefore methods cannot be overloaded if one method takes a ref argument and the other takes an out argument

Example of ref

Class Sample

{

static void Method(ref int i)

{

i = i + 2;

}

static void Main()

{

int value = 2;\\ should be initialized for ref method

Method(ref value);// value is now 4
// We can use this value for further process

}

}

This methods are mainly used when hirarchical function where method A(ref int a) --> calls method B(ref int b) -->calls method C(ref int c)

Here in this case the value got in method c is returned to method B which is returned and got in method A.In this next section we ll discuss about out parameters in SQL2005

No comments: