For most cases, either initialize in the declaration or constructor, if you want to give a default value. The object only exists in memory even at the time it is built.
If you want to be very pedantic, you can debug the construction of the object and you will notice that the properties initialized in the declaration receive values before the start of the constructor method you declared. But that doesn’t have much practical effect.
Regarding good practices: each case is a case, so instead of discussing which form is most recommended, it is more useful to know the advantages and disadvantages of each form.
Declaring values in the constructor has the advantage that things tend to be concentrated at a single point, or at least at a few points in the case of multiple constructors. Compare:
public class Foo
{
public Foo()
{
this.A = new {};
this.B = new {};
this.C = new {};
this.D = new {};
// etc., etc.
this.Z = new {};
}
}
With:
public partial class Foo // Atenção especial para o partial
{
// 26 propriedades
public Foo()
{
/* Seus colegas perguntaram qual era o valor padrão da propriedade Y
* e você veio procurar aqui. E você provavelmente abriu este código
* no github e não em uma IDE. Vou dar uma dica, a declaração está
* em outro arquivo. Descobrir qual será o seu desafio. Compartilhe
* se você encontrar em até 60 segundos.
*/
// Sério, não tem código aqui. Este é um construtor vazio.
}
}
Already initializing in the statement can have its advantages there if you are working with properties. You can do Lazy Loading ("lazy load"), as follows:
private List<string> _afazeres;
public List<string> Afazeres
{
get
{
if (this._afazeres == null)
{
this._afazeres = new List<string>()
{
"Programar",
"Postar no Stack Overflow",
"Estudar",
"Beber café até morrer",
"Fazer tudo de novo"
}
}
return this._afazeres;
}
set { this._afazeres = value; }
}
This ensures that your class can be instantiated without allocating memory to any field - that field will only take up space from the first time it is accessed. Here we have a short list of strings, but this could be some really heavy object.
I don’t know if in c# it makes a difference, but in java it’s the same thing. If I’m not mistaken, even starting in the declaration, the compiler starts inside the default constructor. Referent: http://stackoverflow.com/a/1994232/5524514
– user28595