<p>I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.</p>

<p>Should I do it at declaration?:</p>

<pre><code>public class Dice
{
    private int topFace = 1;
    private Random myRand = new Random();

    public void Roll()
    {
       // ......
    }
}
</code></pre>

<p>or in a constructor?:</p>

<pre><code>public class Dice
{
    private int topFace;
    private Random myRand;

    public Dice()
    {
        topFace = 1;
        myRand = new Random();
    }

    public void Roll()
    {
        // .....
    }
}
</code></pre>

<p>I'm really curious what some of you veterans think is the best practice. I want to be consistent and stick to one approach.</p>

[{'answer_id': 24558, 'author': 'kokos', 'author_id': 1065, 'author_profile': 'https://Stackoverflow.com/users/1065', 'pm_score': 9, 'selected': True, 'text': "<p>My rules:</p>\n\n<ol>\n<li>Don't initialize with the default values in declaration (<code>null</code>, <code>false</code>, <code>0</code>, <code>0.0</code>…).</li>\n<li>Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.</li>\n<li>If the value of the field changes because of a constructor parameter put the initialization in the constructors.</li>\n<li>Be consistent in your practice (the most important rule).</li>\n</ol>\n"}, {'answer_id': 24643, 'author': 'Noel', 'author_id': 2637, 'author_profile': 'https://Stackoverflow.com/users/2637', 'pm_score': 3, 'selected': False, 'text': '<p>Assuming the type in your example, definitely prefer to initialize fields in the constructor. The exceptional cases are:</p>\n\n<ul>\n<li>Fields in static classes/methods</li>\n<li>Fields typed as static/final/et al</li>\n</ul>\n\n<p>I always think of the field listing at the top of a class as the table of contents (what is contained herein, not how it is used), and the constructor as the introduction. Methods of course are chapters.</p>\n'}, {'answer_id': 24659, 'author': 'Dan Blair', 'author_id': 1327, 'author_profile': 'https://Stackoverflow.com/users/1327', 'pm_score': 2, 'selected': False, 'text': "<p>What if I told you, it depends?</p>\n\n<p>I in general initialize everything and do it in a consistent way. Yes it's overly explicit but it's also a little easier to maintain. </p>\n\n<p>If we are worried about performance, well then I initialize only what has to be done and place it in the areas it gives the most bang for the buck.</p>\n\n<p>In a real time system, I question if I even need the variable or constant at all.</p>\n\n<p>And in C++ I often do next to no initialization in either place and move it into an Init() function. Why? Well, in C++ if you're initializing something that can throw an exception during object construction you open yourself to memory leaks.</p>\n"}, {'answer_id': 25126, 'author': 'Iker Jimenez', 'author_id': 2697, 'author_profile': 'https://Stackoverflow.com/users/2697', 'pm_score': 0, 'selected': False, 'text': '<p>I normally try the constructor to do nothing but getting the dependencies and initializing the related instance members with them. This will make you life easier if you want to unit test your classes.</p>\n\n<p>If the value you are going to assign to an instance variable does not get influenced by any of the parameters you are going to pass to you constructor then assign it at declaration time.</p>\n'}, {'answer_id': 25130, 'author': 'Quibblesome', 'author_id': 1143, 'author_profile': 'https://Stackoverflow.com/users/1143', 'pm_score': 7, 'selected': False, 'text': '<p>In C# it doesn\'t matter. The two code samples you give are utterly equivalent. In the first example the C# compiler (or is it the CLR?) will construct an empty constructor and initialise the variables as if they were in the constructor (there\'s a slight nuance to this that Jon Skeet explains in the comments below).\nIf there is already a constructor then any initialisation "above" will be moved into the top of it.</p>\n\n<p>In terms of best practice the former is less error prone than the latter as someone could easily add another constructor and forget to chain it.</p>\n'}, {'answer_id': 34484, 'author': 'John Meagher', 'author_id': 3535, 'author_profile': 'https://Stackoverflow.com/users/3535', 'pm_score': 1, 'selected': False, 'text': '<p>There is a slight performance benefit to setting the value in the declaration.  If you set it in the constructor it is actually being set twice (first to the default value, then reset in the ctor).  </p>\n'}, {'answer_id': 46818, 'author': 'Tom Hawtin - tackline', 'author_id': 4725, 'author_profile': 'https://Stackoverflow.com/users/4725', 'pm_score': 4, 'selected': False, 'text': "<p>The semantics of C# differs slightly from Java here. In C# assignment in declaration is performed before calling the superclass constructor. In Java it is done immediately after which allows 'this' to be used (particularly useful for anonymous inner classes), and means that the semantics of the two forms really do match.</p>\n\n<p>If you can, make the fields final.</p>\n"}, {'answer_id': 19896333, 'author': 'xji', 'author_id': 1460448, 'author_profile': 'https://Stackoverflow.com/users/1460448', 'pm_score': 4, 'selected': False, 'text': '<p>I think there is one caveat. I once committed such an error: Inside of a derived class, I tried to "initialize at declaration" the fields inherited from an abstract base class. The result was that there existed two sets of fields, one is "base" and another is the newly declared ones, and it cost me quite some time to debug.</p>\n\n<p>The lesson: to initialize <strong>inherited</strong> fields, you\'d do it inside of the constructor.</p>\n'}, {'answer_id': 32011236, 'author': 'Miroslav Holec', 'author_id': 794117, 'author_profile': 'https://Stackoverflow.com/users/794117', 'pm_score': 3, 'selected': False, 'text': '<p>There are many and various situations.</p>\n\n<p><strong>I just need an empty list</strong></p>\n\n<p>The situation is clear. I just need to prepare my list and prevent an exception from being thrown when someone adds an item to the list.</p>\n\n<pre><code>public class CsvFile\n{\n    private List&lt;CsvRow&gt; lines = new List&lt;CsvRow&gt;();\n\n    public CsvFile()\n    {\n    }\n}\n</code></pre>\n\n<p><strong>I know the values</strong></p>\n\n<p>I exactly know what values I want to have by default or I need to use some other logic.</p>\n\n<pre><code>public class AdminTeam\n{\n    private List&lt;string&gt; usernames;\n\n    public AdminTeam()\n    {\n         usernames = new List&lt;string&gt;() {"usernameA", "usernameB"};\n    }\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>public class AdminTeam\n{\n    private List&lt;string&gt; usernames;\n\n    public AdminTeam()\n    {\n         usernames = GetDefaultUsers(2);\n    }\n}\n</code></pre>\n\n<p><strong>Empty list with possible values</strong></p>\n\n<p>Sometimes I expect an empty list by default with a possibility of adding values through another constructor.</p>\n\n<pre><code>public class AdminTeam\n{\n    private List&lt;string&gt; usernames = new List&lt;string&gt;();\n\n    public AdminTeam()\n    {\n    }\n\n    public AdminTeam(List&lt;string&gt; admins)\n    {\n         admins.ForEach(x =&gt; usernames.Add(x));\n    }\n}\n</code></pre>\n'}, {'answer_id': 34842991, 'author': 'Raedwald', 'author_id': 545127, 'author_profile': 'https://Stackoverflow.com/users/545127', 'pm_score': 3, 'selected': False, 'text': '<p>In Java, an initializer with the declaration means the field is always initialized the same way, regardless of which constructor is used (if you have more than one) or the parameters of your constructors (if they have arguments), although a constructor might subsequently change the value (if it is not final). So using an initializer with a declaration suggests to a reader that the initialized value is the value that the field has <em>in all cases</em>, regardless of which constructor is used and regardless of the parameters passed to any constructor. Therefore use an initializer with the declaration only if, and always if, the value for all constructed objects is the same.</p>\n'}, {'answer_id': 43960765, 'author': 'Edward Brey', 'author_id': 145173, 'author_profile': 'https://Stackoverflow.com/users/145173', 'pm_score': 2, 'selected': False, 'text': '<p>The design of C# suggests that inline initialization is preferred, or it wouldn\'t be in the language. Any time you can avoid a cross-reference between different places in the code, you\'re generally better off.</p>\n\n<p>There is also the matter of consistency with static field initialization, which needs to be inline for best performance. The Framework Design Guidelines for <a href="https://msdn.microsoft.com/en-us/library/ms229060.aspx" rel="nofollow noreferrer">Constructor Design</a> say this:</p>\n\n<blockquote>\n  <p>✓ CONSIDER initializing static fields inline rather than explicitly using static constructors, because the runtime is able to optimize the performance of types that don’t have an explicitly defined static constructor.</p>\n</blockquote>\n\n<p>"Consider" in this context means to do so unless there\'s a good reason not to. In the case of static initializer fields, a good reason would be if initialization is too complex to be coded inline.</p>\n'}, {'answer_id': 44167904, 'author': 'MeanJerry', 'author_id': 4984898, 'author_profile': 'https://Stackoverflow.com/users/4984898', 'pm_score': 2, 'selected': False, 'text': '<p>Being consistent is important, but this is the question to ask yourself:\n"Do I have a constructor for anything else?"</p>\n\n<p>Typically, I am creating models for data transfers that the class itself does nothing except work as housing for variables.</p>\n\n<p>In these scenarios, I usually don\'t have any methods or constructors. It would feel silly to me to create a constructor for the exclusive purpose of initializing my lists, especially since I can initialize them in-line with the declaration.</p>\n\n<p>So as many others have said, it depends on your usage. Keep it simple, and don\'t make anything extra that you don\'t have to.</p>\n'}, {'answer_id': 46857338, 'author': 'Joe Programmer', 'author_id': 8686463, 'author_profile': 'https://Stackoverflow.com/users/8686463', 'pm_score': 2, 'selected': False, 'text': "<p>Consider the situation where you have more than one constructor. Will the initialization be different for the different constructors? If they will be the same, then why repeat for each constructor? This is in line with kokos statement, but may not be related to parameters. Let's say, for example, you want to keep a flag which shows how the object was created. Then that flag would be initialized differently for different constructors regardless of the constructor parameters. On the other hand, if you repeat the same initialization for each constructor you leave the possibility that you (unintentionally) change the initialization parameter in some of the constructors but not in others. So, the basic concept here is that common code should have a common location and not be potentially repeated in different locations. So I would say always put it in the declaration until you have a specific situation where that no longer works for you.</p>\n"}, {'answer_id': 51232030, 'author': 'user1451111', 'author_id': 1451111, 'author_profile': 'https://Stackoverflow.com/users/1451111', 'pm_score': 0, 'selected': False, 'text': '<p>Not a direct answer to your question about <strong>the best practice</strong> but an important and related refresher point is that in the case of a generic class definition, either leave it on compiler to initialize with default values or we have to use a special method to initialize fields to their default values (if that is absolute necessary for code readability).</p>\n\n<pre><code>class MyGeneric&lt;T&gt;\n{\n    T data;\n    //T data = ""; // &lt;-- ERROR\n    //T data = 0; // &lt;-- ERROR\n    //T data = null; // &lt;-- ERROR        \n\n    public MyGeneric()\n    {\n        // All of the above errors would be errors here in constructor as well\n    }\n}\n</code></pre>\n\n<p>And the special method to initialize a generic field to its default value is the following:</p>\n\n<pre><code>class MyGeneric&lt;T&gt;\n{\n    T data = default(T);\n\n    public MyGeneric()\n    {           \n        // The same method can be used here in constructor\n    }\n}\n</code></pre>\n'}, {'answer_id': 61320158, 'author': 'Yousha Aleayoub', 'author_id': 1429432, 'author_profile': 'https://Stackoverflow.com/users/1429432', 'pm_score': 1, 'selected': False, 'text': '<p><strong>When you don\'t need some logic or error handling:</strong></p>\n\n<ul>\n<li>Initialize class fields at declaration</li>\n</ul>\n\n<p><strong>When you need some logic or error handling:</strong></p>\n\n<ul>\n<li>Initialize class fields in constructor</li>\n</ul>\n\n<blockquote>\n  <p>This works well when the initialization value is available and the\n  initialization can be put on one line. However, this form of\n  initialization has limitations because of its simplicity. If\n  initialization requires some logic (for example, error handling or a\n  for loop to fill a complex array), simple assignment is inadequate.\n  Instance variables can be initialized in constructors, where error\n  handling or other logic can be used.</p>\n</blockquote>\n\n<p><em>From <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html" rel="nofollow noreferrer">https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html</a> .</em></p>\n'}]
['https://Stackoverflow.com/questions/24551', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2635/']