EndlessSpace
EndlessSpace

Reputation: 1370

member initialization inside or outside the constructor

Which one of the 2 initializations is better?

public class ServiceClass
{
    private DataManager dataManager = new DataManager();
    private Dictionary<string, string> stringDictionary = new Dictionary<string, string>();
    private Dictionary<string, DateTime> timeDictionary = new Dictionary<string, DateTime>();
    public ServiceClass()
    {
        //other object creation code
    }
}

OR

public class ServiceClass
{
    private DataManager dataManager;
    private Dictionary<string, string> stringDictionary;
    private Dictionary<string, DateTime> timeDictionary;
    public ServiceClass()
    {
       dataManager = new DataManager();
       stringDictionary = new Dictionary<string, string>();
       timeDictionary = new Dictionary<string, DateTime>();
       //other object creation code
    }
}

Upvotes: 5

Views: 1231

Answers (2)

Reddog
Reddog

Reputation: 15579

I would prefer to use the constructor.

This is because one gotcha that we cruelly discovered was that objects rebuilt via the serializer (in this case a data contract serializer) did not have their field initializers called.

In addition, it ensures that all intialization logic is grouped together accordingly rather than potentially being interspersed throughout the code (where-ever you like to define your field variables).

Upvotes: 5

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

Since you have other code ("other object creation code") in an explicit constructor, I would prefer putting all the initialization there.

Upvotes: 2

Related Questions