As a developer initially having a bit confussion on this topic,to day i want to dicuss about this not in detail but with a simple example,The arguments passed to function can be of two types namely
1.passing value of variables
2.passing address of the varialbes
The first type refer to the call by value and second type refer to the call by reference
CallBy Value Program:
class Callbyvalue
{
static void Main(string[] args)
{
int a = 10;
int b = 20;
Console.WriteLine("initial a value is "+a);
Console.WriteLine("initial b value is " + b);
interchangevalues(a, b);
Console.WriteLine("After Calling Interchangevalues methos a value is "+a);
Console.WriteLine("After Calling Interchangevalues methos b value is "+b);
Console.Read();
}
public static void interchangevalues(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
}
Explanation of Callbyvalue program:
The OutPut of the program is
initial "a" value is 10;
initial "b" value is 20;
After Calling Interchangevalues methos "a" value is 10
After Calling Interchangevalues methos "b" value is 20;
This is because in case of call by value the copy of orginal varable value is passed to function Interchangevalues this function does interchanging the values from ato band "b" to "a" using temp variable but it wont effect the orginal variable values here we are interchaning the copy of orginal variable.Therefore original values of "a" and "b" as remain same.
CallBY Reference Program:
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 20;
Console.WriteLine("initial a value is "+a);
Console.WriteLine("initial b value is " + b);
interchangevalues( ref a, ref b);
Console.WriteLine("After Calling Interchangevalues methos a value is "+a);
Console.WriteLine("After Calling Interchangevalues methos b value is "+b);
Console.Read();
}
public static void interchangevalues( ref int x, ref int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
}
1 comment:
The blog is helpfull...
visit also asp.net [c#]
Post a Comment