Difference between ref and out parameters
These parameters are used with the arguments within a method.
Ref
This keyword is used to pass an arguement as a reference.
It means that when values changed in the called method it will reflected in the calling method.
An argument passed with a ref keyword must be initilzed in the calling method before passing in the called method.
Out
The out keyword is also pass an argument as a reference.
The arguement can be passed without assigning any value to it.
An arguement that is passed using an out keyword must be initialized in the called method before it returns back to the calling method.
Example:
public class Example
{
public static void Main() //calling method
{
int val1 = 0; //must be initialized
int val2; //optional
Example1(ref val1);
Console.WriteLine(val1); // val1=1
Example2(out val2);
Console.WriteLine(val2); // val2=2
}
static void Example1(ref int value) //called method
{
value = 1;
}
static void Example2(out int value) //called method
{
value = 2; //must be initialized
}
}
/*
Output
1
2
{
public static void Main() //calling method
{
int val1 = 0; //must be initialized
int val2; //optional
Example1(ref val1);
Console.WriteLine(val1); // val1=1
Example2(out val2);
Console.WriteLine(val2); // val2=2
}
static void Example1(ref int value) //called method
{
value = 1;
}
static void Example2(out int value) //called method
{
value = 2; //must be initialized
}
}
/*
Output
1
2
Function overloading with Ref and Out Keyword
- Ref and Out cannot be used in function overloading together.
- Ref and Out are considered different at run time but they are considered same at compile time.
- Therefore functions cannot be overloaded if one method takes a ref keyword and other function takes an out keyword.
class SampleClass
{
public void Area(out int a) // compiler error “cannot define overloaded”
{
// method that differ only on ref and out"
}
public void Area(ref int a)
{
// method that differ only on ref and out"
}
}
{
public void Area(out int a) // compiler error “cannot define overloaded”
{
// method that differ only on ref and out"
}
public void Area(ref int a)
{
// method that differ only on ref and out"
}
}
Function overloading can be done, if one function takes a ref or out keyword and other function takes argument without ref or out keyword.
class SampleClass
{
public void Area(int a)
{
}
public void Area(out int a)
{
// method differ in signature.
}
}
{
public void Area(int a)
{
}
public void Area(out int a)
{
// method differ in signature.
}
}
Hi Guys,
ReplyDeleteIf you have any questions regarding the blog please write to me.