Tuesday, August 23, 2011

Call by Value and Reference over an Object of a class.















For your knowledge J
Please correct me if I am wrong.

Object are always send as a reference into a method whether you do call by value or call by reference.
Whenever we send an object as parameter, a new Method Variable get created in Stack and it points to an Object reference into Heap in memory.
Now making changes in property or method using Method variable would directly make changes in Object as it is referencing to the object only.
Now if you assign NULL to the Method Variable then what would happen?
The value of Method Variable would get NULL not the object or the main variable which was send as parameter to the method.
Hence we are still able to access the object through main variable as we didn't assign NULL to it.
         
Please go through the proof of the concept.

namespace OOPSConcepts
{
    class Program
    {       
        static void Main(string[] args)
        {
            try
            {
                //Varaible of Employee type that contains object of Employee class.
                Employee emp = new Employee { Name = "Sandeep" };
                Console.WriteLine("Name before NULL assignment :" + emp.Name);

                //Here emp is Main variable having reference of Employee Object.
                ChangeEmployeeName(emp);

                Console.WriteLine("Name AFTER NULL assignment :" + emp.Name);
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// Method to change the name of Employee Object. This is example of Call by Value.
        /// </summary>
        /// <param name="employee">Varaible of Employee type that would contain the reference
        /// of Object of Employee class passed as an argument.</param>
        static void ChangeEmployeeName(Employee employee)
        {
            employee.Name = "Siddharth";
            employee = null; //Assigning Null to employee variable.

            /*
             *Scope of employee variable is ended here.
             */
        }
    }

    /// <summary>
    /// Dummy Employee class.
    /// </summary>
    class Employee
    {
        public string Name { get; set; }
    }
}


The output would be :

Name before NULL assignment :Sandeep
Name AFTER NULL assignment :Siddharth

No comments:

Post a Comment