Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Initializing class variables [duplicate]

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 = "";
     }
}
like image 299
softwarematter Avatar asked Feb 24 '23 22:02

softwarematter


1 Answers

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.

like image 188
BrokenGlass Avatar answered Feb 26 '23 16:02

BrokenGlass