3

Possible Duplicate:
Best Practice: Initialize class fields in constructor or at declaration?

Please do you have any advantage for doing

public class MyClass
{
  List<string> list;
  public MyClass
  {
     list = new List<string>();
  }
}

over doing this

public class MyClass
{
  List<string> list = new List<string>();
  public MyClass
  {

  }
}

I guess its all the same. Thus constructors are more important than these simple cases

Community
  • 1
  • 1
David Blay
  • 527
  • 1
  • 3
  • 14

2 Answers2

0

In the first example you are choosing exactly when the list is initialised. If there is other code in the constructor you are responsible for positioning the initialisation in the right place.

Also if the class has a base class, then the base class constructors will be called before your list is initialised.

Justin Harvey
  • 14,446
  • 2
  • 27
  • 30
0

First all the initializers run in order from derived to base, and then all the constructors run in order from base to derived.

Read this article by Eric Lippert.

horgh
  • 17,918
  • 22
  • 68
  • 123