Casting and Type Conversions
Casting and Type Conversions
Casting and Type Conversions
AND
TYPE CONVERSIONS
CASTING AND TYPE CONVERSIONS
• Because C# is statically-typed at compile time, after a variable is declared, it cannot be
declared again or used to store values of another type unless that type is convertible to the
variable's type.
• For example,
int i;
i = "Hello"; // Error: "Cannot implicitly
convert type 'string' to 'int'"
CASTING AND TYPE CONVERSIONS
• However, we might sometimes need to copy a value into a variable or method parameter of
another type.
• For example, we might have an integer variable that you need to pass to a method whose
parameter is typed as double.
• Or we might need to assign a class variable to a variable of a derived type.
• These kinds of operations are called type conversions.
CASTING AND TYPE CONVERSIONS
In C#, we can perform the following kinds of conversions:
•Implicit conversions: No special syntax is required because the conversion is type safe and no
data will be lost. Examples include conversions from smaller to larger integral types, and
conversions from derived classes to base classes.
•Explicit conversions (casts): Explicit conversions require a cast operator. Casting is required
when information might be lost in the conversion, or when the conversion might not succeed
for other reasons. Typical examples include numeric conversion to a type that has less
precision or a smaller range, and conversion of a base-class instance to a derived class.
• For reference types, an implicit conversion always exists from a class to any one of its direct
or indirect base classes. No special syntax is necessary because a derived class always
contains all the members of a base class.
Derived d = new Derived();
Base b = d; // Always OK.
EXPLICIT CONVERSIONS
• However, if a conversion cannot be made
without a risk of losing information, the class Test
{ static void Main()
compiler requires that you perform an explicit {
conversion, which is called a cast. double x = 1234.7;
• int a;
A cast is a way of explicitly informing the // Cast double to int.
compiler that you intend to make the a = (int)x;
conversion and that you are aware that data System.Console.WriteLine(a);
loss might occur. }
}
• To perform a cast, specify the type that you // Output: 1234
are casting to in parentheses in front of the
value or variable to be converted.
EXPLICIT CONVERSIONS
• For reference types, an explicit cast is required if you need to convert from a base type to
a derived type:
• as Operator
• The "as" operator is used to perform conversions between compatible types. Actually, the "as"
operator returns the cast value if the cast can be made successfully.