Difference between Call by value & Call by reference

Call by value :
using System;


namespace call_by_value
{
class c
{
public int x=100;
public void method(int x)
{
x=x+x;
Console.WriteLine("within the method : "+x.ToString());
}
public static void Main()
{
c obj=new c();
Console.WriteLine(obj.x);
obj.method(obj.x);
Console.WriteLine("after coming out of the method : "+obj.x);
Console.ReadLine();
}
}
}

Call by Reference

using System;
namespace call_by_reference
{
class c
{
public int x=100;
public void method(ref int x)
{
x=x+x;
Console.WriteLine("within the method : "+x.ToString());
}
public static void Main()
{
c obj=new c();
Console.WriteLine(obj.x);
obj.method(ref obj.x);
Console.WriteLine("after coming out of the method : "+obj.x);
Console.ReadLine();
}
}

}

We use 'ref' keyword to pass reference value.


Comments

Author: sridhar thota04 Aug 2015 Member Level: Gold   Points : 4

Difference between call by value and call by
reference is given programmatically. Let me provide theoretical.

Call by Value:
1.When formal arguments are modified and that
modifications are not affected on actual
arguments is called call by value.
2.By default all variables we use are passed by
value.

Call by Reference:
1.When formal arguments are modified and that
reflects actual arguments is called call by
reference.
2.Ref keyword should be used with actual and
formal arguments.

Regards

Thota Sridhar.
If you learn from defeat..
You haven't really lost..

Author: Arun Skaria05 Aug 2015 Member Level: Silver   Points : 4

Both are used when we are passing parameters on method call.
Call by value: we are sending the value, it will be hold by another variable in the method eg: you are throwing a ball to another guy for processing; we need two persons to carry the same ball but both situated in two place


Call by reference: we have passing the address to a method for processing. eg: you are playing in one place then u take the same ball and going some other place for play. here there is only one ball and one person.