sjanisz
sjanisz

Reputation: 155

Is possibility to derive from multiple interfaces the only difference between abstract class and interface?

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?

Upvotes: -1

Views: 94

Answers (2)

Pavlo Holotiuk
Pavlo Holotiuk

Reputation: 267

There's a number of differences between interface and abstract class. Abstract classes can:

  1. have virtual members to be overriden in derived classes
  2. 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.

Upvotes: 2

Ivan Petrov
Ivan Petrov

Reputation: 4445

The 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");
    }
}

Upvotes: 0

Related Questions