Why do I still have access to the current state of the object in this case? [EXAMPLE C#]

Asked

Viewed 28 times

1

A very basic doubt, but it’s bugging my head.

I have the following code snippet:

A class that receives a list as a parameter in the constructor:

public class MinhaClasse
{
   IList<int> Items;

   public MinhaClasse(IList<int> Items)
   {
      this.Items = Items;
   }

   // Aqui eu tenho um método que manipula a propriedade Items
   public void MeuMetodo()
   {
       Items[0] = 1+1;
   }

}

When I’m going to instantiate the class, I create the list, pass it as parameter and call the "MeuMetodo()" which changes the value of the first Item in my list from '0' to '2':

IList<int> items = new List<int>(){ 0 };

GildedRose app = new GildedRose(items);
app.MeuMetodo();

// A minha dúvida acontece aqui, pois continuo tendo acesso a lista de items, mas no novo estado, após a alteração pelo método da minha classe
Console.WriteLine(items[0]); // Essa linha imprime o valor '2' e não o valor '0' que é o valor atual da minha lista criada aqui

To have access to the value '2' I would not have to create a "Get" within the "MinhaClasse" to return the "Items" property? Why did you continue to have access to the same value as my class property after calling the "MeuMetodo()"?

1 answer

1


Think about it this way: when you create an object, like this list, you get back a reference to it, which allows you to access and manipulate it. In your example, the variable itens is who keeps reference to the newly created list. This variable was created in a certain scope, and will always be accessible from that scope - as your example shows.

When creating your class instance, what you pass to the constructor is this reference. The manufacturer receives the reference and keeps a copy of it in a private member of his class. And it is this private copy of the reference that cannot be accessed from outside the class (precisely because it is private; if it were not, it could be accessed via app.Items).

It seems you are confused because you think your code directly manipulates "the list". But no. " The list" (or "the object", "the instance" of the type List) is something that exists in memory and, in C#, is not accessed directly, only by means of references. The references are that they are subject to the rules of the language, as the access modifiers of the classes (private, public etc.). And what you have in your code are two references - one outside the class, one inside the class. The class can only be accessed from within objects of that class. The outside has no restrictions, is subject only to the scope visibility rules. Both manipulate the same object, but are different references, with different access rules.

  • Killed! Thank you very much!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.