When to assign types?

So, Ive been studying C # recently, but there is one thing that I cannot find or find the answer to:

Consider this:

class Class1 {
    int myInt = 32;
}

and this:

class Class1 {
    int myInt;

    public Class1(){
        myInt = 32;
    }
}

I just wanted to know when and why I should use one method for another to assign or create values.

+3
source share
3 answers

It is a matter of taste or coding standards for your company.

My rule is that if all my constructors assign the same value to a variable, I use the first form; if the value comes from outside or different constructors assign variables to the variables, I use the second form.

+4
source

ctor, "this", :

class C
{
    int x = MakeX();  
    int MakeX() { whatever } 
}

, this.MakeX() , ctor, , , this. :

class C
{
    int x;
    int MakeX() { whatever }
    public C() { this.x = this.MakeX(); } 
}

, , this ctor.

, . . , .

" ". , - ctor; .

+11

This mainly concerns personal preferences or coding agreements for your project, if you are working in the industry, that is, there is no “right” or “wrong” way to initialize member variables. In the end, the important thing is that you agree on how you do it.

+2
source

All Articles