17. Out Parameter OUT is a keyword which is used to the passing the arguments to the method as a reference type. It is generally used when a method returns multiple values.
we will discuss..
1. Declaring out parameters
2. Important point out
3. c# 6.0 & c# 7.0
4. Multiple out Parameters
Declaring
out
parameters:-
Declaring a method with
out
arguments is a classic workaround to return multiple values.
Ex:-
Public void Method declare( out string name)
{
name ="chandan";
}
{
name ="chandan";
}
Important point to remember.
- Out is similarly to ref keyword. But there is some difference between ref and out keyword.
- ref needs that the variable must be initialized before it passed to the method. But out parameter doesn’t require any variables to be initialized before it passed to the method. But before it returns a value to the calling method, the variable must be initialized in the called method.
-in and ref we will see after the tutorial.
3. The out parameters are not allowed to use in asynchronous methods.
// Asynchronous method
async static Task add(out name)
{
}
*Compile time error through.
4. There can be more than one out parameter in a method.
class Program
{
static void Main(string[] args)
{
int i , j , c ;
Add(out i, out j, out c);
Console.WriteLine("The addition of value i is {0}:",c);
Console.ReadLine();
}
private static void Add(out int i,int j,out int c)
{
i = 10;
j =20;
c= i+ j;
}
}
5. Method overloading can be done using out parameters.
6. Up to C# 6.0, a user first declares the variable then it can only pass as an out argument. But from C# 7.0, excepting a separate variable declaration, the user can also declare the out variable in the argument list of the method call.
C# 6.0 C# 7.0
int Id;
methodName(out Id); methodName(out int Id);
class Program
{
static void Main()
{
int i;
Add(out i);
Console.WriteLine("The addition of the value is: {0}", i);
Console.ReadLine();
}
public static void Add(out int i)
{
i = 30;
i += i;
}
}
In C# 7.0, the out parameter can pass without its declaration and initialization which is termed as the In-line declaration of Out parameter or Implict Type Out Parameter. Its scope is limited to the method body i.e. local scope.
Note: You need to require C# 7.0 version to run this example.
class Program
{
static void Main(string[] args)
{
Add(out i, out j, out c);
Console.WriteLine("The addition of value i is {0}:",c);
Console.ReadLine();
}
private static void Add(out int i , out int j , out int c)
{
i = 10;
j =20;
c= i+ j;
}
}
In out parameter, it is not compulsory that the name of the out parameter is same in both definition and call.