Compartilhar via


Choosing Between Classes and Interfaces 

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 class that implements the interface must supply the implementation details for theses members. Classes can implement multiple interfaces.

Classes define both member signatures and implementation details for each member. Abstract (MustInherit in Visual Basic) classes can behave like interfaces or regular classes in that they can define members, and they can provide implementation details but are not required to do so. If an abstract class does not provide implementation details, concrete classes that inherit from the abstract class are required to provide the implementation.

While both abstract classes and interfaces support separating contract from implementation, interfaces cannot specify new members in later versions while abstract classes can add members as needed to support additional functionality.

Do favor defining classes over interfaces.

In later versions of your library, you can safely add new members to classes; you cannot add members to interfaces without breaking existing code.

Do use abstract (MustInherit in Visual Basic) classes instead of interfaces to decouple the contract from implementations.

Do define an interface if you need to provide a polymorphic hierarchy of value types.

Value types must inherit from ValueType, and can inherit only from ValueType, so they cannot use classes to separate contract and implementation. In this case, you must use an interface if your value types require polymorphic behavior.

Consider defining interfaces to achieve an effect similar to that of multiple inheritance.

If a type must implement multiple contracts, or the contract is applicable to a wide variety of types, use an interface. For example, IDisposable is implemented by types used in many different scenarios. Requiring classes to inherit from a base class to be disposable would make the class hierarchy too inflexible. Classes such as MemoryStream, which should inherit their stream-based contracts from their parent classes, would not be able to do so and also be disposable.

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 Structures

Other Resources

Type Design Guidelines
Design Guidelines for Developing Class Libraries