ProgrammerGuy123
ProgrammerGuy123

Reputation: 357

When to Assign Types?

So, Iv'e been learning C# lately but there is one thing I cant figure out or find an answer to:

Consider this:

class Class1 {
    int myInt = 32;
}

and this:

class Class1 {
    int myInt;

    public Class1(){
        myInt = 32;
    }
}

I would simply like to know when and why I should use one method over the other for assigning or instantiating values.

Upvotes: 3

Views: 201

Answers (3)

Eric Lippert
Eric Lippert

Reputation: 660377

First off, you must initialize in the ctor when the initialization requires a reference to "this", either explicitly or implicitly:

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

That's illegal, because the call is implicitly to this.MakeX() and you haven't even run the ctor yet, so it is probably wrong to use this. This is legal:

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

because obviously we cannot restrict use of this in the ctor body itself.

Also note that the field initializers run in order from most derived to least derived and run first. The base class constructors run in order from least derived to most derived and run second. That rarely matters, but it is helpful to know anyway.

Generally the advice is just "be consistent". Do not initialize some fields with initializers and some with statements in the ctor body; pick one and do it consistently.

Upvotes: 11

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

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

My rule of thumb 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 different values to a variable, I use the second form.

Upvotes: 4

Tyler Treat
Tyler Treat

Reputation: 15008

It's mostly up to personal preference or coding conventions for your project if you're working in industry, i.e. there is no "right" or "wrong" way to initialize member variables. In the end, what matters is that you're consistent in how you do it.

Upvotes: 2

Related Questions