Let's come from the beginning, we know that there are four kinds of formal parameters in a C# method declaration, namely
- Value parameters, which are declared without any modifiers. (default)
- Reference parameters, which are declared with the ref modifier.
- Output parameters, which are declared with the out modifier.
- Parameter arrays, which are declared with the params modifier.
If so, then, if we pass two objects to a regular swap method and come back to the calling procedure to see whether they have got swapped, they would have not! Look down the code below,
public class SwapClass
{
public int x;
public int y;
public SwapClass(int xval, int yval)
{
x = xval;
y = yval;
}
}
public class Swaper
{
public static void SwapWithRef(ref SwapClass param1, ref SwapClass param2)
{
param1.y = 2000;
param1.x = 1000;
SwapClass temp = param1;
param1 = param2;
param2 = temp;
}
public static void SwapWithOutRef(SwapClass param1, SwapClass param2)
{
param1.y = 2000;
param1.x = 1000;
SwapClass temp = param1;
param1 = param2;
param2 = temp;
}
}
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SwapClass obj1 = new SwapClass(0, 0);
SwapClass obj2 = new SwapClass(10, 20);
Response.Write("
");
Response.Write("
X1: " + obj1.x + " Y1: " + obj1.y);
Response.Write("
X2: " + obj2.x + " Y2: " + obj2.y);
Response.Write("
");
Swaper.SwapWithOutRef(obj1, obj2);
Response.Write("
After SwapWithOutRef");
Response.Write("
X1: " + obj1.x + " Y1:" + obj1.y);
Response.Write("
X2: " + obj2.x + " Y2:" + obj2.y);
Response.Write("
");
Response.Write("
After SwapWithRef");
Swaper.SwapWithRef(ref obj1, ref obj2);
Response.Write("
X1: " + obj1.x + " Y1:" + obj1.y);
Response.Write("
X2: " + obj2.x + " Y2:" + obj2.y);
Response.Write("
");
Response.Write("---------------------------------");
SwapClass obj3 = new SwapClass(0, 0);
SwapClass obj4 = new SwapClass(100, 200);
obj3.x = 10;
obj3.y = 20;
SwapClass temp = obj3;
obj3 = obj4;
obj4 = temp;
Response.Write("
After Normal Swap Without passing the parameter towards a method");
Response.Write("
X3: " + obj3.x + " Y3:" + obj3.y);
Response.Write("
X4: " + obj4.x + " Y4:" + obj4.y);
Response.Write("
");
}
}
Enjoy swapping
0 comments:
Post a Comment