Freigeben über


Interface Design 

An interface defines the signatures for a set of members that implementers must provide. Interfaces cannot provide implementation details for the members. For example, the ICollection interface defines members related to working with collections. Every concrete class that implements the interface must supply the implementation details for theses members. While classes can inherit only from a single class, they can implement multiple interfaces. The following guidelines help ensure that your interfaces are correctly designed.

Do define an interface if you need some common functionality to be supported by a set of types that includes some value types.

Value types must inherit from ValueType. For this reason, abstract classes cannot be used to specify a contract for value types; interfaces must be used instead.

Consider defining an interface if you need to support its functionality on types that already inherit from some other type.

Avoid using marker interfaces (interfaces with no members).

Custom attributes provide a way to mark a type. For more information about custom attributes, see Writing Custom Attributes. Custom attributes are preferred when you can defer checking for the attribute until the code is executing. If your scenario requires compile-time checking, you cannot comply with this guideline.

Do provide at least one type that is an implementation of an interface.

This helps ensure that the interface is well designed and can be implemented without too much difficulty. The Int32 class provides an implementation for the IComparable interface.

Do provide at least one member that consumes each interface you define (for example, a method that takes the interface as a parameter or a property typed as the interface).

This is another mechanism that helps ensure that the interface is well designed and can be used without too much difficulty.

Do not add members to an interface that has previously shipped.

Adding new members will break code that implemented the previous version of the interface. This is one of the main reasons why, in general and where possible, classes are preferable to interfaces. For more information, see Choosing Between Classes and Interfaces.

If the shipping definition of the interface requires additional members, you can implement a new interface and the appropriate members to consume it.

Portions Copyright 2005 Microsoft Corporation. All rights reserved.

Portions Copyright Addison-Wesley Corporation. All rights reserved.

For more information on design guidelines, see the "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries" book by Krzysztof Cwalina and Brad Abrams, published by Addison-Wesley, 2005.

See Also

Concepts

Choosing Between Classes and Interfaces

Other Resources

Type Design Guidelines
Design Guidelines for Developing Class Libraries