Writing constructors is often a repetitive task. Many developers write the first constructor and then copy and paste the code into another constrcutor to satisfy the multiple overrides defined in the class interface. Here's an example:
1public class Menu
2{
3 //private variables
4 private string mstrName;
5 private string[] marrItems;
6
7 public Menu() : this("", 0)
8 {
9 }
10
11 public Menu(int intNumItems) : this("", intNumItems)
12 {
13 }
14
15 public Menu(string strName, int intNumItems)
16 {
17 marrItems = (intNumItems > 0) ? new string[intNumItems] : null;
18 mstrName = strName;
19 }
20} This is not a good idea. A better approach is constrcutor chaining where you create a common method to do the initializing. Here's a better approach:
1public class Menu
2{
3 //private variables
4 private string mstrName;
5 private string[] marrItems;
6
7 public Menu()
8 {
9 MenuConstructor("", 0);
10 }
11
12 public Menu(int intNumItems)
13 {
14 MenuConstructor("", intNumItems);
15 }
16
17 public Menu(string strName, int intNumItems)
18 {
19 MenuConstructor(strName, intNumItems);
20 }
21
22 private void MenuConstructor(string strName, int intNumItems)
23 {
24 marrItems = (intNumItems > 0) ? new string[intNumItems] : null;
25 mstrName = strName;
26 }
27}The second approach generates far more efficient code. In the first example, the compiler adds code to perform several functions on your behalf in constructors. It adds statements for all variable initializers and calls the base class constructor...this is a very big difference! Also consider readonly constants. By nature, they can only be set in the constructor. By centralizing this action, we avoid more redundancy.
These are just a few reasons why...to read more, pick up "Effective C#: 50 Specific Ways to Improve Your C#" by Bill Wagner.
You can buy it at the Addison-Wesley website:
http://www.aw-bc.com/
Comments
|
On
8/24/2006
Julie Brazier
said:
Hmm, I think you should pull out your copy of Effective C# and read it again if you think that is what Bill Wagner was saying about common constructors...
|
Leave a Comment