What Does Cast Mean?
Cast, in the context of C#, is a method by which a value is converted from one data type to another. Cast is an explicit conversion by which the compiler is informed about the conversion and the resulting possibility of data loss.
Cast is typically used when the explicit conversion should be aware to the users who are performing the cast operation. It helps in the conversions where information might be lost or that might not succeed for other reasons. Cast operations can be performed for numeric conversions in which the destination type is of lesser precision or a smaller range. It is also used for conversion from base class instance to derived class.
Due to the inherent feature of variables in C# language being statically typed at compile time, variables declared once in code cannot be declared again and store values of another type, unless that type is convertible to a variable‘s type. Cast helps in copying a value of a particular type into a variable or parameter of a method which is of different type.
Cast is also known as an explicit conversion.
Techopedia Explains Cast
The operator used to perform cast operation in C# is parentheses. To perform a cast operation, the destination data type is explicitly written in parentheses before the value to be converted. An example for cast operation can be the conversion of a variable of double or float type to an integer type.
In case of cast operations that involve base and derived types, there is a risk of throwing exceptions. To test for compatibility before actually performing a cast, C# has provided two operators to allow casting safely without causing any exceptions. The two operators are:
- The ‘Is’ operator used to check for successful casting from one reference type to another and to determine an object ‘s type without casting it.
- The ‘As’ operator used to obtain the cast value, if the cast can be made successfully and hence more efficient.
Since it is potentially unsafe to use casts due to the possibility of failure, it is highly recommended to perform cast operations with structured exception handling code to handle exceptions.