Prizes & Awards
My Profile
Active Members
TodayLast 7 Days
more...
|
New Feature: Community Sites:
Create your own .NET community website and start earning from Google AdSense !
It's Free !
|
Passing Reference types by value!
Posted Date: 16 Nov 2007 Resource Type: Articles Category: .NET Framework
|
Posted By: madhu panisetty Member Level: Bronze Rating: Points: 20
|
<H2><B>Passing Reference types by value!</B></H2> I asked this question “Can I pass reference type to a parameter with pass by value in C#.NET 2005?” to many of my friends and almost all answered NO. When I personally researched and studied in various books, I found answer as YES. Before going to discuss the actual topic you need some introduction.
<H2><B>Parameter Modifiers</B></H2> <H2>Pass by Value</H2> None – indicates pass by value, i.e. you are passing only the value but you are not informing where it is actually stored. So the called method can use the value sent, but cannot change the value sent by caller method. To understand this more, I will give a file example, let’s consider I wrote “1” in a text file and saved in my computer. I will tell my friend that I have “1” in my text file, so now can he change the value I have written. No, he cannot, because he doesn’t know the name of the file I saved.
Let’s check real example
<font color="blue"> public class PassByValue { public static void Main() { int i=1; System.Console.WriteLine("Before changing::{0}",i); ChangeTo100(i); System.Console.WriteLine("After changing::{0}",i); } private static void ChangeTo100(int j) //pass by value { j=100; } }</font>
Output: Before changing::1 After changing::1
<H2>Pass by reference</H2> ref – indicates pass by reference or address, i.e. you are passing address not the value. So the called method can read and change the value in address. To understand this more, my file example continues, let’s consider I wrote “1” in a text file and save as “i.txt” in “c:\” drive. I will tell my friend that I have written value in “c:\i.txt”, so now my friend can read the value “1” from “c:\i.txt” and can even change that value to a new value.
Let’s check real example
<font color="blue"> public class PassByReference { public static void Main() { int i=1; System.Console.WriteLine("Before changing::{0}",i); ChangeTo100(ref i); //note that ref should be added here also – indicates passing address of i System.Console.WriteLine("After changing::{0}",i); } private static void ChangeTo100(ref int j) //note the ref keyword { j=100; } }</font>
Output: Before changing::1 After changing::100
There are two other modifiers out and params which are not considered for this topic but I will give few details on them to complete parameter modifiers.
out – indicates pass by reference, where return value is guaranteed. This is similar to pass by reference but only difference is that return value is always guaranteed so no need to initialize the value before passing to method.
Let’s check real example
<font color="blue"> public class PassByOut { public static void Main() { int i; ChangeTo100(ref i); //this will raise an error as i is not initialized – comment this to work ChangeTo1000(out i); //this works fine even without initialization System.Console.WriteLine("After changing::{0}",i); } private static void ChangeTo100(ref int j) //note the ref keyword { j=100; } private static void ChangeTo1000(out int j) //note the out keyword { j=1000; } }</font>
Output: (Above code wont compile, you have to comment ChangeTo100(ref i); to compile) After changing::1000
params – indicates the caller can send any number of parameters. Let’s consider that I want to write a method which adds numbers given.
<font color="blue"> public int AddNumbers(int a,int b) { Return a+b; }</font>
Above method works fine as long I use only 2 inputs, now how can I add 3 numbers and more, I have to rewrite the add method, so lets change as
<font color="blue"> public int AddNumbers(params int[] values) { int sum=0; for(int i=0; i>values.Length; i++) sum=sum + values[i]; Return sum; }</font>
So, I hope now you have a strong understanding on pass by value and pass by reference.
If you closely observe my examples in above you see that all my examples are based on value types only. So you actually understood only half part, still there is other half; you have to understand behavior of reference types in pass by value and pass by reference. Before going to other half you need to know difference between value types and reference types. Understanding complete details on value types and reference types is really a big topic but I give you some basic details which are must for any dot net developer. Value and Reference data types Integer, double, char… all comes under value types and string, classes, arrays… comes under reference types. Basic difference between value types and reference types is that value types are stored on stack and reference types are stored on heap.
Let’s consider an example of two variables int age=23; Employee emp1=new Employee(”madhu”); //code for this class can be seen in example below
Now “23” is stored in stack and “madhu” is stored in heap and its address is stored on stack. To clearly understand this, my file example continues, there are two folders in my c: drive “stack” and “heap”, now I write “23” in “age.txt” and save the file in “c:\stack” folder and I write “madhu” in “temp1.txt” and save it in “c:\heap” folder and I write “c:\heap\temp1.txt” in “emp1.txt” and save it in “c:\stack” folder. Now my folders are like this Stack - age.txt - “23” emp1.txt - “c:\heap\temp1.txt” Heap - temp1.txt - “madhu” So from where this “temp1.txt” comes from? When you use new keyword, actually it creates a space in heap and returns its memory reference, in our assumption it is “temp1.txt”.
What is the advantage of storing reference types on heap is left as a research for the readers; I will also try to give another article on that.
<H2>Actual story begins</H2> Now I hope you understand how value types and reference types are stored logically. Now our actual question begins “can we send reference type as pass by value?” after understanding concepts given in part1 and difference of value type and reference type, it is very easy to answer this.
<H2><B>Reference type Pass by value</B></H2> Let’s consider an example
<font color="blue"> public class RefPassByValue { public static void Main() { Employee emp1=new Employee("madhu"); System.Console.WriteLine("Before changing::{0}",emp1.name); ChangeName(emp1); System.Console.WriteLine("After changing::{0}",emp1.name);
} private static void ChangeName(Employee emp) //pass by value { emp.name="kishore"; //this has effect emp=new Employee("jana"); //this has no effect } } public class Employee { public string name; public Employee(string n) { name=n; } }</font>
Output: Before changing:: madhu After changing:: kishore
Let’s trace above example with our file example
Employee emp1=new Employee("madhu"); After this line our file contains as below Stack - emp1.txt - “c:\heap\temp1.txt” Heap - Temp1.txt - “madhu”
ChangeName(Employee emp) After entering the method our files contains as below Stack - emp1.txt - “c:\heap\temp1.txt” emp.txt - “c:\heap\temp1.txt” // only value is passed in pass by value Heap - Temp1.txt - “madhu”
emp.name="kishore"; After this line our files contains as below Stack - emp1.txt - “c:\heap\temp1.txt” emp.txt - “c:\heap\temp1.txt” Heap - Temp1.txt - “kishore” // changed as we emp.txt is referencing temp1.txt – we can write any thing into this
emp=new Employee("jana"); After this line our files contains as below Stack - emp1.txt - “c:\heap\temp1.txt” // note that we cannot change this value in value type – so still pointing to “kishore” emp.txt - “c:\heap\temp2.txt” //this is changed to new reference Heap - Temp1.txt - “kishore” Temp2.txt - “jana”
If you don’t understand why we cannot change “emp1.txt” in step 4 just read again <B>Parameter modifiers – Pass by value</B> So now you agree that reference types can also be passed by value, but what about pass by reference, let’s look at it.
<H2><B>Reference type Pass by reference</B></H2> Now use sample example with reference
<font color="blue"> public class RefPassByReference { public static void Main() { Employee emp1=new Employee("madhu"); System.Console.WriteLine("Before changing::{0}",emp1.name); ChangeName(ref emp1); System.Console.WriteLine("After changing::{0}",emp1.name);
} private static void ChangeName(ref Employee emp) //pass by reference { emp.name="kishore"; //this will have effect emp=new Employee("jana"); //this will have effect } } public class Employee { public string name; public Employee(string n) { name=n; } }</font>
Output: Before changing:: madhu After changing:: jana
Let’s trace above example with our file example
Employee emp1=new Employee("madhu"); After this line our file contains as below Stack - emp1.txt - “c:\heap\temp1.txt” Heap - Temp1.txt - “madhu”
ChangeName(Employee emp) After entering the method our files contains as below Stack - emp1.txt - “c:\heap\temp1.txt” emp.txt - “emp1.txt” // we are passing the reference/address not the value Heap - Temp1.txt - “madhu”
emp.name="kishore"; After this line our files contains as below Stack - emp1.txt - “c:\heap\temp1.txt” emp.txt - “emp1.txt” Heap - Temp1.txt - “kishore” // changed as we are referencing emp1.txt - we can read and write to temp1.txt also
emp=new Employee("jana"); Stack - emp1.txt - “c:\heap\temp2.txt” // note that we can change this value in reference type – now pointing to “jana” emp.txt - “emp1.txt” // we are referencing to emp1.txt – so we can read and write to emp1.txt Heap - Temp1.txt - “kishore” Temp2.txt - “jana”
If you don’t understand why we can change “emp1.txt” in step 4 just read again the <B>Parameter modifiers – Pass by Reference</B>
So I hope now you understood that even reference types can also be passed by value. Now, before passing any parameter to methods feel proud you know what you are doing.
Conclusion
<Table border="1"> <TR><TD></TD><TD>Value Type</TD><TD>Reference Type</TD></TR> <TR><TD>Pass By Value</TD><TD>Can only read the data in variable</TD><TD>Can read and write the data in the object</TD></TR> <TR><TD>Pass By Reference</TD><TD>Can read and write the data in variable</TD><TD>Can read and write the data in the object, Can change the address pointed by the object</TD></TR> </Table>
Hi, this is my first article; please correct me if my article editing is not proper. I hope my article can be understood even by beginners, if you find anything difficult, please give your comments, I will clarify as early as possible, if I don’t respond to you quickly, please forgive me, I may be busy with my work. HaPpY CodinG.
Madhu madhupanisetty@yahoo.co.in QSI
|
Responses
|
| Author: rahul 19 Nov 2007 | Member Level: Gold Points : 0 | Very Very Good Article... Thanks for this article. It cleared all my doubt about pass by value and pass by reference.... Keep It Up.......
|
|