Can you explain why
1) method nochange() doesn't change the object argument, although the object is of reference-type passed by value?
2) method change2() can change the field of the object passed without REF?
More comments in the code below.
Thanx. Bye.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ref_obj
{
class clsTest
{
public int a;
public clsTest(int i)
{
a = i;
}
//this will not change the argument
public void noChange(clsTest obj)
{
clsTest newObj = new clsTest(0);
obj = newObj; // this has no effect outside of noChange()
}
//this will change what the argument refers to
public void change1(ref clsTest obj)
{
clsTest newObj = new clsTest(0);
obj = newObj;//this affects the calling argument
}
// changing Object argument field without REF
public void change2(clsTest obj)
{
obj.a = 33;// this changes a field of the called argument
}
}
}
namespace ref_obj
{
class Program
{
static void Main(string[] args)
{
clsTest ob = new clsTest(100);
Console.WriteLine("ob.a before call: " + ob.a);
ob.noChange(ob);
Console.WriteLine("ob.a after nochange call: " + ob.a);
ob.change1(ref ob);
Console.WriteLine("ob.a after change1 call: " + ob.a);
ob.change2(ob);
Console.WriteLine("ob.a after change2 call: " + ob.a);
Console.ReadLine();
}
}
}
OUTPUT:
ob.a before call: 100
ob.a after call to NoChange(): 100
ob.a after call to Change1(): 0
ob.a after call to Change2(): 33