0

What is the difference between instantiating a variable inside constructor vs. outside in the class declaration, for example:

public class Test
{
    private decimal a = new decimal(1.0);
    private decimal b;
    public Test() { b = new decimal (1.0); }
}

I'm using 'decimal', but the question is a general one, is there a difference, or a preference as to which method should be used?

Alex
  • 1,192
  • 14
  • 30
  • 4
    possible duplicate of [Best Practice: Initialize class fields in constructor or at declaration?](http://stackoverflow.com/questions/24551/best-practice-initialize-class-fields-in-constructor-or-at-declaration) – Fiddles Feb 12 '15 at 04:47
  • Yes it doesn't matter provided your fields are independent of the parameters passed in the constructor. – Mahesh Malpani Feb 12 '15 at 05:01

1 Answers1

1

It doesn't matter for C#, just be consistent and use the same practice everywhere in your code.

If your are working with a team and your team is already using a standard practice follow it, otherwise decide what's best for yourself and go with it.

Just keep in mind that if you decide use the declaration, your variables will be initialized before the constructor.

M. Mennan Kara
  • 10,072
  • 2
  • 35
  • 39