How to detect the difference between an interface and an abstract class?

210 views Asked by At

Given the following types:

public interface Interface { }
public abstract class Abstract { }

Why is this:

typeof(Interface).IsAbstract == true;

Note the IsInterface exists to check if it is an interface:

typeof(Abstract).IsInterface == false;
1

There are 1 answers

4
Johnathan Barclay On BEST ANSWER

From the docs:

The IsAbstract property returns true in the following cases:

  • The current type is abstract; that is, it cannot be instantiated, but can only serve as the base class for derived classes. In C#, abstract classes are marked with the abstract keyword; in Visual Basic, they are marked with the MustInherit keyword.

  • The current type is an interface.

So an interface is considered abstract because it cannot be instantiated.

If you want to determine that a type is an abstract class, you should do the following:

typeof(YourType).IsClass && typeof(YourType).IsAbstract