Working with Interfaces
Now that you have learned the importance of using interfaces in your component-based application, it’s time to examine a number of practical issues regarding working with interfaces and tying them to the rest of your application. Later in this chapter, you will also see the support Visual Studio 2005 offers component developers when it comes to adding implementation to your classes for predefined interfaces.
Tip
When you name a new interface type, you should prefix it with a capital I
and capitalize the first letter of the domain term, as in IAccount
, IController
, ICalculator
, and so on. Use the I
prefix even if the domain term itself starts with an I
(such as in IIDentity
or IImage
). .NET tries to do away with the old Windows and C++ Hungarian naming notations (that is, prefixing a variable name with its type), but the I
prefix is a direct legacy from COM, and that tradition is maintained in .NET.
Interfaces and Type Safety
Interfaces are abstract types and, as such, can’t be used directly. To use an interface, you need to cast into an interface reference an object that supports it. There are two types of casting—implicit and explicit—and which type you use has an impact on type safety.
Assigning a class instance to an interface variable directly is called an implicit cast, because the compiler is required to figure out which type to cast the class to:
IMyInterface obj; obj = new MyClass(); obj.Method1();
When you use implicit casts, the compiler enforces type ...
Get Programming .NET Components, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.