Cast

Why Trust Techopedia

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.

Advertisements

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.

Advertisements

Related Terms

Margaret Rouse
Technology Specialist
Margaret Rouse
Technology Specialist

Margaret is an award-winning writer and educator known for her ability to explain complex technical topics to a non-technical business audience. Over the past twenty years, her IT definitions have been published by Que in an encyclopedia of technology terms and cited in articles in the New York Times, Time Magazine, USA Today, ZDNet, PC Magazine, and Discovery Magazine. She joined Techopedia in 2011. Margaret’s idea of ​​a fun day is to help IT and business professionals to learn to speak each other’s highly specialized languages.