tags:

views:

90

answers:

4

Possible Duplicate:
Casting: (NewType) vs. Object as NewType

Just wanted to know which one is faster and what's the difference.

MyClass test = someclass as MyClass;

or

MyClass test = (MyClass)someclass;

+3  A: 

The difference is that the as keyword does not throw an exception when it fails and instead it fills the l-value with null whereas casting with brackets will throw an InvalidCastException.

rmx
And it is much preferable to have a meaningful exception now than a NullReferenceException later. So I would say stick with a regular cast unless you handle the nulliness immediately after an 'as' cast.
Paul Ruane
Also note that you can't use the as keyword with value types.
Dr. Wily's Apprentice
+1  A: 

The as keyword will return null if the desired cast is not valid. Explicit casting will throw an exception in that case. Consequently, I believe the implicit cast (as) is slower, though it's likely negligible.

TreDubZedd
nope, `as` casting is way faster than prefix casting.
Femaref
Interesting. Do you have a technical reason for that?
TreDubZedd
you can see the technical reasons in the codeproject link I provided in my answer.
Femaref
A: 

as casting is faster than prefix casting, but doesn't produce reliable results, ie. it returns null if the cast can't be executed. You'll have to deal with that yourself. Prefix casting will throw an exception if T1 can't be casted to T2.

See: blog

as vs prefix

See codeproject

Femaref
I thought that as was slower....
Grzenio
gj with the downvote whoever that was.
Femaref
+1  A: 

Faster? It probably isn't going to ever matter. You'll have to wait until there is a scenario where your performance profiling application tells you to that the cast is taking too long.

Difference?

Will set test to null when someclass can't be cast to MyClass.

MyClass test = someclass as MyClass; 

Will throw an exception when someclass can't be cast to MyClass.

MyClass test = (MyClass)someclass;
John Fisher