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:
Fields are initialized immediately before the constructor for the object instance is called. If the constructor assigns the value of a field, it will overwrite any value given during field declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With