I kind of posted a similar question a couple of days ago but that was more geared towards any *.Designer.cs file. This question is geared towards declaration and initialization of global variables within a class. To my knowledge, it's almost common practice (aside from the *.Designer.cs files it seems) to place all global variables at the beginning of a class definition followed by the rest of the code in any order (I prefer Getters and Setters, then Constructors, then Events, then misc functions). Well, I've seen it done and have done it myself where a global variable is set at declaration.
And I'm not referring to:
ClassA clA = new ClassA();
I'm referring to:
private int nViewMode = (int)Constants.ViewMode.Default;
Now, I've heard people say and I can agree with it on some levels, that the initialization of such variables, those variables that don't require a new
statement when you declare the variable, should be done in constructors or initialization functions. However, when they stated that, they may have meant that the previous statements were fine, but not the following:
Wrong Way
private int nTotal = 100;
private int nCount = 10;
private int nDifference = nTotal - nCount;
Possible Right Way
private int nTotal = 100;
private int nCount = 10;
private int nDifference = 0;
void ClassConstructor()
{
nDifference = nTotal - nCount;
}
My questions are:
What is the most common/standard practice in such a situation? What are the pros and cons of either? Are these questions only relevant for some languages and not others?
My last question I thought of as I was typing this up and here's the reason. In Visual Studio 2008 it seems I can place breakpoints on global variable declarations while I don't think I could when I used to write C++ in college. Also, I believe in college, you couldn't use a variable that was declared immediately before the current variable, but then again, that was in C++. So I'm not sure if these questions are only valid for MSVS products (we used Borland in college), newer compilers, or what not. If anyone has any insight, it's appreciated. Thanks.