Are class declarations that are initially set, internally the same as setting them in the constructor?
example:
class test
{
int test1 = 5;
}
Is there any difference between that and
class test
{
int test1;
public test()
{
test1 = 5;
}
}
If there is no difference, which is more correct to do?
For most purposes, you can consider the two styles of member initialization functionally equivalent.
However, you should keep in mind that assignments made in the member declarations execute before any constructors execute. As Jon Skeet points out in comments, this difference in timing can create observable artifacts if virtual methods are called from base constructors.
“Correctness” is a matter of opinion. For simple integer values the initial value assignments seem innocuous enough, but when you get into more complex types like dates or other full-on objects, the clutter factor starts to rise.
For myself, I generally prefer to see initialization performed as explicit assignment statements in the body of the constructor, not scattered all over the class in declarations.