Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
As operator, in C#, is an operator that is used to convert a reference type expression from one type to another compatible type.
The as operator attempts to perform a silent cast of an object to a given type without raising any exception upon failure. It can be used to compare two types. Because it is not used for user-defined conversion, it is more consistent than a normal cast. It never creates temporary objects and does not require the target variable to be converted to null before conversion. It is usually used when the type of the expression or object to which it has to be cast is not already known.
The as operator provides an elegant method of performing cast operation by making the code more readable without any code for exception handling. This results in reduced code size and lesser development effort. For reference types, the as operator is a good alternative to the cast operator because it is safer and provides better performance.
The as operator is a type testing operator with two parameters that include the expression of reference type that needs to be converted and the destination type to which the conversion has to be performed. If the conversion is successful, it returns the converted object, or null on failure.
For example, the as operator can be used by a collection object that can store a list of items of different types - such as integer, string and objects of user-defined types - and iterate through the collection to access each of the items as a string type.
The as operator is used to perform reference and boxing conversions only.
Although the as operator performs similarly to the cast operator, it differs in that it is only applicable to conversions between reference types without the occurrence of exceptions after cast operation. It cannot be used for user-defined conversions.
While performing type conversions using the as operator, the return value has to be checked for null before using the variable that is converted. When used with the generic method, which can receive reference and value types as input, the method has to be restricted to only accept reference types.
The as operator is more efficient than the is operator because it not only tests for the success of a cast but also returns a cast value for a successful cast operation, or null on failure.