Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No compile time error when casting to the wrong type

Tags:

c#

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

like image 746
GPuri Avatar asked Jan 24 '14 04:01

GPuri


People also ask

What causes a compile time error?

A compile time error is an error that is detected by the compiler. Common causes for compile time errors include: Syntax errors such as missing semi-colon or use of a reserved keyword (such as 'class'). When you try and access a variable that is not in scope.

What is compile time error with example?

The Errors that occur due to incorrect syntax are known as compile-time errors or sometimes also referred to as syntax errors in java. Examples of compile-time errors include: missing parenthesis, missing a semicolon, utilizing undeclared variables, etc.

What is compile time error checking?

Compile-time checking occurs during the compile time. Compile time errors are error occurred due to typing mistake, if we do not follow the proper syntax and semantics of any programming language then compile time errors are thrown by the compiler.

What is the meaning of compilation error in Java?

Compilation error refers to a state when a compiler fails to compile a piece of computer program source code, either due to errors in the code, or, more unusually, due to errors in the compiler itself. A compilation error message often helps programmers debugging the source code.


1 Answers

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'"
like image 174
Scott Chamberlain Avatar answered Sep 26 '22 23:09

Scott Chamberlain