Understanding the concept of pass by value and pass by reference with an example?

 

Before we try to understand the concept of passing parameters let’s just first understand about value types and reference types because passing parameters is all about how to pass a value type and to pass a reference type.

What are Value Types?

A data type is a value type if it holds the data within its own memory allocation.
All numeric data types like Boolean, char, date, int and struct all are value types.
All structures are value types, even if their members are reference types.
A Value Type Memory is allocated on stack.

For Example

 
int i = 009; 
Char ch = "w";    

A reference type contains a pointer to another memory location that holds the actual data. In reference types data is not hold within its own memory allocation it contains reference of another memory location which actually holds the data.

All interfaces, delegates, class objects, arrays and dynamic types all are reference types.

A value type inside a class scope also known as reference type.

Reference type Memory is allocated in heap.

Example 1

 
string[] str = new string[2] {"ABC","PQR"}; 
class obj = new class();   

Example 2

 
    class Employee
        {
         Private int empCode = 4545; 
        }   

Integer is a value type but since it's in class scope (reference type).indirectly it also becomes a reference type.

So now that you have understood about value types and reference types let's come back to our main topic on passing parameters.

What are Passing Parameters?

 

Passing the parameters is of two types

Pass by Value Type
Pass by Reference Type

Passing the value type or reference type can be done through using methods, properties, constructors and indexers.

Pass By Value Type

Pass by value assumes that the variable value is set before the method or function is called.

We can pass the value type in two ways

Pass value types by value
Pass value type by reference

Pass by Reference Type

A variable of reference type contains a pointer to another memory location that holds the data.

To pass a parameter by reference, you can use the 'ref' or 'out' keyword.

Ref:

Pass by reference using 'ref' keyword assumes that the variable value is already set before the function is called.

Out:

Pass by reference using 'out' keyword assumes that the variable value is will be set by calling function.

We can pass the reference type in two ways

Pass reference types by value
Pass reference type by reference

To keep it simple let's just understand these topics one by one.  We will first understand Pass by Value Type and their ways of passing parameter then Pass by Reference Type and their ways of passing parameter.

Understanding Pass By Value Type


We can pass the value type in two ways

Pass value types by value
Pass value type by reference


Pass value types by value

To a method or a function we need to pass value type as value

For Example:

 
        public static void PassValueByValue(int val)
        {
            val *= val;
            Console.WriteLine("Output : PassValueByValue : {0}", val);
        } 

In above the code we have created a static method "PassValueByValue" with an input parameter value type. This method squares the input parameter and displays the output.

To test Pass value types by value we have created a main method which has value type "testval" and initialized to 5 and pass same input parameter to a method "PassValueByValue"  as shown below code.

static void Main(string[] args)
{
  int testval = 5;
  Console.WriteLine("Main method value : {0} \n", testval);
  PassValueByValue(testval);
  Console.WriteLine("Main method value After PassValueByValue : {0} \n", testval); 
} 

Display output for above result as follows.

        
       Output // 5 ;
        PassValueByValue // 25;
        After the PassValueByValue // 5;

So when we pass a value as value type parameter "testval" to a method "PassValueByValue". Parameter "testval" does not change. Tested value type holds the data within its own memory allocation.

Pass value types by reference

To a method or a function we need to pass value type as reference. To pass reference types we will use the prefix of 'ref' and 'out' keyword.

 

For Example:

 
        public static void PassValueByReferenceByRef(ref int val)
        {
            val = val + 55;
            Console.WriteLine("Output : PassValueByReference : {0}", val);
        }

In above the code we have created a static method "PassValueByReferenceByRef" with an input reference type using 'ref' keyword. This method adds the input parameter by 55 and displays the output.

To test we have created a main method which has value type "testval" and initialized to 5 and pass same input parameter as reference to a method "PassValueByReferenceByRef"  as shown below code.

 
static void Main(string[] args)
 {
  int testval = 5;
  Console.WriteLine("Main method value : {0} \n", testval);
  PassValueByReferenceByRef(ref testval);
  Console.WriteLine("Main method value After PassValueByReference : {0} \n", testval);
} 

Display output for above result as follows.

 
Output // 5 ;
        PassValueByReferenceByRef // 60;
        After the PassValueByReference // 60;

So when we pass a value as reference type parameter “testval” to a method "PassValueByReferenceByRef". Parameter "testval" changes. The effect of passing parameter by reference is that any change to the parameter inside the method is also reflected outside in the calling method or main method.

Same way we repeat same procedure by using 'out' keyword. So this is all about Pass by Value Type.

Understanding Pass by Reference Type

We can pass the reference type in two ways

  • Pass reference types by value
  • Pass reference type by reference

Pass reference types by value

As we all know that reference type's means dynamic data types for dynamic allocation of data like class objects, arrays, and interfaces and so on this can hold dynamic values as reference.

For this example let's create a simple class "Employee" with Employee Name and Employee Code as shown in below snippet of code.

 
public class Employee{

   public string EmployeeName{ set; get; }
   public int  EmployeeCode { set; get; }
   public Employee(int emplcode, string emplname)
   {
            EmployeeCode = emplcode;
            EmployeeName = emplname;
   }

}

Now let's create an object in Main method of a program and pass some input values as shown below.

 
static void Main(string[] args)
{
Employee objEmp = new Employee(009, "Questpond");
Console.WriteLine("Main Method Employee Code & Name : {0} , {1} \n", objEmp.EmployeeCode, objEmp.EmployeeName);
}

