One of the most powerful features in C# is its ability to define casting rules. For example, you can define that your object is compatible with a type that isn't in the class's hierarchy. In the case of the SuperheroMouse class you could say that SuperheroMouse objects can be converted to Entrepreneur-Mouse types. Defining casting rules is done by adding a cast operator. Cast operators come in two flavors: explicit cast operators and implicit cast operators. Choosing between them is just a matter of style. Remember that when an implicit cast is possible you can just make a variable of one type equal to a variable of a different type and the compiler takes care of the conversion. If you implement implicit cast operators, this means less typing for the users of the class but the potential for more confusion. With explicit casts the compiler allows the conversion only if the programmer does an explicit case; this means more typing but less confusion. This is known as the Law of Inverse Productivity: the less typing you do, the more confused your readers are. (I just made that up, in case you're wondering.) To define an explicit cast operator:
Tips
|