Possible Duplicate:
Best Practice: Initialize class fields in constructor or at declaration?
I am working with C# but this probably applies to Java (or any other language that allows this behavior as well)...
Which way is preferable/best practice? Assume I will ALWAYS need _memberVar
1.
class MyClass
{
private Dictionary<int, string> _memberVar = new Dictionary<int, string>();
public MyClass() {}
}
- OR -
2.
class MyClass
{
private Dictionary<int, string> _memberVar = null
public MyClass()
{
_memberVar = new Dictionary<int, string>();
}
}
Now lets say that MyClass has upwards of 10 constructors... So I don't want to have _memberVar = new Dictionary<int, string>(); in all of those constructors lol. Is there anything wrong with the 1st way? Thanks
Edit: I realize I can chain the constructors, but this is a rather complex class... some constructors call the base, some call other constructors already etc etc.
You do not have to initialise member variables, but it does not hurt if you do. Member variables acquire their default values automatically, usually a null for objects and the default value for primitive types (such as 0 for an int).
As for having different constructors, you do not have to repeat the member initialisation in each version since you can call an overloaded constructor from any other just as you would with an overloaded method.
Regarding best practice, personally I initialise member variables in the constructor as this is where I want to "construct" my object into a stable state. In other words, even if I would have initialised member variables where I declare them, when the constructor is called, it would be as if I was wiping the slate clean.
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