How do properties work in C #?

8

In Java, I usually create private attributes and create getters and setters methods because of encapsulation. I could not understand right how this works in C# .

    
asked by anonymous 05.10.2016 / 14:44

2 answers

8

In C # what you call an attribute is treated as a field, since attribute is something else in the language (something similar to Java annotation ).

Although it can do exactly the same in C #, it is not idiomatic. C # has a syntactic sugar that makes it easy to use. In the background what is being done internally is to create a field and a pair (even can be only one) of methods ( get and set ). What changes is in the call.

Instead of calling a

x + objeto.getValor()
objeto.setValor(10)

use

x + objeto.Valor
objeto.Valor = 10

The declaration of this would be something like this:

public int Valor { get; set; }

What is the same as writing:

private int valor;
public int {
    get { return valor; }
    set { valor = value; }
}

Note that value is a contextual keyword, it is the parameter that receives the value to be setado . This longer syntax is only used when you need to create a specific logic other than the default one.

This code in Java would look something like this:

private int valor;
public int getValor() {
    return valor;
}
public void setValor(int value) {
     valor = value;
}

Obviously, just like Java, you can put any logic in there. If you understand that deep down it is a method it is easy to understand its use.

You can indicate that set is private and can put an initial value (C # 6 up ). This example creates a property that can not be externally changed:

public int Valor { get; private set; } = 10;

Or it may be all immutable :

public int Valor { get; } = 10;

Ideally in this case initialization should be in a constructor. In this way a static and read-only property would be better, since the value is not parametrizable and never changes. But that's a subject for build .

properties can be initialized in construction even where there is no builder . But there may be semantic differences in that.

I have already answered the question in several questions:

05.10.2016 / 14:57
4

C # simplifies some of this for you, though underneath the cloths, is exactly the same thing.

You define an access modifier for the attribute (in C #, we call property) in general

public string Nome { get; set; }

Name will have your getter and public setter .

You can also set it separately

public string Nome { get; private set; }

In this case, Name will have the private setter and public getter     

05.10.2016 / 14:55