(MyClassName)object vs. object as MyClassName

Posted by Matthew Doyle on Stack Overflow See other posts from Stack Overflow or by Matthew Doyle
Published on 2010-04-01T16:47:32Z Indexed on 2010/04/01 16:53 UTC
Read the original article Hit count: 299

Filed under:
|

Hello all, I was wondering what is the better method for Casting objects for C#:

MyClassName test = (MyClassName)object;

MyClassName test = object as MyClassName;

I know already that if you do the first way, you get an exception, and the second way it sets test as null. However, I was wondering why do one over the other? I see the first way a lot, but I like how the second way because then I can check for null...

If there isn't a 'better way' of doing it, what are the guidelines for using one way or the other?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET