Tuesday, October 14, 2008

Call By Value and Call By Reference

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;

}
}

Monday, October 13, 2008

About View State

Most of the DotNet developers thinking that View State is responsable for maintaining the control values at page post back,it is not true for all controls if you want check with a simple example Example:Create a new ASP.Net web application take a textbox web server control on default.aspx and set view state property for that textbox control to False and place a button control on the page now run this application,then place some text on the textbox control and click on button to post back the page,though page is post back and txtbox view state property is Flase,textbox is maintaing the value!
The reason for this behavior is that ViewState is not responsible for maintaing the values for controls which inherit from the IPostBackDataHandler interface these controls are maintaing their values at HTTPPOST header at post backs instead of using view state,the controls which inherit IPostBackDataHandler interface are TextBox,CheckBox etc..