Click here to Skip to main content
15,942,449 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
C#
interface ITest{}

class MyClass{}

class Main {
     public static void main(String[] args) 
     {
         MyClass obj = new MyClass();

         ITest iObj = (ITest)obj;  //compiles fine --Line 2
         
         SomeMethod(obj);          // compile time error --Line 3
     }

     public static void SomeMethod(ITest test) {}

}

In above code snippet, though MyClass does not implement ITest interface, Line 2 compiles without any error. This makes sense, since obj at runtime can have a reference of some class derived from MyClass and implementing ITest as well.

But Line 3 gives compile time error (cannot convert from MyClass to ITest), does not above explanation holds true here as well ?

Thanks!!
Rahul
Posted
Updated 28-Oct-12 11:42am
v2

Casting is a dangerous beast: you tell the compiler in this case that you know better than he knows (or at least you assume you know better...;-)).
So, with casting you defer the type check to run time.
That's why I consider casting a code smell.

Cheers
Andi
 
Share this answer
 
try this
C#
interface ITest{}
 
class MyClass{}
 
class Main {
     public static void main(String[] args) 
     {
         MyClass obj = new MyClass();
 
         ITest iObj = (ITest)obj;  //compiles fine --Line 2
         
         SomeMethod(obj);          // compile time error --Line 3
                   //you have pass obj rather than Iobj
                        // try this SomeMethod(IObj);
     }
 
     public static void SomeMethod(ITest test) {}
 
}


[edit] added code tags [/edit]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900