Possible Duplicate:
Casting vs using the 'as' keyword in the CLR
What is actually the difference between these two casts?
SomeClass sc = (SomeClass)SomeObject;
SomeClass sc2 = SomeObject as SomeClass;
Normally, they should both be explicit casts to the specified type?
Here is a good way to remember the process that each of them follow that I use when trying to decide which is better for my circumstance.
and the next should be easy to guess what it does
in the first case if the value cannot be cast than an exception is thrown in the second case if the value cannot be cast, i is set to null.
So in the first case a hard stop is made if the cast fails in the second cast a soft stop is made and you might encounter a NullReferenceException later on.
They'll throw different exceptions.
() : NullReferenceException
as : InvalidCastException
Which could help for debugging.
The "as" keyword attempts to cast the object and if the cast fails, null is returned silently. The () cast operator will throw an exception immediately if the cast fails.
"Only use the C# "as" keyword where you are expecting the cast to fail in a non-exceptional case. If you are counting on a cast to succeed and are unprepared to receive any object that would fail, you should use the () cast operator so that an appropriate and helpful exception is thrown."
For code examples and a further explanation: http://blog.nerdbank.net/2008/06/when-not-to-use-c-keyword.html
Typecasting using "as" is of course much faster when the cast fails, as it avoids the expense of throwing an exception.
But it is not faster when the cast succeeds. The graph at http://www.codeproject.com/KB/cs/csharpcasts.aspx is misleading because it doesn't explain what it's measuring.
The bottom line is:
If you expect the cast to succeed (i.e. a failure would be exceptional), use a cast.
If you don't know if it will succeed, use the "as" operator and test the result for null.
The former will throw an exception if the source type can't be cast to the target type. The latter will result in sc2 being a null reference, but no exception.
[Edit]
My original answer is certainly the most pronounced difference, but as Eric Lippert points out, it's not the only one. Other differences include:
And finally, using 'as' vs. the cast operator, you're also saying "I'm not sure if this will succeed."
The parenthetical cast throws an exception if the cast attempt fails. The "as" cast returns null if the cast attempt fails.
Also note that you can only use the as keyword with a reference type or a nullable type
ie:
will not compile
will compile.