Possible Duplicate:
C# member variable initialization; best practice?
Which is the right way to initialize class variables. What is the difference between [1] and [2].
//[1]
public class Person
{
private int mPersonID = 0;
private string mPersonName = "";
}
OR
//[2]
public class Person
{
private int mPersonID = 0;
private string mPersonName = "";
public Person()
{
InitializePerson();
}
private void InitializePerson()
{
mPersonID = 0;
mPersonName = "";
}
}
Instance variables that are assigned a default value as part of their declaration will get this value assigned right before the constructor is run, from the outside there is no perceptible difference in behavior between 1) and 2), it’s mostly a matter of style.
You also introduce an additional
InitializePerson()method in your approach 2) – this can be beneficial if you have multiple constructors that then all can use the same common initialization method (which keeps the code DRY).Edit in response to comment, see MSDN: