tags:

views:

74

answers:

1

I've been learning Java these days and what I've read just is "Be careful not to write accessor methods that return references to mutable objects" which is really interesting. And now I am wondering whether it is same for Properties and Accessor methods in C#? Or C# already returns cloned copies automatically?

Thanks.

+8  A: 

A reference is just that... a reference to some object that is stored in memory. Unless you explictly write code to create a clone and return a reference to that object, then you will always be passing around a reference to the same instance.

The situation it is trying to get you to avoid is handing over an object reference to the caller in which you are dependent on. You have no control over who or what might be changing the state of that object and therefore your class might end up with unpredictable results.

A silly example:

public class Employee
{
    public Salary Salary {get; set;}

    public void GiveRaise()
    {
        Salary.Total *= .25;

        if(Salary.Total > 100000)
        {
            Promote();
            GiveBiggerOffice();
        }
        else
        {
            GiveWatch();
        }
    }
}

So lets say this guy had a salary of $50,000 and just got a raise. Now his salary is at $62,500 and he should be getting a nice new watch. However, it is very possible that another Thread has a reference to this Employee object. That means they also have access to the Salary property, and could change the salary total above $100,000 before the if block runs.

In this awkward scenario, the employee would be getting a promotion and a new office even though the Raise() method was only called once.

Silly I know, but demonstrates the point.

Josh
Correction (since I need 2 more rep before I can edit your post!): "...you will always be passing around a reference to the same instance".
dty
What you are saying is C# doesn't create cloned copies automatically when you return a for example a 'Date' type.
Braveyard
@Braveyard: `DateTime` (that I assume that you are referring to) is a value type, not a reference type.
Fredrik Mörk
@dty - some rep for you and the wording has been changed :)
Josh
@Josh : Yeah, I mean something which is reference type like 'Stream'
Braveyard