Use C# Object Initializers

They make code much more readable than constructors. Use empty constructors and public getters/setters or public properties when you have a lot of properties you want to initialize. Compare edge2 where we insert all the variables in the constructor with the object initializer below it. Once you have more than three parameters passed in, keeping the constructor in order becomes a pain. For example changing some parameters to be optional means you have to move them so that they’re after non-optional parameters. With object initializers you can do them in any order and define yourself any time which properties should get initialized.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
        // Lame old constructor
        Edge edge2 = new Edge(new Center(), new Center(), 5, 0, "edge_01", "edge_02", 7, false);
 
        // Cool and attractive object initializer
        Edge edge = new Edge()
        {
            leftCorner = new Center(),
            rightCorner = new Center(),
            name = "edge_01",
            neighborName = "edge_02",
            index = 5,
            river = 0,
            height = 7,
            isVisible = false
        };
        // Lame old constructor
        Edge edge2 = new Edge(new Center(), new Center(), 5, 0, "edge_01", "edge_02", 7, false);

        // Cool and attractive object initializer
        Edge edge = new Edge()
        {
            leftCorner = new Center(),
            rightCorner = new Center(),
            name = "edge_01",
            neighborName = "edge_02",
            index = 5,
            river = 0,
            height = 7,
            isVisible = false
        };