Confusing encapsulation in c#

Asked

Viewed 181 times

3

I was creating a model that in his construtor i defined the attribute Nome. however this attribute will only have the get, as different from java c# has the resource for getters and setters I thought I’d just declare the get, since Nome would be set inside the classe I believe there would be no restriction, but I was surprised when the VS accused erro. saying that the attribute Nome is somente leitura. but I’m setting him inside my própria classe, Excuse my ignorance but why this restriction? It makes sense ? I believe that if this does not work I will have to work as in java attribute privado and getter public, right ?

public class Pessoa
{
      public String Nome { get; }    
      public Pessoa(String nome) {
          Nome = nome;
      }
}

2 answers

8


To avoid the set being public too, you can do so:

public class Pessoa
{
      public String Nome {private set; get; }    
      public Pessoa(String nome) {
          Nome = nome;
      }
}

8

Vinicius is something simple what is happening... It’s not all wrong with your logic, but what happens in your case is that you made the property only with the get

There are some ways to work like this, but note that at some point they must allow SET

Example of Rodrigo Santos

    public class Pessoa
    { 
          public String Nome {private set; get; }    
          public Pessoa(String nome) {
               Nome = nome;
          }
    }

Another way:

    public class Pessoa
    {
           private string _nome;
           public String Nome { get { return _nome; } }    
           public Pessoa(String nome) {
                _nome = nome;
           }
    }

As you declared your Property without SET or a Field, the compiler will file an error, as it will generate the code you typed and you will see that you do not have a SET property, then you will not be able to set the value and generate an Exception

Browser other questions tagged

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