C# – Casting an interface to another interface that it does not inherit

ccastinginheritanceinterface

I'm hoping someone here can explain what incorrect assumptions I'm making. In C# 4.0, I have 2 interfaces and a class that implements them both. In a method I declare a variable with the type of the first interface, instantiate it using the class that implements both interfaces and can somehow cast it successfully to the second interface like in the following code:

    public interface IFirstInterface 
    {
        void Method1();
    }

    public interface ISecondInterface
    {
        void Method2();
    }

    public class InterfaceImplementation : IFirstInterface, ISecondInterface
    {
        public void Method1() { }
        public void Method2() { }
    }

    public class SomeClass
    {
        public void SomeMethod()
        {
            IFirstInterface first = new InterfaceImplementation();
            first.Method1();

            // Shouldn't the next line return null?
            ISecondInterface second = first as ISecondInterface; 
            // second is not null and the call to Method2() works fine
            second.Method2();
        }
    }

I'm trying to understand why the casting is successful. Yes, the class implements both interfaces, but I would think that since the first variable is declared as IFirstInterface (which doesn't inherit from ISecondInterface), the casting should still fail.

I've also tried restructuring my code in other ways, such as not using 'as', but the cast is still successful.

What am I missing?

Best Answer

From your example, you should be good by testing type type before calling any of the functionality. The first creation will create a fully qualified "InterfaceImplementation" that supports both interfaces. However, you are putting it into a declared type of only the first interface. So from the "first" object's perspective, it only cares about anything associated as an IFirstInterface implementation.

Now, on to you second... Even though you've created the object, you can still ask... By the way... are you also a Second Interface? If so, do this...

IFirstInterface first = new InterfaceImplementation();

if( first is ISecondInterface )
  // typecast since the second interface is legit, then call it's method 2
  ((ISecondInterface)first).Method2();