OUT parameters are
parameters which are passed back from a function to the calling function or
method, it is good enough to declare the parameters in the calling method they
need not be initialized in the calling class, instead their values will be
assigned in the function which is returning the out parameters.
OUT parameters are declared similar to the normal parameters by adding an out keyword in front of the parameter as follows.
OUT parameters are declared similar to the normal parameters by adding an out keyword in front of the parameter as follows.
public int GetEmployeeDetails(out string empName)
OUT parameters come in handy when we need to return more than one value from a function, functions can always return only one value, OUT parameters help in overcoming this limitations by allowing us to pass additional values from a function.
In the following class we will pass the employee name as an OUT parameter to the function GetEmployeeDetails.
class CEmployee
{
int nId;
string sName;
//
public CEmployee(int
id, string name)
{
nId = id;
sName = name;
}
//
public int
GetEmployeeDetails(out string
empName)
{
empName = sName;
return nId;
}
}
The code to call this function is as
follows.
string employeeName;
string employeeName;
CEmployee objEmployee = new
CEmployee(1, "Name1");
//
int empID = objEmployee.GetEmployeeDetails(out employeeName);
Console.WriteLine("EMP
ID: " + empID.ToString());
Console.WriteLine("EMP
Name: " + employeeName);
Notice that the out
parameter employeeName is just declared in the calling function
and the actual value assignment to the parameter happens in the the
GetEmployeeDetails method of the called function. Even if we
try to assign some value to the parameter variable in the calling function it
will be overwritten by the called function.
No comments:
Post a Comment