July 30, 2009

Referenc type are pass by value or reference?

No, you are wrong, Reference types are passed by Value by default, surprised?

Test(object R2)
//you call
object R1 = new object();
WriteLine(R1==null) //result false.

Reference type R1 is created on address y100 and its value is some another address called x100; // as we know refrence type refer to an address
now in method
Reference type R2 is created on a memory address y200,
and it is copied value of R1 ie. x100;
so when you reset R2=null. only value of the r2 set to null. means now its not pointing to address x100. but R1 still pointing to address x100.
NOTE: if value at address x100 is changed, both R2 and R1 will show that, because both pointing to the same address.

Pass-By-Reference ->
Test(ref object R2)
object R1 = new Object();
Test(ref R1);
WriteLine(R1==null) //result true.

now we are passing variable by Reference. now here address of R1 is passed i.e y100. so R1 & R2 both are pointing to y100. so if you change R2's value, R1's will also changed

Any issue please comment.

No comments: