C# FAQ: What is the difference between using a cast and the as operator
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:FAQs |
| edit |
[edit]
What is the difference between using a cast and the as operator?
Performing an explicit cast differs from using the as operator in three major aspects.
The as operator
- returns a
nullif the variable being converted is not of the requested type nor present in its inheritance chain. On the other hand, a cast would throw an exception. - can be applied only to reference type variables being converted to reference types.
- cannot perform user-defined conversions—e.g., explicit or implicit conversion operators. A cast could perform these types of conversions.
Far from being merely cosmetic, the as operator and casting are handled by two seperate operations defined in Intermediate Language (IL)—the castclass and isinst IL instructions.
Developers report that the as operator is slightly faster than casting in C#.
[edit]