Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# hack: low level difference between interface and abstract class

This is a philosophical question about C# fundamentals: I am wondering how close an interface may be simulated by fully abstract class. Assume we have following interface:

public interface INativeInterface
{
    void PerformAction();
    String Property { get; set; }
}

And following abstract class:

public abstract class ISimulatedInterface
{
    public abstract void PerformAction();
    public abstract String Property { get; set; }
}

They are having so much in common, aren't they? The differences I know are that:

  • Multiple inheritance does not work for abstract classes
  • Explicit implementation does not work abstract classes

Can these restrictions be skipped by using reflection or something like this?

I realize that interface and abstract class are different in root: interface declares a condition of "can behave like", abstract class - "is a kind of", but even this seems to be so close that a low level differences between these entities have to be discussed. This question can even sound like "What would you do to make an interface in C++".

like image 690
Ilya Tereschuk Avatar asked Jan 02 '14 16:01

Ilya Tereschuk


1 Answers

Can these restrictions be skipped by using reflection or something like this?

No. Abstract classes and interfaces are different concepts at the Common Language Runtime level. Hence it is neither possible in C# because of being ultimately limited be CLR's boundaries.

I am wondering how close an interface may be simulated by fully abstract class.

It is doable, but requires support (or 'allowance') from the underlying execution evironment (be it physical or managed).

In the past I designed a language that completely substituted abstract classes for interfaces. And yes, it did support multiple inheritance of such 'interfaces'. However, the implementation peculiarities are probably not worth the effort. The major 'low-level difference' was that an internal, embedded instance of the inherited abstract class had to be kept within the implementing class'es instance, and a chain of this pointers had to be maintained. Needless to say, it was a joyful experience :-)

like image 154
Ondrej Tucny Avatar answered Sep 26 '22 02:09

Ondrej Tucny