casting vs using the 'as' keyword in the CLR

Posted by Frank V on Stack Overflow See other posts from Stack Overflow or by Frank V
Published on 2009-01-30T16:20:52Z Indexed on 2010/05/13 16:04 UTC
Read the original article Hit count: 224

Filed under:
|
|

I'm learning about design patterns and because of that I've ended using a lot of interfaces. One of my "goals" is to program to an interface, not an implementation.

What I've found is that I'm doing a lot of casting or object type conversion. What I'd like to know is if there is a difference between these two methods of conversion:

public interface IMyInterface
{
    void AMethod();
}

public class MyClass : IMyInterface
{
    public void AMethod()
    {
       //Do work
    }

    // other helper methods....
}

public class Implementation
{
    IMyInterface _MyObj;
    MyClass _myCls1;
    MyClass _myCls2;

    public Implementation()
    {
    	_MyObj = new MyClass();

    	// What is the difference here:
    	_myCls1 = (MyClass)_MyObj;
    	_myCls2 = (_MyObj as MyClass);
    }
}

If there is a difference, is there a cost difference or how does this affect my program?

Hopefully this makes sense. Sorry for the bad example; it is all I could think of...

Update: What is "in general" the preferred method? (I had a question similar to this posted in the 'answers'. I moved it up here at the suggestion of Michael Haren. Also, I want to thank everyone who's provided insight and perspective on my question.

© Stack Overflow or respective owner

Related posts about clr

Related posts about casting