CKTIS / C#
Explicit type cast: (T)expression
The expression `(T)expression` explicitly converts the result of `expression` to type `T`. It can perform a numeric conversion, reference conversion, unboxing, or a user-defined conversion. Success is not guaranteed: it can lose data or throw an exception.
Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification
Syntax
(T)expressionThe expression (T)expression requests an explicit conversion: T is the target type, and expression supplies the value to convert. A cast can also request a conversion that is available implicitly. If no applicable conversion exists, the compiler rejects the code; adding (T) does not allow arbitrary conversions between types.
Numeric conversions can lose information. For a finite double whose integral part fits in int, (int)value discards the fractional part toward zero: -12.75 becomes -12, not -13. When narrowing between integer types in a checked context, an out-of-range runtime value causes the conversion to throw OverflowException. If the operand is a constant expression whose value is outside the target type's range, the conversion is a compile-time error in a checked context, as in checked((byte)256). In an unchecked context, this kind of narrowing conversion discards excess bits. Do not generalize that rule to every numeric conversion.
A reference conversion does not change the object or its runtime type. Casting an incompatible object can throw InvalidCastException; casting a null reference to a reference type still produces null. When the source reference is not null, unboxing requires a boxed value of the appropriate type: if boxed contains an int, (long)boxed throws InvalidCastException, but (long)(int)boxed first unboxes the int and then converts it to long. An unboxing conversion from a null reference to a nullable value type yields null: for example, (int?)(object)null produces a null int? without any boxed value.
Unlike a cast, is checks compatibility, while as returns null on incompatibility and does not support numeric or user-defined conversions. A type can define implicit and explicit conversion operators used by casts; it cannot overload () itself. The example demonstrates fractional truncation, unboxing followed by widening, and a reference conversion.
Examples
using System;
internal static class Program
{
private static void Main()
{
double value = -12.75;
int whole = (int)value;
Console.WriteLine(whole);
object boxed = 42;
long widened = (long)(int)boxed;
Console.WriteLine(widened);
object text = "hello";
string word = (string)text;
Console.WriteLine(word.Length);
}
}Result
-12 42 5
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.