Encapsulation confusing in C #

3

I was creating a template that in its construtor I set the Nome attribute. however, this attribute will only have get , as opposed to java oc # has the resource for getters and setters I thought I would simply declare get , since since Nome would be set inside classe I believe that there would be no restriction, but I was surprised when VS accused erro . saying that the Nome attribute is somente leitura . but I'm setting it inside my própria classe , excuse my ignorance but why this restriction? that makes sense ? I believe that if this does not work I will have to work as in java atributto privado and getter public, right?

public class Pessoa
{
      public String Nome { get; }    
      public Pessoa(String nome) {
          Nome = nome;
      }
}
    
asked by anonymous 14.03.2014 / 20:50

2 answers

8

To prevent the set from being public too, you can do this:

public class Pessoa
{
      public String Nome {private set; get; }    
      public Pessoa(String nome) {
          Nome = nome;
      }
}
    
14.03.2014 / 20:53
8

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

There are some ways to work like this, but keep in mind that at some point they should 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 have declared your property without SET or a field, the compiler will acknowledge an error because it will generate the code you entered and you will see that you do not have a SET property, so you can not set the value and generate a exception

    
14.03.2014 / 20:57