To a method or a function we need to pass reference type as value

For Example:

 
public static void PassReferenceByValue(Employee emp)
{
    emp.EmployeeName = "Questpond Added Value";
    emp.EmployeeCode = 8;
    Console.WriteLine("PassReferenceByValue Employee Code & Name : {0} , {1} \n", emp.EmployeeCode, emp.EmployeeName);
}   

In above the code we have created a static method "PassReferenceByValue" with a input parameter as class object "Employee emp". This method assigns the new values to object and displays the output.

To test Pass reference types by value we have created a main method in which we have already created the "Employee" object and assign values to both "EmployeeName" and "EmployeeCode" via constructor and passes the same object reference as input value to a method "PassReferenceByValue" as shown in below code.

 
static void Main(string[] args)
{
Employee objEmp = new Employee(009, "Questpond");
Console.WriteLine("Main Method Employee Code & Name : {0} , {1} \n", objEmp.EmployeeCode, objEmp.EmployeeName);
PassReferenceByValue(objEmp);
Console.WriteLine("Main Method Employee Code & Name After PassReferenceByValue : {0} , {1} \n", objEmp.EmployeeCode, objEmp.EmployeeName);
}

Display output for above result as follows.

 
        Main Method Output Before PassReferenceByValue  // 9 , Questpond ;
        PassReferenceByValue  Output // 8 , Questpond Added Value;
        After the PassReferenceByValue  // 8 , Questpond Added Value;

So when we pass a reference type as value "Employee emp" to a method "PassReferenceByValue" object changes. The effect of passing reference type as value is that any change to the object inside the method is also reflected outside in the calling method or main method.

Pass reference type by reference

To a method or a function we need to pass reference types as reference. To pass reference types we will use the prefix of 'ref' and 'out' keyword.

For this we will use same example as used in Pass reference type as Value (Employee Class).

Now let’s create an object in Main method of a program and pass some input values as shown below.

 
static void Main(string[] args)
{
Employee objEmp = new Employee(009, "Questpond");
Console.WriteLine("Main Method Employee Code & Name : {0} , {1} \n", objEmp.EmployeeCode, objEmp.EmployeeName);
}

To a method or a function we need to pass reference type as reference. To pass reference types we will use the prefix of ‘ref’ keyword.

For Example:

 
public static void PassReferenceByRefernce(ref Employee emp)
{
    emp.EmployeeName = "Questpond Added RefernceByRef";
    emp.EmployeeCode = 7;
    Console.WriteLine("PassReferenceByRefernce Employee Code & Name : {0} , {1} \n", emp.EmployeeCode, emp.EmployeeName);
}

In above the code we have created a static method "PassReferenceByRefernce" with an input parameter as class object "Employee emp". This method assigns the new values to object and displays the output.

To test Pass reference types by reference we have used ‘ref’ keyword and we have created a main method in which we have already created the "Employee" object and assign values to both "EmployeeName" and "EmployeeCode" via constructor and passes the same object reference as input value to a method "PassReferenceByRefernce" as shown in below code.

 
static void Main(string[] args)
{
Employee objEmp = new Employee(009, "Questpond");
Console.WriteLine("Main Method Employee Code & Name : {0} , {1} \n", objEmp.EmployeeCode, objEmp.EmployeeName);
PassReferenceByRefernce(ref objEmp);
Console.WriteLine("Main Method Employee Code & Name After PassReferenceByRefernce : {0} , {1} \n", objEmp.EmployeeCode, objEmp.EmployeeName); 
}

Display output for above result as follows.

 
Main Method Output Before PassReferenceByRefernce // 9 , Questpond ;
 PassReferenceByRefernce Output // 7 , Questpond Added RefernceByRef;
 After the PassReferenceByRefernce // 7 , Questpond Added RefernceByRef;

So when we pass a reference type as reference "Employee emp" using 'ref' keyword to a method "PassReferenceByRefernce" object changes. The effect of passing reference type as reference is that any change to the object inside the method is also reflected outside in the calling method or main method.

Repeat the same process using 'out' keyword.

So this is all about passing parameters in c-sharp. So if you have any doubts regarding passing parameters kindly let me know through your comments. If you like this article kindly share this with your friends.

 

 

:: SHARE THIS POST ::

        
 

More C# Articles To Read Next:

 
Jun
25
2013

Sealed Classes in C# with an example and explanation

CLICK TO READ FULL ARTICLE

Views - 32110 |Category - C#

Jun
22
2013

Understanding the Relationships - Inheritance, Association, Aggregation and Composition in C#

CLICK TO READ FULL ARTICLE

Views - 33575 |Category - C#

Jun
09
2013

What is a constructor in c# and list types of constructors in C#?

CLICK TO READ FULL ARTICLE

Views - 31144 |Category - C#

May
27
2013

Implementing Interface in C# with an example

CLICK TO READ FULL ARTICLE

Views - 65378 |Category - C#

May
21
2013

OOPS Principle - Polymorphism in C# with an example

CLICK TO READ FULL ARTICLE

Views - 100451 |Category - C#

 
Author: Gurunatha Dogi
is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server, Cell Phones and lots more. Follow me @ and twitter.
Leave a Comment......

All fields marked with * are mandatory

8n7gr