12.07.2015 Views

Accelerated

Accelerated

Accelerated

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

370CHAPTER 13 ■ IN SEARCH OF C# CANONICAL FORMS}// ICloneable implementationpublic object Clone() {return new Dimensions(this);}private long width;private long height;This method of cloning an object is the safest way in the sense that you have full control overhow the copy is made. Any changes that need to be done regarding the way the object is copied canbe made in the copy constructor. You must take care to consider what happens when you declare aconstructor in a class. Any time you do so, the compiler will not emit the default constructor that itnormally does when you don’t provide a constructor. If the private copy constructor listed here wasthe only constructor defined in the class, users of the class would never be able to create instancesof it. That’s because the default constructor is now gone, and no other publicly accessible constructorwould exist. In this case, you have nothing to worry about since you also defined a publicconstructor that takes two parameters. Nevertheless, it’s an important point to consider duringclass design.Now, let’s also consider objects that themselves contain references to other objects. Supposeyou have an employee database, and you represent each employee with an object of type Employee.This Employee type contains vital information such as the employee’s name, title, and ID number.The name and possibly the formatted ID number are represented by strings, which are themselvesreference type objects. For the sake of example, let’s implement the employee title as a separateclass named Title. If you follow the guideline I stated previously where you always do a deep copyon a clone, then you could implement the following clone method:using System;// Title class//public sealed class Title : ICloneable{public enum TitleNameEnum {GreenHorn,HotshotGuru}public Title( TitleNameEnum title ) {this.title = title;}LookupPayScale();private Title( Title other ) {this.title = other.title;}LookupPayScale();// ICloneable implementationpublic object Clone() {return new Title(this);}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!