asp net 3.5unleashed

Page 302

to be garbage collected. So the fifth call to WriteLine displays "(2, 2)"—many developers won’t expect this result. In the last example, the boxed Point referred to by o is cast to an IChangeBoxedPoint. No boxing is necessary here because o is already a boxed Point. Then Change is called, which does change the boxed Point’s x and y fields. The interface method Change has allowed me to change the fields in a boxed Point object! Now, when WriteLine is called, it displays "(5, 5)", as expected. The purpose of this whole example is to demonstrate how an interface method is able to modify the fields of a boxed value type. In C#, this isn’t possible without using an interface method. Important A number of developers reviewed the chapters of this book. After reading through some of my code samples (such as the preceding one), these reviewers would tell me that they’ve sworn off value types. I must say that these little value type nuances have cost me days of debugging time, which is why I spend time pointing them out in this book. I hope you’ll remember some of these nuances and that you’ll be prepared for them if and when they strike you and your code. Certainly, you shouldn’t be scared of value types. They are useful types, and they have their place. After all, a program needs a little Int32 love now and then. Just keep in mind that value types and reference types have very different behaviors, depending on how they’re used. In fact, you should take the preceding code and declare the Point as a class instead of a struct to appreciate the results.

Implementing Multiple Interfaces That Have the Same Method Defining a type that implements an interface is usually easy and straightforward. You simply implement methods in the type that match the methods and signatures defined by the interface. You do have to remember to make the methods public, but there’s nothing special about the code in the implementation of an interface method. And calling an interfacedefined method is easy; you can just call the method as if it were any other method defined by the type. Occasionally, you might find yourself defining a type that implements multiple interfaces that define methods with the same name and signature. For example, imagine that there are two interfaces defined as follows: public interface IWindow { Object GetMenu(); }

public interface IRestaurant { Object GetMenu(); } Let’s say that you want to define a type that implements both these interfaces. You’d have to implement the type’s method as follows: // This type is derived from System.Object and // implements the IWindow and IRestaurant interfaces.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.