0 Comments

By default C# and JavaScript pass object references by value not by reference, but what does that mean?

Well if you assign an object to a variable, this variable is just a pointer to that object in memory.

(Examples in C#)

var person = new Person
            {
                Id = 2,
                Name = "John"
            };

The variable person is just a pointer to the object in memory, the memory contains the object { Id = 2, Name = “John”}

When passed to a function, a copy of this pointer is supplied to the function, not the object itself.

So when you update properties of the object in the function, the variable outside the function will get updated.

 

But when you set the object to NULL in the function, the variable outside the function will NOT be set to NULL.

 

In C# you can override this by adding the “ref” keyword before the parameter, in that case the pointer of the variable will be passed and thus setting the object to null in the function will set the variable outside the function to NULL.

 

Some unit test to explain this:

namespace Test
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;      

[TestClass]
public class Research
{

[TestMethod]
public void Update_object_properties_should_update_variable()
{

    var person = new Person
    {
        Id = 2,
        Name = "John"
    };

    UpdateObjectProperties(person);

    Assert.IsTrue(person.Name == "Mike");
}

public void UpdateObjectProperties(Person person)
{
    person.Name = "Mike";
}

[TestMethod]
public void Update_object_pointer_should_not_update_variable()
{

    var person = new Person
    {
        Id = 2,
        Name = "John"
    };

    UpdateObjectPointer(person);

    Assert.IsTrue(person.Name == "John");
}

public void UpdateObjectPointer(Person person)
{
    person = null;
}
}

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

 

image

 

More info can be found at:

http://stackoverflow.com/questions/9717057/c-sharp-passing-arguments-by-default-is-byref-instead-of-byval

http://jonskeet.uk/csharp/parameters.html

http://jonskeet.uk/csharp/references.html

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts