Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lPass by value & Pass by Reference

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 : Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        String nameString = "string Lijo";

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

        Utilityclass.TestMethod(nameString, p);
        string classResult = p.Name;
        Response.Write(nameString + "....." + classResult);
    }
}

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

public class Person
{
    public string Name
    {
        get; set;
    }
}

Update: When I pass a String, it does not get actually changed.

like image 986
Lijo Avatar asked May 26 '10 06:05

Lijo


People also ask

What is pass by value with example?

"Passing by value" means that you pass the actual value of the variable into the function. So, in your example, it would pass the value 9. "Passing by reference" means that you pass the variable itself into the function (not just the value). So, in your example, it would pass an integer object with the value of 9.

What is pass by value and reference?

Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that's why it's called pass by value. Pass by Reference: An alias or reference to the actual parameter is passed to the method, that's why it's called pass by reference.

What does passed by value mean in C?

Pass by Value, means that a copy of the data is made and stored by way of the name of the parameter. Any changes to the parameter have NO affect on data in the calling function.

Should I pass by reference or value?

To make a decision whether to use pass by reference or pass by value, there are two simple general rules: If a function should return a single value: use pass by value. If a function should return two or more distinct values: use pass by reference.


2 Answers

The briefest answer is: read my article on parameter passing which goes into this in a fair amount of detail.

The slightly longer answer is to compare these two methods, both of which use value parameters:

public void ChangeMe(string x)
{
    x = "changed";
}

public void ChangeMe(Person x)
{
    x.Name = "changed";
}

In the first case, you are changing the value of the parameter. That is completely isolated from the original argument. You can't change the content of the string itself, because strings are immutable.

In the second case, you are changing the contents of the object which the parameter's value refers to. That's not changing the value of the parameter itself - it will be the same reference. To give a real world example, if someone delivers something to your house that changes the contents of your house, but it doesn't change your house's address.

If you changed the second method to this:

public void ChangeMe(Person x)
{
    x = new Person("Fred");
}

then the caller wouldn't see any change. This is closer to what you're doing with a string - you're making the parameter refer to a different object, rather than changing the contents of the existing object.

Now, when you use a ref parameter, the variable used by the caller as the argument is "aliased" with the parameter - so if you change the value of the parameter, that changes the value of the argument as well. So if we change the last method like this:

public void ChangeMe(ref Person x)
{
    x = new Person("Fred");
}

then:

Person y = new Person("Eric");
ChangeMe(ref y);
Console.WriteLine(y.Name);

this will print out "Fred".

The key concept to understand is that the value of a variable is never an object - it's either a value type value or a reference. If an object's data is changed, that change will be visible through other references. Once you understand that copying a reference isn't the same as copying an object, the rest falls into place reasonably easily.

like image 61
Jon Skeet Avatar answered Oct 06 '22 18:10

Jon Skeet


Person is a reference type, so no matter whether you use ref, out or nothing, you will always be able to modify it inside the method. You never pass the real person object to the method, you are passing the pointer as reference but not the actual Person. The ref keyword is useful with value types (such as structs, int, float, DateTime, ...). It could also be used with reference types but only to indicate behavior but cannot enforce it. If you use it with reference types it allows you to change the object this reference is pointing to.

like image 22
Darin Dimitrov Avatar answered Oct 06 '22 19:10

Darin Dimitrov