Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Whats the difference between using cast syntax and the as operator?

Cast operator syntax
0
Posted

Whats the difference between using cast syntax and the as operator?

0

Using the as operator differs from a cast in C# in three important ways: • It returns a null when the variable you are trying to convert is not of the requested type or in its inheritance chain, instead of throwing an exception. • It can only be applied to reference type variables converting to reference types. • 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).

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123