What is the difference between C # interface and abstract class? In what situation do you use interfaces and abstract classes?

Time:2021-2-23

The difference between interface and abstract class:

Interfaces support multiple inheritance; abstract classes cannot implement multiple inheritance.

Interfaces can be used to support callbacks; abstract classes cannot implement callbacks because inheritance does not support them

Interfaces only contain signatures of methods, properties, indexers and events, but cannot define fields and methods containing implementations; abstract classes can define fields, properties and methods containing implementations

Interfaces can act on value types and reference types; abstract classes can only act on reference types

 

 

In what situation do you use interfaces and abstract classes?

Abstract class:

You define a set of interfaces, but you don’t want to force every implementation class to implement all interfaces. You can use itAbstract class defines a group of method bodies, or even empty method bodies, and then subclasses choose the methods they are interested in to cover.

In some cases, only relying on the pure interface can not meet the coordination between classes, and it is also necessary to distinguish different relationships by the variables representing the state in the class.The mediating role of abstract can satisfy this point.

Some methods are common, state independent, and can be shared, without the need for subclasses to implement separately; while others require subclasses to implement specific functions according to their own specific states

 

Interface:

Classes need to coordinate with specific interfaces before classes, regardless of how they are implemented.

As an identifier that can implement a specific function, it can also be a pure identifier without any interface method.

We need to treat a group of classes as a single class, and callers only contact this group of classes through interfaces.

A number of specific functions need to be implemented, and these functions may not have any connection at all.