!Dan Vallejo's WebLog!

Visual Studio .NET Developer

Getting an Interface Object

You have several ways of getting an interface object.

The implicit way has the advantage in that the compiler makes sure that the interface is implemented by the class. The disadvantage is that someone reading your code won't know that this is an interface being torn off. This just might need some more comments, that's it.

The explicit way has the advantage in that you have exactly called out the interface name. The problem is that you won't find out until runtime whether the code actually works or not. An exception will be thrown if the conversion is not able to take place.

The explicit way with the "as" has the advantage of being able to check if the interface is implemented similar to what was discussed above. Keep in mind that when you use the "as" method then you should be checking for null.

static void Main()
{
    Tester    tst = new Tester();
    IReader  reader;
    // implicit compile-time conversion
    reader = tst;
   
    // explicit run-time conversion with exception
    reader = (IReader)tst;
    // explicit run-time conversion with null
    reader = tst as IReader;
}
Published Saturday, May 22, 2004 4:34 PM by DanVallejo
Filed under:

Comments

 

Nick Parker said:

Are you saying that type casting with the "as" statement is more safe than wrapping your first explicit cast in a try-catch block handling an InvalidCastException or does it simply offer fewer keyboard strokes?
May 22, 2004 10:11 PM
 

Getting an Interface Object said:

November 27, 2007 8:28 AM
Anonymous comments are disabled

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker