views:

138

answers:

3

Hi All,

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.

+1  A: 

CLR via C# 3.0 has virtually everything you will ever want to know about the CLR in it, so I recommend that you pick up a copy of it.

The answer to your question is on page 314 specifically.

Edit I was on the verge of retyping half of it here, but you're better off just buying it. Trust me.

Aaronontheweb
time to buy the book :) ....may be answer cud be better since not all have the book :) just to make this complete :)
Amitd
+1  A: 

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.

Gorkem Pacaci
wow the 2nd link seems very daunting to grasp :)
Amitd
not after reading it 10 times.
Gorkem Pacaci
read it thrice and still not getting it :) ..i keep trying ;)
Amitd
A: 

Using the interface while creating the object reference is considered a better practice as compared to directly instanciating it with a class type. This comes under the programming to an interface principle.

This means you can change the concrete class which implements the same interface at runtime using something like dependency injection or even may be reflection. Your code will not be required to be changed if you program to an interface as compared to programming to an concrete type.

Nilesh Gule
This seems better explanation of programming to an interface http://stackoverflow.com/questions/1848442/what-exactly-is-interface-based-programming
Amitd