Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an interface get emitted at the IL level as an "abstract interface"?

Tags:

c#

.net

clr

roslyn

cil

I've been trying to learn more about the CLR and while doing so noticed that the following interface in C# will be compiled to IL that contains some kind of "abstract interface".

Given that declaring an interface as abstract in C# is not valid, what does it mean to allow an abstract interface at the IL level? Initially I wondered if this was how the runtime internally represents an interface, by declaring an abstract class thus preventing it being new-ed up.

It does appear to be following this idea, as shown by the .class. However, following that is interface. So the idea of needing to actually create an abstract class appears to be moot when the runtime already seems to support the concept of an interface.

This leads me to a couple of questions:

  1. What is the purpose of the abstract interface, and why is an abstract interface valid at the IL level?
  2. Why is .class and interface necessary, and why is this valid at the IL level?
  3. If the runtime supports the concept of an interface, why is the .class or abstract required at all?

C#:

public interface IExample
{
    void SomeMethod(int number);
}

IL:

.class interface public auto ansi abstract IExample
{
    // Methods
    .method public hidebysig newslot abstract virtual 
        instance void SomeMethod (
            int32 number
        ) cil managed 
    {
    } // end of method IExample::SomeMethod

}
like image 448
user9993 Avatar asked Jun 08 '17 10:06

user9993


1 Answers

If you look at how metadata (PDF) is defined at the IL level, all types are introduced by a .class header (even value types).

interface is described as a "Type semantic attribute" (10.1.3) and is used to distinguish whether what is being defined is, indeed, an interface, as opposed to an abstract class in which all members are abstract.

abstract is described as a "Inheritance attribute" (10.1.4) and specifically means the type cannot be instantiated.

That covers the intended meanings. As to why they're necessary (i.e. why interface doesn't automatically imply abstract), I believe it was done to make everything explicit at this level. Since you don't often have to write IL yourself, having some overlap between some of these flags isn't harmful.

like image 191
Damien_The_Unbeliever Avatar answered Oct 02 '22 12:10

Damien_The_Unbeliever