01 June 2014

difference between abstract class and interface in c#

When you start designing class level diagrams, knowing the difference between abstract class and interface helps you in choosing right designs.

Syntactical difference

  • Abstract class can have abstract and non abstract methods. Abstract methods cannot have implementation and non abstract methods will have implementation. And these non abstract can have reusable implementation for the derived class where applicable.
  • Interface methods cannot have implementation, they are just declaration.

Difference when it come to Inheritance

  • A C# class cannot inherit from more than one class.
  • However a C# class can inherit from more than one interface. In C# .NET multiple inheritance if needed can be achieved using interfaces. If two base interfaces have the same method we can use explicit interface implementation.

Which is more flexible? interface or abstract class?

Abstract class are flexible compare to interface. Let's take an example.

Assume that you are building library which has contract defined using interfaces. These libraries are used by lot of projects in your organization. First you have released contracts.dll. So people are using the contracts which are defined by interfaces.

Now new requirements have come, to meet those requirements you are required add new method to the existing interface which is already in use by many projects. Later when you deploy this new contracts.dll containing the interface, all the existing implementation will start failing. This is because the classes which implemented the interfaces doesn't have the new method implementation. So interfaces aren't backword compatible.

Assume that for instance you have defined your contracts using the abstract class instead of interface. You can easily add new non abstract methods to your abstract class without breaking the existing implementations. Here the existing implementations are classes deriving from the abstract class. The newly added non abstract methods can throw System.NotImplementedException when released. Hence abstract classes are more flexible compare to interfaces.

RELATED ARTICLES

No comments:

Post a Comment