Recently I was asked in an interview that, can an Interface be considered as a class in C#? I.e. is an interface is a class in C#?
I was confused.
What can be the answer?
No, an interface is not a class.
An interface is a set of method signatures and possibly properties that all relate to a single idea. For example, the IList interface will have methods for indexing, inserting, and getting the number of elements. However, it does not define any implementation details. The list interface could be implemented as a linked list, or a wrapped up array, or anything you want, as long as it defines those methods in the interface.
A class is the template from which to create an actual object. Classes are a collection of method signatures, plus the implementations of those methods.
So no, an interface is not a class, as it merely defines a specific contract, while a class defines the whole behaviour of the object.
Commenter SquareCog accurately points out that the above is not entirely true. Since classes can be subclassed, and methods overridden, the class' relationship to the actual behaviour of an object gets somewhat more complicated. I'm just going to handwave that problem away by saying that classes are individual entities. You can read the source code for a class and know what behaviour that class encompasses. However, at runtime, objects have types instead of classes. Types are the entire inheritance tree, instead of a singular class, and thus a type's behaviour could be defined over several different classes. Luckily, this does not change the basic conceptual difference that interfaces are contracts that can imply (through names, argument types, etc) certain implementations, but cannot enforce anything but the method signatures, while classes do define an implementation, even if that is not the actual implementation used at runtime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With