Monday 15 April 2013

c# - Best practice on initialising member variables -



c# - Best practice on initialising member variables -

is improve initalise private fellow member variable service in constructor so:

public partial class datapumpservice : servicebase { private taskmanager _taskmanager; public datapumpservice() { initializecomponent(); _taskmanager = new taskmanager(); }

or in class so:

public partial class datapumpservice : servicebase { private taskmanager _taskmanager = new taskmanager(); public datapumpservice() { initializecomponent(); }

or create no difference?

it create bit difference. both initialized during object instantiation time (i.e. you've total guarantee class field initialized before object can consumed other code). makes difference (a quote msdn):

the instance field variable initializers of class correspond sequence of assignments executed upon entry 1 of instance constructors (section 10.10.1) of class. variable initializers executed in textual order in appear in class declaration.

that is, if got class next one:

public class { public string text = "hello"; public a() { text = "world"; } }

...and create instance of a, text retain world.

in case, utilize both approaches depending on utilize case. anyway, tend initialization in constructor gain clarity in terms of discovering class fields initialized (because other class fields should initialized property setter instead of class field directly... wrong!?).

c# windows-services initialization

No comments:

Post a Comment