Hi All, I was working on a demo method and found something strange(at least to me :-))
enter code here class Program
{
public void AnotherSwap<T>(T a, T b)
{
T temp;
temp = a;
a = b;
b = temp;
Console.WriteLine(a);
Console.WriteLine(b);
}
public void swap<T>(T a, T b) where T : MyInt // Passing without ref
{
object temp;
temp = a.MyProperty;
a.MyProperty = b.MyProperty;
b.MyProperty = (int)temp;
Console.WriteLine(a.MyProperty);
Console.WriteLine(b.MyProperty);
}
static void Main(string[] args)
{
Program p = new Program();
MyInt a = new MyInt() { MyProperty = 10 };
MyInt b = new MyInt() { MyProperty = 20 };
p.swap<MyInt>(a, b);
Console.WriteLine(a.MyProperty); // changed values get reflected
Console.WriteLine(b.MyProperty); // changed values get reflected
Console.WriteLine("Another Swap");
object x = 10;
object y = 20;
p.AnotherSwap(x, y);
Console.WriteLine(x); // changed values are not getting reflected
Console.WriteLine(y); // changed values are not getting reflected
Console.ReadKey();
}
public class MyInt
{
public int MyProperty { get; set; }
}
}
Here when I am calling the swap() , though I haven't mentioned ref , the changed values are automatically getting reflected (as in p.swap(a, b); a and b are instance of Myint and thus will by default work as ref..as per my understanding.) But same should happen with Anotherswap() here also I am passing object x,y but now the values are not getting reflected in Main() .i.e. now its working as a value type. Can somebody explain where my understanding is going wrong. Let me know if u guys want more info.