Thursday, February 19, 2015

C#.Net 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
1int i = 009;
2Char ch = "w";    

What are Reference Types?


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
1string[] str = new string[2] {"ABC","PQR"};
2class obj = new class();  
Example 2
1class Employee
2    {
3     Private int empCode = 4545;
4    }  
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:
1public static void PassValueByValue(int val)
2{
3    val *= val;
4    Console.WriteLine("Output : PassValueByValue : {0}", val);
5}
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.
1static void Main(string[] args)
2{
3  int testval = 5;
4  Console.WriteLine("Main method value : {0} \n", testval);
5  PassValueByValue(testval);
6  Console.WriteLine("Main method value After PassValueByValue : {0} \n", testval);
7}
Display output for above result as follows.
1Output // 5 ;
2 PassValueByValue // 25;
3 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:
1public static void PassValueByReferenceByRef(ref int val)
2{
3    val = val + 55;
4    Console.WriteLine("Output : PassValueByReference : {0}", val);
5}
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.
1static void Main(string[] args)
2 {
3  int testval = 5;
4  Console.WriteLine("Main method value : {0} \n", testval);
5  PassValueByReferenceByRef(ref testval);
6  Console.WriteLine("Main method value After PassValueByReference : {0} \n", testval);
7}
Display output for above result as follows.
1Output // 5 ;
2        PassValueByReferenceByRef // 60;
3        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.
01public class Employee{
02
03   public string EmployeeName{ set; get; }
04   public int  EmployeeCode { set; get; }
05   public Employee(int emplcode, string emplname)
06   {
07            EmployeeCode = emplcode;
08            EmployeeName = emplname;
09   }
10
11}
Now let's create an object in Main method of a program and pass some input values as shown below.
1static void Main(string[] args)
2{
3Employee objEmp = new Employee(009, "xyzcompany");
4Console.WriteLine("Main Method Employee Code & Name : {0} , {1} \n", objEmp.EmployeeCode, objEmp.EmployeeName);
5}
To a method or a function we need to pass reference type as value
For Example:
1public static void PassReferenceByValue(Employee emp)
2{
3    emp.EmployeeName = "xyzcompany Added Value";
4    emp.EmployeeCode = 8;
5    Console.WriteLine("PassReferenceByValue Employee Code & Name : {0} , {1} \n", emp.EmployeeCode, emp.EmployeeName);
6}  
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.
1static void Main(string[] args)
2{
3Employee objEmp = new Employee(009, "xyzcompany");
4Console.WriteLine("Main Method Employee Code & Name : {0} , {1} \n", objEmp.EmployeeCode, objEmp.EmployeeName);
5PassReferenceByValue(objEmp);
6Console.WriteLine("Main Method Employee Code & Name After PassReferenceByValue : {0} , {1} \n", objEmp.EmployeeCode, objEmp.EmployeeName);
7}
Display output for above result as follows.
1Main Method Output Before PassReferenceByValue  // 9 , xyzcompany;
2PassReferenceByValue  Output // 8 , xyzcompany Added Value;
3After the PassReferenceByValue  // 8 , xyzcompany 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.
1static void Main(string[] args)
2{
3Employee objEmp = new Employee(009, "xyzcompany");
4Console.WriteLine("Main Method Employee Code & Name : {0} , {1} \n", objEmp.EmployeeCode, objEmp.EmployeeName);
5}
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:
1public static void PassReferenceByRefernce(ref Employee emp)
2{
3    emp.EmployeeName = "xyzcompany Added RefernceByRef";
4    emp.EmployeeCode = 7;
5    Console.WriteLine("PassReferenceByRefernce Employee Code & Name : {0} , {1} \n", emp.EmployeeCode, emp.EmployeeName);
6}
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.
1static void Main(string[] args)
2{
3Employee objEmp = new Employee(009, "xyzcompany");
4Console.WriteLine("Main Method Employee Code & Name : {0} , {1} \n", objEmp.EmployeeCode, objEmp.EmployeeName);
5PassReferenceByRefernce(ref objEmp);
6Console.WriteLine("Main Method Employee Code & Name After PassReferenceByRefernce : {0} , {1} \n", objEmp.EmployeeCode, objEmp.EmployeeName);
7}
Display output for above result as follows.
1Main Method Output Before PassReferenceByRefernce // 9 , xyzcompany ;
2 PassReferenceByRefernce Output // 7 , xyzcompany Added RefernceByRef;
3 After the PassReferenceByRefernce // 7 , xyzcompany 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.


 Now over to you:
"A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work, you can appreciate by leaving your comments. Stay tuned and stay connected for more technical updates."

No comments:

Post a Comment