Tuesday, May 28, 2013

REF Parameter

REF parameters are parameters which are passed between the calling function and the function being called, we need to declare and initialize the parameters in the calling method, their values will be re-assigned in the actual function and returned back to the calling function.

REF parameters are declared similar to the normal parameters by adding a ref keyword in front of the parameter as follows.

public int GetEmployeeDetails(ref string empName)

REF parameters come in handy when we need to return more than one value from a function, functions can always return only one value, REF 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 a REF parameter to the function
    class CEmployee
        int nId;
        string sName;
        public CEmployee(int id, string name)
            nId = id;
            sName = name;
        public int GetEmployeeDetails(ref string empName)
            empName = sName;
            return nId;

The code to call this function is as follows.

    string employeeName;
    employeeName = "Test Name";
    CEmployee objEmployee = new CEmployee(1, "Name1");
    int empID = objEmployee.GetEmployeeDetails(ref employeeName);
    Console.WriteLine("EMP ID: " + empID.ToString());
    Console.WriteLine("EMP Name: " + employeeName);

Notice that the variable passed as ref parameter employeeName is just declared and initialized in the calling function and the value is re-assigned in the GetEmployeeDetails method of the called function.

REF parameters can be used when we need to share values between 2 values, where both the functions have control over the parameter and can set/get values from the parameter variable.

Search Flipkart Products:

No comments: