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?
It's like the difference between Parse and TryParse. You use TryParse when you expect it might fail, but when you have strong assurance it won't fail you use Parse.
To expand on Rytmis's comment, you can't use the as keyword for structs (Value Types), as they have no null value.
Well the 'as' operator "helps" you bury your problem way lower because when it is provided an incompatible instance it will return null, maybe you'll pass that to a method which will pass it to another and so on and finally you'll get a NullReferenceException which will make your debugging harder.
Don't abuse it. The direct cast operator is better in 99% of the cases.
A difference between the two approaches is that the the first ((SomeClass)obj) may cause a type converter to be called.
For those of you with VB.NET experience, (type) is the same as DirectCast and "as type" is the same as TryCast.
All of this applies to reference types, value types cannot use the
as
keyword as they cannot be null.The cast syntax is quicker, but only when successful, it's much slower to fail.
Best practice is to use
as
when you don't know the type:However if you are absolutely sure that
someObject
is an instance ofSomeClass
then use cast.In .Net 2 or above generics mean that you very rarely need to have an un-typed instance of a reference class, so the latter is less often used.