Alex Rivera | Logout

Field initialization

Asked 2009-12-17T09:53:55.933
32

Are there any differences between the following two ways of field initialization? When to use which one?

First way

public class Class1
{
   private SomeClass someclass;

   public Class1()
   {
       someclass = new SomeClass(some arg);
   }
}

Second way

public class Class1
{
   private SomeClass someclass = new SomeClass(some arg);
}

The field in the second example could be readonly.

Edit
Report

2 Answers

44

There is a subtle difference, in that the field in the second example will be initialised before fields in the base class are initialised, and the field in the first example will be initialised after. This very rarely has any impact, however.

Largely it's a matter of style and preference. Personally I prefer the second, as it leaves the constructor clear for more logic based initialisation, but there is a strong case to make for having all initialisation done in the constructor.

Just for completeness, the order of initialisation goes:

  1. Static fields
  2. Static constructor
  3. Instance fields
  4. Base static fields
  5. Base static constructor
  6. Base instance fields
  7. Base constructor
  8. Constructor
answered 2009-12-17T10:00:44.380
6

Apart from the number of lines of code, there are subtle differences.

Field initializations happen before constructors are run, for example. Doesn't make much of a difference in your example, but is something to keep in mind.

I would keep field initialsizations as in your second example to simple ones (strings or integers), to avoid possible exceptions occuring during initialization.

And as mentioned, in both ways the field can be readonly, as readonly fields can only be written to during construction.

answered 2009-12-17T09:59:09.123

Your Answer