Are there methods that return reference types, return links, or a cloned copy?

I am learning Java these days, and what I read is "Be careful not to write accessor methods that return references to mutable objects" , which is really interesting. And now I'm wondering if this is the same for Accessor properties and methods in C #? Or is C # already automatically returning cloned copies?

Thanks.

+1
source share
1 answer

A link is just ... a reference to some object that is stored in memory. Unless you explicitly write code to create a clone and return a link to this object, you will always pass a link to the same instance.

The situation you are trying to avoid is to pass the object reference to the caller in which you are dependent. You have no control over who or what can change the state of this object, and therefore your class may end up with unpredictable results.

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 let's say this guy had a salary of $ 50,000 and just got a raise. Now his salary is $ 62,500, and he should get a good new watch. However, it is very possible that another thread has a reference to this Employee object. This means that they also have access to the Salary property and can change the total salary above $ 100,000 before the if block is executed.

In this awkward scenario, the worker will get promoted and have a new office, although the Raise() method was called only once.

Stupidly I know, but demonstrates the essence.

+8
source

Source: https://habr.com/ru/post/894941/


All Articles