In the past life was easy, interfaces could not have implementations, abstract classes could. Nowadays (like for 5+ years already lol), the only difference between abstract class and interface in C# is that deriving classes can derive from multiple interfaces and they can derive only from one abstract class. Is above statement true or do i miss something?
2 Answers
There's a number of differences between interface and abstract class. Abstract classes can:
- have virtual members to be overriden in derived classes
- enforce initialization data with constructors
Abstract classes are great at combining multiple classes that share a lot of behavior. Interfaces are used to enforce same behavior to unrelated classes.
Default interface implementation can reduce code duplication but you cannot access class' private/protected fields in default implementation.
There are probably more differences but as others have said they have different purposes.
3 Comments
private and protected) 4. this also true for interfaces =)new as a mistake when used with interfaces and advises to remove it. I wonder why it does thatThe most significant difference is that you cannot call interface methods with default implementation from a class reference that doesn't directly implement the interface.
This is not the case with default implementation provided from an abstract class.
void Main()
{
Derived derived = new Derived();
derived.FooBase(); // Abstract
derived.FooWithImplementation(); // Derived implementation
//derived.FooInterface does not compile
I interfaceReference = derived;
interfaceReference.FooInterface(); // Interface
}
interface I
{
public void FooInterface()
{
Console.WriteLine("Interface");
}
public void FooWithImplementation()
{
Console.WriteLine("Interface implementation");
}
}
abstract class Base
{
public void FooBase()
{
Console.WriteLine("Abstract");
}
}
class Derived : Base, I
{
public void FooWithImplementation()
{
Console.WriteLine("Derived implementation");
}
}
the only difference between abstract class and interface in C# is that deriving classes can derive from multiple interfacesThis isn't true. The kind of code you can put into an abstract class is considerably broader than you can get away with on a default interface method. The decision point here for your code is super simple. Is there any common code - use an abstract class. If there isn't - use an interface. Are there edge cases where you can have default code on an interface? Yes, but day to day it is not a useful feature.default-interface-membertag description for clarification and examples