Tuesday, November 6, 2018

Interface vs. abstract class in C#

An abstract class is somewhere in between of an interface and a typical class.

An abstract class can only be a base class of other (non-abstract) classes; it can't be used to create objects with the new keyword.

A class can inherit multiple interfaces, while it can only inherit one class, whether it is abstract or not.

Interfaces and abstract classes can't be instantiated

The following is an example of what CANNOT be done with an abstract class:

namespace ConsoleApp6
{
 public abstract class AbstractBook
 {
  private int _number { getset; }
 
  public AbstractBook(int number)
  {
   _number = number;
  }
 }
 
 public class Program
 {
  static void Main(string[] args)
  {
   var ab = new AbstractBook(5);
  }
 }
}

An abstract class can't be instantiated, even though, as you can see, a constructor can be placed inside of such a class.

No comments:

Post a Comment