GPuri
GPuri

Reputation: 833

No compile time error when casting to the wrong type

My question is regarding Type Casting in different interfaces

Suppose I have an interface

public interface I
{
    void method();
}

A class implementing it

public class C : I
{
    public void method()
    {
    }
}

I have another interface

public interface I1
{
    void method1();
}

Now if i do something like this

C c1 = new C();
((I1)c1).method1();

It throws a run time exception rather than a compile time error

Upvotes: 5

Views: 217

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127593

Because C is not marked sealed I could potentially do this

public D : C, I1
{
    public void method1()
    {
    }
}

Which would make the following code perfectly legal.

C c1 = new D();
((I1)c1).method1();

If C is marked sealed you should get a compile time error as there can't exist a more derived class that could be implementing the interface.

public sealed class C : I
{
    public void method()
    {
    }
}

//You should now get the compile time error "Cannot convert type 'SandboxConsole.C' to 'SandboxConsole.I1'"

Upvotes: 12

Related Questions