C# - Pass by value & Pass by Reference

Posted by Lijo on Stack Overflow See other posts from Stack Overflow or by Lijo
Published on 2010-05-26T06:34:12Z Indexed on 2010/05/26 6:41 UTC
Read the original article Hit count: 755

Filed under:

Hi Team,

Could you please explain the following behavior of C# Class. I expect the classResult as "Class Lijo"; but actual value is “Changed”.

We’re making a copy of the reference. Though the copy is pointing to the same address, the method receiving the argument cannot change original.

Still why the value gets changed ?

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

        Person p = new Person();
        p.Name = "Class Lijo";

        Utilityclass.TestMethod(p);
        string classResult = p.Name;
        Response.Write(classResult);

    }

}

public class Utilityclass
{
    public static void TestMethod(Person k)
    {
        k.Name = "Changed";

    }
}

public class Person
{
    private string name;
    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }

}

Thanks

Lijo

© Stack Overflow or respective owner

Related posts about c#