Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does .Net CLR implement an "Interface" internally?

Just curious about how .NET CLR handles interfaces internally?

Q1] What happens when CLR encounters something like :

simple interface example. (same used below.)

interface ISampleInterface
    {
        void SampleMethod();
    }

    class ImplementationClass : ISampleInterface
    {
        // Explicit interface member implementation: 
        public void SampleMethod()
        {
            // Method implementation.

        }

        static void Main()
        {
            //Declare an interface instance.
            ISampleInterface mySampleIntobj = new ImplementationClass();  // (A)
           // Call the member.
            mySampleIntobj.SampleMethod();

            // Declare an interface instance. 
            ImplementationClass myClassObj = new ImplementationClass();  // (B)
           //Call the member.
            myClassObj.SampleMethod();

        }
    }

Q2 : In the above example how are (A) and (B) differentiated ?

Q3 : Are Generic Interfaces treated differently?

(Feel like a noob when asking basic questions like these ...anyways....)

Thx all.

like image 764
Amitd Avatar asked Jul 16 '10 06:07

Amitd


People also ask

How does CLR work in C#?

Common Language Runtime (CLR) manages the execution of . NET programs. The just-in-time compiler converts the compiled code into machine instructions. This is what the computer executes.

Can interface be internal?

The internal interface is properties and methods that can be accessed only from other methods of the object, they are also called "private" (there are other terms, we will meet them further). The external interface is the properties and methods available outside the object, they are called "public".

What is default implementation of interface in C#?

Default interface methods enable an API author to add methods to an interface in future versions without breaking source or binary compatibility with existing implementations of that interface. The feature enables C# to interoperate with APIs targeting Android (Java) and iOS (Swift), which support similar features.

Can interface methods be implemented in C#?

With C# 8.0, you can now have default implementations of methods in an interface. Interface members can be private, protected, and static as well. Protected members of an interface cannot be accessed in the class that extends the interface. Rather, they can be accessed only in the derived interface.


1 Answers

There are practically no differences in those bits of code. Both end up calling the same function. There may be minor performance benefits in calling the method through the class type.

If you want to how these stuff are implemented, have a look at Virtual Method Tables.

For deeper information, see this.

like image 167
Gorkem Pacaci Avatar answered Nov 15 '22 10:11

Gorkem Pacaci