Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When an object is returned from a method, is a new instance or a reference created? [duplicate]

Possible Duplicate:
Do methods which return Reference Types return references or cloned copy?

A co-worker of mine stated that when a method returns an object like the following, a new instance/copy of the object is created as opposed to passing back a reference:

public CustomerEntity Customer { get; set; }

public CustomerEntity GetCustomer() {
    Customer = new CustomerEntity();
    return Customer;    
}

Is that correct? My tests seem to indicate otherwise, but I am not certain how to confirm this. He is concerned about the overhead in copying data to the new object.

For good measure, in which of the following methods/scenarios are new objects created? In which situations does the calling class access a reference to or a copy of the to the original object? Assume the 'CustomerEntity' is a very large object.

public class CustMan {
public CustomerEntity GetCustomer() {
    Customer = new CustomerEntity();
    return Customer
}

public void FillCustomer(CustomerEntity customer)
{
    customer = new CustomerEntity();
    // Calling class: 
    // CustomerEntity ce = new CustomerEntity(); 
    // l_custMan.FillCustomer(ce);  WriteLine(ce.Name);   
}

public void LoadCustomer()
{
    Customer = new CustomerEntity();
    // Calling Class access customerEntity via l_custMan.CustomerEntity
}
}

Clarification: My co-worker believes it would be better to use a 'Load' method than a 'Get' method:

l_custMan.Load();
CustomerEntity = l_custMan.Customer;

vs.

CustomerEntity = l_custMan.GetCustomer();
like image 664
davewilliams459 Avatar asked Aug 12 '11 19:08

davewilliams459


1 Answers

A co-worker of mine stated that when a method returns an object like the following, a new instance/copy of the object is created as opposed to passing back a reference:

Your coworker is incorrect*. For return types that are reference types, a copy is always made, it's just that it is a copy of the reference that is made.

I can be a bit more explicit:

Assuming that ReturnType is a reference type and given

public ReturnType M() {
    // some code
    return E;
}

where E is an expression that evaluates to an instance I of ReturnType, you are asking if a copy C of I is made and a reference to C is returned to the caller, or if a reference to I is returned to the caller. The answer is that a reference to I is returned to the caller.

This is the same for parameters of reference type passed into methods (unless they are marked with ref or out): a copy is always made, it is just a copy of the reference that is passed.

*: In his defense, he's possibly getting confused by some knowledge of C++, where you have to be explicit that you are returning a reference.

like image 71
jason Avatar answered Oct 27 '22 08:10

jason