C# Frequently Asked Questions

The C# team posts answers to common questions

What's the difference between cast syntax and using the as operator?

Using the as operator differs from a cast in C# in three important ways:

  1. It returns null when the variable you are trying to convert is not of the requested type or in it's inheritance chain, instead of throwing an exception.
  2. It can only be applied to reference type variables converting to reference types.
  3. Using as will not perform user-defined conversions, such as implicit or explicit conversion operators, which casting syntax will do.

There are in fact two completely different operations defined in IL that handle these two keywords (the castclass and isinst instructions) - it's not just "syntactic sugar" written by C# to get this different behavior. The as operator appears to be slightly faster in v1.0 and v1.1 of Microsoft's CLR compared to casting (even in cases where there are no invalid casts which would severely lower casting's performance due to exceptions).

[Author: Jon Skeet]

Published Friday, March 12, 2004 12:22 AM by CSharpFAQ

Comments

 

Ed Ball said:

Really? I figured a cast with no invalid casts would be faster than the 'as' operator, and I thought I even did a little measuring... I think I'll just latch onto your statement, though, because I think 'as' is beautiful compared to the ugly C-style cast, and I can't help but use it for that very reason.

http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=6b7a5401-6d44-4f6c-a155-a19fa84fb2e6
March 15, 2004 1:03 PM
 

Jon Skeet said:

No, casts are definitely slightly slower, at least in the current implementation.

What is even slower is an "is" test followed by a cast.
March 26, 2004 1:17 PM
 

C# with CF and casting vs AS | keyongtech said:

January 22, 2009 12:04 AM
 

What did we learn this week? Week of 26 januari 2009 « Hungry for Knowledge said:

February 1, 2009 11:31 AM
Anonymous comments are disabled

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker