# Safe downcasting

The `as` operator returns `null` when a dynamic cast fails. You can use it combined with `IsDefined` to perform safe downcasts. The following example shows how you can safe downcast a [VehicleObject](https://nativedb.red4ext.com/VehicleObject) to a [WheeledObject](https://nativedb.red4ext.com/WheeledObject), a [CarObject](https://nativedb.red4ext.com/CarObject) or a [BikeObject](https://nativedb.red4ext.com/BikeObject):

```swift
let vehicle: ref<VehicleObject>;

let wheels = vehicle as WheeledObject;
if IsDefined(wheels) {
  // vehicle is known to be a WheeledObject.
}

let car = vehicle as CarObject;
if IsDefined(car) {
  // vehicle is known to be a CarObject.
}

let bike = vehicle as BikeObject;
if IsDefined(bike) {
  // vehicle is known to be a BikeObject.
}
```

{% hint style="info" %}
`as` operator will keep the same kind of reference, that is `ref<T>` to `ref<U>` and `wref<T>` to `wref<U>`.
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wiki.redmodding.org/redscript/references-and-examples/common-patterns/safe-downcasting.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
