CKTIS / C#
Type conversions
Conversions let you use an expression as a value of another type. Learn about implicit conversions, explicit casts, boxing, and unboxing. The C# specification requires an exact type match when unboxing to a non-nullable value type, but the .NET runtime also lets you unbox an enum as its underlying integral type. Under the specification, a nullable target accepts `null` or a boxed value of its underlying type.
Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification
Syntax
Target implicitResult = expression;
Target explicitResult = (Target)expression;
object boxed = 42;
int unboxed = (int)boxed;
long widened = (long)(int)boxed;A conversion lets an expression be treated as having a particular type; it may change the value's representation. An implicit conversion, such as int → long, needs no cast. Write an explicit conversion as (Target)expression. This syntax alone guarantees neither success nor preservation of all information.
Numeric conversions can lose precision: (int)19.75 produces 19, discarding the fractional part toward zero. A reference conversion neither copies the object nor changes its runtime type. To read numbers from text, use an API such as int.TryParse, not a cast.
Boxing and exact-type unboxing: boxing an ordinary int value to object stores a copy in an object on the managed heap. Later changes to the source variable do not change that copy. Unboxing is explicit: (int)boxed retrieves the boxed int value. (long)boxed throws InvalidCastException, even though an int → long numeric conversion exists. Use (long)(int)boxed: unbox first, then perform the numeric conversion.
The portable rule in the C# specification is that when unboxing to a non-nullable value type, the target type must exactly match the boxed value's type. The .NET runtime, however, lets you unbox a boxed enum directly as its underlying integral type, as in (int)(object)DayOfWeek.Monday. This does not mean that unboxing performs arbitrary numeric conversions.
Unboxing null to a non-nullable value type throws NullReferenceException. Nullable types have separate rules: boxing an int? without a value produces null; with a value, it boxes an int, not an int?. Under the specification, unboxing to int? accepts either null or a boxed int.
Examples
using System;
int original = 42;
long widened = original;
int truncated = (int)19.75;
object boxed = original;
original = 99;
Console.WriteLine(widened);
Console.WriteLine(truncated);
Console.WriteLine((int)boxed);
Console.WriteLine((long)(int)boxed);
try
{
long invalid = (long)boxed;
Console.WriteLine(invalid);
}
catch (InvalidCastException)
{
Console.WriteLine("InvalidCastException");
}Result
42 19 42 42 InvalidCastException
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.