How to use out and ref keywords in .net with examples, Benefits of out and ref
This resource explains the use of out and ref keywords in .net. Examples are also given for better understanding of the concept. Just copy the code given in the article and paste into visual studio and it is gonna work for you.
Description: out and ref keywords are used to pass "value type" variables by reference while calling functions. The difference is,
For using ref, we first need to initialize variable, only then we can pass it to a function.
For using out, we do not need to initialize variable, while passing it to a function. However, we need to initialize it in another function, before using it.
Example for using out keyword: Below example explains the way we can use out keyword in .net.
class Program
{
static void Main(string[] args)
{
int i;
//Passing uninitialized variable.
int j=outFunction(out i);
//Displaying the changed value.
Console.WriteLine(j.ToString());
Console.ReadLine();
}
private static int outFunction(out int i)
{
//Initializing variable, as it need to be initialized before using it.
i = 0;
return i + 2;
}
}
Example of using ref keyword: Below example explains the way we can use out keyword in .net.
class Program
{
static void Main(string[] args)
{
int i;
//Following statement will give compile time error,
//as we are passing uninitialized variable.
refFunction(ref i);
}
private static int refFunction(ref int i)
{
i = 0;
return i + 2;
}
}
Benefit of ref and out keyword: The Scenario is given below:
Scenario: When we want to return more than 1 value from function.
Solution: As we know a function can not return more than value, So we can pass parameters by "ref" or "out" keyword to the called function . By passing parameters by ref or out, the changed value of the variable in the called function would be reflected in the calling function.