Interfaces


Now that we've seen how value types and reference types work in C#, let's turn our attention to interfaces. An interface is similar to a class, except that none of the methods in an interface have any implementation. An interface just specifies a set of related methods that must be implemented by other classes and structures. Because they contain no implementation, you cannot instantiate interfaces. In object-oriented design terms, interfaces are similar to pure abstract classes.

Note

An interface can also contain properties, indexers, and events. For more information about these kinds of members, see Chapter 2.

Interfaces play an extremely important role in object-oriented design. We can define interfaces to represent contractual obligations, without worrying about how these obligations will be satisfied by classes and structures in the application. Interfaces allow us to separate what an object can do, from how the object will do it.

By writing a generic method that takes an interface type as a parameter, and then implementing that interface in otherwise unrelated classes, we can provide a type-safe way of generalizing functionality across classes. If we access an object via an interface, the type of the object doesn't matter. For example, we only need to implement the IComparable interface in our own classes to allow them to be ordered correctly in a collection using, for example, the Array.Sort() method. The System.Array class only accesses instances of our class using this interface and doesn't care whether it's sorting strings, integers, apples, pears, oranges, or whatever.

Using interfaces in the design of our systems has several benefits:

  • It enables us to defer decisions about how to implement a particular behavior. We can write the implementing classes and structures later in the development process.

  • It allows us to provide several alternative implementations for the same interface.

  • It provides a hook for future extensions to our code. We can come back to our application in six months time and define new implementing classes if necessary, without having to change code that relies on them as the interface stays the same.

C++ and Java developers should be familiar with this concept, but this will be new ground for Visual Basic developers.

By convention, all interfaces in the .NET Framework start with the letter I. This makes it easy to distinguish interfaces from classes and structures. The .NET Framework class library has interfaces such as IDisposable, ICloneable, IComparable, and so on.




C# Class Design Handbook(c) Coding Effective Classes
C# Class Design Handbook: Coding Effective Classes
ISBN: 1590592573
EAN: 2147483647
Year: N/A
Pages: 90

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net