Call by
value is when you create a local copy of the variable. This is usually only a good idea for small
variables that you will not need to change.
Call by
reference occurs when you pass the address of the variable to the function
(receiving a pointer or reference). It
is useful if you need to be able to change the
variable's value in the function, or if the variable is extremely large
and passing it by value would be extremely inefficient (because of the cost of
creating a local copy).
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();
}
}
}
No comments:
Post a Comment