Object Initializers Versus Optional Parameters

Instead of using object initializers, we could make  Bunny’s constructor accept
optional parameters:

1 public Bunny (string name,
2 bool likesCarrots = false,
3 bool likesHumans = false)
4 {
5 Name = name;
6 LikesCarrots = likesCarrots;
7 LikesHumans = likesHumans;
8 }

This would allow us to construct a Bunnyas follows:

1 Bunny b1 = new Bunny (name: "Bo",
2 likesCarrots: true);

An advantage of this approach is that we could make  Bunny’s fields (or  proper-ties, as we’ll explain shortly) read-only if we choose. Making fields or properties
read-only is good practice when there’s no valid reason for them to change
throughout the life of the object.
The disadvantage in this approach is that each optional parameter value is baked
into the calling site. In other words, C# translates our constructor call into this:
Bunny b1 = new Bunny ("Bo", true, false);
This can be problematic if we instantiate the Bunnyclass from another assembly,
and later modify  Bunnyby adding another optional parameter—such as  likes
Cats. Unless the referencing assembly is also recompiled, it will continue to call
the (now nonexistent) constructor with three parameters and fail at runtime. (A
subtler problem is that if we changed the value of one of the optional parameters,
callers in other assemblies would continue to use the old optional value until they
were recompiled.)
Hence, optional parameters are best avoided in public functions if you want to
offer binary compatibility between assembly versions.

posted @ 2013-06-05 20:29  futan57  阅读(157)  评论(0编辑  收藏  举报