I’ve researched this several times now and keep forgetting the results. So, putting it here to record it for next time. What is the difference and usage for c# interfaces, virtual and abstract classes and methods? And where do you use them?
Interface
An interface specifies a contract.
- Interfaces contain only declarations of the members in the class but cannot contain implementation details.
- Interfaces do not have constructors
- All methods in an interface MUST be implemented by the class
- It only contains public access modifier because everything in the interface is public.
- A child class can inherit from multiple interfaces (multiple inheritance)
- [Note that properties in C# are in effect a method, so you can specify a property in an interface, but the property needs to be implemented by the derived class].
Abstract Class
An abstract class is a bit like an interface, but it can contain implementation details.
- Other classes can inherit from an abstract class and either use the implementation provided OR override the methods in the class with their own implementation.
- You cannot instantiate an abstract class
- It can contain different types of access modifiers like public, private, protected etc.
- Abstract classes typically define a base class in a hierarchy
- A class can only inherit from one abstract class (single inheritance)
Where to use abstract? If it makes sense for the base class in question to exist on it’s own without being derived from, then it should be a regular class, otherwise, it should be an abstract class.
Virtual methods
A virtual method can can be overridden in the inheriting class. Normally a class that inherits from another class cannot change the methods in the base class.
Abstract methods
An abstract method HAS to be overridden in the child class. A good example of the difference is found in this post.
An abstract function cannot have functionality. You’re basically saying, any child class MUST give their own version of this method, however it’s too general to even try to implement in the parent class.
A virtual function, is basically saying look, here’s the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality.