Object and Dyn
The object Type
A type-safe universal GC reference that can hold any GC reference or auto-boxed value type:
object o = new Person("Alice"); // GC ref stored directlyobject n = 42; // int auto-boxedobject f = 3.14; // float auto-boxedobject s = "hello"; // string auto-boxedType Checking and Unboxing
Use is and as to inspect and extract the underlying value:
object o = 42;
if (o is int){ int val = o as int; // unboxes to 42}
if (o is Person p){ p.Greet(); // pattern binding with unbox}The dyn Type
A dynamic dispatch type that resolves field access and method calls at runtime:
dyn d = new Person("Alice");
int age = d.age; // runtime field lookupd.age = 30; // runtime field writed.Greet(); // runtime method resolution + callIf a field or method is not found at runtime, an exception is raised.
Auto-Boxing
Value types are automatically boxed when assigned to object or dyn:
| Source Type | Box Type |
|---|---|
int / int64 | __Box_i64 |
int32 | __Box_i32 |
int16 | __Box_i16 |
int8 | __Box_i8 |
float / float64 | __Box_f64 |
float32 | __Box_f32 |
bool | __Box_bool |
string | __Box_string |
object vs dyn
| Feature | object | dyn |
|---|---|---|
| Holds any type | Yes | Yes |
| Auto-boxing | Yes | Yes |
| Type-safe access | Via is/as | No (runtime only) |
| Field access by name | No | Yes |
| Method call by name | No | Yes |
| Runtime overhead | Minimal | Lookup per access |